[PATCH] D159064: [Modules] Make clang modules for the C standard library headers

2023-10-02 Thread Ian Anderson via Phabricator via cfe-commits
iana marked 5 inline comments as done.
iana added inline comments.



Comment at: clang/test/Modules/Inputs/System/usr/include/stdint.h:2
 typedef int my_awesome_nonstandard_integer_type;
+
+/* C99 7.18.1.1 Exact-width integer types.

dexonsmith wrote:
> Bigcheese wrote:
> > iana wrote:
> > > dexonsmith wrote:
> > > > benlangmuir wrote:
> > > > > iana wrote:
> > > > > > iana wrote:
> > > > > > > benlangmuir wrote:
> > > > > > > > Why do we need all this code now (I assume this is copied from 
> > > > > > > > the real header)?
> > > > > > > It's to support the tests I added to Modules/compiler_builtins.m. 
> > > > > > > stdatomic.h and inttypes.h rely on stdint.h contents from the C 
> > > > > > > library, and on complex.h and inttypes.h and math.h being 
> > > > > > > present. I could just test the modules with `-ffreestanding` I 
> > > > > > > think, would that be better?
> > > > > > (and yes I just copied it from the builtin header)
> > > > > I'm not sure what the best approach is here, but this seems heavy for 
> > > > > a test.  Do we expect to need to keep this up to date? If so maybe 
> > > > > ffreestanding for the specific test cases this affects would be a 
> > > > > better tradeoff.  Maybe someone else has a suggestion here
> > > > This reflects *most* of the content in `stdint.h`.
> > > > 
> > > > One idea would be to copy the full header over during the test setup 
> > > > and fix it up, either:
> > > > - strip out the header/footer or
> > > > - `sed -e "s/__STDC_HOSTED__/0/g"`
> > > > so that it always provides content (even when not freestanding).
> > > IMO it doesn't need to be that sophisticated, the types just have to 
> > > exist for stdtomic.h to compile. I could chop all the comments and define 
> > > everything to `int` and I think that'd be fine too.
> > Looking at stdatomic.h I think this approach would be fine. It just wants 
> > the types to exist.
> SGTM.
Mostly copied clang/test/Modules/Inputs/libc-libcxx/sysroot/usr/include/stdint.h


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159064

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


[PATCH] D159064: [Modules] Make clang modules for the C standard library headers

2023-10-02 Thread Ian Anderson via Phabricator via cfe-commits
iana updated this revision to Diff 557549.
iana added a comment.

Minimize the testing stdint.h


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159064

Files:
  clang/lib/Basic/Module.cpp
  clang/lib/Headers/__stddef_max_align_t.h
  clang/lib/Headers/__stddef_null.h
  clang/lib/Headers/__stddef_nullptr_t.h
  clang/lib/Headers/__stddef_offsetof.h
  clang/lib/Headers/__stddef_ptrdiff_t.h
  clang/lib/Headers/__stddef_rsize_t.h
  clang/lib/Headers/__stddef_size_t.h
  clang/lib/Headers/__stddef_unreachable.h
  clang/lib/Headers/__stddef_wchar_t.h
  clang/lib/Headers/__stddef_wint_t.h
  clang/lib/Headers/module.modulemap
  clang/lib/Headers/stdarg.h
  clang/lib/Headers/stddef.h
  clang/test/Headers/stdarg.c
  clang/test/Headers/stdargneeds.c
  clang/test/Headers/stddef.c
  clang/test/Headers/stddefneeds.c
  clang/test/Modules/Inputs/System/usr/include/complex.h
  clang/test/Modules/Inputs/System/usr/include/inttypes.h
  clang/test/Modules/Inputs/System/usr/include/math.h
  clang/test/Modules/Inputs/System/usr/include/module.map
  clang/test/Modules/Inputs/System/usr/include/stdint.h
  clang/test/Modules/compiler_builtins.m
  clang/test/Modules/stddef.c
  clang/test/Modules/stddef.m

Index: clang/test/Modules/stddef.m
===
--- clang/test/Modules/stddef.m
+++ clang/test/Modules/stddef.m
@@ -4,4 +4,6 @@
 
 // RUN: rm -rf %t
 // RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fbuiltin-headers-in-system-modules -fmodules-cache-path=%t -I %S/Inputs/StdDef %s -verify
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/StdDef %s -verify
 // expected-no-diagnostics
Index: clang/test/Modules/stddef.c
===
--- clang/test/Modules/stddef.c
+++ clang/test/Modules/stddef.c
@@ -1,13 +1,29 @@
 // RUN: rm -rf %t
 // RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fbuiltin-headers-in-system-modules -fmodules-cache-path=%t -I%S/Inputs/StdDef %s -verify -fno-modules-error-recovery
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I%S/Inputs/StdDef %s -verify -fno-modules-error-recovery
 
 #include "ptrdiff_t.h"
 
 ptrdiff_t pdt;
 
-size_t st; // expected-error {{missing '#include "include_again.h"'; 'size_t' must be declared before it is used}}
-// expected-note@__stddef_size_t.h:* {{here}}
+// size_t is declared in both size_t.h and __stddef_size_t.h, both of which are
+// modular headers. Regardless of whether stddef.h joins the StdDef test module
+// or is in its _Builtin_stddef module, __stddef_size_t.h will be in
+// _Builtin_stddef.size_t. It's not defined which module will win as the expected
+// provider of size_t. For the purposes of this test it doesn't matter which header
+// gets reported, just as long as it isn't other.h or include_again.h.
+size_t st; // expected-error-re {{missing '#include "{{size_t|__stddef_size_t}}.h"'; 'size_t' must be declared before it is used}}
+// expected-note@size_t.h:* 0+ {{here}}
+// expected-note@__stddef_size_t.h:* 0+ {{here}}
 
 #include "include_again.h"
+// Includes  which includes <__stddef_size_t.h> which imports the
+// _Builtin_stddef.size_t module.
 
 size_t st2;
+
+#include "size_t.h"
+// Redeclares size_t, but the type merger should figure it out.
+
+size_t st3;
Index: clang/test/Modules/compiler_builtins.m
===
--- clang/test/Modules/compiler_builtins.m
+++ clang/test/Modules/compiler_builtins.m
@@ -1,7 +1,7 @@
 // RUN: rm -rf %t
-// RUN: %clang_cc1 -fsyntax-only -fmodules -fimplicit-module-maps -fmodules-cache-path=%t %s -I%S/Inputs/System/usr/include -verify
-// RUN: %clang_cc1 -fsyntax-only -std=c99 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t %s -I%S/Inputs/System/usr/include -verify
-// RUN: %clang_cc1 -fsyntax-only -fmodules -fmodule-map-file=%resource_dir/module.modulemap -fmodules-cache-path=%t %s -I%S/Inputs/System/usr/include -verify
+// RUN: %clang_cc1 -fsyntax-only -fmodules -fimplicit-module-maps -fmodules-cache-path=%t %s -internal-isystem %S/Inputs/System/usr/include -verify
+// RUN: %clang_cc1 -fsyntax-only -std=c99 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t %s -internal-isystem %S/Inputs/System/usr/include -verify
+// RUN: %clang_cc1 -fsyntax-only -fmodules -fmodule-map-file=%resource_dir/module.modulemap -fmodules-cache-path=%t %s -I%S/Inputs/System/usr/include -DNO_SYSTEM_MODULES -verify
 // expected-no-diagnostics
 
 #ifdef __SSE__
@@ -11,3 +11,19 @@
 #ifdef __AVX2__
 @import _Builtin_intrinsics.intel.avx2;
 #endif
+
+#ifndef NO_SYSTEM_MODULES
+@import _Builtin_float;
+@import _Builtin_inttypes;
+@import _Builtin_iso646;
+@import _Builtin_limits;
+@import _Builtin_stdalign;
+@import _Builtin_stdarg;
+@import _Builtin_stdatomic;
+@import _Builtin_stdbool;

[PATCH] D158069: [clang][Interp] Fix getIndex() for composite array elements

2023-10-02 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Pointer.h:81-88
+  /// Equality operators are just for tests.
+  bool operator==(const Pointer ) const {
+return Pointee == P.Pointee && Base == P.Base && Offset == P.Offset;
+  }
+
+  bool operator!=(const Pointer ) const {
+return Pointee != P.Pointee || Base != P.Base || Offset != P.Offset;

aaron.ballman wrote:
> tbaeder wrote:
> > aaron.ballman wrote:
> > > Same here -- can these be private and friended?
> > Don't you need a class to friend something? I only have the `TEST(...)` 
> > function in the unit test, so I can't do that, right?
> `FRIEND_TEST` does this, I believe: 
> https://google.github.io/googletest/reference/testing.html#FRIEND_TEST
Is this something we should be doing? There's nothing else in clang using 
`FRIEND_TEST` and only stuff in `Testing/` includes gtest.h.


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

https://reviews.llvm.org/D158069

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


[clang] [clang][Interp] Diagnose uninitialized bases (PR #67131)

2023-10-02 Thread Timm Baeder via cfe-commits

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


[clang] f58d54a - [clang][Interp] Diagnose uninitialized bases (#67131)

2023-10-02 Thread via cfe-commits

Author: Timm Baeder
Date: 2023-10-03T06:46:31+02:00
New Revision: f58d54ab969b2f342a882dfb03334f18f4ec1dcc

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

LOG: [clang][Interp] Diagnose uninitialized bases (#67131)

Added: 
clang/test/AST/Interp/constexpr-subobj-initialization.cpp

Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeStmtGen.cpp
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/Opcodes.td

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e266804a4e75dea..f4ab30a5c8e7238 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -561,7 +561,7 @@ bool ByteCodeExprGen::visitInitList(ArrayRef Inits,
 if (!this->visitInitializer(Init))
   return false;
 
-if (!this->emitPopPtr(E))
+if (!this->emitInitPtrPop(E))
   return false;
 // Base initializers don't increase InitIndex, since they don't count
 // into the Record's fields.
@@ -1718,7 +1718,7 @@ bool 
ByteCodeExprGen::visitZeroRecordInitializer(const Record *R,
   return false;
 if (!this->visitZeroRecordInitializer(B.R, E))
   return false;
-if (!this->emitPopPtr(E))
+if (!this->emitInitPtrPop(E))
   return false;
   }
 

diff  --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp 
b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
index 15eae8e20b3a678..a81c82c38955e9c 100644
--- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -191,7 +191,7 @@ bool ByteCodeStmtGen::visitFunc(const FunctionDecl 
*F) {
   return false;
 if (!this->visitInitializer(InitExpr))
   return false;
-if (!this->emitPopPtr(InitExpr))
+if (!this->emitInitPtrPop(InitExpr))
   return false;
   }
 }

diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index e1951574edb6288..8e851595963184c 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -467,6 +467,12 @@ static bool CheckFieldsInitialized(InterpState , CodePtr 
OpPC,
   // Check Fields in all bases
   for (const Record::Base  : R->bases()) {
 Pointer P = BasePtr.atField(B.Offset);
+if (!P.isInitialized()) {
+  S.FFDiag(BasePtr.getDeclDesc()->asDecl()->getLocation(),
+   diag::note_constexpr_uninitialized_base)
+  << B.Desc->getType();
+  return false;
+}
 Result &= CheckFieldsInitialized(S, OpPC, P, B.R);
   }
 

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 9d5ec3315415cf7..d62e64bedb213ac 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1245,6 +1245,12 @@ inline bool GetPtrThisBase(InterpState , CodePtr OpPC, 
uint32_t Off) {
   return true;
 }
 
+inline bool InitPtrPop(InterpState , CodePtr OpPC) {
+  const Pointer  = S.Stk.pop();
+  Ptr.initialize();
+  return true;
+}
+
 inline bool VirtBaseHelper(InterpState , CodePtr OpPC, const RecordDecl 
*Decl,
const Pointer ) {
   Pointer Base = Ptr;

diff  --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 9fc4938bb37bde8..50b6c0ac154de30 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -304,6 +304,10 @@ def GetPtrBasePop : Opcode {
   let Args = [ArgUint32];
 }
 
+def InitPtrPop : Opcode {
+  let Args = [];
+}
+
 def GetPtrDerivedPop : Opcode {
   let Args = [ArgUint32];
 }

diff  --git a/clang/test/AST/Interp/constexpr-subobj-initialization.cpp 
b/clang/test/AST/Interp/constexpr-subobj-initialization.cpp
new file mode 100644
index 000..4976b165468bd61
--- /dev/null
+++ b/clang/test/AST/Interp/constexpr-subobj-initialization.cpp
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s 
-fexperimental-new-constant-interpreter
+
+/// This is like the version in test/SemaCXX/, but some of the
+/// output types and their location has been adapted.
+/// Differences:
+///   1) The type of the uninitialized base class is printed WITH the 
namespace,
+///  i.e. 'baseclass_uninit::DelBase' instead of just 'DelBase'.
+///   2) The location is not the base specifier declaration, but the call site
+///  of the constructor.
+
+
+namespace baseclass_uninit {
+struct DelBase {
+  constexpr DelBase() = delete; // expected-note {{'DelBase' has been 
explicitly marked deleted here}}
+};
+
+struct Foo : DelBase {
+  constexpr Foo() {}; // expected-error {{call to deleted constructor of 
'DelBase'}}
+};
+constexpr Foo f; // expected-error {{must be initialized by a constant 
expression}} \
+ // 

[clang] [clang][Interp] Diagnose uninitialized bases (PR #67131)

2023-10-02 Thread Timm Baeder via cfe-commits

tbaederr wrote:

> Maybe we should change the existing evaluator to be consistent? Otherwise LGTM

I'm not 100% sure what output is better, but we can change that later. This 
change is more about correctness.

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


[clang] fb0a7c8 - [clang][Interp][NFC] Make IntegralAP::V private

2023-10-02 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-03T06:31:03+02:00
New Revision: fb0a7c8589e1320de1bf48161a4995a0e5dc8b77

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

LOG: [clang][Interp][NFC] Make IntegralAP::V private

Added: 


Modified: 
clang/lib/AST/Interp/IntegralAP.h

Removed: 




diff  --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index 0876d7fae958a54..a8df431bef11784 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -33,14 +33,14 @@ class Boolean;
 
 template  class IntegralAP final {
 private:
+  friend IntegralAP;
+  APSInt V;
+
   template  static T truncateCast(const APSInt ) {
 return std::is_signed_v ? V.trunc(sizeof(T) * 8).getSExtValue()
: V.trunc(sizeof(T) * 8).getZExtValue();
   }
 
-public:
-  APSInt V;
-
 public:
   using AsUnsigned = IntegralAP;
 



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


[clang] [RISCV][AArch64] Don't allow -mvscale-min/max options to be passed to the clang driver. (PR #68065)

2023-10-02 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-risc-v


Changes

The driver doesn't have code to pass these down to cc1. It just prints an 
unused option warning. Remove them from the driver.

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


1 Files Affected:

- (modified) clang/include/clang/Driver/Options.td (+2-4) 


``diff
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index ee4e23f335e7875..87159dd64dc7a7b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4563,13 +4563,11 @@ def msve_vector_bits_EQ : Joined<["-"], 
"msve-vector-bits=">, Group,
   MarshallingInfoInt>;
 def mvscale_max_EQ : Joined<["-"], "mvscale-max=">,
-  Group, Flags<[NoXarchOption]>,
-  Visibility<[ClangOption, CC1Option, FC1Option]>,
+  Visibility<[CC1Option, FC1Option]>,
   HelpText<"Specify the vscale maximum. Defaults to the"
" vector length agnostic value of \"0\". (AArch64/RISC-V only)">,
   MarshallingInfoInt>;

``




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


[clang] [RISCV][AArch64] Don't allow -mvscale-min/max options to be passed to the clang driver. (PR #68065)

2023-10-02 Thread Craig Topper via cfe-commits

https://github.com/topperc created 
https://github.com/llvm/llvm-project/pull/68065

The driver doesn't have code to pass these down to cc1. It just prints an 
unused option warning. Remove them from the driver.

>From b6be263a9b07425471f17e66b506bb805f29b8a0 Mon Sep 17 00:00:00 2001
From: Craig Topper 
Date: Mon, 2 Oct 2023 21:06:56 -0700
Subject: [PATCH] [RISCV][AArch64] Don't allow -mvscale-min/max options to be
 passed to the clang driver.

The driver doesn't have code to pass these down to cc1. It just
prints an unused option warning. Remove them from the driver.
---
 clang/include/clang/Driver/Options.td | 6 ++
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index ee4e23f335e7875..87159dd64dc7a7b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4563,13 +4563,11 @@ def msve_vector_bits_EQ : Joined<["-"], 
"msve-vector-bits=">, Group,
   MarshallingInfoInt>;
 def mvscale_max_EQ : Joined<["-"], "mvscale-max=">,
-  Group, Flags<[NoXarchOption]>,
-  Visibility<[ClangOption, CC1Option, FC1Option]>,
+  Visibility<[CC1Option, FC1Option]>,
   HelpText<"Specify the vscale maximum. Defaults to the"
" vector length agnostic value of \"0\". (AArch64/RISC-V only)">,
   MarshallingInfoInt>;

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


[clang] [clang] Ignore GCC 11 `[[malloc(x)]]` attribute (PR #68059)

2023-10-02 Thread Timm Baeder via cfe-commits


@@ -4122,6 +4122,9 @@ def RestrictDocs : Documentation {
 The ``malloc`` attribute indicates that the function acts like a system memory
 allocation function, returning a pointer to allocated storage disjoint from the
 storage for any other object accessible to the caller.
+
+The form of ``malloc`` with one or two arguments (supported by GCC 11) is
+currently ignored by Clang.

tbaederr wrote:

Is it really ignored or is it just treated as if it had no arguments?

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


[clang] [analyzer] Fix false negative when accessing a nonnull property from … (PR #67563)

2023-10-02 Thread Gábor Horváth via cfe-commits

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


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


[clang] [clang][Interp] Fix value truncation when casting int128 to smaller size (PR #67961)

2023-10-02 Thread Timm Baeder via cfe-commits

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


[clang] ef9666a - [clang][Interp] Fix value truncation when casting int128 to smaller size (#67961)

2023-10-02 Thread via cfe-commits

Author: Timm Baeder
Date: 2023-10-03T06:05:39+02:00
New Revision: ef9666aa81abdbcff54448446ba1f6fffe5fa45c

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

LOG: [clang][Interp] Fix value truncation when casting int128 to smaller size 
(#67961)

Before this patch, we would run into an assertion in
`APInt::get{S,Z}ExtValue()` because the `AllOnes` value had more than 64
active bits.

Added: 


Modified: 
clang/lib/AST/Interp/IntegralAP.h
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index 42f44354cbd2599..0876d7fae958a54 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -32,6 +32,12 @@ template  class Integral;
 class Boolean;
 
 template  class IntegralAP final {
+private:
+  template  static T truncateCast(const APSInt ) {
+return std::is_signed_v ? V.trunc(sizeof(T) * 8).getSExtValue()
+   : V.trunc(sizeof(T) * 8).getZExtValue();
+  }
+
 public:
   APSInt V;
 
@@ -55,14 +61,14 @@ template  class IntegralAP final {
   bool operator<=(IntegralAP RHS) const { return V <= RHS.V; }
 
   explicit operator bool() const { return !V.isZero(); }
-  explicit operator int8_t() const { return V.getSExtValue(); }
-  explicit operator uint8_t() const { return V.getZExtValue(); }
-  explicit operator int16_t() const { return V.getSExtValue(); }
-  explicit operator uint16_t() const { return V.getZExtValue(); }
-  explicit operator int32_t() const { return V.getSExtValue(); }
-  explicit operator uint32_t() const { return V.getZExtValue(); }
-  explicit operator int64_t() const { return V.getSExtValue(); }
-  explicit operator uint64_t() const { return V.getZExtValue(); }
+  explicit operator int8_t() const { return truncateCast(V); }
+  explicit operator uint8_t() const { return truncateCast(V); }
+  explicit operator int16_t() const { return truncateCast(V); }
+  explicit operator uint16_t() const { return truncateCast(V); }
+  explicit operator int32_t() const { return truncateCast(V); }
+  explicit operator uint32_t() const { return truncateCast(V); }
+  explicit operator int64_t() const { return truncateCast(V); }
+  explicit operator uint64_t() const { return truncateCast(V); }
 
   template  static IntegralAP from(T Value, unsigned NumBits = 0) {
 assert(NumBits > 0);

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 00182ba4ab1d918..00875bcf44dc8e6 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -53,7 +53,7 @@ namespace i128 {
   static_assert(Two == 2, "");
 
   constexpr uint128_t AllOnes = ~static_cast(0);
-  static_assert(AllOnes == static_cast(-1), "");
+  static_assert(AllOnes == UINT128_MAX, "");
 
 #if __cplusplus >= 201402L
   template 
@@ -70,6 +70,14 @@ namespace i128 {
   static_assert(CastFrom(12) == 12, "");
   static_assert(CastFrom(12) == 12, "");
 
+  static_assert(CastFrom(AllOnes) == -1, "");
+  static_assert(CastFrom(AllOnes) == 0xFF, "");
+  static_assert(CastFrom(AllOnes) == -1, "");
+  static_assert(CastFrom(AllOnes) == 0x, "");
+  static_assert(CastFrom(AllOnes) == -1, "");
+  static_assert(CastFrom(AllOnes) == -1, "");
+  static_assert(CastFrom(AllOnes) == AllOnes, "");
+
   template 
   constexpr __int128 CastTo(T A) {
 int128_t B = (int128_t)A;



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


[PATCH] D145262: [clang-format] Treat AttributeMacros more like attribute macros

2023-10-02 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/ContinuationIndenter.cpp:1338-1341
 PreviousNonComment->isOneOf(
-TT_AttributeRParen, TT_AttributeSquare, 
TT_FunctionAnnotationRParen,
-TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
+TT_AttributeRParen, TT_AttributeMacro, TT_AttributeSquare,
+TT_FunctionAnnotationRParen, TT_JavaAnnotation,
+TT_LeadingJavaAnnotation))) ||

Basically, insert the first two lines and undo the changes to the last three 
lines.



Comment at: clang/lib/Format/TokenAnnotator.cpp:4390-4391
 // Space in __attribute__((attr)) ::type.
 if (Left.is(TT_AttributeRParen) && Right.is(tok::coloncolon))
   return true;
 

Please also add a test case for this.



Comment at: clang/lib/Format/TokenAnnotator.cpp:4706
   return true;
-if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right)) {
+// Apply this logic for parens that are not function attribute macros.
+if (Left.is(tok::r_paren) && Left.isNot(TT_AttributeRParen) &&

Please delete this comment, which IMO doesn't quite match the code below.


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

https://reviews.llvm.org/D145262

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


[clang] [HIP] Support compressing device binary (PR #67162)

2023-10-02 Thread Yaxun Liu via cfe-commits

https://github.com/yxsamliu updated 
https://github.com/llvm/llvm-project/pull/67162

>From c2d5f809ab0f1be50cee4baaffdf3994807e5ef2 Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Thu, 21 Sep 2023 13:52:16 -0400
Subject: [PATCH] [HIP] Support compressing device binary

Add option -f[no-]offload-compress to clang to enable/disable
compression of device binary for HIP. By default it is disabled.

Add option -compress to clang-offload-bundler to enable
compression of offload bundle. By default it is disabled.

When enabled, zstd or zlib is used for compression when
available.

When disabled, it is NFC compared to previous behavior. The
same offload bundle format is used as before.

Clang-offload-bundler automatically detects whether the
input file to be unbundled is compressed and the compression
method and decompress if necessary.
---
 clang/docs/ClangOffloadBundler.rst|  27 ++
 clang/include/clang/Driver/OffloadBundler.h   |  37 ++
 clang/include/clang/Driver/Options.td |   4 +
 clang/lib/Driver/OffloadBundler.cpp   | 340 +++---
 clang/lib/Driver/ToolChains/Clang.cpp |   7 +
 clang/lib/Driver/ToolChains/HIPUtility.cpp|   6 +
 .../test/Driver/clang-offload-bundler-zlib.c  |  75 
 .../test/Driver/clang-offload-bundler-zstd.c  |  72 
 .../test/Driver/hip-offload-compress-zlib.hip |  47 +++
 .../test/Driver/hip-offload-compress-zstd.hip |  47 +++
 .../clang-offload-bundler/CMakeLists.txt  |   1 +
 .../ClangOffloadBundler.cpp   |  10 +
 llvm/include/llvm/BinaryFormat/Magic.h|  28 +-
 llvm/lib/BinaryFormat/Magic.cpp   |  11 +
 llvm/lib/Object/Binary.cpp|   2 +
 llvm/lib/Object/ObjectFile.cpp|   2 +
 16 files changed, 656 insertions(+), 60 deletions(-)
 create mode 100644 clang/test/Driver/clang-offload-bundler-zlib.c
 create mode 100644 clang/test/Driver/clang-offload-bundler-zstd.c
 create mode 100644 clang/test/Driver/hip-offload-compress-zlib.hip
 create mode 100644 clang/test/Driver/hip-offload-compress-zstd.hip

diff --git a/clang/docs/ClangOffloadBundler.rst 
b/clang/docs/ClangOffloadBundler.rst
index d08bf4b97781fa4..1e21d3e7264d5c3 100644
--- a/clang/docs/ClangOffloadBundler.rst
+++ b/clang/docs/ClangOffloadBundler.rst
@@ -309,3 +309,30 @@ target by comparing bundle ID's. Two bundle ID's are 
considered compatible if:
   * Their offload kind are the same
   * Their target triple are the same
   * Their GPUArch are the same
+
+Compression and Decompression
+=
+
+``clang-offload-bundler`` provides features to compress and decompress the full
+bundle, leveraging inherent redundancies within the bundle entries. Use the
+`-compress` command-line option to enable this compression capability.
+
+The compressed offload bundle begins with a header followed by the compressed 
binary data:
+
+- **Magic Number (4 bytes)**:
+This is a unique identifier to distinguish compressed offload bundles. The 
value is the string 'CCOB' (Compressed Clang Offload Bundle).
+
+- **Version Number (16-bit unsigned int)**:
+This denotes the version of the compressed offload bundle format. The 
current version is `1`.
+
+- **Compression Method (16-bit unsigned int)**:
+This field indicates the compression method used. The value corresponds to 
either `zlib` or `zstd`, represented as a 16-bit unsigned integer cast from the 
LLVM compression enumeration.
+
+- **Uncompressed Binary Size (32-bit unsigned int)**:
+This is the size (in bytes) of the binary data before it was compressed.
+
+- **Hash (64-bit unsigned int)**:
+This is a 64-bit truncated MD5 hash of the uncompressed binary data. It 
serves for verification and caching purposes.
+
+- **Compressed Data**:
+The actual compressed binary data follows the header. Its size can be 
inferred from the total size of the file minus the header size.
diff --git a/clang/include/clang/Driver/OffloadBundler.h 
b/clang/include/clang/Driver/OffloadBundler.h
index 28473c53662de2c..17df31d31071d99 100644
--- a/clang/include/clang/Driver/OffloadBundler.h
+++ b/clang/include/clang/Driver/OffloadBundler.h
@@ -19,6 +19,7 @@
 
 #include "llvm/Support/Error.h"
 #include "llvm/TargetParser/Triple.h"
+#include 
 #include 
 #include 
 
@@ -26,11 +27,15 @@ namespace clang {
 
 class OffloadBundlerConfig {
 public:
+  OffloadBundlerConfig();
+
   bool AllowNoHost = false;
   bool AllowMissingBundles = false;
   bool CheckInputArchive = false;
   bool PrintExternalCommands = false;
   bool HipOpenmpCompatible = false;
+  bool Compress = false;
+  bool Verbose = false;
 
   unsigned BundleAlignment = 1;
   unsigned HostInputIndex = ~0u;
@@ -84,6 +89,38 @@ struct OffloadTargetInfo {
   std::string str() const;
 };
 
+// CompressedOffloadBundle represents the format for the compressed offload
+// bundles.
+//
+// The format is as follows:
+// - Magic Number (4 bytes) - A constant "CCOB".
+// - Version (2 bytes)
+// - 

[clang] [HIP] Support compressing device binary (PR #67162)

2023-10-02 Thread Yaxun Liu via cfe-commits


@@ -1183,6 +1183,10 @@ def fgpu_inline_threshold_EQ : Joined<["-"], 
"fgpu-inline-threshold=">,
 def fgpu_sanitize : Flag<["-"], "fgpu-sanitize">, Group,
   HelpText<"Enable sanitizer for supported offloading devices">;
 def fno_gpu_sanitize : Flag<["-"], "fno-gpu-sanitize">, Group;
+
+def foffload_compress : Flag<["-"], "foffload-compress">,

yxsamliu wrote:

The convention is to introduce a generic option which works for a specific 
offloading language, and the help message indicates which languages are 
supported. It is not feasible to support a feature in all offloading languages 
at once by one developer since a developer is usually only familiar with one 
offloading language. Once a feature is introduced for one offloading language, 
it can be extended or adopted by other offloading languages. This is better 
than each offloading language introducing an individual option for the same 
purpose.

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


[PATCH] D159064: [Modules] Make clang modules for the C standard library headers

2023-10-02 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added inline comments.



Comment at: clang/test/Modules/Inputs/System/usr/include/stdint.h:2
 typedef int my_awesome_nonstandard_integer_type;
+
+/* C99 7.18.1.1 Exact-width integer types.

Bigcheese wrote:
> iana wrote:
> > dexonsmith wrote:
> > > benlangmuir wrote:
> > > > iana wrote:
> > > > > iana wrote:
> > > > > > benlangmuir wrote:
> > > > > > > Why do we need all this code now (I assume this is copied from 
> > > > > > > the real header)?
> > > > > > It's to support the tests I added to Modules/compiler_builtins.m. 
> > > > > > stdatomic.h and inttypes.h rely on stdint.h contents from the C 
> > > > > > library, and on complex.h and inttypes.h and math.h being present. 
> > > > > > I could just test the modules with `-ffreestanding` I think, would 
> > > > > > that be better?
> > > > > (and yes I just copied it from the builtin header)
> > > > I'm not sure what the best approach is here, but this seems heavy for a 
> > > > test.  Do we expect to need to keep this up to date? If so maybe 
> > > > ffreestanding for the specific test cases this affects would be a 
> > > > better tradeoff.  Maybe someone else has a suggestion here
> > > This reflects *most* of the content in `stdint.h`.
> > > 
> > > One idea would be to copy the full header over during the test setup and 
> > > fix it up, either:
> > > - strip out the header/footer or
> > > - `sed -e "s/__STDC_HOSTED__/0/g"`
> > > so that it always provides content (even when not freestanding).
> > IMO it doesn't need to be that sophisticated, the types just have to exist 
> > for stdtomic.h to compile. I could chop all the comments and define 
> > everything to `int` and I think that'd be fine too.
> Looking at stdatomic.h I think this approach would be fine. It just wants the 
> types to exist.
SGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159064

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


[clang-tools-extra] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-10-02 Thread Jocelyn Castellano via cfe-commits

https://github.com/pandaninjas updated 
https://github.com/llvm/llvm-project/pull/66315

>From ead65bfcb70be46788bc9e88c891e7ae7f91b8d7 Mon Sep 17 00:00:00 2001
From: PandaNinjas 
Date: Wed, 13 Sep 2023 17:38:17 -0700
Subject: [PATCH 01/22] [libc++] Prevent calling the projection more than three
 times

---
 libcxx/include/__algorithm/ranges_clamp.h | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 9613f7f37720a6c..ca46675eb4b3041 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -37,9 +37,10 @@ struct __fn {
 _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
  "Bad bounds passed to std::ranges::clamp");
 
-if (std::invoke(__comp, std::invoke(__proj, __value), std::invoke(__proj, 
__low)))
+auto  = std::invoke(__proj, __value);
+if (std::invoke(__comp, projection, std::invoke(__proj, __low)))
   return __low;
-else if (std::invoke(__comp, std::invoke(__proj, __high), 
std::invoke(__proj, __value)))
+else if (std::invoke(__comp, std::invoke(__proj, __high), projection))
   return __high;
 else
   return __value;

>From c18d60870ac342a95a5528396a8e0c7b91717cbb Mon Sep 17 00:00:00 2001
From: PandaNinjas 
Date: Wed, 13 Sep 2023 18:56:44 -0700
Subject: [PATCH 02/22] [libc++] Run clang-format on file

---
 libcxx/include/__algorithm/ranges_clamp.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index ca46675eb4b3041..3469a6419b2270f 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -37,7 +37,7 @@ struct __fn {
 _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
  "Bad bounds passed to std::ranges::clamp");
 
-auto  = std::invoke(__proj, __value);
+auto& projection = std::invoke(__proj, __value);
 if (std::invoke(__comp, projection, std::invoke(__proj, __low)))
   return __low;
 else if (std::invoke(__comp, std::invoke(__proj, __high), projection))

>From b40e791f0e9fedbb19936851e1e71decf00331fa Mon Sep 17 00:00:00 2001
From: Jocelyn Castellano 
Date: Wed, 13 Sep 2023 19:11:20 -0700
Subject: [PATCH 03/22] [libcxx] CamelCase projection and make variable name
 more descriptive

---
 libcxx/include/__algorithm/ranges_clamp.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 3469a6419b2270f..3adb5fa828e1ee5 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -37,7 +37,7 @@ struct __fn {
 _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
  "Bad bounds passed to std::ranges::clamp");
 
-auto& projection = std::invoke(__proj, __value);
+auto& ValueProjection = std::invoke(__proj, __value);
 if (std::invoke(__comp, projection, std::invoke(__proj, __low)))
   return __low;
 else if (std::invoke(__comp, std::invoke(__proj, __high), projection))

>From a8907624defa4cc4f47520a2d93a8bd042816aa2 Mon Sep 17 00:00:00 2001
From: Jocelyn Castellano 
Date: Wed, 13 Sep 2023 19:11:47 -0700
Subject: [PATCH 04/22] [libcxx] properly change variable name

---
 libcxx/include/__algorithm/ranges_clamp.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 3adb5fa828e1ee5..3d7a224b3649a3f 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -38,9 +38,9 @@ struct __fn {
  "Bad bounds passed to std::ranges::clamp");
 
 auto& ValueProjection = std::invoke(__proj, __value);
-if (std::invoke(__comp, projection, std::invoke(__proj, __low)))
+if (std::invoke(__comp, ValueProjection, std::invoke(__proj, __low)))
   return __low;
-else if (std::invoke(__comp, std::invoke(__proj, __high), projection))
+else if (std::invoke(__comp, std::invoke(__proj, __high), ValueProjection))
   return __high;
 else
   return __value;

>From 15d3b2b79fbd61f97b0312e0913cede36b5b202d Mon Sep 17 00:00:00 2001
From: Jocelyn Castellano 
Date: Thu, 14 Sep 2023 10:37:34 -0700
Subject: [PATCH 05/22] Apply suggestions from code review

---
 libcxx/include/__algorithm/ranges_clamp.h | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 3d7a224b3649a3f..a97538e4c0e3f65 

[clang] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-10-02 Thread Jocelyn Castellano via cfe-commits

https://github.com/pandaninjas updated 
https://github.com/llvm/llvm-project/pull/66315

>From ead65bfcb70be46788bc9e88c891e7ae7f91b8d7 Mon Sep 17 00:00:00 2001
From: PandaNinjas 
Date: Wed, 13 Sep 2023 17:38:17 -0700
Subject: [PATCH 01/22] [libc++] Prevent calling the projection more than three
 times

---
 libcxx/include/__algorithm/ranges_clamp.h | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 9613f7f37720a6c..ca46675eb4b3041 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -37,9 +37,10 @@ struct __fn {
 _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
  "Bad bounds passed to std::ranges::clamp");
 
-if (std::invoke(__comp, std::invoke(__proj, __value), std::invoke(__proj, 
__low)))
+auto  = std::invoke(__proj, __value);
+if (std::invoke(__comp, projection, std::invoke(__proj, __low)))
   return __low;
-else if (std::invoke(__comp, std::invoke(__proj, __high), 
std::invoke(__proj, __value)))
+else if (std::invoke(__comp, std::invoke(__proj, __high), projection))
   return __high;
 else
   return __value;

>From c18d60870ac342a95a5528396a8e0c7b91717cbb Mon Sep 17 00:00:00 2001
From: PandaNinjas 
Date: Wed, 13 Sep 2023 18:56:44 -0700
Subject: [PATCH 02/22] [libc++] Run clang-format on file

---
 libcxx/include/__algorithm/ranges_clamp.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index ca46675eb4b3041..3469a6419b2270f 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -37,7 +37,7 @@ struct __fn {
 _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
  "Bad bounds passed to std::ranges::clamp");
 
-auto  = std::invoke(__proj, __value);
+auto& projection = std::invoke(__proj, __value);
 if (std::invoke(__comp, projection, std::invoke(__proj, __low)))
   return __low;
 else if (std::invoke(__comp, std::invoke(__proj, __high), projection))

>From b40e791f0e9fedbb19936851e1e71decf00331fa Mon Sep 17 00:00:00 2001
From: Jocelyn Castellano 
Date: Wed, 13 Sep 2023 19:11:20 -0700
Subject: [PATCH 03/22] [libcxx] CamelCase projection and make variable name
 more descriptive

---
 libcxx/include/__algorithm/ranges_clamp.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 3469a6419b2270f..3adb5fa828e1ee5 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -37,7 +37,7 @@ struct __fn {
 _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
  "Bad bounds passed to std::ranges::clamp");
 
-auto& projection = std::invoke(__proj, __value);
+auto& ValueProjection = std::invoke(__proj, __value);
 if (std::invoke(__comp, projection, std::invoke(__proj, __low)))
   return __low;
 else if (std::invoke(__comp, std::invoke(__proj, __high), projection))

>From a8907624defa4cc4f47520a2d93a8bd042816aa2 Mon Sep 17 00:00:00 2001
From: Jocelyn Castellano 
Date: Wed, 13 Sep 2023 19:11:47 -0700
Subject: [PATCH 04/22] [libcxx] properly change variable name

---
 libcxx/include/__algorithm/ranges_clamp.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 3adb5fa828e1ee5..3d7a224b3649a3f 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -38,9 +38,9 @@ struct __fn {
  "Bad bounds passed to std::ranges::clamp");
 
 auto& ValueProjection = std::invoke(__proj, __value);
-if (std::invoke(__comp, projection, std::invoke(__proj, __low)))
+if (std::invoke(__comp, ValueProjection, std::invoke(__proj, __low)))
   return __low;
-else if (std::invoke(__comp, std::invoke(__proj, __high), projection))
+else if (std::invoke(__comp, std::invoke(__proj, __high), ValueProjection))
   return __high;
 else
   return __value;

>From 15d3b2b79fbd61f97b0312e0913cede36b5b202d Mon Sep 17 00:00:00 2001
From: Jocelyn Castellano 
Date: Thu, 14 Sep 2023 10:37:34 -0700
Subject: [PATCH 05/22] Apply suggestions from code review

---
 libcxx/include/__algorithm/ranges_clamp.h | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 3d7a224b3649a3f..a97538e4c0e3f65 

[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits

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


[PATCH] D159064: [Modules] Make clang modules for the C standard library headers

2023-10-02 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese added a comment.

This change looks good with the stdint.h comments resolved.




Comment at: clang/test/Modules/Inputs/System/usr/include/stdint.h:2
 typedef int my_awesome_nonstandard_integer_type;
+
+/* C99 7.18.1.1 Exact-width integer types.

iana wrote:
> dexonsmith wrote:
> > benlangmuir wrote:
> > > iana wrote:
> > > > iana wrote:
> > > > > benlangmuir wrote:
> > > > > > Why do we need all this code now (I assume this is copied from the 
> > > > > > real header)?
> > > > > It's to support the tests I added to Modules/compiler_builtins.m. 
> > > > > stdatomic.h and inttypes.h rely on stdint.h contents from the C 
> > > > > library, and on complex.h and inttypes.h and math.h being present. I 
> > > > > could just test the modules with `-ffreestanding` I think, would that 
> > > > > be better?
> > > > (and yes I just copied it from the builtin header)
> > > I'm not sure what the best approach is here, but this seems heavy for a 
> > > test.  Do we expect to need to keep this up to date? If so maybe 
> > > ffreestanding for the specific test cases this affects would be a better 
> > > tradeoff.  Maybe someone else has a suggestion here
> > This reflects *most* of the content in `stdint.h`.
> > 
> > One idea would be to copy the full header over during the test setup and 
> > fix it up, either:
> > - strip out the header/footer or
> > - `sed -e "s/__STDC_HOSTED__/0/g"`
> > so that it always provides content (even when not freestanding).
> IMO it doesn't need to be that sophisticated, the types just have to exist 
> for stdtomic.h to compile. I could chop all the comments and define 
> everything to `int` and I think that'd be fine too.
Looking at stdatomic.h I think this approach would be fine. It just wants the 
types to exist.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159064

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


[PATCH] D159436: [clang-tidy] Add support for optional parameters in config.

2023-10-02 Thread Félix-Antoine Constantin via Phabricator via cfe-commits
felix642 updated this revision to Diff 557546.
felix642 added a comment.

Wrong check name


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159436

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp
  clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability/function-size.rst
  clang-tools-extra/test/clang-tidy/checkers/readability/function-size.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
@@ -55,5 +55,12 @@
 // CHECK-CHILD6: Checks: {{.*-llvm-qualified-auto'? *$}}
 // CHECK-CHILD6-NOT: modernize-use-using.IgnoreMacros
 
+// RUN: clang-tidy -dump-config \
+// RUN: --config='{CheckOptions: {readability-function-size.LineThreshold: ""}, \
+// RUN: Checks: readability-function-size}' \
+// RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD7
+// CHECK-CHILD7: readability-function-size.LineThreshold: none
+
+
 // Validate that check options are printed in alphabetical order:
 // RUN: clang-tidy --checks="-*,readability-identifier-naming" --dump-config %S/Inputs/config-files/- -- | grep "readability-identifier-naming\." | sort --check
Index: clang-tools-extra/test/clang-tidy/checkers/readability/function-size.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/function-size.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/function-size.cpp
@@ -8,6 +8,16 @@
 // RUN: readability-function-size.VariableThreshold: 1 \
 // RUN: }}'
 
+
+// RUN: %check_clang_tidy -check-suffixes=OPTIONAL %s readability-function-size %t -- \
+// RUN: -config='{CheckOptions: { \
+// RUN: readability-function-size.StatementThreshold: "-1", \
+// RUN: readability-function-size.BranchThreshold: "5", \
+// RUN: readability-function-size.ParameterThreshold: "none", \
+// RUN: readability-function-size.NestingThreshold: "", \
+// RUN: readability-function-size.VariableThreshold: "" \
+// RUN: }}'
+
 // Bad formatting is intentional, don't run clang-format over the whole file!
 
 void foo1() {
@@ -103,9 +113,11 @@
 // check that nested if's are not reported. this was broken initially
 void nesting_if() { // 1
   // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'nesting_if' exceeds recommended size/complexity
-  // CHECK-MESSAGES: :[[@LINE-2]]:6: note: 23 lines including whitespace and comments (threshold 0)
+  // CHECK-MESSAGES: :[[@LINE-2]]:6: note: 25 lines including whitespace and comments (threshold 0)
   // CHECK-MESSAGES: :[[@LINE-3]]:6: note: 18 statements (threshold 0)
   // CHECK-MESSAGES: :[[@LINE-4]]:6: note: 6 branches (threshold 0)
+  // CHECK-MESSAGES-OPTIONAL: :[[@LINE-5]]:6: warning: function 'nesting_if' exceeds recommended size/complexity
+  // CHECK-MESSAGES-OPTIONAL: :[[@LINE-6]]:6: note: 6 branches (threshold 5)
   if (true) { // 2
  int j;
   } else if (true) { // 2
@@ -123,7 +135,7 @@
   } else if (true) { // 2
  int j;
   }
-  // CHECK-MESSAGES: :[[@LINE-22]]:6: note: 6 variables (threshold 1)
+  // CHECK-MESSAGES: :[[@LINE-24]]:6: note: 6 variables (threshold 1)
 }
 
 // however this should warn
Index: clang-tools-extra/docs/clang-tidy/checks/readability/function-size.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability/function-size.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability/function-size.rst
@@ -12,7 +12,7 @@
 
 .. option:: LineThreshold
 
-   Flag functions exceeding this number of lines. The default is `-1` (ignore
+   Flag functions exceeding this number of lines. The default is `none` (ignore
the number of lines).
 
 .. option:: StatementThreshold
@@ -24,22 +24,22 @@
 .. option:: BranchThreshold
 
Flag functions exceeding this number of control statements. The default is
-   `-1` (ignore the number of branches).
+   `none` (ignore the number of branches).
 
 .. option:: ParameterThreshold
 
Flag functions that exceed a specified number of parameters. The default
-   is `-1` (ignore the number of parameters).
+   is `none` (ignore the number of parameters).
 
 .. option:: NestingThreshold
 
 Flag compound statements which create next nesting level after
 `NestingThreshold`. This may differ significantly from the expected value
-for macro-heavy code. The default is `-1` (ignore the nesting level).
+for macro-heavy code. The default is `none` (ignore the 

[PATCH] D159436: [clang-tidy] Add support for optional parameters in config.

2023-10-02 Thread Félix-Antoine Constantin via Phabricator via cfe-commits
felix642 updated this revision to Diff 557545.
felix642 marked 3 inline comments as done.
felix642 added a comment.

Updated documentation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159436

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.cpp
  clang-tools-extra/clang-tidy/readability/FunctionSizeCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability/function-size.rst
  clang-tools-extra/test/clang-tidy/checkers/readability/function-size.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
@@ -55,5 +55,12 @@
 // CHECK-CHILD6: Checks: {{.*-llvm-qualified-auto'? *$}}
 // CHECK-CHILD6-NOT: modernize-use-using.IgnoreMacros
 
+// RUN: clang-tidy -dump-config \
+// RUN: --config='{CheckOptions: {readability-function-size.LineThreshold: ""}, \
+// RUN: Checks: readability-function-size}' \
+// RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD7
+// CHECK-CHILD7: readability-function-size.LineThreshold: none
+
+
 // Validate that check options are printed in alphabetical order:
 // RUN: clang-tidy --checks="-*,readability-identifier-naming" --dump-config %S/Inputs/config-files/- -- | grep "readability-identifier-naming\." | sort --check
Index: clang-tools-extra/test/clang-tidy/checkers/readability/function-size.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/function-size.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/function-size.cpp
@@ -8,6 +8,16 @@
 // RUN: readability-function-size.VariableThreshold: 1 \
 // RUN: }}'
 
+
+// RUN: %check_clang_tidy -check-suffixes=OPTIONAL %s readability-function-size %t -- \
+// RUN: -config='{CheckOptions: { \
+// RUN: readability-function-size.StatementThreshold: "-1", \
+// RUN: readability-function-size.BranchThreshold: "5", \
+// RUN: readability-function-size.ParameterThreshold: "none", \
+// RUN: readability-function-size.NestingThreshold: "", \
+// RUN: readability-function-size.VariableThreshold: "" \
+// RUN: }}'
+
 // Bad formatting is intentional, don't run clang-format over the whole file!
 
 void foo1() {
@@ -103,9 +113,11 @@
 // check that nested if's are not reported. this was broken initially
 void nesting_if() { // 1
   // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'nesting_if' exceeds recommended size/complexity
-  // CHECK-MESSAGES: :[[@LINE-2]]:6: note: 23 lines including whitespace and comments (threshold 0)
+  // CHECK-MESSAGES: :[[@LINE-2]]:6: note: 25 lines including whitespace and comments (threshold 0)
   // CHECK-MESSAGES: :[[@LINE-3]]:6: note: 18 statements (threshold 0)
   // CHECK-MESSAGES: :[[@LINE-4]]:6: note: 6 branches (threshold 0)
+  // CHECK-MESSAGES-OPTIONAL: :[[@LINE-5]]:6: warning: function 'nesting_if' exceeds recommended size/complexity
+  // CHECK-MESSAGES-OPTIONAL: :[[@LINE-6]]:6: note: 6 branches (threshold 5)
   if (true) { // 2
  int j;
   } else if (true) { // 2
@@ -123,7 +135,7 @@
   } else if (true) { // 2
  int j;
   }
-  // CHECK-MESSAGES: :[[@LINE-22]]:6: note: 6 variables (threshold 1)
+  // CHECK-MESSAGES: :[[@LINE-24]]:6: note: 6 variables (threshold 1)
 }
 
 // however this should warn
Index: clang-tools-extra/docs/clang-tidy/checks/readability/function-size.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability/function-size.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability/function-size.rst
@@ -12,7 +12,7 @@
 
 .. option:: LineThreshold
 
-   Flag functions exceeding this number of lines. The default is `-1` (ignore
+   Flag functions exceeding this number of lines. The default is `none` (ignore
the number of lines).
 
 .. option:: StatementThreshold
@@ -24,22 +24,22 @@
 .. option:: BranchThreshold
 
Flag functions exceeding this number of control statements. The default is
-   `-1` (ignore the number of branches).
+   `none` (ignore the number of branches).
 
 .. option:: ParameterThreshold
 
Flag functions that exceed a specified number of parameters. The default
-   is `-1` (ignore the number of parameters).
+   is `none` (ignore the number of parameters).
 
 .. option:: NestingThreshold
 
 Flag compound statements which create next nesting level after
 `NestingThreshold`. This may differ significantly from the expected value
-for macro-heavy code. The default is `-1` (ignore the nesting level).
+for 

[clang] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-02 Thread via cfe-commits

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

>From c7c9e907d897ae667331761d8097ccb7852c5d93 Mon Sep 17 00:00:00 2001
From: Shraiysh Vaishay 
Date: Mon, 2 Oct 2023 16:43:13 -0500
Subject: [PATCH 1/2] [mlir][OpenMP] Added translation for `omp.teams` to LLVM
 IR

This patch adds translation from `omp.teams` operation to LLVM IR using
OpenMPIRBuilder.

The clauses are not handled in this patch.
---
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  |  21 +++
 mlir/test/Target/LLVMIR/openmp-teams.mlir | 136 ++
 2 files changed, 157 insertions(+)
 create mode 100644 mlir/test/Target/LLVMIR/openmp-teams.mlir

diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 8f7f1963b3e5a4f..b9643be40e13c01 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -661,6 +661,24 @@ convertOmpSingle(omp::SingleOp , 
llvm::IRBuilderBase ,
   return bodyGenStatus;
 }
 
+// Convert an OpenMP Teams construct to LLVM IR using OpenMPIRBuilder
+static LogicalResult convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
, LLVM::ModuleTranslation ) {
+  using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+  LogicalResult bodyGenStatus = success();
+  if(op.getNumTeamsLower() || op.getNumTeamsUpper() || op.getIfExpr() || 
op.getThreadLimit() || !op.getAllocatorsVars().empty() || op.getReductions()) {
+return op.emitError("unhandled clauses for translation to LLVM IR");
+  }
+  auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP){
+LLVM::ModuleTranslation::SaveStack 
frame(moduleTranslation, allocaIP);
+builder.restoreIP(codegenIP);
+convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder, 
moduleTranslation, bodyGenStatus);
+  };
+
+  llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
+  builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(ompLoc, 
bodyCB));
+  return bodyGenStatus;
+}
+
 /// Converts an OpenMP task construct into LLVM IR using OpenMPIRBuilder.
 static LogicalResult
 convertOmpTaskOp(omp::TaskOp taskOp, llvm::IRBuilderBase ,
@@ -2406,6 +2424,9 @@ LogicalResult 
OpenMPDialectLLVMIRTranslationInterface::convertOperation(
   .Case([&](omp::SingleOp op) {
 return convertOmpSingle(op, builder, moduleTranslation);
   })
+  .Case([&](omp::TeamsOp op) {
+return convertOmpTeams(op, builder, moduleTranslation);
+  })
   .Case([&](omp::TaskOp op) {
 return convertOmpTaskOp(op, builder, moduleTranslation);
   })
diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
new file mode 100644
index 000..c9005fca94a7c20
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/openmp-teams.mlir
@@ -0,0 +1,136 @@
+// RUN: mlir-translate -mlir-to-llvmir -split-input-file %s | FileCheck %s
+
+llvm.func @foo()
+
+// CHECK-LABEL: @omp_teams_simple
+// CHECK: call void {{.*}} @__kmpc_fork_teams(ptr @{{.+}}, i32 0, ptr 
[[wrapperfn:.+]])
+// CHECK: ret void
+llvm.func @omp_teams_simple() {
+omp.teams {
+llvm.call @foo() : () -> ()
+omp.terminator
+}
+llvm.return
+}
+
+// CHECK: define internal void @[[outlinedfn:.+]]()
+// CHECK:   call void @foo()
+// CHECK:   ret void
+// CHECK: define void [[wrapperfn]](ptr %[[global_tid:.+]], ptr 
%[[bound_tid:.+]])
+// CHECK:   call void @[[outlinedfn]]
+// CHECK:   ret void
+
+// -
+
+llvm.func @foo(i32) -> ()
+
+// CHECK-LABEL: @omp_teams_shared_simple
+// CHECK-SAME: (i32 [[arg0:%.+]])
+// CHECK: [[structArg:%.+]] = alloca { i32 }
+// CHECK: br
+// CHECK: [[gep:%.+]] = getelementptr { i32 }, ptr [[structArg]], i32 0, i32 0
+// CHECK: store i32 [[arg0]], ptr [[gep]]
+// CHECK: call void {{.+}} @__kmpc_fork_teams(ptr @{{.+}}, i32 1, ptr 
[[wrapperfn:.+]], ptr [[structArg]])
+// CHECK: ret void
+llvm.func @omp_teams_shared_simple(%arg0: i32) {
+omp.teams {
+llvm.call @foo(%arg0) : (i32) -> ()
+omp.terminator
+}
+llvm.return
+}
+
+// CHECK: define internal void [[outlinedfn:@.+]](ptr [[structArg:%.+]])
+// CHECK:   [[gep:%.+]] = getelementptr { i32 }, ptr [[structArg]], i32 0, i32 0
+// CHECK:   [[loadgep:%.+]] = load i32, ptr [[gep]]
+// CHECK:   call void @foo(i32 [[loadgep]])
+// CHECK:   ret void
+// CHECK: define void [[wrapperfn]](ptr [[global_tid:.+]], ptr 
[[bound_tid:.+]], ptr [[structArg:.+]])
+// CHECK:   call void [[outlinedfn]](ptr [[structArg]])
+// CHECK:   ret void
+
+// -
+
+llvm.func @my_alloca_fn() -> !llvm.ptr
+llvm.func @foo(i32, f32, !llvm.ptr, f128, !llvm.ptr, i32) -> ()
+llvm.func @bar()
+
+// CHECK-LABEL: @omp_teams_branching_shared
+// CHECK-SAME: (i1 [[condition:%.+]], i32 [[arg0:%.+]], float [[arg1:%.+]], 
ptr [[arg2:%.+]], fp128 [[arg3:%.+]])
+
+// Checking that the allocation for struct argument 

[clang] Add a release note for https://github.com/llvm/llvm-project/pull/68001 (PR #68061)

2023-10-02 Thread Akira Hatanaka via cfe-commits

https://github.com/ahatanak created 
https://github.com/llvm/llvm-project/pull/68061

None

>From bc5093e4942b3ac3d538eb1253515e4b7c562a4a Mon Sep 17 00:00:00 2001
From: Akira Hatanaka 
Date: Mon, 2 Oct 2023 18:43:26 -0700
Subject: [PATCH] Add a release note for
 https://github.com/llvm/llvm-project/pull/68001

---
 clang/docs/ReleaseNotes.rst | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6be824771c583be..f5825e15c76f1da 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -410,6 +410,8 @@ Miscellaneous Clang Crashes Fixed
   `Issue 64065 `_
 - Fixed a crash when check array access on zero-length element.
   `Issue 64564 `_
+- Fixed a crash when an ObjC ivar has an invalid type. See
+  (`#68001 `_)
 
 Target Specific Changes
 ---

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


[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits


@@ -923,6 +923,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
 
   ModulePassManager MPM;
+  // Add a verifier pass, before any other passes, to catch CodeGen issues.
+  MPM.addPass(VerifierPass());

mizvekov wrote:

There is actually just an option to disable it, it's otherwise on by default.
See this post for more details: 
https://discourse.llvm.org/t/rfc-running-llvm-verifier-right-out-of-codegen/73823/4

I have changed the current MR to also add the new pass under the same flag, as 
it's useful to allow folks to disable it, but it's otherwise going to be on for 
the majority of cases.

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


[clang] [clang][codegen] Add a verifier IR pass before any further passes. (PR #68015)

2023-10-02 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/68015

>From be5fab19a147c979c7e8afb421d157b194f4a125 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 2 Oct 2023 13:52:35 +0200
Subject: [PATCH] [clang][codegen] Add a verifier IR pass before any further
 passes.

This helps check clang generated good IR in the first place,
as otherwise this can cause UB in subsequent passes,
with the final verification pass not catching any issues.

This for example would have helped catch
https://github.com/llvm/llvm-project/issues/67937 earlier.
---
 clang/lib/CodeGen/BackendUtil.cpp   | 17 +++--
 clang/test/CodeGen/code-coverage.c  |  4 ++--
 clang/test/CodeGen/lto-newpm-pipeline.c | 10 ++
 3 files changed, 19 insertions(+), 12 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index b0fe8e03aa0f5f0..d066819871dfde3 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -923,6 +923,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
 
   ModulePassManager MPM;
+  // Add a verifier pass, before any other passes, to catch CodeGen issues.
+  if (CodeGenOpts.VerifyModule)
+MPM.addPass(VerifierPass());
 
   if (!CodeGenOpts.DisableLLVMPasses) {
 // Map our optimization levels into one of the distinct levels used to
@@ -1020,21 +1023,23 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 }
 
 if (CodeGenOpts.FatLTO) {
-  MPM = PB.buildFatLTODefaultPipeline(Level, PrepareForThinLTO,
-  PrepareForThinLTO ||
-  shouldEmitRegularLTOSummary());
+  MPM.addPass(PB.buildFatLTODefaultPipeline(
+  Level, PrepareForThinLTO,
+  PrepareForThinLTO || shouldEmitRegularLTOSummary()));
 } else if (PrepareForThinLTO) {
-  MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
+  MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
 } else if (PrepareForLTO) {
-  MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
+  MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
 } else {
-  MPM = PB.buildPerModuleDefaultPipeline(Level);
+  MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
 }
   }
 
   // Add a verifier pass if requested. We don't have to do this if the action
   // requires code generation because there will already be a verifier pass in
   // the code-generation pipeline.
+  // Since we already added a verifier pass above, this
+  // might even not run the analysis, if previous passes caused no changes.
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
diff --git a/clang/test/CodeGen/code-coverage.c 
b/clang/test/CodeGen/code-coverage.c
index af02a6ddaef990a..d7994bab35d81a0 100644
--- a/clang/test/CodeGen/code-coverage.c
+++ b/clang/test/CodeGen/code-coverage.c
@@ -15,10 +15,10 @@
 // RUN: %clang_cc1 -emit-llvm-bc -o /dev/null -fdebug-pass-manager 
-coverage-data-file=/dev/null %s 2>&1 | FileCheck --check-prefix=NEWPM %s
 // RUN: %clang_cc1 -emit-llvm-bc -o /dev/null -fdebug-pass-manager 
-coverage-data-file=/dev/null -O3 %s 2>&1 | FileCheck --check-prefix=NEWPM-O3 %s
 
-// NEWPM-NOT: Running pass
+// NEWPM: Running pass: VerifierPass
 // NEWPM: Running pass: GCOVProfilerPass
 
-// NEWPM-O3-NOT: Running pass
+// NEWPM-O3: Running pass: VerifierPass
 // NEWPM-O3: Running pass: Annotation2MetadataPass
 // NEWPM-O3: Running pass: ForceFunctionAttrsPass
 // NEWPM-O3: Running pass: GCOVProfilerPass
diff --git a/clang/test/CodeGen/lto-newpm-pipeline.c 
b/clang/test/CodeGen/lto-newpm-pipeline.c
index 1aaa7d46f3ff06f..f58757efbf686f2 100644
--- a/clang/test/CodeGen/lto-newpm-pipeline.c
+++ b/clang/test/CodeGen/lto-newpm-pipeline.c
@@ -25,7 +25,9 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm-bc -o /dev/null 
-mllvm -verify-analysis-invalidation=0 -fdebug-pass-manager -flto=thin -Oz %s 
2>&1 | FileCheck %s \
 // RUN:   -check-prefix=CHECK-THIN-OPTIMIZED
 
-// CHECK-FULL-O0: Running pass: AlwaysInlinerPass
+// CHECK-FULL-O0: Running pass: VerifierPass
+// CHECK-FULL-O0-NEXT: Running analysis: VerifierAnalysis
+// CHECK-FULL-O0-NEXT: Running pass: AlwaysInlinerPass
 // CHECK-FULL-O0-NEXT: Running analysis: InnerAnalysisManagerProxy
 // CHECK-FULL-O0-NEXT: Running analysis: ProfileSummaryAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: CoroConditionalWrapper
@@ -34,10 +36,11 @@
 // CHECK-FULL-O0-NEXT: Running pass: AnnotationRemarksPass
 // CHECK-FULL-O0-NEXT: Running analysis: TargetLibraryAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: VerifierPass
-// CHECK-FULL-O0-NEXT: Running analysis: VerifierAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: BitcodeWriterPass
 
-// CHECK-THIN-O0: Running pass: AlwaysInlinerPass
+// CHECK-THIN-O0: Running pass: VerifierPass
+// CHECK-THIN-O0-NEXT: Running analysis: 

[clang] e897014 - [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (#67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2023-10-03T03:23:34+02:00
New Revision: e8970141ec4326acb139789db01fb7c51538a4be

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

LOG: [NFC][Clang][CodeGen] Improve performance for vtable metadata generation 
(#67066)

Mangle each AddressPoint once, instead of once per comparison.

Added: 


Modified: 
clang/lib/CodeGen/CGVTables.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index d782da2103b4c79..c81b67ecf4fee0d 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -24,6 +24,7 @@
 #include "llvm/Transforms/Utils/Cloning.h"
 #include 
 #include 
+#include 
 
 using namespace clang;
 using namespace CodeGen;
@@ -1308,44 +1309,34 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
 
   CharUnits ComponentWidth = GetTargetTypeStoreSize(getVTableComponentType());
 
-  typedef std::pair AddressPoint;
+  struct AddressPoint {
+const CXXRecordDecl *Base;
+size_t Offset;
+std::string TypeName;
+bool operator<(const AddressPoint ) const {
+  int D = TypeName.compare(RHS.TypeName);
+  return D < 0 || (D == 0 && Offset < RHS.Offset);
+}
+  };
   std::vector AddressPoints;
-  for (auto & : VTLayout.getAddressPoints())
-AddressPoints.push_back(std::make_pair(
-AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
-AP.second.AddressPointIndex));
-
-  // Sort the address points for determinism.
-  // FIXME: It's more efficient to mangle the types before sorting.
-  llvm::sort(AddressPoints, [this](const AddressPoint ,
-   const AddressPoint ) {
-if ( == )
-  return false;
-
-std::string S1;
-llvm::raw_string_ostream O1(S1);
-getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(AP1.first->getTypeForDecl(), 0), O1);
-O1.flush();
-
-std::string S2;
-llvm::raw_string_ostream O2(S2);
+  for (auto & : VTLayout.getAddressPoints()) {
+AddressPoint N{AP.first.getBase(),
+   VTLayout.getVTableOffset(AP.second.VTableIndex) +
+   AP.second.AddressPointIndex,
+   {}};
+llvm::raw_string_ostream Stream(N.TypeName);
 getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(AP2.first->getTypeForDecl(), 0), O2);
-O2.flush();
-
-if (S1 < S2)
-  return true;
-if (S1 != S2)
-  return false;
+QualType(N.Base->getTypeForDecl(), 0), Stream);
+AddressPoints.push_back(std::move(N));
+  }
 
-return AP1.second < AP2.second;
-  });
+  // Sort the address points for determinism.
+  llvm::sort(AddressPoints);
 
   ArrayRef Comps = VTLayout.vtable_components();
   for (auto AP : AddressPoints) {
 // Create type metadata for the address point.
-AddVTableTypeMetadata(VTable, ComponentWidth * AP.second, AP.first);
+AddVTableTypeMetadata(VTable, ComponentWidth * AP.Offset, AP.Base);
 
 // The class associated with each address point could also potentially be
 // used for indirect calls via a member function pointer, so we need to
@@ -1357,7 +1348,7 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
   llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
   Context.getMemberPointerType(
   Comps[I].getFunctionDecl()->getType(),
-  Context.getRecordType(AP.first).getTypePtr()));
+  Context.getRecordType(AP.Base).getTypePtr()));
   VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
 }
   }



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


[clang] Mark an ObjCIvarDecl as invalid if its type contains errors (PR #68001)

2023-10-02 Thread Akira Hatanaka via cfe-commits

ahatanak wrote:

The commit fixed an assertion that was failing in SemaInit.cpp. 

Assertion failed: (Kind.getKind() == InitializationKind::IK_Copy || 
Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList), 
function Perform, file SemaInit.cpp, line 8607.

The assertion in `InitializationSequence::Perform` was failing because an ivar 
that had an invalid type wasn't marked as invalid (`ivar0[Count]` in the test 
case). `Sema::SetIvarInitializers`, which calls 
`InitializationSequence::Perform` to initialize ivars, should have skipped the 
invalid ivar, but it wasn't because the ivar wasn't marked as invalid.

There's no github issue for this fix.

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


[clang] [diag] Silence `-Wfixed-enum-extension` in C23 (PR #68060)

2023-10-02 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

The C23 standard supports enums with fixed underlying types (N3030 [1]),
so we shouldn't emit `-Wfixed-enum-extension` in C23 mode (since it's no
longer a Clang extension at that point).

[1] 
https://thephd.dev/_vendor/future_cxx/papers/C%20-%20Enhanced%20Enumerations.html


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


2 Files Affected:

- (modified) clang/lib/Parse/ParseDecl.cpp (+1-1) 
- (modified) clang/test/Sema/fixed-enum.c (+8-4) 


``diff
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index a1491596ef6145c..735da4aafae1ca5 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -5019,7 +5019,7 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, 
DeclSpec ,
 else if (getLangOpts().MicrosoftExt)
   Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
   << BaseRange;
-else
+else if (!getLangOpts().C23)
   Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
   << BaseRange;
   }
diff --git a/clang/test/Sema/fixed-enum.c b/clang/test/Sema/fixed-enum.c
index c77f5b0cbe79c5b..73a3fd2b09114c0 100644
--- a/clang/test/Sema/fixed-enum.c
+++ b/clang/test/Sema/fixed-enum.c
@@ -4,13 +4,17 @@
 // RUN: %clang_cc1 -Weverything -std=c11 -xc -DC11 -verify %s
 // RUN: %clang_cc1 -pedantic-std=c11 -xc -DC11 -verify %s
 // RUN: %clang_cc1 -Weverything -std=c11 -xc -fms-extensions -DMS -verify %s
+// RUN: %clang_cc1 -Weverything -std=c2x -xc -DC23 -verify %s
+// RUN: %clang_cc1 -pedantic-std=c2x -xc -DC23 -verify %s
+// RUN: %clang_cc1 -Weverything -std=c23 -xc -DC23 -verify %s
+// RUN: %clang_cc1 -pedantic-std=c23 -xc -DC23 -verify %s
 
 enum X : int {e};
 #if defined(CXX11)
 // expected-warning@-2{{enumeration types with a fixed underlying type are 
incompatible with C++98}}
 #elif defined(CXX03)
 // expected-warning@-4{{enumeration types with a fixed underlying type are a 
C++11 extension}}
-#elif defined(OBJC)
+#elif defined(OBJC) || defined(C23)
 // No diagnostic
 #elif defined(C11)
 // expected-warning@-8{{enumeration types with a fixed underlying type are a 
Clang extension}}
@@ -21,19 +25,19 @@ enum X : int {e};
 // Don't warn about the forward declaration in any language mode.
 enum Fwd : int;
 enum Fwd : int { e2 };
-#ifndef OBJC
+#if !defined(OBJC) && !defined(C23)
 // expected-warning@-3 {{enumeration types with a fixed underlying type}}
 // expected-warning@-3 {{enumeration types with a fixed underlying type}}
 #endif
 
 // Always error on the incompatible redeclaration.
 enum BadFwd : int;
-#ifndef OBJC
+#if !defined(OBJC) && !defined(C23)
 // expected-warning@-2 {{enumeration types with a fixed underlying type}}
 #endif
 // expected-note@-4 {{previous declaration is here}}
 enum BadFwd : char { e3 };
-#ifndef OBJC
+#if !defined(OBJC) && !defined(C23)
 // expected-warning@-2 {{enumeration types with a fixed underlying type}}
 #endif
 // expected-error@-4 {{enumeration redeclared with different underlying type 
'char' (was 'int')}}

``




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


[clang] [diag] Silence `-Wfixed-enum-extension` in C23 (PR #68060)

2023-10-02 Thread Shoaib Meenai via cfe-commits

https://github.com/smeenai created 
https://github.com/llvm/llvm-project/pull/68060

The C23 standard supports enums with fixed underlying types (N3030 [1]),
so we shouldn't emit `-Wfixed-enum-extension` in C23 mode (since it's no
longer a Clang extension at that point).

[1] 
https://thephd.dev/_vendor/future_cxx/papers/C%20-%20Enhanced%20Enumerations.html


>From b931e047168d2312f05c0fbf2813915cc4e06ae8 Mon Sep 17 00:00:00 2001
From: Shoaib Meenai 
Date: Mon, 2 Oct 2023 17:50:36 -0700
Subject: [PATCH] [diag] Silence `-Wfixed-enum-extension` in C23

The C23 standard supports enums with fixed underlying types (N3030 [1]),
so we shouldn't emit `-Wfixed-enum-extension` in C23 mode (since it's no
longer a Clang extension at that point).

[1] 
https://thephd.dev/_vendor/future_cxx/papers/C%20-%20Enhanced%20Enumerations.html
---
 clang/lib/Parse/ParseDecl.cpp |  2 +-
 clang/test/Sema/fixed-enum.c  | 12 
 2 files changed, 9 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index a1491596ef6145c..735da4aafae1ca5 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -5019,7 +5019,7 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, 
DeclSpec ,
 else if (getLangOpts().MicrosoftExt)
   Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
   << BaseRange;
-else
+else if (!getLangOpts().C23)
   Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
   << BaseRange;
   }
diff --git a/clang/test/Sema/fixed-enum.c b/clang/test/Sema/fixed-enum.c
index c77f5b0cbe79c5b..73a3fd2b09114c0 100644
--- a/clang/test/Sema/fixed-enum.c
+++ b/clang/test/Sema/fixed-enum.c
@@ -4,13 +4,17 @@
 // RUN: %clang_cc1 -Weverything -std=c11 -xc -DC11 -verify %s
 // RUN: %clang_cc1 -pedantic-std=c11 -xc -DC11 -verify %s
 // RUN: %clang_cc1 -Weverything -std=c11 -xc -fms-extensions -DMS -verify %s
+// RUN: %clang_cc1 -Weverything -std=c2x -xc -DC23 -verify %s
+// RUN: %clang_cc1 -pedantic-std=c2x -xc -DC23 -verify %s
+// RUN: %clang_cc1 -Weverything -std=c23 -xc -DC23 -verify %s
+// RUN: %clang_cc1 -pedantic-std=c23 -xc -DC23 -verify %s
 
 enum X : int {e};
 #if defined(CXX11)
 // expected-warning@-2{{enumeration types with a fixed underlying type are 
incompatible with C++98}}
 #elif defined(CXX03)
 // expected-warning@-4{{enumeration types with a fixed underlying type are a 
C++11 extension}}
-#elif defined(OBJC)
+#elif defined(OBJC) || defined(C23)
 // No diagnostic
 #elif defined(C11)
 // expected-warning@-8{{enumeration types with a fixed underlying type are a 
Clang extension}}
@@ -21,19 +25,19 @@ enum X : int {e};
 // Don't warn about the forward declaration in any language mode.
 enum Fwd : int;
 enum Fwd : int { e2 };
-#ifndef OBJC
+#if !defined(OBJC) && !defined(C23)
 // expected-warning@-3 {{enumeration types with a fixed underlying type}}
 // expected-warning@-3 {{enumeration types with a fixed underlying type}}
 #endif
 
 // Always error on the incompatible redeclaration.
 enum BadFwd : int;
-#ifndef OBJC
+#if !defined(OBJC) && !defined(C23)
 // expected-warning@-2 {{enumeration types with a fixed underlying type}}
 #endif
 // expected-note@-4 {{previous declaration is here}}
 enum BadFwd : char { e3 };
-#ifndef OBJC
+#if !defined(OBJC) && !defined(C23)
 // expected-warning@-2 {{enumeration types with a fixed underlying type}}
 #endif
 // expected-error@-4 {{enumeration redeclared with different underlying type 
'char' (was 'int')}}

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


[clang] [HIP] Support compressing device binary (PR #67162)

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


@@ -1183,6 +1183,10 @@ def fgpu_inline_threshold_EQ : Joined<["-"], 
"fgpu-inline-threshold=">,
 def fgpu_sanitize : Flag<["-"], "fgpu-sanitize">, Group,
   HelpText<"Enable sanitizer for supported offloading devices">;
 def fno_gpu_sanitize : Flag<["-"], "fno-gpu-sanitize">, Group;
+
+def foffload_compress : Flag<["-"], "foffload-compress">,

jdoerfert wrote:

General comment: can we make sure --offload is not language specific.
The hip in the title makes me worry.

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


[clang] [HIP] Support compressing device binary (PR #67162)

2023-10-02 Thread Yaxun Liu via cfe-commits


@@ -881,6 +900,184 @@ CreateFileHandler(MemoryBuffer ,
"'" + FilesType + "': invalid file type specified");
 }
 
+OffloadBundlerConfig::OffloadBundlerConfig() {
+  auto IgnoreEnvVarOpt =
+  llvm::sys::Process::GetEnv("OFFLOAD_BUNDLER_IGNORE_ENV_VAR");
+  if (IgnoreEnvVarOpt.has_value() && IgnoreEnvVarOpt.value() == "1")
+return;
+
+  auto VerboseEnvVarOpt = 
llvm::sys::Process::GetEnv("OFFLOAD_BUNDLER_VERBOSE");
+  if (VerboseEnvVarOpt.has_value())
+Verbose = VerboseEnvVarOpt.value() == "1";
+
+  auto CompressEnvVarOpt =
+  llvm::sys::Process::GetEnv("OFFLOAD_BUNDLER_COMPRESS");
+  if (CompressEnvVarOpt.has_value())
+Compress = CompressEnvVarOpt.value() == "1";
+}
+
+llvm::Expected>
+CompressedOffloadBundle::compress(const llvm::MemoryBuffer ,
+  bool Verbose) {
+  llvm::Timer HashTimer("Hash Calculation Timer", "Hash calculation time",
+ClangOffloadBundlerTimerGroup);
+  if (Verbose)
+HashTimer.startTimer();
+  llvm::MD5 Hash;
+  llvm::MD5::MD5Result Result;
+  Hash.update(Input.getBuffer());
+  Hash.final(Result);
+  uint64_t TruncatedHash = Result.low();
+  if (Verbose)
+HashTimer.stopTimer();
+
+  SmallVector CompressedBuffer;
+  auto BufferUint8 = llvm::ArrayRef(
+  reinterpret_cast(Input.getBuffer().data()),
+  Input.getBuffer().size());
+
+  llvm::compression::Format CompressionFormat;
+
+  if (llvm::compression::zstd::isAvailable())
+CompressionFormat = llvm::compression::Format::Zstd;
+  else if (llvm::compression::zlib::isAvailable())
+CompressionFormat = llvm::compression::Format::Zlib;
+  else
+return createStringError(llvm::inconvertibleErrorCode(),
+ "Compression not supported");
+
+  llvm::Timer CompressTimer("Compression Timer", "Compression time",
+ClangOffloadBundlerTimerGroup);
+  if (Verbose)
+CompressTimer.startTimer();
+  llvm::compression::compress(CompressionFormat, BufferUint8, 
CompressedBuffer);
+  if (Verbose)
+CompressTimer.stopTimer();
+
+  uint16_t CompressionMethod = static_cast(CompressionFormat);
+  uint32_t UncompressedSize = Input.getBuffer().size();
+
+  SmallVector FinalBuffer;

yxsamliu wrote:

Yes. fixed

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


[clang] [HIP] Support compressing device binary (PR #67162)

2023-10-02 Thread Yaxun Liu via cfe-commits

https://github.com/yxsamliu updated 
https://github.com/llvm/llvm-project/pull/67162

>From b4b44809dcbc487239b4430751a232563c5ac590 Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Thu, 21 Sep 2023 13:52:16 -0400
Subject: [PATCH] [HIP] Support compressing device binary

Add option -f[no-]offload-compress to clang to enable/disable
compression of device binary for HIP. By default it is disabled.

Add option -compress to clang-offload-bundler to enable
compression of offload bundle. By default it is disabled.

When enabled, zstd or zlib is used for compression when
available.

When disabled, it is NFC compared to previous behavior. The
same offload bundle format is used as before.

Clang-offload-bundler automatically detects whether the
input file to be unbundled is compressed and the compression
method and decompress if necessary.
---
 clang/docs/ClangOffloadBundler.rst|  27 ++
 clang/include/clang/Driver/OffloadBundler.h   |  37 ++
 clang/include/clang/Driver/Options.td |   4 +
 clang/lib/Driver/OffloadBundler.cpp   | 340 +++---
 clang/lib/Driver/ToolChains/Clang.cpp |   7 +
 clang/lib/Driver/ToolChains/HIPUtility.cpp|   6 +
 .../test/Driver/clang-offload-bundler-zlib.c  |  75 
 .../test/Driver/clang-offload-bundler-zstd.c  |  72 
 .../test/Driver/hip-offload-compress-zlib.hip |  47 +++
 .../test/Driver/hip-offload-compress-zstd.hip |  47 +++
 .../clang-offload-bundler/CMakeLists.txt  |   1 +
 .../ClangOffloadBundler.cpp   |  10 +
 llvm/include/llvm/BinaryFormat/Magic.h|  28 +-
 llvm/lib/BinaryFormat/Magic.cpp   |  11 +
 llvm/lib/Object/Binary.cpp|   2 +
 15 files changed, 654 insertions(+), 60 deletions(-)
 create mode 100644 clang/test/Driver/clang-offload-bundler-zlib.c
 create mode 100644 clang/test/Driver/clang-offload-bundler-zstd.c
 create mode 100644 clang/test/Driver/hip-offload-compress-zlib.hip
 create mode 100644 clang/test/Driver/hip-offload-compress-zstd.hip

diff --git a/clang/docs/ClangOffloadBundler.rst 
b/clang/docs/ClangOffloadBundler.rst
index d08bf4b97781fa4..1e21d3e7264d5c3 100644
--- a/clang/docs/ClangOffloadBundler.rst
+++ b/clang/docs/ClangOffloadBundler.rst
@@ -309,3 +309,30 @@ target by comparing bundle ID's. Two bundle ID's are 
considered compatible if:
   * Their offload kind are the same
   * Their target triple are the same
   * Their GPUArch are the same
+
+Compression and Decompression
+=
+
+``clang-offload-bundler`` provides features to compress and decompress the full
+bundle, leveraging inherent redundancies within the bundle entries. Use the
+`-compress` command-line option to enable this compression capability.
+
+The compressed offload bundle begins with a header followed by the compressed 
binary data:
+
+- **Magic Number (4 bytes)**:
+This is a unique identifier to distinguish compressed offload bundles. The 
value is the string 'CCOB' (Compressed Clang Offload Bundle).
+
+- **Version Number (16-bit unsigned int)**:
+This denotes the version of the compressed offload bundle format. The 
current version is `1`.
+
+- **Compression Method (16-bit unsigned int)**:
+This field indicates the compression method used. The value corresponds to 
either `zlib` or `zstd`, represented as a 16-bit unsigned integer cast from the 
LLVM compression enumeration.
+
+- **Uncompressed Binary Size (32-bit unsigned int)**:
+This is the size (in bytes) of the binary data before it was compressed.
+
+- **Hash (64-bit unsigned int)**:
+This is a 64-bit truncated MD5 hash of the uncompressed binary data. It 
serves for verification and caching purposes.
+
+- **Compressed Data**:
+The actual compressed binary data follows the header. Its size can be 
inferred from the total size of the file minus the header size.
diff --git a/clang/include/clang/Driver/OffloadBundler.h 
b/clang/include/clang/Driver/OffloadBundler.h
index 28473c53662de2c..17df31d31071d99 100644
--- a/clang/include/clang/Driver/OffloadBundler.h
+++ b/clang/include/clang/Driver/OffloadBundler.h
@@ -19,6 +19,7 @@
 
 #include "llvm/Support/Error.h"
 #include "llvm/TargetParser/Triple.h"
+#include 
 #include 
 #include 
 
@@ -26,11 +27,15 @@ namespace clang {
 
 class OffloadBundlerConfig {
 public:
+  OffloadBundlerConfig();
+
   bool AllowNoHost = false;
   bool AllowMissingBundles = false;
   bool CheckInputArchive = false;
   bool PrintExternalCommands = false;
   bool HipOpenmpCompatible = false;
+  bool Compress = false;
+  bool Verbose = false;
 
   unsigned BundleAlignment = 1;
   unsigned HostInputIndex = ~0u;
@@ -84,6 +89,38 @@ struct OffloadTargetInfo {
   std::string str() const;
 };
 
+// CompressedOffloadBundle represents the format for the compressed offload
+// bundles.
+//
+// The format is as follows:
+// - Magic Number (4 bytes) - A constant "CCOB".
+// - Version (2 bytes)
+// - Compression Method (2 bytes) - Uses the values from
+// 

[clang] [Clang][OpenMP][OMPIRBuilder] Move Clang's OpenMP Member/MemberOf flag helpers into the OMPIRBuilder (PR #67844)

2023-10-02 Thread via cfe-commits

shraiysh wrote:

> I'll see what I can do about adding an OpenMPIRBuilderTest.cpp to the patch.

I think it’s okay if it’s tested by clang tests (as Johannes mentioned). In 
case you decide to add tests for this, there is already an 
OpenMPIRBuilderTest.cpp in `llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp`. 
You can add one there if you’d like to. 

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


[clang] [lld][ELF] Warn instead of error when linker script fails to find section (PR #68058)

2023-10-02 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 149346286801a5f32d254676760a7f4211801667 
4dc3e74efa5dae42c2ffa408ef5d4a83c4b4754c -- lld/ELF/LinkerScript.cpp
``





View the diff from clang-format here.


``diff
diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp
index 84658751b304..b1633471b651 100644
--- a/lld/ELF/LinkerScript.cpp
+++ b/lld/ELF/LinkerScript.cpp
@@ -328,7 +328,7 @@ void LinkerScript::processInsertCommands() {
 });
 if (insertPos == sectionCommands.end()) {
   warn("unable to insert " + cmd.names[0] +
-(cmd.isAfter ? " after " : " before ") + cmd.where);
+   (cmd.isAfter ? " after " : " before ") + cmd.where);
 } else {
   if (cmd.isAfter)
 ++insertPos;

``




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


[clang] [analyzer] Fix false negative when accessing a nonnull property from … (PR #67563)

2023-10-02 Thread via cfe-commits

tripleCC wrote:

> Looks good, thanks! I think a comment about how the types in the AST already 
> has the nullability propagated correctly might be helpful for the future 
> readers, otherwise it looks good to me!
Thanks for reviewing, I added a comment for nullability propagated now. 


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


[clang] [clang] Ignore GCC 11 `[[malloc(x)]]` attribute (PR #68059)

2023-10-02 Thread Alois Klink via cfe-commits

https://github.com/aloisklink created 
https://github.com/llvm/llvm-project/pull/68059

Ignore the `[[malloc(x)]]` or `[[malloc(x, 1)]]` function attribute syntax 
added in [GCC 11][1].

Unlike `[[malloc]]` with no arguments (which is supported by Clang), GCC uses 
the one or two argument form to specify a deallocator for GCC's static analyzer.

Code currently compiled with `[[malloc(x)]]` or `__attribute__((malloc(x)))` 
fails with the following error: `'malloc' attribute takes no arguments`.

[1]: 
https://gcc.gnu.org/git/?p=gcc.git;a=commitdiff;f=gcc/doc/extend.texi;h=dce6c58db87ebf7f4477bd3126228e73e497#patch6

Fixes: https://github.com/llvm/llvm-project/issues/51607
Partial-Bug: https://github.com/llvm/llvm-project/issues/53152 (this PR only 
ignores `__attribute__((malloc(x)))` and allows it to compile, so only 
partially fixes the problem).

---

In the future, we can add this attribute to the AST as well. This will let us 
improve the clang static analyzer's 
[`unix.MismatchedDeallocator`](https://clang.llvm.org/docs/analyzer/checkers.html#id93)
 checker.

>From f9c914729a5f5ac7f8b61ea2d39509ff0236a228 Mon Sep 17 00:00:00 2001
From: Alois Klink 
Date: Mon, 2 Oct 2023 19:59:06 +0100
Subject: [PATCH] [clang] Ignore GCC 11 [[malloc(x)]] attribute

Ignore the `[[malloc(x)]]` or `[[malloc(x, 1)]]` function attribute
syntax added in [GCC 11][1].

Unlike `[[malloc]]` with no arguments (which is supported by Clang),
GCC uses the one or two argument form to specify a deallocator for
GCC's static analyzer.

Code currently compiled with `[[malloc(x)]]` or
`__attribute((malloc(x)))` fails with the following error:
`'malloc' attribute takes no arguments`.

[1]: 
https://gcc.gnu.org/git/?p=gcc.git;a=commitdiff;f=gcc/doc/extend.texi;h=dce6c58db87ebf7f4477bd3126228e73e497#patch6

Fixes: https://github.com/llvm/llvm-project/issues/51607
Partial-Bug: https://github.com/llvm/llvm-project/issues/53152
---
 clang/include/clang/Basic/Attr.td |  2 ++
 clang/include/clang/Basic/AttrDocs.td |  3 +++
 clang/lib/Sema/SemaDeclAttr.cpp   | 19 ---
 clang/test/Sema/attr-args.c   |  5 +++--
 clang/test/SemaCXX/attr-print.cpp |  8 
 5 files changed, 32 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 7a6ec77ae84b15a..db1f332efdb7653 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1629,6 +1629,8 @@ def IFunc : Attr, TargetSpecificAttr {
 
 def Restrict : InheritableAttr {
   let Spellings = [Declspec<"restrict">, GCC<"malloc">];
+  let Args = [IdentifierArgument<"Deallocator", /*opt*/ 1>,
+  ParamIdxArgument<"DeallocatorPtrArgIndex", /*opt*/ 1>];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [RestrictDocs];
 }
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 8d928dcc146b254..1e498aeea6b7832 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4122,6 +4122,9 @@ def RestrictDocs : Documentation {
 The ``malloc`` attribute indicates that the function acts like a system memory
 allocation function, returning a pointer to allocated storage disjoint from the
 storage for any other object accessible to the caller.
+
+The form of ``malloc`` with one or two arguments (supported by GCC 11) is
+currently ignored by Clang.
   }];
 }
 
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index ed0b4d29b056397..fcc63cc27c1b537 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2064,13 +2064,26 @@ static void handleTLSModelAttr(Sema , Decl *D, const 
ParsedAttr ) {
 
 static void handleRestrictAttr(Sema , Decl *D, const ParsedAttr ) {
   QualType ResultType = getFunctionOrMethodResultType(D);
-  if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
+  if (!ResultType->isAnyPointerType() && !ResultType->isBlockPointerType()) {
+S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
+<< AL << getFunctionOrMethodResultSourceRange(D);
+return;
+  }
+
+  if (getNumAttributeArgs(AL) == 0) {
 D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
 return;
   }
 
-  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
-  << AL << getFunctionOrMethodResultSourceRange(D);
+  if (AL.getAttributeSpellingListIndex() == RestrictAttr::Declspec_restrict) {
+// __declspec(restrict) accepts no arguments
+S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 0;
+return;
+  }
+
+  // FIXME: GCC uses [[malloc(my_func)]] to specify a deallocator for the
+  // returned pointer, but this isn't currently supported in LLVM
+  // see https://github.com/llvm/llvm-project/issues/51607
 }
 
 static void handleCPUSpecificAttr(Sema , Decl *D, const ParsedAttr ) {
diff --git a/clang/test/Sema/attr-args.c 

[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

@kstoimenov I believe you are supposed to notify the MR in case of reverts, 
otherwise I could have missed this if I wasn't awake.

I believe in this case the bot is misconfigured, it's using 
`-Werror,-Wmissing-field-initializers`, the 'error' is just a missing 
initializer, which I didn't add because I think it makes the intent clearer.

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


[clang] [lld][ELF] Warn instead of error when linker script fails to find section (PR #68058)

2023-10-02 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-lld


Changes

It can be hard to predict whether a section exist when using the `INSERT 
AFTER/BEFORE section` directive, this makes it difficult to apply a 
global linker script that's applicable to the entire build system. We should 
warn instead of hard error in such cases.

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


2 Files Affected:

- (modified) lld/ELF/LinkerScript.cpp (+1-1) 
- (modified) lld/test/ELF/linkerscript/insert-not-exist.test (+3-3) 


``diff
diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp
index df091613dc0a144..84658751b30487d 100644
--- a/lld/ELF/LinkerScript.cpp
+++ b/lld/ELF/LinkerScript.cpp
@@ -327,7 +327,7 @@ void LinkerScript::processInsertCommands() {
   return to != nullptr && to->osec.name == cmd.where;
 });
 if (insertPos == sectionCommands.end()) {
-  error("unable to insert " + cmd.names[0] +
+  warn("unable to insert " + cmd.names[0] +
 (cmd.isAfter ? " after " : " before ") + cmd.where);
 } else {
   if (cmd.isAfter)
diff --git a/lld/test/ELF/linkerscript/insert-not-exist.test 
b/lld/test/ELF/linkerscript/insert-not-exist.test
index 8bb8a7d0ce8dc8f..4f68ad378678edd 100644
--- a/lld/test/ELF/linkerscript/insert-not-exist.test
+++ b/lld/test/ELF/linkerscript/insert-not-exist.test
@@ -1,9 +1,9 @@
 # REQUIRES: x86
 # RUN: llvm-mc -filetype=obj -triple=x86_64 %p/Inputs/insert-after.s -o %t.o
-# RUN: not ld.lld -T %s %t.o -o /dev/null 2>&1 | FileCheck %s
+# RUN: ld.lld -T %s %t.o -o /dev/null 2>&1 | FileCheck %s
 
-# CHECK: error: unable to insert .foo.data after .not_exist
-# CHECK: error: unable to insert .foo.text before .not_exist
+# CHECK: warning: unable to insert .foo.data after .not_exist
+# CHECK: warning: unable to insert .foo.text before .not_exist
 
 SECTIONS { .foo.data : {} } INSERT AFTER .not_exist;
 SECTIONS { .foo.text : {} } INSERT BEFORE .not_exist;

``




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


[clang] [lld][ELF] Warn instead of error when linker script fails to find section (PR #68058)

2023-10-02 Thread via cfe-commits

https://github.com/christycylee created 
https://github.com/llvm/llvm-project/pull/68058

It can be hard to predict whether a section exist when using the `INSERT 
AFTER/BEFORE ` directive, this makes it difficult to apply a global 
linker script that's applicable to the entire build system. We should warn 
instead of hard error in such cases.

>From 639029ce60d22aaeed46675b1fea0f0f20f0e014 Mon Sep 17 00:00:00 2001
From: Christy Lee 
Date: Mon, 2 Oct 2023 16:46:07 -0700
Subject: [PATCH] Warn instead of error when linker script fails to find
 section

---
 lld/ELF/LinkerScript.cpp| 2 +-
 lld/test/ELF/linkerscript/insert-not-exist.test | 6 +++---
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp
index df091613dc0a144..84658751b30487d 100644
--- a/lld/ELF/LinkerScript.cpp
+++ b/lld/ELF/LinkerScript.cpp
@@ -327,7 +327,7 @@ void LinkerScript::processInsertCommands() {
   return to != nullptr && to->osec.name == cmd.where;
 });
 if (insertPos == sectionCommands.end()) {
-  error("unable to insert " + cmd.names[0] +
+  warn("unable to insert " + cmd.names[0] +
 (cmd.isAfter ? " after " : " before ") + cmd.where);
 } else {
   if (cmd.isAfter)
diff --git a/lld/test/ELF/linkerscript/insert-not-exist.test 
b/lld/test/ELF/linkerscript/insert-not-exist.test
index 8bb8a7d0ce8dc8f..4f68ad378678edd 100644
--- a/lld/test/ELF/linkerscript/insert-not-exist.test
+++ b/lld/test/ELF/linkerscript/insert-not-exist.test
@@ -1,9 +1,9 @@
 # REQUIRES: x86
 # RUN: llvm-mc -filetype=obj -triple=x86_64 %p/Inputs/insert-after.s -o %t.o
-# RUN: not ld.lld -T %s %t.o -o /dev/null 2>&1 | FileCheck %s
+# RUN: ld.lld -T %s %t.o -o /dev/null 2>&1 | FileCheck %s
 
-# CHECK: error: unable to insert .foo.data after .not_exist
-# CHECK: error: unable to insert .foo.text before .not_exist
+# CHECK: warning: unable to insert .foo.data after .not_exist
+# CHECK: warning: unable to insert .foo.text before .not_exist
 
 SECTIONS { .foo.data : {} } INSERT AFTER .not_exist;
 SECTIONS { .foo.text : {} } INSERT BEFORE .not_exist;

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


[clang] [analyzer] Fix false negative when accessing a nonnull property from … (PR #67563)

2023-10-02 Thread via cfe-commits

https://github.com/tripleCC updated 
https://github.com/llvm/llvm-project/pull/67563

>From 0783db5bcaed863cd0cd5c5a2e0d8cc3355e7f51 Mon Sep 17 00:00:00 2001
From: tripleCC 
Date: Wed, 27 Sep 2023 22:05:19 +0800
Subject: [PATCH] [analyzer] Fix false negative when accessing a nonnull
 property from a nullable object

---
 .../lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp | 10 +-
 clang/test/Analysis/nullability.mm |  7 +++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
index 906f4e85a8e5b5b..627b51af6bd44af 100644
--- a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
@@ -899,6 +899,14 @@ void NullabilityChecker::checkPostCall(const CallEvent 
,
   const NullabilityState *TrackedNullability =
   State->get(Region);
 
+  // ObjCMessageExpr gets the actual type through
+  // Sema::getMessageSendResultType, instead of using the return type of
+  // MethodDecl directly. The final type is generated by considering the
+  // nullability of receiver and MethodDecl together. Thus, The type of
+  // ObjCMessageExpr is prefer.
+  if (const Expr *E = Call.getOriginExpr())
+ReturnType = E->getType();
+
   if (!TrackedNullability &&
   getNullabilityAnnotation(ReturnType) == Nullability::Nullable) {
 State = State->set(Region, Nullability::Nullable);
@@ -1053,7 +1061,7 @@ void NullabilityChecker::checkPostObjCMessage(const 
ObjCMethodCall ,
   }
 
   // No tracked information. Use static type information for return value.
-  Nullability RetNullability = getNullabilityAnnotation(RetType);
+  Nullability RetNullability = getNullabilityAnnotation(Message->getType());
 
   // Properties might be computed, which means the property value could
   // theoretically change between calls even in commonly-observed cases like
diff --git a/clang/test/Analysis/nullability.mm 
b/clang/test/Analysis/nullability.mm
index 06bb9912296e32f..d69116d03df7465 100644
--- a/clang/test/Analysis/nullability.mm
+++ b/clang/test/Analysis/nullability.mm
@@ -55,6 +55,7 @@ - (void)takesUnspecified:(int *)p;
 @property(readonly, nullable) void (^propReturnsNullableBlock)(void);
 @property(readonly, nullable) int *propReturnsNullable;
 @property(readonly) int *propReturnsUnspecified;
++ (nullable TestObject *)getNullableObject;
 @end
 
 TestObject * getUnspecifiedTestObject();
@@ -256,6 +257,12 @@ void testObjCPropertyReadNullability() {
   case 8:
 [o takesNonnullBlock:o.propReturnsNullableBlock]; // expected-warning 
{{Nullable pointer is passed to a callee that requires a non-null 1st 
parameter}}
 break;
+  case 9:
+[o takesNonnull:getNullableTestObject().propReturnsNonnull]; // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 1st parameter}}
+break;
+  case 10:
+[o takesNonnull:[TestObject getNullableObject].propReturnsNonnull]; // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 1st parameter}}
+break;
   }
 }
 

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


[clang] 1493462 - Revert "[NFC][Clang][CodeGen] Improve performance for vtable metadata generation (#67066)"

2023-10-02 Thread Kirill Stoimenov via cfe-commits

Author: Kirill Stoimenov
Date: 2023-10-03T00:09:46Z
New Revision: 149346286801a5f32d254676760a7f4211801667

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

LOG: Revert "[NFC][Clang][CodeGen] Improve performance for vtable metadata 
generation (#67066)"

This reverts commit 22d8f1dd533e3e56512237811b8d8db83d85edce.

Broke sanitizer bots: https://lab.llvm.org/buildbot/#/builders/269/builds/59

Added: 


Modified: 
clang/lib/CodeGen/CGVTables.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index 5ec38e0397bf4f7..d782da2103b4c79 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -24,7 +24,6 @@
 #include "llvm/Transforms/Utils/Cloning.h"
 #include 
 #include 
-#include 
 
 using namespace clang;
 using namespace CodeGen;
@@ -1309,33 +1308,44 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
 
   CharUnits ComponentWidth = GetTargetTypeStoreSize(getVTableComponentType());
 
-  struct AddressPoint {
-const CXXRecordDecl *Base;
-size_t Offset;
-std::string TypeName;
-bool operator<(const AddressPoint ) const {
-  int D = TypeName.compare(RHS.TypeName);
-  return D < 0 || (D == 0 && Offset < RHS.Offset);
-}
-  };
+  typedef std::pair AddressPoint;
   std::vector AddressPoints;
-  for (auto & : VTLayout.getAddressPoints()) {
-AddressPoint N{AP.first.getBase(),
-   VTLayout.getVTableOffset(AP.second.VTableIndex) +
-   AP.second.AddressPointIndex};
-llvm::raw_string_ostream Stream(N.TypeName);
-getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(N.Base->getTypeForDecl(), 0), Stream);
-AddressPoints.push_back(std::move(N));
-  }
+  for (auto & : VTLayout.getAddressPoints())
+AddressPoints.push_back(std::make_pair(
+AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
+AP.second.AddressPointIndex));
 
   // Sort the address points for determinism.
-  llvm::sort(AddressPoints);
+  // FIXME: It's more efficient to mangle the types before sorting.
+  llvm::sort(AddressPoints, [this](const AddressPoint ,
+   const AddressPoint ) {
+if ( == )
+  return false;
+
+std::string S1;
+llvm::raw_string_ostream O1(S1);
+getCXXABI().getMangleContext().mangleCanonicalTypeName(
+QualType(AP1.first->getTypeForDecl(), 0), O1);
+O1.flush();
+
+std::string S2;
+llvm::raw_string_ostream O2(S2);
+getCXXABI().getMangleContext().mangleCanonicalTypeName(
+QualType(AP2.first->getTypeForDecl(), 0), O2);
+O2.flush();
+
+if (S1 < S2)
+  return true;
+if (S1 != S2)
+  return false;
+
+return AP1.second < AP2.second;
+  });
 
   ArrayRef Comps = VTLayout.vtable_components();
   for (auto AP : AddressPoints) {
 // Create type metadata for the address point.
-AddVTableTypeMetadata(VTable, ComponentWidth * AP.Offset, AP.Base);
+AddVTableTypeMetadata(VTable, ComponentWidth * AP.second, AP.first);
 
 // The class associated with each address point could also potentially be
 // used for indirect calls via a member function pointer, so we need to
@@ -1347,7 +1357,7 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
   llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
   Context.getMemberPointerType(
   Comps[I].getFunctionDecl()->getType(),
-  Context.getRecordType(AP.Base).getTypePtr()));
+  Context.getRecordType(AP.first).getTypePtr()));
   VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
 }
   }



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


[clang] [IRPGO][ValueProfile] Instrument virtual table address that could be used to do virtual table address comparision for indirect-call-promotion. (PR #66825)

2023-10-02 Thread Mingming Liu via cfe-commits


@@ -90,9 +90,33 @@ public:
   }
 };
 
+/// VirtualTableValueProfilingPlugin 

+class VTableProfilingPlugin {
+  Function 
+
+public:
+  static constexpr InstrProfValueKind Kind = IPVK_VTableTarget;
+
+  VTableProfilingPlugin(Function , TargetLibraryInfo ) : F(Fn) {}

minglotus-6 wrote:

I added a FIXME to do more efficient vtable instrumentation. To fix this, need 
to make sure one instrumented value profile gets used at more than one virtual 
callsite (correctly).

To elaborate, take https://gcc.godbolt.org/z/K7a37546E as an example

C++ source 

```
class Base1 {
public:
virtual int func1(int a, int b) ;
virtual int func2();
};

class Derived : public Base1 {
public:
Derived(int c) : v(c) {}
  
private:
int v;
};

Derived* createType(int c);

int func(int a, int b, int c) {
Derived* d = createType(c);

return d->func2() + d->func1(b, a);
}
```

and IR 

```
define dso_local i32 @func(int, int, int)(i32 %a, i32 %b, i32 %c) 
local_unnamed_addr #0 {
entry:
  %call = tail call ptr @createType(int)(i32 %c)
  %vtable = load ptr, ptr %call, align 8, !tbaa !7
  %vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
  # %0 is one virtual func, loaded from %vtable
  %0 = load ptr, ptr %vfn, align 8
  %call1 = tail call i32 %0(ptr nonnull align 8 dereferenceable(8) %call)
  %vtable2 = load ptr, ptr %call, align 8, !tbaa !7
  # %1 is another virtual func, loaded from %vtable2
  %1 = load ptr, ptr %vtable2, align 8
  %call4 = tail call i32 %1(ptr nonnull align 8 dereferenceable(8) %call, i32 
%b, i32 %a)
  %add = add nsw i32 %call4, %call1
  ret i32 %add
}
```

Without `-fstrict-vtable-pointers`, `func1` and `func2` are load different 
vtable SSA variable. Instrument the first vtable but not the second gives more 
efficient instrumentation; yet at profile-use time, it would require analysis 
and value profile propagation (first prove load invariance, and then copy 
`vtable` value profie to `vtable2`) to associate value profiles of `vtable` 
(the 1st vtable) with `%1` (the 2nd virtual call), since the 2nd virtual call 
loads from `vtable2`.

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


[PATCH] D157547: Arm64EC entry/exit thunks, consolidated.

2023-10-02 Thread Daniel Paoliello via Phabricator via cfe-commits
dpaoliello added inline comments.



Comment at: llvm/lib/Target/AArch64/AArch64CallingConvention.td:248-257
+  // The first 4 FP/Vector arguments are passed in XMM registers.
+  CCIfType<[f16],
+   CCAssignToRegWithShadow<[H0, H1, H2, H3],
+   [X0, X1, X2, X2]>>,
+  CCIfType<[f32],
+   CCAssignToRegWithShadow<[S0, S1, S2, S3],
+   [X0, X1, X2, X2]>>,

These seem wrong, shouldn't the shadows be `[X0, X1, X2, X3]` (instead of `X2` 
twice)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157547

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


[clang] [clang][modules] Move `SLocEntry` search into `ASTReader` (PR #66966)

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

https://github.com/jansvoboda11 updated 
https://github.com/llvm/llvm-project/pull/66966

>From 4edf9d8559339a12108d9c4d1e2f3bb062a5a768 Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Wed, 20 Sep 2023 17:30:45 -0700
Subject: [PATCH 1/7] [clang][modules] Move `SLocEntry` search into `ASTReader`

In `getFileID()` the `SourceManager` ends up doing a binary search over its 
buffer of `SLocEntries`. For modules, this binary search fully deserializes the 
entire `SLocEntry` block for visited each entry. This shows up in profiles of 
the dependency scanner, since that operation includes decompressing buffers 
associated with some entries.

This patch moves the binary search over loaded entries into `ASTReader`, which 
now only performs partial deserialization during the binary search, speeding up 
the scanner by ~3.3%.
---
 clang/include/clang/Basic/SourceManager.h |  3 +
 clang/include/clang/Serialization/ASTReader.h |  6 ++
 clang/lib/Basic/SourceManager.cpp | 70 +--
 clang/lib/Serialization/ASTReader.cpp | 63 +
 4 files changed, 75 insertions(+), 67 deletions(-)

diff --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 2f846502d6f3327..a4c7facddd53d64 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -533,6 +533,9 @@ class ExternalSLocEntrySource {
   /// entry from being loaded.
   virtual bool ReadSLocEntry(int ID) = 0;
 
+  /// Get the index ID for the loaded SourceLocation offset.
+  virtual int getSLocEntryID(SourceLocation::UIntTy SLocOffset) = 0;
+
   /// Retrieve the module import location and name for the given ID, if
   /// in fact it was loaded from a module (rather than, say, a precompiled
   /// header).
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index dc1eb21c27801fe..e643fcf4c930f09 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -2153,6 +2153,12 @@ class ASTReader
 
   /// Read the source location entry with index ID.
   bool ReadSLocEntry(int ID) override;
+  /// Get the index ID for the loaded SourceLocation offset.
+  int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override;
+  /// Read the offset of the SLocEntry at the given index in the given module
+  /// file.
+  std::optional readSLocOffset(ModuleFile *F,
+   unsigned Index);
 
   /// Retrieve the module import location and module name for the
   /// given source manager entry ID.
diff --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 0521ac7b30339ab..f881afc2e46c5c6 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -864,74 +864,10 @@ FileID 
SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
 /// This function knows that the SourceLocation is in a loaded buffer, not a
 /// local one.
 FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const 
{
-  if (SLocOffset < CurrentLoadedOffset) {
-assert(0 && "Invalid SLocOffset or bad function choice");
-return FileID();
-  }
-
-  // Essentially the same as the local case, but the loaded array is sorted
-  // in the other direction (decreasing order).
-  // GreaterIndex is the one where the offset is greater, which is actually a
-  // lower index!
-  unsigned GreaterIndex = 0;
-  unsigned LessIndex = LoadedSLocEntryTable.size();
-  if (LastFileIDLookup.ID < 0) {
-// Prune the search space.
-int LastID = LastFileIDLookup.ID;
-if (getLoadedSLocEntryByID(LastID).getOffset() > SLocOffset)
-  GreaterIndex =
-  (-LastID - 2) + 1; // Exclude LastID, else we would have hit the 
cache
-else
-  LessIndex = -LastID - 2;
-  }
-
-  // First do a linear scan from the last lookup position, if possible.
-  unsigned NumProbes;
+  int ID = ExternalSLocEntries->getSLocEntryID(SLocOffset);
   bool Invalid = false;
-  for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++GreaterIndex) {
-// Make sure the entry is loaded!
-const SrcMgr::SLocEntry  = getLoadedSLocEntry(GreaterIndex, );
-if (Invalid)
-  return FileID(); // invalid entry.
-if (E.getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(-int(GreaterIndex) - 2);
-  LastFileIDLookup = Res;
-  NumLinearScans += NumProbes + 1;
-  return Res;
-}
-  }
-
-  // Linear scan failed. Do the binary search.
-  NumProbes = 0;
-  while (true) {
-++NumProbes;
-unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
-const SrcMgr::SLocEntry  = getLoadedSLocEntry(MiddleIndex, );
-if (Invalid)
-  return FileID(); // invalid entry.
-
-if (E.getOffset() > SLocOffset) {
-  if (GreaterIndex == MiddleIndex) {
-assert(0 && "binary search missed the entry");
-return FileID();
-  

[clang] [clang][modules] Move `SLocEntry` search into `ASTReader` (PR #66966)

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


@@ -50,6 +50,7 @@ int y = a2;
 // CHECK: In module 'a':
 // CHECK-NEXT: a.h:1:45: error:
 
+int z = b;
 // MISSING-B: could not find file '{{.*}}b.h'
 // MISSING-B-NOT: please delete the module cache

jansvoboda11 wrote:

I'm not sure. To me, this seems like an implementation detail we shouldn't test 
for.

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


[clang] [clang][modules] Move `SLocEntry` search into `ASTReader` (PR #66966)

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


@@ -288,10 +288,12 @@ class ModuleFile {
   /// for the entry is SLocEntryOffsetsBase + SLocEntryOffsets[i].
   uint64_t SLocEntryOffsetsBase = 0;
 
-  /// Offsets for all of the source location entries in the
-  /// AST file.
+  /// Stream bit offsets for all of the source location entries in the AST 
file.
   const uint32_t *SLocEntryOffsets = nullptr;
 
+  /// SLocEntry offsets that have been loaded from the AST file.
+  std::vector SLocEntryOffsetLoaded;

jansvoboda11 wrote:

This ends up being ~10MB for single TU using 37 modules from the Darwin SDK. 
I'm not thrilled about that, what do you think? We could store these offsets in 
`SourceManager::LoadedSLocEntryTable` and mark the fact that the entry has not 
been fully deserialized in a counterpart to `llvm::BitVector SLocEntryLoaded`.

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


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

Weird, the commit in the MR has a description, but it lost the description when 
merging through the github interface.

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


[clang] Avoid need for SLocEntryLoaded BitVector (PR #67960)

2023-10-02 Thread Jakub Kuderski via cfe-commits

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


[clang] Avoid need for SLocEntryLoaded BitVector (PR #67960)

2023-10-02 Thread Jakub Kuderski via cfe-commits


@@ -180,6 +180,20 @@ TEST(PagedVectorTest, FillNonTrivialConstructor) {
   EXPECT_EQ(std::distance(V.materialized_begin(), V.materialized_end()), 10LL);
 }
 
+// Test that isMaterialized returns true for all the elements
+// of the page, not only the one that was accessed.
+TEST(PagedVectorTest, IsMaterialized) {
+  PagedVector V;
+  V.resize(20);
+  EXPECT_EQ(V.isMaterialized(0), false);

kuhar wrote:

We can Uluse `EXPECT_TRUE`/`FALSE`.

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


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Shafik Yaghmour via cfe-commits

shafik wrote:

Please next time before you commit add a more detailed description of the 
change so that readers of git log can get a better understanding of the change 
w/o having to view it in detail.

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


[clang] [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (PR #67066)

2023-10-02 Thread Matheus Izvekov via cfe-commits

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


[clang] 22d8f1d - [NFC][Clang][CodeGen] Improve performance for vtable metadata generation (#67066)

2023-10-02 Thread via cfe-commits

Author: Matheus Izvekov
Date: 2023-10-03T00:45:00+02:00
New Revision: 22d8f1dd533e3e56512237811b8d8db83d85edce

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

LOG: [NFC][Clang][CodeGen] Improve performance for vtable metadata generation 
(#67066)

Added: 


Modified: 
clang/lib/CodeGen/CGVTables.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index d782da2103b4c79..5ec38e0397bf4f7 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -24,6 +24,7 @@
 #include "llvm/Transforms/Utils/Cloning.h"
 #include 
 #include 
+#include 
 
 using namespace clang;
 using namespace CodeGen;
@@ -1308,44 +1309,33 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
 
   CharUnits ComponentWidth = GetTargetTypeStoreSize(getVTableComponentType());
 
-  typedef std::pair AddressPoint;
+  struct AddressPoint {
+const CXXRecordDecl *Base;
+size_t Offset;
+std::string TypeName;
+bool operator<(const AddressPoint ) const {
+  int D = TypeName.compare(RHS.TypeName);
+  return D < 0 || (D == 0 && Offset < RHS.Offset);
+}
+  };
   std::vector AddressPoints;
-  for (auto & : VTLayout.getAddressPoints())
-AddressPoints.push_back(std::make_pair(
-AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
-AP.second.AddressPointIndex));
-
-  // Sort the address points for determinism.
-  // FIXME: It's more efficient to mangle the types before sorting.
-  llvm::sort(AddressPoints, [this](const AddressPoint ,
-   const AddressPoint ) {
-if ( == )
-  return false;
-
-std::string S1;
-llvm::raw_string_ostream O1(S1);
-getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(AP1.first->getTypeForDecl(), 0), O1);
-O1.flush();
-
-std::string S2;
-llvm::raw_string_ostream O2(S2);
+  for (auto & : VTLayout.getAddressPoints()) {
+AddressPoint N{AP.first.getBase(),
+   VTLayout.getVTableOffset(AP.second.VTableIndex) +
+   AP.second.AddressPointIndex};
+llvm::raw_string_ostream Stream(N.TypeName);
 getCXXABI().getMangleContext().mangleCanonicalTypeName(
-QualType(AP2.first->getTypeForDecl(), 0), O2);
-O2.flush();
-
-if (S1 < S2)
-  return true;
-if (S1 != S2)
-  return false;
+QualType(N.Base->getTypeForDecl(), 0), Stream);
+AddressPoints.push_back(std::move(N));
+  }
 
-return AP1.second < AP2.second;
-  });
+  // Sort the address points for determinism.
+  llvm::sort(AddressPoints);
 
   ArrayRef Comps = VTLayout.vtable_components();
   for (auto AP : AddressPoints) {
 // Create type metadata for the address point.
-AddVTableTypeMetadata(VTable, ComponentWidth * AP.second, AP.first);
+AddVTableTypeMetadata(VTable, ComponentWidth * AP.Offset, AP.Base);
 
 // The class associated with each address point could also potentially be
 // used for indirect calls via a member function pointer, so we need to
@@ -1357,7 +1347,7 @@ void CodeGenModule::EmitVTableTypeMetadata(const 
CXXRecordDecl *RD,
   llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
   Context.getMemberPointerType(
   Comps[I].getFunctionDecl()->getType(),
-  Context.getRecordType(AP.first).getTypePtr()));
+  Context.getRecordType(AP.Base).getTypePtr()));
   VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
 }
   }



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


[PATCH] D145262: [clang-format] Treat AttributeMacros more like attribute macros

2023-10-02 Thread Jared Grubb via Phabricator via cfe-commits
jaredgrubb updated this revision to Diff 557542.
jaredgrubb added a comment.

Address review comments, and adjusting the patch to address other merges since 
this patch was started.


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

https://reviews.llvm.org/D145262

Files:
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestObjC.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1770,6 +1770,116 @@
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacros) {
+  // '__attribute__' has special handling.
+  auto Tokens = annotate("__attribute__(X) void Foo(void);");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw___attribute, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_AttributeLParen);
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_AttributeRParen);
+
+  // Generic macro has no special handling in this location.
+  Tokens = annotate("A(X) void Foo(void);");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_Unknown);
+
+  // Add a custom AttributeMacro. Test that it has the same behavior.
+  FormatStyle Style = getLLVMStyle();
+  Style.AttributeMacros.push_back("A");
+
+  // An "AttributeMacro" gets annotated like '__attribute__'.
+  Tokens = annotate("A(X) void Foo(void);", Style);
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_AttributeMacro);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_AttributeLParen);
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_AttributeRParen);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacrosOnObjCDecl) {
+  // '__attribute__' has special handling.
+  auto Tokens = annotate("__attribute__(X) @interface Foo");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw___attribute, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_AttributeLParen);
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_AttributeRParen);
+
+  // Generic macro has no special handling in this location.
+  Tokens = annotate("A(X) @interface Foo");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  // Note: Don't check token-type as a random token in this position is hard to
+  // reason about.
+  EXPECT_TOKEN_KIND(Tokens[0], tok::identifier);
+  EXPECT_TOKEN_KIND(Tokens[1], tok::l_paren);
+
+  // Add a custom AttributeMacro. Test that it has the same behavior.
+  FormatStyle Style = getLLVMStyle();
+  Style.AttributeMacros.push_back("A");
+
+  // An "AttributeMacro" gets annotated like '__attribute__'.
+  Tokens = annotate("A(X) @interface Foo", Style);
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_AttributeMacro);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_AttributeLParen);
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_AttributeRParen);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacrosOnObjCMethodDecl) {
+  // '__attribute__' has special handling.
+  auto Tokens = annotate("- (id)init __attribute__(X);");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw___attribute, TT_Unknown);
+  EXPECT_TOKEN(Tokens[6], tok::l_paren, TT_AttributeLParen);
+  EXPECT_TOKEN(Tokens[8], tok::r_paren, TT_AttributeRParen);
+
+  // Generic macro has no special handling in this location.
+  Tokens = annotate("- (id)init A(X);");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  // Note: Don't check token-type as a random token in this position is hard to
+  // reason about.
+  EXPECT_TOKEN_KIND(Tokens[5], tok::identifier);
+  EXPECT_TOKEN_KIND(Tokens[6], tok::l_paren);
+
+  // Add a custom AttributeMacro. Test that it has the same behavior.
+  FormatStyle Style = getLLVMStyle();
+  Style.AttributeMacros.push_back("A");
+
+  // An "AttributeMacro" gets annotated like '__attribute__'.
+  Tokens = annotate("- (id)init A(X);", Style);
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::identifier, TT_AttributeMacro);
+  EXPECT_TOKEN(Tokens[6], tok::l_paren, TT_AttributeLParen);
+  EXPECT_TOKEN(Tokens[8], tok::r_paren, TT_AttributeRParen);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacrosOnObjCProperty) {
+  // '__attribute__' has special handling.
+  auto Tokens = annotate("@property(weak) id delegate __attribute__(X);");
+  ASSERT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::kw___attribute, TT_Unknown);
+  EXPECT_TOKEN(Tokens[8], tok::l_paren, TT_AttributeLParen);
+  EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_AttributeRParen);
+
+  // Generic macro has no special handling in this location.
+  Tokens = annotate("@property(weak) id delegate A(X);");

[clang] [clang][modules] Move `SLocEntry` search into `ASTReader` (PR #66966)

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


@@ -864,74 +864,7 @@ FileID 
SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
 /// This function knows that the SourceLocation is in a loaded buffer, not a
 /// local one.
 FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const 
{
-  if (SLocOffset < CurrentLoadedOffset) {
-assert(0 && "Invalid SLocOffset or bad function choice");

jansvoboda11 wrote:

It would probably fail to find the offset in `ASTReader::GlobalSLocOffsetMap` 
and fail with more generic error. I'll add this back.

https://github.com/llvm/llvm-project/pull/66966
___
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-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,190 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "almost_satisfies_types.h"
+#include "boolean_testable.h"
+#include "test_iterators.h"
+
+struct NotEqualityComparable {};
+
+template 
+concept HasContainsIt = requires(Iter iter, Sent sent) { 
std::ranges::contains(iter, sent, *iter); };
+
+static_assert(HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt, 
SentinelForNotSemiregular>);
+static_assert(!HasContainsIt, 
InputRangeNotSentinelEqualityComparableWith>);
+
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+
+template 
+concept HasContainsR = requires(Range range) { std::ranges::contains(range, 
ValT{}); };
+
+static_assert(HasContainsR, int>);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR, 
NotEqualityComparable>);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+
+static std::vector comparable_data;
+
+// clang-format off
+template 
+constexpr void test_iterators() {
+  using ValueT = std::iter_value_t;
+  {  // simple tests
+{
+  ValueT a[] = {1, 2, 3, 4, 5, 6};
+  std::same_as auto ret =
+std::ranges::contains(Iter(a), Sent(Iter(a + 6)), 3);
+  assert(ret);
+}
+{
+  ValueT a[] = {1, 2, 3, 4, 5, 6};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
+  std::same_as decltype(auto) ret =
+std::ranges::contains(range, 3);
+  assert(ret);
+}
+  }
+
+  { // check that an empty range works
+{
+  ValueT a[] = {};
+  auto ret = std::ranges::contains(Iter(a), Sent(Iter(a)), 1);
+  assert(!ret);
+}
+{
+  ValueT a[] = {};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a)));
+  auto ret = std::ranges::contains(range, 1);
+  assert(!ret);
+}
+  }
+
+  { // check that no match
+{
+  ValueT a[] = {13, 1, 21, 4, 5};
+  auto ret = std::ranges::contains(Iter(a), Sent(Iter(a + 5)), 10);
+  assert(!ret);
+}
+{
+  ValueT a[] = {13, 1, 21, 4, 5};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
+  auto ret = std::ranges::contains(range, 10);
+  assert(!ret);
+}
+  }
+
+  if (!std::is_constant_evaluated())
+comparable_data.clear();
+}
+template 
+class TriviallyComparable {

var-const wrote:

Thanks for pointing me to the patch. It looks like this is to test an 
optimization that's specific to `find`. IMO we shouldn't duplicate those tests 
here, so I'd just remove the `Comparable` and `TriviallyComparable` tests. It 
might make sense to add a benchmark for `ranges::contains`, though.

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,190 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "almost_satisfies_types.h"
+#include "boolean_testable.h"
+#include "test_iterators.h"
+
+struct NotEqualityComparable {};
+
+template 
+concept HasContainsIt = requires(Iter iter, Sent sent) { 
std::ranges::contains(iter, sent, *iter); };
+
+static_assert(HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt, 
SentinelForNotSemiregular>);
+static_assert(!HasContainsIt, 
InputRangeNotSentinelEqualityComparableWith>);
+
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+
+template 
+concept HasContainsR = requires(Range range) { std::ranges::contains(range, 
ValT{}); };
+
+static_assert(HasContainsR, int>);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR, 
NotEqualityComparable>);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+
+static std::vector comparable_data;
+
+// clang-format off
+template 
+constexpr void test_iterators() {
+  using ValueT = std::iter_value_t;
+  {  // simple tests
+{
+  ValueT a[] = {1, 2, 3, 4, 5, 6};
+  std::same_as auto ret =
+std::ranges::contains(Iter(a), Sent(Iter(a + 6)), 3);
+  assert(ret);
+}
+{
+  ValueT a[] = {1, 2, 3, 4, 5, 6};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
+  std::same_as decltype(auto) ret =
+std::ranges::contains(range, 3);
+  assert(ret);
+}
+  }
+
+  { // check that an empty range works
+{
+  ValueT a[] = {};
+  auto ret = std::ranges::contains(Iter(a), Sent(Iter(a)), 1);
+  assert(!ret);
+}
+{
+  ValueT a[] = {};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a)));
+  auto ret = std::ranges::contains(range, 1);
+  assert(!ret);
+}
+  }
+
+  { // check that no match
+{
+  ValueT a[] = {13, 1, 21, 4, 5};
+  auto ret = std::ranges::contains(Iter(a), Sent(Iter(a + 5)), 10);
+  assert(!ret);
+}
+{
+  ValueT a[] = {13, 1, 21, 4, 5};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
+  auto ret = std::ranges::contains(range, 10);
+  assert(!ret);
+}
+  }
+
+  if (!std::is_constant_evaluated())
+comparable_data.clear();
+}
+template 
+class TriviallyComparable {

var-const wrote:

Thanks for pointing me to the patch. It looks like this is to test an 
optimization that's specific to `find`. IMO we shouldn't duplicate those tests 
here, so I'd just remove the `Comparable` and `TriviallyComparable` tests. It 
might make sense to add a benchmark for `ranges::contains`, though.

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,190 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "almost_satisfies_types.h"
+#include "boolean_testable.h"
+#include "test_iterators.h"
+
+struct NotEqualityComparable {};
+
+template 
+concept HasContainsIt = requires(Iter iter, Sent sent) { 
std::ranges::contains(iter, sent, *iter); };
+
+static_assert(HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt, 
SentinelForNotSemiregular>);
+static_assert(!HasContainsIt, 
InputRangeNotSentinelEqualityComparableWith>);
+
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+
+template 
+concept HasContainsR = requires(Range range) { std::ranges::contains(range, 
ValT{}); };
+
+static_assert(HasContainsR, int>);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR, 
NotEqualityComparable>);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+
+static std::vector comparable_data;
+
+// clang-format off
+template 
+constexpr void test_iterators() {
+  using ValueT = std::iter_value_t;
+  {  // simple tests
+{
+  ValueT a[] = {1, 2, 3, 4, 5, 6};
+  std::same_as auto ret =
+std::ranges::contains(Iter(a), Sent(Iter(a + 6)), 3);
+  assert(ret);
+}
+{
+  ValueT a[] = {1, 2, 3, 4, 5, 6};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
+  std::same_as decltype(auto) ret =
+std::ranges::contains(range, 3);
+  assert(ret);
+}
+  }
+
+  { // check that an empty range works
+{
+  ValueT a[] = {};
+  auto ret = std::ranges::contains(Iter(a), Sent(Iter(a)), 1);
+  assert(!ret);
+}
+{
+  ValueT a[] = {};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a)));
+  auto ret = std::ranges::contains(range, 1);
+  assert(!ret);
+}
+  }
+
+  { // check that no match
+{
+  ValueT a[] = {13, 1, 21, 4, 5};
+  auto ret = std::ranges::contains(Iter(a), Sent(Iter(a + 5)), 10);
+  assert(!ret);
+}
+{
+  ValueT a[] = {13, 1, 21, 4, 5};
+  auto range = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
+  auto ret = std::ranges::contains(range, 10);
+  assert(!ret);
+}
+  }
+
+  if (!std::is_constant_evaluated())
+comparable_data.clear();
+}
+template 
+class TriviallyComparable {

var-const wrote:

Thanks for pointing me to the patch. It looks like this is to test an 
optimization that's specific to `find`. IMO we shouldn't duplicate those tests 
here, so I'd just remove the `Comparable` and `TriviallyComparable` tests. It 
might make sense to add a benchmark for `ranges::contains`, though.

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


[clang] [clang-format] Fix alignment in presence of template functions (PR #68029)

2023-10-02 Thread via cfe-commits

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


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


[clang] [clang-format] Annotate ctors/dtors as CtorDtorDeclName instead (PR #67955)

2023-10-02 Thread via cfe-commits

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

Looks like it fixes some bugs in the tests too!

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


[clang] [clang][modules] Remove preloaded SLocEntries from PCM files (PR #66962)

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

https://github.com/jansvoboda11 updated 
https://github.com/llvm/llvm-project/pull/66962

>From 61e8961cde95e9e8ce8cea3efd6aa52273f430e9 Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Wed, 20 Sep 2023 16:50:48 -0700
Subject: [PATCH 1/3] [clang][modules] Remove preloaded SLocEntries from PCM
 files

This commit removes the list of SLocEntry offsets to preload eagerly from PCM 
files. Commit introducing this functionality (258ae54a) doesn't clarify why 
this would be more performant than the lazy approach used regularly.

Currently, the only SLocEntry the reader is supposed to preload is the 
predefines buffer, but in my experience, it's not actually referenced in most 
modules, so the time spent deserializing its SLocEntry is wasted. This is 
especially noticeable in the dependency scanner, where this change brings 4.56% 
speedup on my benchmark.
---
 .../include/clang/Serialization/ASTBitCodes.h | 10 ++--
 .../include/clang/Serialization/ModuleFile.h  |  3 ---
 clang/lib/Serialization/ASTReader.cpp | 23 ---
 clang/lib/Serialization/ASTWriter.cpp |  8 ---
 4 files changed, 2 insertions(+), 42 deletions(-)

diff --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index 9e115f2a5cce3f9..85f49e21b2e2ec1 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -51,7 +51,7 @@ const unsigned VERSION_MAJOR = 29;
 /// for the previous version could still support reading the new
 /// version by ignoring new kinds of subblocks), this number
 /// should be increased.
-const unsigned VERSION_MINOR = 0;
+const unsigned VERSION_MINOR = 1;
 
 /// An ID number that refers to an identifier in an AST file.
 ///
@@ -524,13 +524,7 @@ enum ASTRecordTypes {
   /// of source-location information.
   SOURCE_LOCATION_OFFSETS = 14,
 
-  /// Record code for the set of source location entries
-  /// that need to be preloaded by the AST reader.
-  ///
-  /// This set contains the source location entry for the
-  /// predefines buffer and for any file entries that need to be
-  /// preloaded.
-  SOURCE_LOCATION_PRELOADS = 15,
+  // ID 15 used to be for source location entry preloads.
 
   /// Record code for the set of ext_vector type names.
   EXT_VECTOR_DECLS = 16,
diff --git a/clang/include/clang/Serialization/ModuleFile.h 
b/clang/include/clang/Serialization/ModuleFile.h
index 0af5cae6aebc375..48be8676cc26a4c 100644
--- a/clang/include/clang/Serialization/ModuleFile.h
+++ b/clang/include/clang/Serialization/ModuleFile.h
@@ -292,9 +292,6 @@ class ModuleFile {
   /// AST file.
   const uint32_t *SLocEntryOffsets = nullptr;
 
-  /// SLocEntries that we're going to preload.
-  SmallVector PreloadSLocEntries;
-
   /// Remapping table for source locations in this module.
   ContinuousRangeMap
   SLocRemap;
diff --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 0952244d037a77c..e796617455ac390 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -3226,7 +3226,6 @@ llvm::Error ASTReader::ReadASTBlock(ModuleFile ,
   case SOURCE_LOCATION_OFFSETS:
   case MODULE_OFFSET_MAP:
   case SOURCE_MANAGER_LINE_TABLE:
-  case SOURCE_LOCATION_PRELOADS:
   case PPD_ENTITIES_OFFSETS:
   case HEADER_SEARCH_TABLE:
   case IMPORTED_MODULES:
@@ -3576,18 +3575,6 @@ llvm::Error ASTReader::ReadASTBlock(ModuleFile ,
   ParseLineTable(F, Record);
   break;
 
-case SOURCE_LOCATION_PRELOADS: {
-  // Need to transform from the local view (1-based IDs) to the global 
view,
-  // which is based off F.SLocEntryBaseID.
-  if (!F.PreloadSLocEntries.empty())
-return llvm::createStringError(
-std::errc::illegal_byte_sequence,
-"Multiple SOURCE_LOCATION_PRELOADS records in AST file");
-
-  F.PreloadSLocEntries.swap(Record);
-  break;
-}
-
 case EXT_VECTOR_DECLS:
   for (unsigned I = 0, N = Record.size(); I != N; ++I)
 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
@@ -4417,16 +4404,6 @@ ASTReader::ASTReadResult ASTReader::ReadAST(StringRef 
FileName, ModuleKind Type,
   for (ImportedModule  : Loaded) {
 ModuleFile  = *M.Mod;
 
-// Preload SLocEntries.
-for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
-  int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
-  // Load it through the SourceManager and don't call ReadSLocEntry()
-  // directly because the entry may have already been loaded in which case
-  // calling ReadSLocEntry() directly would trigger an assertion in
-  // SourceManager.
-  SourceMgr.getLoadedSLocEntryByID(Index);
-}
-
 // Map the original source file ID into the ID space of the current
 // compilation.
 if (F.OriginalSourceFileID.isValid())
diff --git a/clang/lib/Serialization/ASTWriter.cpp 

[clang] [clang][modules] Remove preloaded SLocEntries from PCM files (PR #66962)

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

jansvoboda11 wrote:

I don't understand why the tie-breaking code calls the previously visited 
`FileID` a parent. We're walking **up** the include/expansion tree, so I think 
it should be called child instead. LMK if I'm misunderstanding.

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


[clang] [clang][modules] Remove preloaded SLocEntries from PCM files (PR #66962)

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

jansvoboda11 wrote:

Turns out some clients are calling `isBeforeInTranslationUnit()` before 
checking if both `SourceLocations` are indeed in the same TU. I left behind a 
FIXME to call `llvm_unreachable()`, but for now, I just compare the `FileIDs` 
to keep things working.

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


[clang] [clang][modules] Remove preloaded SLocEntries from PCM files (PR #66962)

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

jansvoboda11 wrote:

Since I moved up the special-casing of built-ins buffer up in my last commit, 
it was happening before we got chance to walk up from `FileID(3)` to 
`FileID(2)`, meaning it wasn't kicking in. I think we need to sink the 
special-casing into `isInTheSameTranslationUnit()` and apply it to whatever 
`FileID` we end up with after not finding the common ancestor without assuming 
they are in different TUs entirely.

Also, it seems that the code previously assumed that two `SourceLocations` are 
in the same TU iff they have the same common ancestor. There are at least two 
counter-examples to this:
* The built-ins buffer doesn't have any ancestor, but still is part of the TU.
* With implicit modules (or lazy loaded explicit modules), all top-level 
SLocEntries loaded from PCM files have their include location adjusted to the 
import statement, so they became part of the importer SLocEntry tree and are 
all considered to be part of the importing TU.

I started tracking the SLocEntries allocated for each AST file and use that to 
cut off the include chain walk in order to stay in the same TU we started in. 
This basically make sure we don't skip the special case for loaded built-ins 
buffers.

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


[clang] [clang][modules] Remove preloaded SLocEntries from PCM files (PR #66962)

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

jansvoboda11 wrote:

I got around investigating 
"SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp" and found out it uses 
this pattern:
```
%clang_cc1 ... -include %s %s
```

This means `FileID(1)` is the main input file `%s` and `FileID(2)` is the 
built-ins buffer that includes `%s` as `FileID(3)`.

Since I moved up the special-casing of built-ins buffer up in my last commit, 
it was happening **before** we got chance to walk up from `FileID(3)` to 
`FileID(2)`, meaning it wasn't kicking in. I think we need to sink the 
special-casing into `isInTheSameTranslationUnit()` and apply it to whatever 
`FileID` we end up with after not finding the common ancestor.

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


[clang] [clang-format] Fix alignment in presence of template functions (PR #68029)

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


@@ -18525,12 +18525,17 @@ TEST_F(FormatTest, AlignConsecutiveAssignments) {
" a_longer_name_for_wrap}};",
Alignment);
 
-  Alignment.ColumnLimit = 60;
+  Alignment = getLLVMStyleWithColumns(60);
+  Alignment.AlignConsecutiveAssignments.Enabled = true;

owenca wrote:

Is this necessary? If `AlignConsecutiveAssignments` is already on, you can use 
`EXPECT_TRUE` instead.

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


[clang] [clang-format] Fix alignment in presence of template functions (PR #68029)

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

owenca wrote:

Can you add an issue to show the incorrect format before this patch?

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


[clang] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-02 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 457f582ffe23e951380bc345c4c96ec053c09681 
dc0304897ba3f8731bb6062f357fe885ca7e584b -- 
mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
``





View the diff from clang-format here.


``diff
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index b9643be40e13..9eefd1be8ad0 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -662,20 +662,27 @@ convertOmpSingle(omp::SingleOp , 
llvm::IRBuilderBase ,
 }
 
 // Convert an OpenMP Teams construct to LLVM IR using OpenMPIRBuilder
-static LogicalResult convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
, LLVM::ModuleTranslation ) {
+static LogicalResult
+convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase ,
+LLVM::ModuleTranslation ) {
   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
   LogicalResult bodyGenStatus = success();
-  if(op.getNumTeamsLower() || op.getNumTeamsUpper() || op.getIfExpr() || 
op.getThreadLimit() || !op.getAllocatorsVars().empty() || op.getReductions()) {
+  if (op.getNumTeamsLower() || op.getNumTeamsUpper() || op.getIfExpr() ||
+  op.getThreadLimit() || !op.getAllocatorsVars().empty() ||
+  op.getReductions()) {
 return op.emitError("unhandled clauses for translation to LLVM IR");
   }
-  auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP){
-LLVM::ModuleTranslation::SaveStack 
frame(moduleTranslation, allocaIP);
+  auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
+LLVM::ModuleTranslation::SaveStack frame(
+moduleTranslation, allocaIP);
 builder.restoreIP(codegenIP);
-convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder, 
moduleTranslation, bodyGenStatus);
+convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder,
+moduleTranslation, bodyGenStatus);
   };
 
   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
-  builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(ompLoc, 
bodyCB));
+  builder.restoreIP(
+  moduleTranslation.getOpenMPBuilder()->createTeams(ompLoc, bodyCB));
   return bodyGenStatus;
 }
 

``




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


[libunwind] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-02 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 457f582ffe23e951380bc345c4c96ec053c09681 
dc0304897ba3f8731bb6062f357fe885ca7e584b -- 
mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
``





View the diff from clang-format here.


``diff
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index b9643be40e13..9eefd1be8ad0 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -662,20 +662,27 @@ convertOmpSingle(omp::SingleOp , 
llvm::IRBuilderBase ,
 }
 
 // Convert an OpenMP Teams construct to LLVM IR using OpenMPIRBuilder
-static LogicalResult convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
, LLVM::ModuleTranslation ) {
+static LogicalResult
+convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase ,
+LLVM::ModuleTranslation ) {
   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
   LogicalResult bodyGenStatus = success();
-  if(op.getNumTeamsLower() || op.getNumTeamsUpper() || op.getIfExpr() || 
op.getThreadLimit() || !op.getAllocatorsVars().empty() || op.getReductions()) {
+  if (op.getNumTeamsLower() || op.getNumTeamsUpper() || op.getIfExpr() ||
+  op.getThreadLimit() || !op.getAllocatorsVars().empty() ||
+  op.getReductions()) {
 return op.emitError("unhandled clauses for translation to LLVM IR");
   }
-  auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP){
-LLVM::ModuleTranslation::SaveStack 
frame(moduleTranslation, allocaIP);
+  auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
+LLVM::ModuleTranslation::SaveStack frame(
+moduleTranslation, allocaIP);
 builder.restoreIP(codegenIP);
-convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder, 
moduleTranslation, bodyGenStatus);
+convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder,
+moduleTranslation, bodyGenStatus);
   };
 
   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
-  builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(ompLoc, 
bodyCB));
+  builder.restoreIP(
+  moduleTranslation.getOpenMPBuilder()->createTeams(ompLoc, bodyCB));
   return bodyGenStatus;
 }
 

``




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


[clang] [clang][AIX]Fix -flto-jobs for AIX. (PR #67853)

2023-10-02 Thread Qiongsi Wu via cfe-commits

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

LGTM! Thanks! 

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


[libunwind] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-02 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-flang-openmp


Changes

This patch adds translation from `omp.teams` operation to LLVM IR using 
OpenMPIRBuilder. The clauses are not handled in this patch.

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


2 Files Affected:

- (modified) 
mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp (+21) 
- (added) mlir/test/Target/LLVMIR/openmp-teams.mlir (+136) 


``diff
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 8f7f1963b3e5a4f..b9643be40e13c01 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -661,6 +661,24 @@ convertOmpSingle(omp::SingleOp , 
llvm::IRBuilderBase ,
   return bodyGenStatus;
 }
 
+// Convert an OpenMP Teams construct to LLVM IR using OpenMPIRBuilder
+static LogicalResult convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
, LLVM::ModuleTranslation ) {
+  using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+  LogicalResult bodyGenStatus = success();
+  if(op.getNumTeamsLower() || op.getNumTeamsUpper() || op.getIfExpr() || 
op.getThreadLimit() || !op.getAllocatorsVars().empty() || op.getReductions()) {
+return op.emitError("unhandled clauses for translation to LLVM IR");
+  }
+  auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP){
+LLVM::ModuleTranslation::SaveStack 
frame(moduleTranslation, allocaIP);
+builder.restoreIP(codegenIP);
+convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder, 
moduleTranslation, bodyGenStatus);
+  };
+
+  llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
+  builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(ompLoc, 
bodyCB));
+  return bodyGenStatus;
+}
+
 /// Converts an OpenMP task construct into LLVM IR using OpenMPIRBuilder.
 static LogicalResult
 convertOmpTaskOp(omp::TaskOp taskOp, llvm::IRBuilderBase ,
@@ -2406,6 +2424,9 @@ LogicalResult 
OpenMPDialectLLVMIRTranslationInterface::convertOperation(
   .Case([&](omp::SingleOp op) {
 return convertOmpSingle(op, builder, moduleTranslation);
   })
+  .Case([&](omp::TeamsOp op) {
+return convertOmpTeams(op, builder, moduleTranslation);
+  })
   .Case([&](omp::TaskOp op) {
 return convertOmpTaskOp(op, builder, moduleTranslation);
   })
diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
new file mode 100644
index 000..c9005fca94a7c20
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/openmp-teams.mlir
@@ -0,0 +1,136 @@
+// RUN: mlir-translate -mlir-to-llvmir -split-input-file %s | FileCheck %s
+
+llvm.func @foo()
+
+// CHECK-LABEL: @omp_teams_simple
+// CHECK: call void {{.*}} @__kmpc_fork_teams(ptr @{{.+}}, i32 0, ptr 
[[wrapperfn:.+]])
+// CHECK: ret void
+llvm.func @omp_teams_simple() {
+omp.teams {
+llvm.call @foo() : () -> ()
+omp.terminator
+}
+llvm.return
+}
+
+// CHECK: define internal void @[[outlinedfn:.+]]()
+// CHECK:   call void @foo()
+// CHECK:   ret void
+// CHECK: define void [[wrapperfn]](ptr %[[global_tid:.+]], ptr 
%[[bound_tid:.+]])
+// CHECK:   call void @[[outlinedfn]]
+// CHECK:   ret void
+
+// -
+
+llvm.func @foo(i32) -> ()
+
+// CHECK-LABEL: @omp_teams_shared_simple
+// CHECK-SAME: (i32 [[arg0:%.+]])
+// CHECK: [[structArg:%.+]] = alloca { i32 }
+// CHECK: br
+// CHECK: [[gep:%.+]] = getelementptr { i32 }, ptr [[structArg]], i32 0, i32 0
+// CHECK: store i32 [[arg0]], ptr [[gep]]
+// CHECK: call void {{.+}} @__kmpc_fork_teams(ptr @{{.+}}, i32 1, ptr 
[[wrapperfn:.+]], ptr [[structArg]])
+// CHECK: ret void
+llvm.func @omp_teams_shared_simple(%arg0: i32) {
+omp.teams {
+llvm.call @foo(%arg0) : (i32) -> ()
+omp.terminator
+}
+llvm.return
+}
+
+// CHECK: define internal void [[outlinedfn:@.+]](ptr [[structArg:%.+]])
+// CHECK:   [[gep:%.+]] = getelementptr { i32 }, ptr [[structArg]], i32 0, i32 0
+// CHECK:   [[loadgep:%.+]] = load i32, ptr [[gep]]
+// CHECK:   call void @foo(i32 [[loadgep]])
+// CHECK:   ret void
+// CHECK: define void [[wrapperfn]](ptr [[global_tid:.+]], ptr 
[[bound_tid:.+]], ptr [[structArg:.+]])
+// CHECK:   call void [[outlinedfn]](ptr [[structArg]])
+// CHECK:   ret void
+
+// -
+
+llvm.func @my_alloca_fn() -> !llvm.ptr
+llvm.func @foo(i32, f32, !llvm.ptr, f128, !llvm.ptr, i32) -> ()
+llvm.func @bar()
+
+// CHECK-LABEL: @omp_teams_branching_shared
+// CHECK-SAME: (i1 [[condition:%.+]], i32 [[arg0:%.+]], float [[arg1:%.+]], 
ptr [[arg2:%.+]], fp128 [[arg3:%.+]])
+
+// Checking that the allocation for struct argument happens in the alloca 
block.
+// CHECK: [[structArg:%.+]] = alloca { i1, i32, float, ptr, fp128, ptr, i32 }
+// CHECK: [[allocated:%.+]] = call ptr @my_alloca_fn()
+// CHECK: [[loaded:%.+]] = load i32, ptr 

[clang] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-02 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-flang-openmp


Changes

This patch adds translation from `omp.teams` operation to LLVM IR using 
OpenMPIRBuilder. The clauses are not handled in this patch.

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


2 Files Affected:

- (modified) 
mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp (+21) 
- (added) mlir/test/Target/LLVMIR/openmp-teams.mlir (+136) 


``diff
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 8f7f1963b3e5a4f..b9643be40e13c01 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -661,6 +661,24 @@ convertOmpSingle(omp::SingleOp , 
llvm::IRBuilderBase ,
   return bodyGenStatus;
 }
 
+// Convert an OpenMP Teams construct to LLVM IR using OpenMPIRBuilder
+static LogicalResult convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
, LLVM::ModuleTranslation ) {
+  using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+  LogicalResult bodyGenStatus = success();
+  if(op.getNumTeamsLower() || op.getNumTeamsUpper() || op.getIfExpr() || 
op.getThreadLimit() || !op.getAllocatorsVars().empty() || op.getReductions()) {
+return op.emitError("unhandled clauses for translation to LLVM IR");
+  }
+  auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP){
+LLVM::ModuleTranslation::SaveStack 
frame(moduleTranslation, allocaIP);
+builder.restoreIP(codegenIP);
+convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder, 
moduleTranslation, bodyGenStatus);
+  };
+
+  llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
+  builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(ompLoc, 
bodyCB));
+  return bodyGenStatus;
+}
+
 /// Converts an OpenMP task construct into LLVM IR using OpenMPIRBuilder.
 static LogicalResult
 convertOmpTaskOp(omp::TaskOp taskOp, llvm::IRBuilderBase ,
@@ -2406,6 +2424,9 @@ LogicalResult 
OpenMPDialectLLVMIRTranslationInterface::convertOperation(
   .Case([&](omp::SingleOp op) {
 return convertOmpSingle(op, builder, moduleTranslation);
   })
+  .Case([&](omp::TeamsOp op) {
+return convertOmpTeams(op, builder, moduleTranslation);
+  })
   .Case([&](omp::TaskOp op) {
 return convertOmpTaskOp(op, builder, moduleTranslation);
   })
diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
new file mode 100644
index 000..c9005fca94a7c20
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/openmp-teams.mlir
@@ -0,0 +1,136 @@
+// RUN: mlir-translate -mlir-to-llvmir -split-input-file %s | FileCheck %s
+
+llvm.func @foo()
+
+// CHECK-LABEL: @omp_teams_simple
+// CHECK: call void {{.*}} @__kmpc_fork_teams(ptr @{{.+}}, i32 0, ptr 
[[wrapperfn:.+]])
+// CHECK: ret void
+llvm.func @omp_teams_simple() {
+omp.teams {
+llvm.call @foo() : () -> ()
+omp.terminator
+}
+llvm.return
+}
+
+// CHECK: define internal void @[[outlinedfn:.+]]()
+// CHECK:   call void @foo()
+// CHECK:   ret void
+// CHECK: define void [[wrapperfn]](ptr %[[global_tid:.+]], ptr 
%[[bound_tid:.+]])
+// CHECK:   call void @[[outlinedfn]]
+// CHECK:   ret void
+
+// -
+
+llvm.func @foo(i32) -> ()
+
+// CHECK-LABEL: @omp_teams_shared_simple
+// CHECK-SAME: (i32 [[arg0:%.+]])
+// CHECK: [[structArg:%.+]] = alloca { i32 }
+// CHECK: br
+// CHECK: [[gep:%.+]] = getelementptr { i32 }, ptr [[structArg]], i32 0, i32 0
+// CHECK: store i32 [[arg0]], ptr [[gep]]
+// CHECK: call void {{.+}} @__kmpc_fork_teams(ptr @{{.+}}, i32 1, ptr 
[[wrapperfn:.+]], ptr [[structArg]])
+// CHECK: ret void
+llvm.func @omp_teams_shared_simple(%arg0: i32) {
+omp.teams {
+llvm.call @foo(%arg0) : (i32) -> ()
+omp.terminator
+}
+llvm.return
+}
+
+// CHECK: define internal void [[outlinedfn:@.+]](ptr [[structArg:%.+]])
+// CHECK:   [[gep:%.+]] = getelementptr { i32 }, ptr [[structArg]], i32 0, i32 0
+// CHECK:   [[loadgep:%.+]] = load i32, ptr [[gep]]
+// CHECK:   call void @foo(i32 [[loadgep]])
+// CHECK:   ret void
+// CHECK: define void [[wrapperfn]](ptr [[global_tid:.+]], ptr 
[[bound_tid:.+]], ptr [[structArg:.+]])
+// CHECK:   call void [[outlinedfn]](ptr [[structArg]])
+// CHECK:   ret void
+
+// -
+
+llvm.func @my_alloca_fn() -> !llvm.ptr
+llvm.func @foo(i32, f32, !llvm.ptr, f128, !llvm.ptr, i32) -> ()
+llvm.func @bar()
+
+// CHECK-LABEL: @omp_teams_branching_shared
+// CHECK-SAME: (i1 [[condition:%.+]], i32 [[arg0:%.+]], float [[arg1:%.+]], 
ptr [[arg2:%.+]], fp128 [[arg3:%.+]])
+
+// Checking that the allocation for struct argument happens in the alloca 
block.
+// CHECK: [[structArg:%.+]] = alloca { i1, i32, float, ptr, fp128, ptr, i32 }
+// CHECK: [[allocated:%.+]] = call ptr @my_alloca_fn()
+// CHECK: [[loaded:%.+]] = load i32, ptr 

[clang] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR (PR #68042)

2023-10-02 Thread via cfe-commits

https://github.com/shraiysh created 
https://github.com/llvm/llvm-project/pull/68042

This patch adds translation from `omp.teams` operation to LLVM IR using 
OpenMPIRBuilder. The clauses are not handled in this patch.

>From c7c9e907d897ae667331761d8097ccb7852c5d93 Mon Sep 17 00:00:00 2001
From: Shraiysh Vaishay 
Date: Mon, 2 Oct 2023 16:43:13 -0500
Subject: [PATCH] [mlir][OpenMP] Added translation for `omp.teams` to LLVM IR

This patch adds translation from `omp.teams` operation to LLVM IR using
OpenMPIRBuilder.

The clauses are not handled in this patch.
---
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  |  21 +++
 mlir/test/Target/LLVMIR/openmp-teams.mlir | 136 ++
 2 files changed, 157 insertions(+)
 create mode 100644 mlir/test/Target/LLVMIR/openmp-teams.mlir

diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 8f7f1963b3e5a4f..b9643be40e13c01 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -661,6 +661,24 @@ convertOmpSingle(omp::SingleOp , 
llvm::IRBuilderBase ,
   return bodyGenStatus;
 }
 
+// Convert an OpenMP Teams construct to LLVM IR using OpenMPIRBuilder
+static LogicalResult convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
, LLVM::ModuleTranslation ) {
+  using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+  LogicalResult bodyGenStatus = success();
+  if(op.getNumTeamsLower() || op.getNumTeamsUpper() || op.getIfExpr() || 
op.getThreadLimit() || !op.getAllocatorsVars().empty() || op.getReductions()) {
+return op.emitError("unhandled clauses for translation to LLVM IR");
+  }
+  auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP){
+LLVM::ModuleTranslation::SaveStack 
frame(moduleTranslation, allocaIP);
+builder.restoreIP(codegenIP);
+convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder, 
moduleTranslation, bodyGenStatus);
+  };
+
+  llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
+  builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(ompLoc, 
bodyCB));
+  return bodyGenStatus;
+}
+
 /// Converts an OpenMP task construct into LLVM IR using OpenMPIRBuilder.
 static LogicalResult
 convertOmpTaskOp(omp::TaskOp taskOp, llvm::IRBuilderBase ,
@@ -2406,6 +2424,9 @@ LogicalResult 
OpenMPDialectLLVMIRTranslationInterface::convertOperation(
   .Case([&](omp::SingleOp op) {
 return convertOmpSingle(op, builder, moduleTranslation);
   })
+  .Case([&](omp::TeamsOp op) {
+return convertOmpTeams(op, builder, moduleTranslation);
+  })
   .Case([&](omp::TaskOp op) {
 return convertOmpTaskOp(op, builder, moduleTranslation);
   })
diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
new file mode 100644
index 000..c9005fca94a7c20
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/openmp-teams.mlir
@@ -0,0 +1,136 @@
+// RUN: mlir-translate -mlir-to-llvmir -split-input-file %s | FileCheck %s
+
+llvm.func @foo()
+
+// CHECK-LABEL: @omp_teams_simple
+// CHECK: call void {{.*}} @__kmpc_fork_teams(ptr @{{.+}}, i32 0, ptr 
[[wrapperfn:.+]])
+// CHECK: ret void
+llvm.func @omp_teams_simple() {
+omp.teams {
+llvm.call @foo() : () -> ()
+omp.terminator
+}
+llvm.return
+}
+
+// CHECK: define internal void @[[outlinedfn:.+]]()
+// CHECK:   call void @foo()
+// CHECK:   ret void
+// CHECK: define void [[wrapperfn]](ptr %[[global_tid:.+]], ptr 
%[[bound_tid:.+]])
+// CHECK:   call void @[[outlinedfn]]
+// CHECK:   ret void
+
+// -
+
+llvm.func @foo(i32) -> ()
+
+// CHECK-LABEL: @omp_teams_shared_simple
+// CHECK-SAME: (i32 [[arg0:%.+]])
+// CHECK: [[structArg:%.+]] = alloca { i32 }
+// CHECK: br
+// CHECK: [[gep:%.+]] = getelementptr { i32 }, ptr [[structArg]], i32 0, i32 0
+// CHECK: store i32 [[arg0]], ptr [[gep]]
+// CHECK: call void {{.+}} @__kmpc_fork_teams(ptr @{{.+}}, i32 1, ptr 
[[wrapperfn:.+]], ptr [[structArg]])
+// CHECK: ret void
+llvm.func @omp_teams_shared_simple(%arg0: i32) {
+omp.teams {
+llvm.call @foo(%arg0) : (i32) -> ()
+omp.terminator
+}
+llvm.return
+}
+
+// CHECK: define internal void [[outlinedfn:@.+]](ptr [[structArg:%.+]])
+// CHECK:   [[gep:%.+]] = getelementptr { i32 }, ptr [[structArg]], i32 0, i32 0
+// CHECK:   [[loadgep:%.+]] = load i32, ptr [[gep]]
+// CHECK:   call void @foo(i32 [[loadgep]])
+// CHECK:   ret void
+// CHECK: define void [[wrapperfn]](ptr [[global_tid:.+]], ptr 
[[bound_tid:.+]], ptr [[structArg:.+]])
+// CHECK:   call void [[outlinedfn]](ptr [[structArg]])
+// CHECK:   ret void
+
+// -
+
+llvm.func @my_alloca_fn() -> !llvm.ptr
+llvm.func @foo(i32, f32, !llvm.ptr, f128, !llvm.ptr, i32) -> ()
+llvm.func @bar()
+
+// CHECK-LABEL: @omp_teams_branching_shared
+// CHECK-SAME: (i1 [[condition:%.+]], i32 

[libunwind] [OpenMP] Improve omp offload profiler (PR #68016)

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


@@ -79,15 +79,15 @@ struct TimeTraceProfilerEntry {
   // Calculate timings for FlameGraph. Cast time points to microsecond 
precision

jdoerfert wrote:

Can you split the changes to this file into a separate PR? Also check the file, 
the comment still states microseconds.

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const unassigned 
https://github.com/llvm/llvm-project/pull/65148
___
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-02 Thread Konstantin Varlamov via cfe-commits

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,252 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "almost_satisfies_types.h"
+#include "boolean_testable.h"
+#include "test_iterators.h"
+
+struct NotEqualityComparable {};
+
+template 
+concept HasContainsIt = requires(Iter iter, Sent sent) { 
std::ranges::contains(iter, sent, *iter); };
+
+static_assert(HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt, 
SentinelForNotSemiregular>);
+static_assert(!HasContainsIt, 
InputRangeNotSentinelEqualityComparableWith>);
+static_assert(!HasContainsIt, 
sentinel_wrapper>>);
+
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(HasContainsIt);
+
+template 
+concept HasContainsR = requires(Range&& range) { 
std::ranges::contains(std::forward(range), ValT{}); };
+
+static_assert(!HasContainsR);
+static_assert(HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+
+static std::vector comparable_data;
+
+template 
+constexpr void test_iterators() {
+  using ValueT = std::iter_value_t;
+  {  // simple tests
+ValueT a[] = {1, 2, 3, 4, 5, 6};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole.begin(), whole.end(), 3);
+  assert(ret);
+}
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole, 3);
+  assert(ret);
+}
+  }
+
+  { // check that a range with a single element works
+ValueT a[] = {32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 1)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that an empty range works
+ValueT a[] = {};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 1);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 1);
+  assert(!ret);
+}
+  }
+
+  { // check that the first element matches
+ValueT a[] = {32, 3, 2, 1, 0, 23, 21, 9, 40, 100};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 10)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that the last element matches
+ValueT a[] = {3, 22, 1, 43, 99, 0, 56, 100, 32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 9)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // no match
+ValueT a[] = {13, 1, 21, 4, 5};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 10);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 10);
+  assert(!ret);
+}
+  }
+
+  { // check that the projections are used
+int a[] = {1, 9, 0, 13, 25};
+{
+  bool ret = std::ranges::contains(a, a + 5, -13, [&](int i) { return i * 
-1; });
+  assert(ret);
+}
+{
+  auto range = std::ranges::subrange(a, a + 5);
+  bool ret = std::ranges::contains(range, -13, [&](int i) { return i * -1; 
});
+  assert(ret);
+}
+  }
+
+  { // check the nodiscard extension
+// use #pragma around to suppress error: ignoring return value of function
+// declared with 'nodiscard' attribute [-Werror,-Wunused-result]
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-result"
+ValueT a[] = {1, 9, 0, 13, 25};
+auto 

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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,252 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "almost_satisfies_types.h"
+#include "boolean_testable.h"
+#include "test_iterators.h"
+
+struct NotEqualityComparable {};
+
+template 
+concept HasContainsIt = requires(Iter iter, Sent sent) { 
std::ranges::contains(iter, sent, *iter); };
+
+static_assert(HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt, 
SentinelForNotSemiregular>);
+static_assert(!HasContainsIt, 
InputRangeNotSentinelEqualityComparableWith>);
+static_assert(!HasContainsIt, 
sentinel_wrapper>>);
+
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(HasContainsIt);
+
+template 
+concept HasContainsR = requires(Range&& range) { 
std::ranges::contains(std::forward(range), ValT{}); };
+
+static_assert(!HasContainsR);
+static_assert(HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+
+static std::vector comparable_data;
+
+template 
+constexpr void test_iterators() {
+  using ValueT = std::iter_value_t;
+  {  // simple tests
+ValueT a[] = {1, 2, 3, 4, 5, 6};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole.begin(), whole.end(), 3);
+  assert(ret);
+}
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole, 3);
+  assert(ret);
+}
+  }
+
+  { // check that a range with a single element works
+ValueT a[] = {32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 1)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that an empty range works
+ValueT a[] = {};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 1);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 1);
+  assert(!ret);
+}
+  }
+
+  { // check that the first element matches
+ValueT a[] = {32, 3, 2, 1, 0, 23, 21, 9, 40, 100};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 10)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that the last element matches
+ValueT a[] = {3, 22, 1, 43, 99, 0, 56, 100, 32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 9)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // no match
+ValueT a[] = {13, 1, 21, 4, 5};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 10);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 10);
+  assert(!ret);
+}
+  }
+
+  { // check that the projections are used
+int a[] = {1, 9, 0, 13, 25};
+{
+  bool ret = std::ranges::contains(a, a + 5, -13, [&](int i) { return i * 
-1; });
+  assert(ret);
+}
+{
+  auto range = std::ranges::subrange(a, a + 5);
+  bool ret = std::ranges::contains(range, -13, [&](int i) { return i * -1; 
});
+  assert(ret);
+}
+  }
+
+  { // check the nodiscard extension

var-const wrote:

This test should be in 
`libcxx/test/libcxx/diagnostics/nodiscard_extensions.compile.pass.cpp`.

https://github.com/llvm/llvm-project/pull/65148
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,61 @@
+//===--===//
+//
+// 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 

var-const wrote:

Likewise, I don't think we're testing `input_range`.

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,252 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 

var-const wrote:

Nit: `` is probably no longer needed.

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const unassigned 
https://github.com/llvm/llvm-project/pull/65148
___
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-02 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const requested changes to this pull request.

Thanks for addressing most of the feedback! Did another round.

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,252 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "almost_satisfies_types.h"
+#include "boolean_testable.h"
+#include "test_iterators.h"
+
+struct NotEqualityComparable {};
+
+template 
+concept HasContainsIt = requires(Iter iter, Sent sent) { 
std::ranges::contains(iter, sent, *iter); };
+
+static_assert(HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt, 
SentinelForNotSemiregular>);
+static_assert(!HasContainsIt, 
InputRangeNotSentinelEqualityComparableWith>);
+static_assert(!HasContainsIt, 
sentinel_wrapper>>);
+
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(HasContainsIt);
+
+template 
+concept HasContainsR = requires(Range&& range) { 
std::ranges::contains(std::forward(range), ValT{}); };
+
+static_assert(!HasContainsR);
+static_assert(HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+
+static std::vector comparable_data;
+
+template 
+constexpr void test_iterators() {
+  using ValueT = std::iter_value_t;
+  {  // simple tests
+ValueT a[] = {1, 2, 3, 4, 5, 6};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole.begin(), whole.end(), 3);
+  assert(ret);
+}
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole, 3);
+  assert(ret);
+}
+  }
+
+  { // check that a range with a single element works
+ValueT a[] = {32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 1)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that an empty range works
+ValueT a[] = {};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 1);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 1);
+  assert(!ret);
+}
+  }
+
+  { // check that the first element matches
+ValueT a[] = {32, 3, 2, 1, 0, 23, 21, 9, 40, 100};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 10)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that the last element matches
+ValueT a[] = {3, 22, 1, 43, 99, 0, 56, 100, 32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 9)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // no match
+ValueT a[] = {13, 1, 21, 4, 5};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 10);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 10);
+  assert(!ret);
+}
+  }
+
+  { // check that the projections are used
+int a[] = {1, 9, 0, 13, 25};
+{
+  bool ret = std::ranges::contains(a, a + 5, -13, [&](int i) { return i * 
-1; });
+  assert(ret);
+}
+{
+  auto range = std::ranges::subrange(a, a + 5);
+  bool ret = std::ranges::contains(range, -13, [&](int i) { return i * -1; 
});
+  assert(ret);
+}
+  }
+
+  { // check the nodiscard extension
+// use #pragma around to suppress error: ignoring return value of function
+// declared with 'nodiscard' attribute [-Werror,-Wunused-result]
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-result"
+ValueT a[] = {1, 9, 0, 13, 25};
+auto 

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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,252 @@
+//===--===//

var-const wrote:

Can you please go through various `robust` test files and add tests for 
`contains` where it makes sense? Let me know if you need any help with that!

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,252 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 

var-const wrote:

Nit: `` is probably no longer needed.

https://github.com/llvm/llvm-project/pull/65148
___
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-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,252 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "almost_satisfies_types.h"
+#include "boolean_testable.h"
+#include "test_iterators.h"
+
+struct NotEqualityComparable {};
+
+template 
+concept HasContainsIt = requires(Iter iter, Sent sent) { 
std::ranges::contains(iter, sent, *iter); };
+
+static_assert(HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt, 
SentinelForNotSemiregular>);
+static_assert(!HasContainsIt, 
InputRangeNotSentinelEqualityComparableWith>);
+static_assert(!HasContainsIt, 
sentinel_wrapper>>);
+
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(HasContainsIt);
+
+template 
+concept HasContainsR = requires(Range&& range) { 
std::ranges::contains(std::forward(range), ValT{}); };
+
+static_assert(!HasContainsR);
+static_assert(HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+
+static std::vector comparable_data;
+
+template 
+constexpr void test_iterators() {
+  using ValueT = std::iter_value_t;
+  {  // simple tests
+ValueT a[] = {1, 2, 3, 4, 5, 6};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole.begin(), whole.end(), 3);
+  assert(ret);
+}
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole, 3);
+  assert(ret);
+}
+  }
+
+  { // check that a range with a single element works
+ValueT a[] = {32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 1)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that an empty range works
+ValueT a[] = {};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 1);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 1);
+  assert(!ret);
+}
+  }
+
+  { // check that the first element matches
+ValueT a[] = {32, 3, 2, 1, 0, 23, 21, 9, 40, 100};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 10)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that the last element matches
+ValueT a[] = {3, 22, 1, 43, 99, 0, 56, 100, 32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 9)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // no match
+ValueT a[] = {13, 1, 21, 4, 5};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 10);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 10);
+  assert(!ret);
+}
+  }
+
+  { // check that the projections are used
+int a[] = {1, 9, 0, 13, 25};
+{
+  bool ret = std::ranges::contains(a, a + 5, -13, [&](int i) { return i * 
-1; });
+  assert(ret);
+}
+{
+  auto range = std::ranges::subrange(a, a + 5);
+  bool ret = std::ranges::contains(range, -13, [&](int i) { return i * -1; 
});
+  assert(ret);
+}
+  }
+
+  { // check the nodiscard extension

var-const wrote:

This test should be in 
`libcxx/test/libcxx/diagnostics/nodiscard_extensions.compile.pass.cpp`.

https://github.com/llvm/llvm-project/pull/65148
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,61 @@
+//===--===//
+//
+// 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);

var-const wrote:

Nit: I think this line is a little over the max width.

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


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

2023-10-02 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,252 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// 
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, 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
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include "almost_satisfies_types.h"
+#include "boolean_testable.h"
+#include "test_iterators.h"
+
+struct NotEqualityComparable {};
+
+template 
+concept HasContainsIt = requires(Iter iter, Sent sent) { 
std::ranges::contains(iter, sent, *iter); };
+
+static_assert(HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt, 
SentinelForNotSemiregular>);
+static_assert(!HasContainsIt, 
InputRangeNotSentinelEqualityComparableWith>);
+static_assert(!HasContainsIt, 
sentinel_wrapper>>);
+
+static_assert(!HasContainsIt);
+static_assert(!HasContainsIt);
+static_assert(HasContainsIt);
+
+template 
+concept HasContainsR = requires(Range&& range) { 
std::ranges::contains(std::forward(range), ValT{}); };
+
+static_assert(!HasContainsR);
+static_assert(HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+static_assert(!HasContainsR);
+
+static std::vector comparable_data;
+
+template 
+constexpr void test_iterators() {
+  using ValueT = std::iter_value_t;
+  {  // simple tests
+ValueT a[] = {1, 2, 3, 4, 5, 6};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 6)));
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole.begin(), whole.end(), 3);
+  assert(ret);
+}
+{
+  [[maybe_unused]] std::same_as decltype(auto) ret =
+std::ranges::contains(whole, 3);
+  assert(ret);
+}
+  }
+
+  { // check that a range with a single element works
+ValueT a[] = {32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 1)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that an empty range works
+ValueT a[] = {};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 1);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 1);
+  assert(!ret);
+}
+  }
+
+  { // check that the first element matches
+ValueT a[] = {32, 3, 2, 1, 0, 23, 21, 9, 40, 100};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 10)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // check that the last element matches
+ValueT a[] = {3, 22, 1, 43, 99, 0, 56, 100, 32};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 9)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 32);
+  assert(ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 32);
+  assert(ret);
+}
+  }
+
+  { // no match
+ValueT a[] = {13, 1, 21, 4, 5};
+auto whole = std::ranges::subrange(Iter(a), Sent(Iter(a + 5)));
+{
+  bool ret = std::ranges::contains(whole.begin(), whole.end(), 10);
+  assert(!ret);
+}
+{
+  bool ret = std::ranges::contains(whole, 10);
+  assert(!ret);
+}
+  }
+
+  { // check that the projections are used
+int a[] = {1, 9, 0, 13, 25};
+{
+  bool ret = std::ranges::contains(a, a + 5, -13, [&](int i) { return i * 
-1; });
+  assert(ret);
+}
+{
+  auto range = std::ranges::subrange(a, a + 5);
+  bool ret = std::ranges::contains(range, -13, [&](int i) { return i * -1; 
});
+  assert(ret);
+}
+  }
+
+  { // check the nodiscard extension
+// use #pragma around to suppress error: ignoring return value of function
+// declared with 'nodiscard' attribute [-Werror,-Wunused-result]
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-result"
+ValueT a[] = {1, 9, 0, 13, 25};
+auto 

[clang] [Inliner] Improve propagation of return attributes. (PR #67756)

2023-10-02 Thread via cfe-commits

goldsteinn wrote:

> Apart from that, the functional changes themselves look good to me.

Fixed. Okay to push?

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


[clang] [clang] use absolute path for builtin headers during module compilation (PR #68023)

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

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

>From a44aa3a04dd6391cf4660cefe451ac1d53aa429d Mon Sep 17 00:00:00 2001
From: Richard Howell 
Date: Mon, 2 Oct 2023 11:10:52 -0700
Subject: [PATCH] [clang] use absolute path for builtin headers during module
 compilation

When including builtin headers as part of a system module, ensure
we use absolute paths to those headers. Otherwise the module will
fail to compile when specifying relative resource directories.
---
 clang/lib/Lex/ModuleMap.cpp   | 4 
 .../test/Modules/Inputs/builtin-headers/module.modulemap  | 3 +++
 clang/test/Modules/relative-resource-dir.m| 8 
 3 files changed, 15 insertions(+)
 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/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index e8437572ebf4bf6..80ffdee2e025bc4 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -348,6 +348,10 @@ bool ModuleMap::resolveAsBuiltinHeader(
   if (!File)
 return false;
 
+  // Ensure the path to the module directory is absolute, otherwise
+  // builtin headers will fail to resolve when using relative resource
+  // directory paths without a -I.
+  SourceMgr.getFileManager().makeAbsolutePath(Path);
   auto Role = headerKindToRole(Header.Kind);
   Module::Header H = {Header.FileName, std::string(Path.str()), *File};
   addHeader(Mod, H, Role);
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 [system] {
+header "float.h"
+}
\ No newline at end of file
diff --git a/clang/test/Modules/relative-resource-dir.m 
b/clang/test/Modules/relative-resource-dir.m
new file mode 100644
index 000..1d38fe922e71849
--- /dev/null
+++ b/clang/test/Modules/relative-resource-dir.m
@@ -0,0 +1,8 @@
+// RUN: EXPECTED_RESOURCE_DIR=`%clang -print-resource-dir` && \
+// RUN:  mkdir -p %t && rm -rf %t/resource-dir && \
+// RUN:  cp -R $EXPECTED_RESOURCE_DIR %t/resource-dir
+// RUN: cd %t && %clang -cc1 -x objective-c -fmodules -fmodule-format=obj \
+// RUN:   -fimplicit-module-maps -fmodules-cache-path=%t.mcp \
+// RUN:   -fbuiltin-headers-in-system-modules -resource-dir resource-dir \
+// RUN:   -emit-module %S/Inputs/builtin-headers/module.modulemap \
+// RUN:   -fmodule-name=ModuleWithBuiltinHeader -o %t.pcm

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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

2023-10-02 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 55d8f0cd31311ed3ebc85bef2c9b5cfca1579076 
3724f695e7699840998d8af16a60f02f90f64b95 -- 
clang/lib/AST/Interp/ByteCodeExprGen.cpp clang/lib/AST/Interp/ByteCodeExprGen.h 
clang/test/AST/Interp/arrays.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 27848e7bb732..bcca8a3a87d0 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -828,12 +828,12 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 
 template 
 bool ByteCodeExprGen::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
-  if(OpaqueExprs.contains(E))
+  if (OpaqueExprs.contains(E))
 return this->emitGetLocal(*classify(E), OpaqueExprs[E], E);
 
   if (Initializing)
 return this->visitInitializer(E->getSourceExpr());
-  
+
   return this->visit(E->getSourceExpr());
 }
 
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 0e69eee128f4..1a66a8b76dcb 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -484,19 +484,21 @@ template  class StoredOpaqueValueScope 
final {
 public:
   StoredOpaqueValueScope(ByteCodeExprGen *Ctx) : Ctx(Ctx) {}
 
-  bool VisitAndStoreOpaqueValue(const OpaqueValueExpr* Ove) {
+  bool VisitAndStoreOpaqueValue(const OpaqueValueExpr *Ove) {
 assert(Ove && "OpaqueValueExpr is a nullptr!");
-assert(!Ctx->OpaqueExprs.contains(Ove) && "OpaqueValueExpr already 
stored!");
+assert(!Ctx->OpaqueExprs.contains(Ove) &&
+   "OpaqueValueExpr already stored!");
 
 std::optional CommonTy = Ctx->classify(Ove);
-std::optional LocalIndex = Ctx->allocateLocalPrimitive(Ove, 
*CommonTy, Ove->getType().isConstQualified());
+std::optional LocalIndex = Ctx->allocateLocalPrimitive(
+Ove, *CommonTy, Ove->getType().isConstQualified());
 if (!LocalIndex)
   return false;
 
 if (!Ctx->visit(Ove))
   return false;
 
-if(!Ctx->emitSetLocal(*CommonTy, *LocalIndex, Ove))
+if (!Ctx->emitSetLocal(*CommonTy, *LocalIndex, Ove))
   return false;
 
 Ctx->OpaqueExprs.insert({Ove, *LocalIndex});
@@ -506,13 +508,13 @@ public:
   }
 
   ~StoredOpaqueValueScope() {
-for(const auto *SV : StoredValues)
+for (const auto *SV : StoredValues)
   Ctx->OpaqueExprs.erase(SV);
   }
 
 private:
   ByteCodeExprGen *Ctx;
-  std::vector StoredValues;
+  std::vector StoredValues;
 };
 
 } // namespace interp

``




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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

2023-10-02 Thread via cfe-commits

https://github.com/isuckatcs updated 
https://github.com/llvm/llvm-project/pull/68039

>From baf0fc082f2cfa86346a93b22c39b92e9e7e261b Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Mon, 2 Oct 2023 22:29:14 +0200
Subject: [PATCH 1/4] impl

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 21 +---
 clang/lib/AST/Interp/ByteCodeExprGen.h   | 25 
 clang/test/AST/Interp/arrays.cpp |  6 +-
 3 files changed, 44 insertions(+), 8 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 46906377863bd74..b2cf34ac8c45bbb 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -792,9 +792,20 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 const ArrayInitLoopExpr *E) {
   assert(Initializing);
   assert(!DiscardResult);
-  // TODO: This compiles to quite a lot of bytecode if the array is larger.
-  //   Investigate compiling this to a loop, or at least try to use
-  //   the AILE's Common expr.
+
+  const auto *CommonExpr = E->getCommonExpr();
+  std::optional CommonTy = classify(CommonExpr);
+
+  std::optional LocalIndex = 
this->allocateLocalPrimitive(CommonExpr, *CommonTy, 
CommonExpr->getType().isConstQualified());
+  if (!LocalIndex)
+return false;
+  if (!this->visit(CommonExpr))
+return false;
+  if(!this->emitSetLocal(*CommonTy, *LocalIndex, E))
+return false;
+
+  StoredOpaqueValueScope KnownOpaqueScope(this, *LocalIndex);
+
   const Expr *SubExpr = E->getSubExpr();
   size_t Size = E->getArraySize().getZExtValue();
   std::optional ElemT = classify(SubExpr->getType());
@@ -827,8 +838,12 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 
 template 
 bool ByteCodeExprGen::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
+  if(IgnoreOpaqueValue)
+return this->emitGetLocal(*classify(E), *OpaqueValueIndex, E);
+
   if (Initializing)
 return this->visitInitializer(E->getSourceExpr());
+  
   return this->visit(E->getSourceExpr());
 }
 
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 47a3f75f13459d0..f58def7a3245ca6 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -36,6 +36,7 @@ template  class DeclScope;
 template  class OptionScope;
 template  class ArrayIndexScope;
 template  class SourceLocScope;
+template  class StoredOpaqueValueScope;
 
 /// Compilation context for expressions.
 template 
@@ -219,6 +220,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   friend class OptionScope;
   friend class ArrayIndexScope;
   friend class SourceLocScope;
+  friend class StoredOpaqueValueScope;
 
   /// Emits a zero initializer.
   bool visitZeroInitializer(QualType QT, const Expr *E);
@@ -303,6 +305,10 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   /// Flag inidicating if we're initializing an already created
   /// variable. This is set in visitInitializer().
   bool Initializing = false;
+
+  /// Flag indicating if we ignore an OpaqueValueExpr.
+  bool IgnoreOpaqueValue = false;
+  std::optional OpaqueValueIndex;
 };
 
 extern template class ByteCodeExprGen;
@@ -478,6 +484,25 @@ template  class SourceLocScope final {
   bool Enabled = false;
 };
 
+template  class StoredOpaqueValueScope final {
+public:
+  StoredOpaqueValueScope(ByteCodeExprGen *Ctx, uint64_t LocalIndex, 
bool ignore = true)
+  : Ctx(Ctx), OldIgnoreValue(Ctx->IgnoreOpaqueValue), 
OldLocalIndex(Ctx->OpaqueValueIndex) {
+Ctx->IgnoreOpaqueValue = ignore;
+Ctx->OpaqueValueIndex = LocalIndex;
+  }
+
+  ~StoredOpaqueValueScope() {
+  Ctx->IgnoreOpaqueValue = OldIgnoreValue;
+  Ctx->OpaqueValueIndex = OldLocalIndex;
+  }
+
+private:
+  ByteCodeExprGen *Ctx;
+  bool OldIgnoreValue;
+  std::optional OldLocalIndex;
+};
+
 } // namespace interp
 } // namespace clang
 
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..1f8908f2bed0b24 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -352,9 +352,6 @@ namespace ZeroInit {
 }
 
 namespace ArrayInitLoop {
-  /// FIXME: The ArrayInitLoop for the decomposition initializer in g() has
-  /// f(n) as its CommonExpr. We need to evaluate that exactly once and not
-  /// N times as we do right now.
   struct X {
   int arr[3];
   };
@@ -366,8 +363,7 @@ namespace ArrayInitLoop {
   auto [a, b, c] = f(n).arr;
   return a + b + c;
   }
-  static_assert(g() == 6); // expected-error {{failed}} \
-   // expected-note {{15 == 6}}
+  static_assert(g() == 6);
 }
 
 namespace StringZeroFill {

>From 3724f695e7699840998d8af16a60f02f90f64b95 Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Mon, 2 Oct 2023 22:51:58 +0200
Subject: [PATCH 2/4] cleanup

---
 

[PATCH] D145214: [TSAN] add support for riscv64

2023-10-02 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: compiler-rt/lib/tsan/rtl/CMakeLists.txt:5
 append_list_if(COMPILER_RT_HAS_MSSE4_2_FLAG -msse4.2 TSAN_RTL_CFLAGS)
-append_list_if(SANITIZER_LIMIT_FRAME_SIZE -Wframe-larger-than=530
+append_list_if(SANITIZER_LIMIT_FRAME_SIZE -Wframe-larger-than=656
TSAN_RTL_CFLAGS)

hiraditya wrote:
> dvyukov wrote:
> > vitalybuka wrote:
> > > Maybe this one is not needed after 
> > > b31bd6d8046d01a66aa92993bacb56b115a67fc5
> > Yes, is this needed? What function does have larger frame?
> > If we increase the limit, other arches will slowly slinetly degrade too.
> yeah probably not needed anymore. but if we need this we can just change this 
> only for RISC-V?
I would rather diagnose and fix whatever makes RISC-V code generation less 
efficient


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145214

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


[clang] [clang] Predefined macros for float128 support (PR #67196)

2023-10-02 Thread Pranav Kant via cfe-commits

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


[clang] 457f582 - [clang] Predefined macros for float128 support (#67196)

2023-10-02 Thread via cfe-commits

Author: Pranav Kant
Date: 2023-10-02T14:14:52-07:00
New Revision: 457f582ffe23e951380bc345c4c96ec053c09681

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

LOG: [clang] Predefined macros for float128 support (#67196)

Expose some predefined macros for Float128 support.

Added: 


Modified: 
clang/lib/Frontend/InitPreprocessor.cpp
clang/test/Preprocessor/init-x86.c
clang/test/Preprocessor/init.c

Removed: 




diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index e5db8a654e6707d..9e4d4d398a21da5 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -1076,6 +1076,8 @@ static void InitializePredefinedMacros(const TargetInfo 
,
   DefineFloatMacros(Builder, "FLT", (), "F");
   DefineFloatMacros(Builder, "DBL", (), "");
   DefineFloatMacros(Builder, "LDBL", (), "L");
+  if (TI.hasFloat128Type())
+DefineFloatMacros(Builder, "FLT128", (), "Q");
 
   // Define a __POINTER_WIDTH__ macro for stdint.h.
   Builder.defineMacro("__POINTER_WIDTH__",

diff  --git a/clang/test/Preprocessor/init-x86.c 
b/clang/test/Preprocessor/init-x86.c
index 58be9b716571747..1ee770df0c4a303 100644
--- a/clang/test/Preprocessor/init-x86.c
+++ b/clang/test/Preprocessor/init-x86.c
@@ -1023,6 +1023,21 @@
 // X86_64-LINUX:#define __DBL_MIN_EXP__ (-1021)
 // X86_64-LINUX:#define __DBL_MIN__ 2.2250738585072014e-308
 // X86_64-LINUX:#define __DECIMAL_DIG__ __LDBL_DECIMAL_DIG__
+// X86_64-LINUX:#define __FLOAT128__ 1
+// X86_64-LINUX:#define __FLT128_DECIMAL_DIG__ 36
+// X86_64-LINUX:#define __FLT128_DENORM_MIN__ 
6.47517511943802511092443895822764655e-4966Q
+// X86_64-LINUX:#define __FLT128_DIG__ 33
+// X86_64-LINUX:#define __FLT128_EPSILON__ 
1.92592994438723585305597794258492732e-34Q
+// X86_64-LINUX:#define __FLT128_HAS_DENORM__ 1
+// X86_64-LINUX:#define __FLT128_HAS_INFINITY__ 1
+// X86_64-LINUX:#define __FLT128_HAS_QUIET_NAN__ 1
+// X86_64-LINUX:#define __FLT128_MANT_DIG__ 113
+// X86_64-LINUX:#define __FLT128_MAX_10_EXP__ 4932
+// X86_64-LINUX:#define __FLT128_MAX_EXP__ 16384
+// X86_64-LINUX:#define __FLT128_MAX__ 
1.18973149535723176508575932662800702e+4932Q
+// X86_64-LINUX:#define __FLT128_MIN_10_EXP__ (-4931)
+// X86_64-LINUX:#define __FLT128_MIN_EXP__ (-16381)
+// X86_64-LINUX:#define __FLT128_MIN__ 
3.36210314311209350626267781732175260e-4932Q
 // X86_64-LINUX:#define __FLT_DENORM_MIN__ 1.40129846e-45F
 // X86_64-LINUX:#define __FLT_DIG__ 6
 // X86_64-LINUX:#define __FLT_EPSILON__ 1.19209290e-7F

diff  --git a/clang/test/Preprocessor/init.c b/clang/test/Preprocessor/init.c
index 59c5122afe1e4c3..395c4cebfa5be76 100644
--- a/clang/test/Preprocessor/init.c
+++ b/clang/test/Preprocessor/init.c
@@ -1576,6 +1576,20 @@
 // EMSCRIPTEN-NEXT:#define __EMSCRIPTEN__ 1
 // WEBASSEMBLY-NEXT:#define __FINITE_MATH_ONLY__ 0
 // WEBASSEMBLY-NEXT:#define __FLOAT128__ 1
+// WEBASSEMBLY-NEXT:#define __FLT128_DECIMAL_DIG__ 36
+// WEBASSEMBLY-NEXT:#define __FLT128_DENORM_MIN__ 
6.47517511943802511092443895822764655e-4966Q
+// WEBASSEMBLY-NEXT:#define __FLT128_DIG__ 33
+// WEBASSEMBLY-NEXT:#define __FLT128_EPSILON__ 
1.92592994438723585305597794258492732e-34Q
+// WEBASSEMBLY-NEXT:#define __FLT128_HAS_DENORM__ 1
+// WEBASSEMBLY-NEXT:#define __FLT128_HAS_INFINITY__ 1
+// WEBASSEMBLY-NEXT:#define __FLT128_HAS_QUIET_NAN__ 1
+// WEBASSEMBLY-NEXT:#define __FLT128_MANT_DIG__ 113
+// WEBASSEMBLY-NEXT:#define __FLT128_MAX_10_EXP__ 4932
+// WEBASSEMBLY-NEXT:#define __FLT128_MAX_EXP__ 16384
+// WEBASSEMBLY-NEXT:#define __FLT128_MAX__ 
1.18973149535723176508575932662800702e+4932Q
+// WEBASSEMBLY-NEXT:#define __FLT128_MIN_10_EXP__ (-4931)
+// WEBASSEMBLY-NEXT:#define __FLT128_MIN_EXP__ (-16381)
+// WEBASSEMBLY-NEXT:#define __FLT128_MIN__ 
3.36210314311209350626267781732175260e-4932Q
 // WEBASSEMBLY-NOT:#define __FLT16_DECIMAL_DIG__
 // WEBASSEMBLY-NOT:#define __FLT16_DENORM_MIN__
 // WEBASSEMBLY-NOT:#define __FLT16_DIG__



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


[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

2023-10-02 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

At the moment in `Interp` the source array initialization (`getCommonExpr()`) 
of an `ArrayInitLoopExpr` is evaluated during every iteration, when it should 
only be evaluated once.

The initializer is always wrapped inside an `OpaqueValueExpr`, which in 
`ExprConstant` is evaluated once per scope and their result is stored so that 
the next time `ExprConstant` sees the same expression, it can return the result 
only.

This patch intents to achieve a similar functionality inside `Interp` by 
storing the result of the `OpaqueValueExpr` in a local variable.

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


3 Files Affected:

- (modified) clang/lib/AST/Interp/ByteCodeExprGen.cpp (+7-3) 
- (modified) clang/lib/AST/Interp/ByteCodeExprGen.h (+39) 
- (modified) clang/test/AST/Interp/arrays.cpp (+1-5) 


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 46906377863bd74..d79cc77c5c38952 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -792,9 +792,10 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 const ArrayInitLoopExpr *E) {
   assert(Initializing);
   assert(!DiscardResult);
-  // TODO: This compiles to quite a lot of bytecode if the array is larger.
-  //   Investigate compiling this to a loop, or at least try to use
-  //   the AILE's Common expr.
+
+  StoredOpaqueValueScope StoredOpaqueScope(this);
+  StoredOpaqueScope.VisitAndStoreOpaqueValue(E->getCommonExpr());
+
   const Expr *SubExpr = E->getSubExpr();
   size_t Size = E->getArraySize().getZExtValue();
   std::optional ElemT = classify(SubExpr->getType());
@@ -827,6 +828,9 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 
 template 
 bool ByteCodeExprGen::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
+  if (OpaqueExprs.contains(E))
+return this->emitGetLocal(*classify(E), OpaqueExprs[E], E);
+
   if (Initializing)
 return this->visitInitializer(E->getSourceExpr());
   return this->visit(E->getSourceExpr());
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 47a3f75f13459d0..1a66a8b76dcbf41 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -36,6 +36,7 @@ template  class DeclScope;
 template  class OptionScope;
 template  class ArrayIndexScope;
 template  class SourceLocScope;
+template  class StoredOpaqueValueScope;
 
 /// Compilation context for expressions.
 template 
@@ -219,6 +220,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   friend class OptionScope;
   friend class ArrayIndexScope;
   friend class SourceLocScope;
+  friend class StoredOpaqueValueScope;
 
   /// Emits a zero initializer.
   bool visitZeroInitializer(QualType QT, const Expr *E);
@@ -478,6 +480,43 @@ template  class SourceLocScope final {
   bool Enabled = false;
 };
 
+template  class StoredOpaqueValueScope final {
+public:
+  StoredOpaqueValueScope(ByteCodeExprGen *Ctx) : Ctx(Ctx) {}
+
+  bool VisitAndStoreOpaqueValue(const OpaqueValueExpr *Ove) {
+assert(Ove && "OpaqueValueExpr is a nullptr!");
+assert(!Ctx->OpaqueExprs.contains(Ove) &&
+   "OpaqueValueExpr already stored!");
+
+std::optional CommonTy = Ctx->classify(Ove);
+std::optional LocalIndex = Ctx->allocateLocalPrimitive(
+Ove, *CommonTy, Ove->getType().isConstQualified());
+if (!LocalIndex)
+  return false;
+
+if (!Ctx->visit(Ove))
+  return false;
+
+if (!Ctx->emitSetLocal(*CommonTy, *LocalIndex, Ove))
+  return false;
+
+Ctx->OpaqueExprs.insert({Ove, *LocalIndex});
+StoredValues.emplace_back(Ove);
+
+return true;
+  }
+
+  ~StoredOpaqueValueScope() {
+for (const auto *SV : StoredValues)
+  Ctx->OpaqueExprs.erase(SV);
+  }
+
+private:
+  ByteCodeExprGen *Ctx;
+  std::vector StoredValues;
+};
+
 } // namespace interp
 } // namespace clang
 
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..1f8908f2bed0b24 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -352,9 +352,6 @@ namespace ZeroInit {
 }
 
 namespace ArrayInitLoop {
-  /// FIXME: The ArrayInitLoop for the decomposition initializer in g() has
-  /// f(n) as its CommonExpr. We need to evaluate that exactly once and not
-  /// N times as we do right now.
   struct X {
   int arr[3];
   };
@@ -366,8 +363,7 @@ namespace ArrayInitLoop {
   auto [a, b, c] = f(n).arr;
   return a + b + c;
   }
-  static_assert(g() == 6); // expected-error {{failed}} \
-   // expected-note {{15 == 6}}
+  static_assert(g() == 6);
 }
 
 namespace StringZeroFill {

``




https://github.com/llvm/llvm-project/pull/68039
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

2023-10-02 Thread via cfe-commits

https://github.com/isuckatcs updated 
https://github.com/llvm/llvm-project/pull/68039

>From baf0fc082f2cfa86346a93b22c39b92e9e7e261b Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Mon, 2 Oct 2023 22:29:14 +0200
Subject: [PATCH 1/3] impl

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 21 +---
 clang/lib/AST/Interp/ByteCodeExprGen.h   | 25 
 clang/test/AST/Interp/arrays.cpp |  6 +-
 3 files changed, 44 insertions(+), 8 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 46906377863bd74..b2cf34ac8c45bbb 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -792,9 +792,20 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 const ArrayInitLoopExpr *E) {
   assert(Initializing);
   assert(!DiscardResult);
-  // TODO: This compiles to quite a lot of bytecode if the array is larger.
-  //   Investigate compiling this to a loop, or at least try to use
-  //   the AILE's Common expr.
+
+  const auto *CommonExpr = E->getCommonExpr();
+  std::optional CommonTy = classify(CommonExpr);
+
+  std::optional LocalIndex = 
this->allocateLocalPrimitive(CommonExpr, *CommonTy, 
CommonExpr->getType().isConstQualified());
+  if (!LocalIndex)
+return false;
+  if (!this->visit(CommonExpr))
+return false;
+  if(!this->emitSetLocal(*CommonTy, *LocalIndex, E))
+return false;
+
+  StoredOpaqueValueScope KnownOpaqueScope(this, *LocalIndex);
+
   const Expr *SubExpr = E->getSubExpr();
   size_t Size = E->getArraySize().getZExtValue();
   std::optional ElemT = classify(SubExpr->getType());
@@ -827,8 +838,12 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 
 template 
 bool ByteCodeExprGen::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
+  if(IgnoreOpaqueValue)
+return this->emitGetLocal(*classify(E), *OpaqueValueIndex, E);
+
   if (Initializing)
 return this->visitInitializer(E->getSourceExpr());
+  
   return this->visit(E->getSourceExpr());
 }
 
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 47a3f75f13459d0..f58def7a3245ca6 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -36,6 +36,7 @@ template  class DeclScope;
 template  class OptionScope;
 template  class ArrayIndexScope;
 template  class SourceLocScope;
+template  class StoredOpaqueValueScope;
 
 /// Compilation context for expressions.
 template 
@@ -219,6 +220,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   friend class OptionScope;
   friend class ArrayIndexScope;
   friend class SourceLocScope;
+  friend class StoredOpaqueValueScope;
 
   /// Emits a zero initializer.
   bool visitZeroInitializer(QualType QT, const Expr *E);
@@ -303,6 +305,10 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   /// Flag inidicating if we're initializing an already created
   /// variable. This is set in visitInitializer().
   bool Initializing = false;
+
+  /// Flag indicating if we ignore an OpaqueValueExpr.
+  bool IgnoreOpaqueValue = false;
+  std::optional OpaqueValueIndex;
 };
 
 extern template class ByteCodeExprGen;
@@ -478,6 +484,25 @@ template  class SourceLocScope final {
   bool Enabled = false;
 };
 
+template  class StoredOpaqueValueScope final {
+public:
+  StoredOpaqueValueScope(ByteCodeExprGen *Ctx, uint64_t LocalIndex, 
bool ignore = true)
+  : Ctx(Ctx), OldIgnoreValue(Ctx->IgnoreOpaqueValue), 
OldLocalIndex(Ctx->OpaqueValueIndex) {
+Ctx->IgnoreOpaqueValue = ignore;
+Ctx->OpaqueValueIndex = LocalIndex;
+  }
+
+  ~StoredOpaqueValueScope() {
+  Ctx->IgnoreOpaqueValue = OldIgnoreValue;
+  Ctx->OpaqueValueIndex = OldLocalIndex;
+  }
+
+private:
+  ByteCodeExprGen *Ctx;
+  bool OldIgnoreValue;
+  std::optional OldLocalIndex;
+};
+
 } // namespace interp
 } // namespace clang
 
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..1f8908f2bed0b24 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -352,9 +352,6 @@ namespace ZeroInit {
 }
 
 namespace ArrayInitLoop {
-  /// FIXME: The ArrayInitLoop for the decomposition initializer in g() has
-  /// f(n) as its CommonExpr. We need to evaluate that exactly once and not
-  /// N times as we do right now.
   struct X {
   int arr[3];
   };
@@ -366,8 +363,7 @@ namespace ArrayInitLoop {
   auto [a, b, c] = f(n).arr;
   return a + b + c;
   }
-  static_assert(g() == 6); // expected-error {{failed}} \
-   // expected-note {{15 == 6}}
+  static_assert(g() == 6);
 }
 
 namespace StringZeroFill {

>From 3724f695e7699840998d8af16a60f02f90f64b95 Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Mon, 2 Oct 2023 22:51:58 +0200
Subject: [PATCH 2/3] cleanup

---
 

[clang] [clang][Interp] Only evaluate the source array initialization of an `ArrayInitLoopExpr` once (PR #68039)

2023-10-02 Thread via cfe-commits

https://github.com/isuckatcs created 
https://github.com/llvm/llvm-project/pull/68039

At the moment in `Interp` the source array initialization (`getCommonExpr()`) 
of an `ArrayInitLoopExpr` is evaluated during every iteration, when it should 
only be evaluated once.

The initializer is always wrapped inside an `OpaqueValueExpr`, which in 
`ExprConstant` is evaluated once per scope and their result is stored so that 
the next time `ExprConstant` sees the same expression, it can return the result 
only.

This patch intents to achieve a similar functionality inside `Interp` by 
storing the result of the `OpaqueValueExpr` in a local variable.

>From baf0fc082f2cfa86346a93b22c39b92e9e7e261b Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Mon, 2 Oct 2023 22:29:14 +0200
Subject: [PATCH 1/2] impl

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 21 +---
 clang/lib/AST/Interp/ByteCodeExprGen.h   | 25 
 clang/test/AST/Interp/arrays.cpp |  6 +-
 3 files changed, 44 insertions(+), 8 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 46906377863bd74..b2cf34ac8c45bbb 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -792,9 +792,20 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 const ArrayInitLoopExpr *E) {
   assert(Initializing);
   assert(!DiscardResult);
-  // TODO: This compiles to quite a lot of bytecode if the array is larger.
-  //   Investigate compiling this to a loop, or at least try to use
-  //   the AILE's Common expr.
+
+  const auto *CommonExpr = E->getCommonExpr();
+  std::optional CommonTy = classify(CommonExpr);
+
+  std::optional LocalIndex = 
this->allocateLocalPrimitive(CommonExpr, *CommonTy, 
CommonExpr->getType().isConstQualified());
+  if (!LocalIndex)
+return false;
+  if (!this->visit(CommonExpr))
+return false;
+  if(!this->emitSetLocal(*CommonTy, *LocalIndex, E))
+return false;
+
+  StoredOpaqueValueScope KnownOpaqueScope(this, *LocalIndex);
+
   const Expr *SubExpr = E->getSubExpr();
   size_t Size = E->getArraySize().getZExtValue();
   std::optional ElemT = classify(SubExpr->getType());
@@ -827,8 +838,12 @@ bool ByteCodeExprGen::VisitArrayInitLoopExpr(
 
 template 
 bool ByteCodeExprGen::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
+  if(IgnoreOpaqueValue)
+return this->emitGetLocal(*classify(E), *OpaqueValueIndex, E);
+
   if (Initializing)
 return this->visitInitializer(E->getSourceExpr());
+  
   return this->visit(E->getSourceExpr());
 }
 
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 47a3f75f13459d0..f58def7a3245ca6 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -36,6 +36,7 @@ template  class DeclScope;
 template  class OptionScope;
 template  class ArrayIndexScope;
 template  class SourceLocScope;
+template  class StoredOpaqueValueScope;
 
 /// Compilation context for expressions.
 template 
@@ -219,6 +220,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   friend class OptionScope;
   friend class ArrayIndexScope;
   friend class SourceLocScope;
+  friend class StoredOpaqueValueScope;
 
   /// Emits a zero initializer.
   bool visitZeroInitializer(QualType QT, const Expr *E);
@@ -303,6 +305,10 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   /// Flag inidicating if we're initializing an already created
   /// variable. This is set in visitInitializer().
   bool Initializing = false;
+
+  /// Flag indicating if we ignore an OpaqueValueExpr.
+  bool IgnoreOpaqueValue = false;
+  std::optional OpaqueValueIndex;
 };
 
 extern template class ByteCodeExprGen;
@@ -478,6 +484,25 @@ template  class SourceLocScope final {
   bool Enabled = false;
 };
 
+template  class StoredOpaqueValueScope final {
+public:
+  StoredOpaqueValueScope(ByteCodeExprGen *Ctx, uint64_t LocalIndex, 
bool ignore = true)
+  : Ctx(Ctx), OldIgnoreValue(Ctx->IgnoreOpaqueValue), 
OldLocalIndex(Ctx->OpaqueValueIndex) {
+Ctx->IgnoreOpaqueValue = ignore;
+Ctx->OpaqueValueIndex = LocalIndex;
+  }
+
+  ~StoredOpaqueValueScope() {
+  Ctx->IgnoreOpaqueValue = OldIgnoreValue;
+  Ctx->OpaqueValueIndex = OldLocalIndex;
+  }
+
+private:
+  ByteCodeExprGen *Ctx;
+  bool OldIgnoreValue;
+  std::optional OldLocalIndex;
+};
+
 } // namespace interp
 } // namespace clang
 
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..1f8908f2bed0b24 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -352,9 +352,6 @@ namespace ZeroInit {
 }
 
 namespace ArrayInitLoop {
-  /// FIXME: The ArrayInitLoop for the decomposition initializer in g() has
-  /// f(n) as its CommonExpr. We need to evaluate that exactly once and not
-  /// N times as we do right now.
   

[clang] [clang] use absolute path for builtin headers during module compilation (PR #68023)

2023-10-02 Thread Ben Langmuir via cfe-commits


@@ -348,6 +348,10 @@ bool ModuleMap::resolveAsBuiltinHeader(
   if (!File)
 return false;
 
+  // Ensure the path to the module directory is absolute, otherwise
+  // builtin headers will fail to resolve when using relative resource
+  // directory paths without a -I.
+  llvm::sys::fs::make_absolute(Path);

benlangmuir wrote:

This should be using `FileManager::makeAbsolutePath` to ensure 
`-working-directory` is handled correctly, and so that it goes through VFS 
makeAbsolute instead of using the process working directory.

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


  1   2   3   4   5   >