[clang] [clang][AMDGPU] fix the return type for ballot (PR #73906)

2023-11-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Sameer Sahasrabuddhe (ssahasra)


Changes

In the builtins declaration, "ULi" is a 32-bit integer on Windows. Use "WUi" 
instead to ensure a 64-bit integer on all platforms.


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


2 Files Affected:

- (modified) clang/include/clang/Basic/BuiltinsAMDGPU.def (+2-2) 
- (added) clang/test/CodeGenHIP/ballot.cpp (+15) 


``diff
diff --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index a19c8bd5f219ec6..8b59b3790d7bc66 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -150,8 +150,8 @@ BUILTIN(__builtin_amdgcn_mqsad_u32_u8, "V4UiWUiUiV4Ui", 
"nc")
 // Ballot builtins.
 
//===--===//
 
-TARGET_BUILTIN(__builtin_amdgcn_ballot_w32, "Uib", "nc", "wavefrontsize32")
-TARGET_BUILTIN(__builtin_amdgcn_ballot_w64, "LUib", "nc", "wavefrontsize64")
+TARGET_BUILTIN(__builtin_amdgcn_ballot_w32, "ZUib", "nc", "wavefrontsize32")
+TARGET_BUILTIN(__builtin_amdgcn_ballot_w64, "WUib", "nc", "wavefrontsize64")
 
 // Deprecated intrinsics in favor of __builtin_amdgn_ballot_{w32|w64}
 BUILTIN(__builtin_amdgcn_uicmp, "WUiUiUiIi", "nc")
diff --git a/clang/test/CodeGenHIP/ballot.cpp b/clang/test/CodeGenHIP/ballot.cpp
new file mode 100644
index 000..5685c5cad30d66a
--- /dev/null
+++ b/clang/test/CodeGenHIP/ballot.cpp
@@ -0,0 +1,15 @@
+// REQUIRES: amdgpu-registered-target
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -target-cpu gfx900 -x hip 
-emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -target-cpu gfx900 -x hip -S 
-fcuda-is-device -o - %s | FileCheck %s --check-prefix=GFX9
+
+// CHECK-LABEL: @_Z3fooi
+// CHECK: call i64 @llvm.amdgcn.ballot.i64
+
+// GFX9-LABEL: _Z3fooi:
+// GFX9: v_cmp_ne_u32_e64
+
+#define __device__ __attribute__((device))
+
+__device__ unsigned long long foo(int p) {
+  return __builtin_amdgcn_ballot_w64(p);
+}

``




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


[clang] 5891a8f - [clang] Remove extra ';' in MultiplexExternalSemaSource.cpp (NFC)

2023-11-29 Thread Jie Fu via cfe-commits

Author: Jie Fu
Date: 2023-11-30T15:53:36+08:00
New Revision: 5891a8f7ce0a7b866a5bc06c34092fbdb28dda1c

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

LOG: [clang] Remove extra ';' in MultiplexExternalSemaSource.cpp (NFC)

/llvm-project/clang/lib/Sema/MultiplexExternalSemaSource.cpp:317:2:
error: extra ';' outside of a function is incompatible with C++98 
[-Werror,-Wc++98-compat-extra-semi]
};
 ^
1 error generated.

Added: 


Modified: 
clang/lib/Sema/MultiplexExternalSemaSource.cpp

Removed: 




diff  --git a/clang/lib/Sema/MultiplexExternalSemaSource.cpp 
b/clang/lib/Sema/MultiplexExternalSemaSource.cpp
index d0d6a3a866d62d2..100794de60ee03d 100644
--- a/clang/lib/Sema/MultiplexExternalSemaSource.cpp
+++ b/clang/lib/Sema/MultiplexExternalSemaSource.cpp
@@ -314,7 +314,7 @@ void 
MultiplexExternalSemaSource::ReadPendingInstantiationsOfConstexprEntity(
 const NamedDecl *D, llvm::SmallSetVector ) {
   for (size_t i = 0; i < Sources.size(); ++i)
 Sources[i]->ReadPendingInstantiationsOfConstexprEntity(D, Decls);
-};
+}
 
 void MultiplexExternalSemaSource::ReadLateParsedTemplates(
 llvm::MapVector>



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


[clang] [Clang] Eagerly instantiate used constexpr function upon definition. (PR #73463)

2023-11-29 Thread via cfe-commits

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


[clang] 030047c - [Clang] Eagerly instantiate used constexpr function upon definition. (#73463)

2023-11-29 Thread via cfe-commits

Author: cor3ntin
Date: 2023-11-30T08:45:05+01:00
New Revision: 030047c432cac133738be68fa0974f70e69dd58d

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

LOG: [Clang] Eagerly instantiate used constexpr function upon definition. 
(#73463)

Despite CWG2497 not being resolved, it is reasonable to expect the
following code to compile (and which is supported by other compilers)

```cpp
  template constexpr T f();
  constexpr int g() { return f(); } // #1
  template constexpr T f() { return 123; }
  int k[g()];
  // #2
```

To that end, we eagerly instantiate all referenced specializations of
constexpr functions when they are defined.

We maintain a map of (pattern, [instantiations]) independent of
`PendingInstantiations` to avoid having to iterate that list after each
function definition.

We should apply the same logic to constexpr variables, but I wanted to
keep the PR small.

Fixes #73232

Added: 
clang/test/PCH/instantiate-used-constexpr-function.cpp
clang/test/SemaTemplate/instantiate-used-constexpr-function.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/ExternalSemaSource.h
clang/include/clang/Sema/MultiplexExternalSemaSource.h
clang/include/clang/Sema/Sema.h
clang/include/clang/Serialization/ASTBitCodes.h
clang/include/clang/Serialization/ASTReader.h
clang/lib/Sema/MultiplexExternalSemaSource.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8d2b60dd75acfee..7d64647433d92a7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -793,6 +793,11 @@ Bug Fixes to C++ Support
 - Fix crash when parsing nested requirement. Fixes:
   (`#73112 `_)
 
+- Clang now immediately instantiates function template specializations
+  at the end of the definition of the corresponding function template
+  when the definition appears after the first point of instantiation.
+  (`#73232 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

diff  --git a/clang/include/clang/Sema/ExternalSemaSource.h 
b/clang/include/clang/Sema/ExternalSemaSource.h
index 22d1ee2df115a6e..8b41c5483458a0f 100644
--- a/clang/include/clang/Sema/ExternalSemaSource.h
+++ b/clang/include/clang/Sema/ExternalSemaSource.h
@@ -181,6 +181,9 @@ class ExternalSemaSource : public ExternalASTSource {
  SmallVectorImpl > ) {}
 
+  virtual void ReadPendingInstantiationsOfConstexprEntity(
+  const NamedDecl *D, llvm::SmallSetVector ){};
+
   /// Read the set of late parsed template functions for this source.
   ///
   /// The external source should insert its own late parsed template functions

diff  --git a/clang/include/clang/Sema/MultiplexExternalSemaSource.h 
b/clang/include/clang/Sema/MultiplexExternalSemaSource.h
index 2bf91cb5212c5eb..6054ef39e54ff9a 100644
--- a/clang/include/clang/Sema/MultiplexExternalSemaSource.h
+++ b/clang/include/clang/Sema/MultiplexExternalSemaSource.h
@@ -319,6 +319,9 @@ class MultiplexExternalSemaSource : public 
ExternalSemaSource {
   void ReadPendingInstantiations(
  SmallVectorImpl >& Pending) 
override;
 
+  virtual void ReadPendingInstantiationsOfConstexprEntity(
+  const NamedDecl *D, llvm::SmallSetVector ) 
override;
+
   /// Read the set of late parsed template functions for this source.
   ///
   /// The external source should insert its own late parsed template functions

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e75a8bdb1fc72ff..6de1a098e067a38 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -59,6 +59,7 @@
 #include "clang/Sema/TypoCorrection.h"
 #include "clang/Sema/Weak.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallBitVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -10087,6 +10088,12 @@ class Sema final {
   /// but have not yet been performed.
   std::deque PendingInstantiations;
 
+  /// Track constexpr functions referenced before they are (lexically) defined.
+  /// The key is the pattern, associated with a list of specialisations that
+  /// need to be instantiated when the pattern is defined.
+  llvm::DenseMap>
+  PendingInstantiationsOfConstexprEntities;
+
   /// Queue of implicit template instantiations that cannot be performed
   /// eagerly.
   SmallVector LateParsedInstantiations;
@@ -10405,6 +10412,9 @@ class 

[clang-tools-extra] [libc] [mlir] [libcxxabi] [llvm] [flang] [libunwind] [openmp] [lld] [clang] [libcxx] [C23] Implement N3018: The constexpr specifier for object definitions (PR #73099)

2023-11-29 Thread via cfe-commits

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


[clang-tools-extra] [libc] [mlir] [libcxxabi] [llvm] [flang] [libunwind] [openmp] [lld] [clang] [libcxx] [C23] Implement N3018: The constexpr specifier for object definitions (PR #73099)

2023-11-29 Thread via cfe-commits


@@ -14240,6 +14294,114 @@ StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, 
SourceLocation IdentLoc,
   : IdentLoc);
 }
 
+static ImplicitConversionKind getConversionKind(QualType FromType,
+QualType ToType) {
+  if (ToType->isIntegerType()) {
+if (FromType->isComplexType())
+  return ICK_Complex_Real;
+if (FromType->isFloatingType())
+  return ICK_Floating_Integral;
+if (FromType->isIntegerType())
+  return ICK_Integral_Conversion;
+  }
+
+  if (ToType->isFloatingType()) {
+if (FromType->isComplexType())
+  return ICK_Complex_Real;
+if (FromType->isFloatingType())
+  return ICK_Floating_Conversion;
+if (FromType->isIntegerType())
+  return ICK_Floating_Integral;
+  }
+
+  return ICK_Identity;
+}
+
+static bool checkC23ConstexprInitConversion(Sema , const Expr *Init) {
+  assert(S.getLangOpts().C23);
+  const Expr *InitNoCast = Init->IgnoreImpCasts();
+  StandardConversionSequence SCS;
+  SCS.setAsIdentityConversion();
+  auto FromType = InitNoCast->getType();
+  auto ToType = Init->getType();
+  SCS.setToType(0, FromType);
+  SCS.setToType(1, ToType);
+  SCS.Second = getConversionKind(FromType, ToType);
+
+  APValue Value;
+  QualType PreNarrowingType;
+  // Reuse C++ narrowing check.
+  switch (SCS.getNarrowingKind(S.Context, Init, Value, PreNarrowingType,
+   /*IgnoreFloatToIntegralConversion*/ false)) {
+  // The value doesn't fit.
+  case NK_Constant_Narrowing:
+S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
+<< Value.getAsString(S.Context, PreNarrowingType) << ToType;
+return true;
+
+  // Conversion to a narrower type.
+  case NK_Type_Narrowing:
+S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
+<< ToType << FromType;
+return true;
+
+  // Since we only reuse narrowing check for C23 constexpr variables here, 
we're
+  // not really interested in these cases.
+  case NK_Dependent_Narrowing:
+  case NK_Variable_Narrowing:
+  case NK_Not_Narrowing:
+return false;
+  }
+  llvm_unreachable("unhandled case in switch");
+}
+
+static bool checkC23ConstexprInitStringLiteral(const StringLiteral *SE,
+   Sema ,
+   SourceLocation Loc) {
+  assert(SemaRef.getLangOpts().C23);
+  // String literals have the target type attached but underneath may contain
+  // values that don't really fit into the target type. Check that every
+  // character fits.
+  const ConstantArrayType *CAT =
+  SemaRef.Context.getAsConstantArrayType(SE->getType());
+  QualType CharType = CAT->getElementType();
+  uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
+  bool isUnsigned = CharType->isUnsignedIntegerType();
+  llvm::APSInt Value(BitWidth, isUnsigned);
+  const StringRef S = SE->getBytes();
+  for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
+Value = S[I];
+if (Value != S[I]) {
+  SemaRef.Diag(Loc, diag::err_c23_constexpr_init_not_representable)
+  << S[I] << CharType;

cor3ntin wrote:

Oh wait.
How would you get into a situation where a string literal contains non 
representable data?
StringLiterals ought to be representable per constructions
https://eel.is/c++draft/lex.string#10.2.4
https://eel.is/c++draft/lex.string#10.1.sentence-2

Now that i understand what you are trying to do, I'm not sure that whole 
function is necessary at all.

Is there am example that concerns you?


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


[llvm] [clang-tools-extra] [clang] [STLExtras] Add out-of-line definition of friend operator== for C++20 (PR #72348)

2023-11-29 Thread via cfe-commits

cor3ntin wrote:

@usx95 stupid question, how does that affects llvm when built with GCC/MSVC?
If we do require a too recent version of compiler to build in C++20 mode it 
will make it harder to move llvm to C++20.


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


[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits

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


[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -485,20 +499,83 @@ Pointer types in a ``typedef`` can still have explicit 
annotations, e.g.,
 ``typedef int *__single``, in which case the bounds annotation ``__single`` 
will
 apply to every use of the ``typedef``.
 
-Array to pointer promotion
---
-
-In C, when an array is referenced, it is automatically promoted (or “decayed”)
-to a pointer to its first element (e.g., ``[0]``). Similarly, in
-``-fbounds-safety``, arrays are also promoted to pointers, but with the 
addition
-of an implicit bounds annotation. Arrays on function parameters are promoted to
-corresponding ``__counted_by`` pointers. Consequently, incomplete arrays (or
-arrays without size) will cause a compiler error unless it has ``__counted_by``
-annotation in its bracket. All other arrays are promoted to 
``__bidi_indexable``
-pointers, with the equivalent of ``[0]`` serving as the lower bound and
-``[array_size]`` (or one past the last element) serving as the upper bound.
-This way, all array accesses are subject to bounds checking, just as their
-corresponding pointers are.
+Array to pointer promotion to secure arrays (including VLAs)

rapidsna wrote:

@AaronBallman I extended this section to explicitly mention VLAs and added some 
examples to describe the semantics.

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


[clang] [Clang] Eagerly instantiate used constexpr function upon definition. (PR #73463)

2023-11-29 Thread via cfe-commits

cor3ntin wrote:

> Thanks! I assume you'll also be looking at the variable case (perhaps as a 
> separate commit)?

I'll try to get to it, yes!
Thanks for the review

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


[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.

rapidsna wrote:

Fixed it!

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


[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.

rapidsna wrote:

I added a caveat that this still requires inclusion of header to define the 
bounds annotations to empty.

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


[clang] [Clang] Eagerly instantiate used constexpr function upon definition. (PR #73463)

2023-11-29 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/73463

>From af4176fba7e7b6e45ddd5b7730c7b1c2cbd69537 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Sun, 26 Nov 2023 22:47:51 +0100
Subject: [PATCH 1/4] [Clang] Eagerly instantiate used constexpr function upon
 definition.

Despite CWG2497 not being resolved, it is reasonable to expect the following
code to compile (and which is supported by other compilers)

```cpp
  template constexpr T f();
  constexpr int g() { return f(); } // #1
  template constexpr T f() { return 123; }
  int k[g()];
  // #2
```

To that end, we eagerly instantiate all referenced
specializations of constexpr functions when they are defined.

We maintain a map of (pattern, [instantiations]) independant of
`PendingInstantiations` to avoid having to iterate that list after
each function definition.

We should apply the same logic to constexpr variables,
but I wanted to keep the PR small.

Fixes #73232
---
 clang/docs/ReleaseNotes.rst   |  5 
 clang/include/clang/Sema/Sema.h   | 11 +++
 clang/lib/Sema/SemaDecl.cpp   |  3 ++
 clang/lib/Sema/SemaExpr.cpp   |  9 --
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 17 +++
 .../SemaCXX/cxx2b-consteval-propagate.cpp |  8 +++--
 .../instantiate-used-constexpr-function.cpp   | 30 +++
 7 files changed, 78 insertions(+), 5 deletions(-)
 create mode 100644 
clang/test/SemaTemplate/instantiate-used-constexpr-function.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8d2b60dd75acfee..7d64647433d92a7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -793,6 +793,11 @@ Bug Fixes to C++ Support
 - Fix crash when parsing nested requirement. Fixes:
   (`#73112 `_)
 
+- Clang now immediately instantiates function template specializations
+  at the end of the definition of the corresponding function template
+  when the definition appears after the first point of instantiation.
+  (`#73232 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e75a8bdb1fc72ff..d1685ba2c209189 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -59,6 +59,7 @@
 #include "clang/Sema/TypoCorrection.h"
 #include "clang/Sema/Weak.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallBitVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -10087,6 +10088,12 @@ class Sema final {
   /// but have not yet been performed.
   std::deque PendingInstantiations;
 
+  /// Track constexpr functions referenced before they are (lexically) defined.
+  /// The key is the pattern, associated with a list of specialisations that
+  /// need to be instantiated when the pattern is defined.
+  llvm::DenseMap>
+  PendingInstantiationsOfConstexprEntities;
+
   /// Queue of implicit template instantiations that cannot be performed
   /// eagerly.
   SmallVector LateParsedInstantiations;
@@ -10405,6 +10412,10 @@ class Sema final {
  bool Recursive = false,
  bool DefinitionRequired = false,
  bool AtEndOfTU = false);
+
+  void InstantiateFunctionTemplateSpecializations(
+  SourceLocation PointOfInstantiation, FunctionDecl *Template);
+
   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
   VarTemplateDecl *VarTemplate, VarDecl *FromVar,
   const TemplateArgumentList ,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 77ff4e1df8e9c90..eddaa95606b1106 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16275,6 +16275,9 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt 
*Body,
   if (FD && !FD->isDeleted())
 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
 
+  if (FD && FD->isConstexpr() && FD->isTemplated())
+InstantiateFunctionTemplateSpecializations(FD->getEndLoc(), FD);
+
   return dcl;
 }
 
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index d1b2b8084b8ffea..b204cb01a0deffd 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -19053,12 +19053,17 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
   CodeSynthesisContexts.size())
 PendingLocalImplicitInstantiations.push_back(
 std::make_pair(Func, PointOfInstantiation));
-  else if (Func->isConstexpr())
+  else if (Func->isConstexpr()) {
 // Do not defer instantiations of constexpr functions, to avoid the
 // expression evaluator needing to call back 

[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.
+* It has a relatively low adoption cost.
+* It can be implemented on top of Clang.

rapidsna wrote:

Done!

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


[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.
+* It has a relatively low adoption cost.
+* It can be implemented on top of Clang.
+
+This document discusses the key designs of ``-fbounds-safety``. The document 
is subject to be actively updated with a more detailed specification. The 
implementation plan can be found in `Implementation plans for -fbounds-safety 
`_.
+
+Programming Model
+=
+
+Overview
+
+
+``-fbounds-safety`` ensures that pointers are not used to access memory beyond 
their bounds by performing bounds checking. If a bounds check fails, the 
program will deterministically trap before out-of-bounds memory is accessed.
+
+In our model, every pointer has an explicit or implicit bounds attribute that 
determines its bounds and ensures guaranteed bounds checking. Consider the 
example below where the ``__counted_by(count)`` annotation indicates that 
parameter ``p`` points to a buffer of integers containing ``count`` elements. 
An off-by-one error is present in the loop condition, leading to ``p[i]`` being 
out-of-bounds access during the loop’s final iteration. The compiler inserts a 
bounds check before ``p`` is dereferenced to ensure that the access remains 
within the specified bounds.
+
+.. code-block:: c
+
+   void fill_array_with_indices(int *__counted_by(count) p, unsigned count) {
+   // off-by-one error (i < count)
+  for (unsigned i = 0; i <= count; ++i) {
+ // bounds check inserted:
+ //   if (i >= count) trap();
+ p[i] = i;
+  }
+   }
+
+A bounds annotation defines an invariant for the pointer type, and the model 
ensures that this invariant remains true. In the example below, pointer ``p`` 
annotated with ``__counted_by(count)`` must always point to a memory buffer 
containing at least ``count`` elements of the pointee type. Increasing the 
value of ``count``, like in the example below, would violate this invariant and 
permit out-of-bounds access to the pointer. To avoid this, the compiler emits 
either a compile-time error or a run-time trap. Section `Maintaining 
correctness of bounds annotations`_ provides more details about the programming 
model.

rapidsna wrote:

Good point. The compiler still insert run-time checks even when `count` seems 
to be decreasing because `count` may be underflow or wrap. I tweaked the text 
and added more examples.

https://github.com/llvm/llvm-project/pull/70749

[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.
+* It has a relatively low adoption cost.
+* It can be implemented on top of Clang.
+
+This document discusses the key designs of ``-fbounds-safety``. The document 
is subject to be actively updated with a more detailed specification. The 
implementation plan can be found in `Implementation plans for -fbounds-safety 
`_.
+
+Programming Model
+=
+
+Overview
+
+
+``-fbounds-safety`` ensures that pointers are not used to access memory beyond 
their bounds by performing bounds checking. If a bounds check fails, the 
program will deterministically trap before out-of-bounds memory is accessed.
+
+In our model, every pointer has an explicit or implicit bounds attribute that 
determines its bounds and ensures guaranteed bounds checking. Consider the 
example below where the ``__counted_by(count)`` annotation indicates that 
parameter ``p`` points to a buffer of integers containing ``count`` elements. 
An off-by-one error is present in the loop condition, leading to ``p[i]`` being 
out-of-bounds access during the loop’s final iteration. The compiler inserts a 
bounds check before ``p`` is dereferenced to ensure that the access remains 
within the specified bounds.
+
+.. code-block:: c
+
+   void fill_array_with_indices(int *__counted_by(count) p, unsigned count) {
+   // off-by-one error (i < count)
+  for (unsigned i = 0; i <= count; ++i) {
+ // bounds check inserted:
+ //   if (i >= count) trap();
+ p[i] = i;
+  }
+   }
+
+A bounds annotation defines an invariant for the pointer type, and the model 
ensures that this invariant remains true. In the example below, pointer ``p`` 
annotated with ``__counted_by(count)`` must always point to a memory buffer 
containing at least ``count`` elements of the pointee type. Increasing the 
value of ``count``, like in the example below, would violate this invariant and 
permit out-of-bounds access to the pointer. To avoid this, the compiler emits 
either a compile-time error or a run-time trap. Section `Maintaining 
correctness of bounds annotations`_ provides more details about the programming 
model.
+
+.. code-block:: c
+
+   void foo(int *__counted_by(count) p, size_t count) {
+  count++; // violates the invariant of __counted_by
+   }
+
+The requirement to annotate all pointers with explicit bounds information 
could present a significant adoption burden. To tackle 

[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.
+* It has a relatively low adoption cost.
+* It can be implemented on top of Clang.
+
+This document discusses the key designs of ``-fbounds-safety``. The document 
is subject to be actively updated with a more detailed specification. The 
implementation plan can be found in `Implementation plans for -fbounds-safety 
`_.
+
+Programming Model
+=
+
+Overview
+
+
+``-fbounds-safety`` ensures that pointers are not used to access memory beyond 
their bounds by performing bounds checking. If a bounds check fails, the 
program will deterministically trap before out-of-bounds memory is accessed.
+
+In our model, every pointer has an explicit or implicit bounds attribute that 
determines its bounds and ensures guaranteed bounds checking. Consider the 
example below where the ``__counted_by(count)`` annotation indicates that 
parameter ``p`` points to a buffer of integers containing ``count`` elements. 
An off-by-one error is present in the loop condition, leading to ``p[i]`` being 
out-of-bounds access during the loop’s final iteration. The compiler inserts a 
bounds check before ``p`` is dereferenced to ensure that the access remains 
within the specified bounds.
+
+.. code-block:: c
+
+   void fill_array_with_indices(int *__counted_by(count) p, unsigned count) {
+   // off-by-one error (i < count)
+  for (unsigned i = 0; i <= count; ++i) {
+ // bounds check inserted:
+ //   if (i >= count) trap();
+ p[i] = i;
+  }
+   }
+
+A bounds annotation defines an invariant for the pointer type, and the model 
ensures that this invariant remains true. In the example below, pointer ``p`` 
annotated with ``__counted_by(count)`` must always point to a memory buffer 
containing at least ``count`` elements of the pointee type. Increasing the 
value of ``count``, like in the example below, would violate this invariant and 
permit out-of-bounds access to the pointer. To avoid this, the compiler emits 
either a compile-time error or a run-time trap. Section `Maintaining 
correctness of bounds annotations`_ provides more details about the programming 
model.
+
+.. code-block:: c
+
+   void foo(int *__counted_by(count) p, size_t count) {
+  count++; // violates the invariant of __counted_by
+   }
+
+The requirement to annotate all pointers with explicit bounds information 
could present a significant adoption burden. To tackle 

[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.
+* It has a relatively low adoption cost.
+* It can be implemented on top of Clang.
+
+This document discusses the key designs of ``-fbounds-safety``. The document 
is subject to be actively updated with a more detailed specification. The 
implementation plan can be found in `Implementation plans for -fbounds-safety 
`_.
+
+Programming Model
+=
+
+Overview
+
+
+``-fbounds-safety`` ensures that pointers are not used to access memory beyond 
their bounds by performing bounds checking. If a bounds check fails, the 
program will deterministically trap before out-of-bounds memory is accessed.
+
+In our model, every pointer has an explicit or implicit bounds attribute that 
determines its bounds and ensures guaranteed bounds checking. Consider the 
example below where the ``__counted_by(count)`` annotation indicates that 
parameter ``p`` points to a buffer of integers containing ``count`` elements. 
An off-by-one error is present in the loop condition, leading to ``p[i]`` being 
out-of-bounds access during the loop’s final iteration. The compiler inserts a 
bounds check before ``p`` is dereferenced to ensure that the access remains 
within the specified bounds.
+
+.. code-block:: c
+
+   void fill_array_with_indices(int *__counted_by(count) p, unsigned count) {
+   // off-by-one error (i < count)
+  for (unsigned i = 0; i <= count; ++i) {
+ // bounds check inserted:
+ //   if (i >= count) trap();
+ p[i] = i;
+  }
+   }
+
+A bounds annotation defines an invariant for the pointer type, and the model 
ensures that this invariant remains true. In the example below, pointer ``p`` 
annotated with ``__counted_by(count)`` must always point to a memory buffer 
containing at least ``count`` elements of the pointee type. Increasing the 
value of ``count``, like in the example below, would violate this invariant and 
permit out-of-bounds access to the pointer. To avoid this, the compiler emits 
either a compile-time error or a run-time trap. Section `Maintaining 
correctness of bounds annotations`_ provides more details about the programming 
model.
+
+.. code-block:: c
+
+   void foo(int *__counted_by(count) p, size_t count) {
+  count++; // violates the invariant of __counted_by
+   }
+
+The requirement to annotate all pointers with explicit bounds information 
could present a significant adoption burden. To tackle 

[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.
+* It has a relatively low adoption cost.
+* It can be implemented on top of Clang.
+
+This document discusses the key designs of ``-fbounds-safety``. The document 
is subject to be actively updated with a more detailed specification. The 
implementation plan can be found in `Implementation plans for -fbounds-safety 
`_.
+
+Programming Model
+=
+
+Overview
+
+
+``-fbounds-safety`` ensures that pointers are not used to access memory beyond 
their bounds by performing bounds checking. If a bounds check fails, the 
program will deterministically trap before out-of-bounds memory is accessed.
+
+In our model, every pointer has an explicit or implicit bounds attribute that 
determines its bounds and ensures guaranteed bounds checking. Consider the 
example below where the ``__counted_by(count)`` annotation indicates that 
parameter ``p`` points to a buffer of integers containing ``count`` elements. 
An off-by-one error is present in the loop condition, leading to ``p[i]`` being 
out-of-bounds access during the loop’s final iteration. The compiler inserts a 
bounds check before ``p`` is dereferenced to ensure that the access remains 
within the specified bounds.
+
+.. code-block:: c
+
+   void fill_array_with_indices(int *__counted_by(count) p, unsigned count) {
+   // off-by-one error (i < count)
+  for (unsigned i = 0; i <= count; ++i) {
+ // bounds check inserted:
+ //   if (i >= count) trap();
+ p[i] = i;
+  }
+   }
+
+A bounds annotation defines an invariant for the pointer type, and the model 
ensures that this invariant remains true. In the example below, pointer ``p`` 
annotated with ``__counted_by(count)`` must always point to a memory buffer 
containing at least ``count`` elements of the pointee type. Increasing the 
value of ``count``, like in the example below, would violate this invariant and 
permit out-of-bounds access to the pointer. To avoid this, the compiler emits 
either a compile-time error or a run-time trap. Section `Maintaining 
correctness of bounds annotations`_ provides more details about the programming 
model.
+
+.. code-block:: c
+
+   void foo(int *__counted_by(count) p, size_t count) {
+  count++; // violates the invariant of __counted_by
+   }
+
+The requirement to annotate all pointers with explicit bounds information 
could present a significant adoption burden. To tackle 

[clang] [BoundsSafety] Initial documentation for -fbounds-safety (PR #70749)

2023-11-29 Thread Yeoul Na via cfe-commits


@@ -0,0 +1,362 @@
+==
+``-fbounds-safety``: Enforcing bounds safety for C
+==
+
+.. contents::
+   :local:
+
+Overview
+
+
+``-fbounds-safety`` is a C extension to enforce bounds safety to prevent 
out-of-bounds (OOB) memory accesses, which remain a major source of security 
vulnerabilities in C. ``-fbounds-safety`` aims to eliminate this class of bugs 
by turning OOB accesses into deterministic traps.
+
+The ``-fbounds-safety`` extension offers bounds annotations that programmers 
can use to attach bounds to pointers. For example, programmers can add the 
``__counted_by(N)`` annotation to parameter ``ptr``, indicating that the 
pointer has ``N`` valid elements:
+
+.. code-block:: c
+
+   void foo(int *__counted_by(N) ptr, size_t N);
+
+Using this bounds information, the compiler inserts bounds checks on every 
pointer dereference, ensuring that the program does not access memory outside 
the specified bounds. The compiler requires programmers to provide enough 
bounds information so that the accesses can be checked at either run time or 
compile time — and it rejects code if it cannot.
+
+The most important contribution of ``-fbounds-safety`` is how it reduces the 
programmer’s annotation burden by reconciling bounds annotations at ABI 
boundaries with the use of implicit wide pointers (a.k.a. “fat” pointers) that 
carry bounds information on local variables without the need for annotations. 
We designed this model so that it preserves ABI compatibility with C while 
minimizing adoption effort.
+
+The ``-fbounds-safety`` extension has been adopted on millions of lines of 
production C code and proven to work in a consumer operating system setting. 
The extension was designed to enable incremental adoption — a key requirement 
in real-world settings where modifying an entire project and its dependencies 
all at once is often not possible. It also addresses multiple of other 
practical challenges that have made existing approaches to safer C dialects 
difficult to adopt, offering these properties that make it widely adoptable in 
practice:
+
+* It is designed to preserve the Application Binary Interface (ABI).
+* It interoperates well with plain C code.
+* It can be adopted partially and incrementally while still providing safety 
benefits.
+* It is syntactically and semantically compatible with C.
+* Consequently, source code that adopts the extension can continue to be 
compiled by toolchains that do not support the extension.
+* It has a relatively low adoption cost.
+* It can be implemented on top of Clang.
+
+This document discusses the key designs of ``-fbounds-safety``. The document 
is subject to be actively updated with a more detailed specification. The 
implementation plan can be found in `Implementation plans for -fbounds-safety 
`_.
+
+Programming Model
+=
+
+Overview
+
+
+``-fbounds-safety`` ensures that pointers are not used to access memory beyond 
their bounds by performing bounds checking. If a bounds check fails, the 
program will deterministically trap before out-of-bounds memory is accessed.
+
+In our model, every pointer has an explicit or implicit bounds attribute that 
determines its bounds and ensures guaranteed bounds checking. Consider the 
example below where the ``__counted_by(count)`` annotation indicates that 
parameter ``p`` points to a buffer of integers containing ``count`` elements. 
An off-by-one error is present in the loop condition, leading to ``p[i]`` being 
out-of-bounds access during the loop’s final iteration. The compiler inserts a 
bounds check before ``p`` is dereferenced to ensure that the access remains 
within the specified bounds.
+
+.. code-block:: c
+
+   void fill_array_with_indices(int *__counted_by(count) p, unsigned count) {
+   // off-by-one error (i < count)
+  for (unsigned i = 0; i <= count; ++i) {
+ // bounds check inserted:
+ //   if (i >= count) trap();
+ p[i] = i;
+  }
+   }
+
+A bounds annotation defines an invariant for the pointer type, and the model 
ensures that this invariant remains true. In the example below, pointer ``p`` 
annotated with ``__counted_by(count)`` must always point to a memory buffer 
containing at least ``count`` elements of the pointee type. Increasing the 
value of ``count``, like in the example below, would violate this invariant and 
permit out-of-bounds access to the pointer. To avoid this, the compiler emits 
either a compile-time error or a run-time trap. Section `Maintaining 
correctness of bounds annotations`_ provides more details about the programming 
model.
+
+.. code-block:: c
+
+   void foo(int *__counted_by(count) p, size_t count) {
+  count++; // violates the invariant of __counted_by
+   }
+
+The requirement to annotate all pointers with explicit bounds information 
could present a significant adoption burden. To tackle 

[clang-tools-extra] [llvm] [clang] [Clang][Sema] Don't say "is declared here" for invalid template locations (PR #71264)

2023-11-29 Thread Justin Bogner via cfe-commits

bogner wrote:

> I agree that "is declared here" is useless when "here" is... nowhere. But the 
> point to the note is to help the user to see what the actual declaration is 
> to help them repair the issue. Losing the note entirely isn't the worst 
> thing, but I wonder if it would be better for declarations coming from 
> external AST sources to pretty print the declaration instead? e.g., Before:
> 
> ```
> hlsl::vector<1> BadVec; // expected-error{{template argument for template 
> type parameter must be a type}}
> // expected-note@*:* {{template is declared here}}
> // expected-note@*:* {{template parameter is declared here}}
> ```
> 
> After:
> 
> ```
> hlsl::vector<1> BadVec; // expected-error{{template argument for template 
> type parameter must be a type}}
> // expected-note@-1 {{template declaration from hidden source: template 
>  vector}}
> // expected-note@-2 {{template parameter from hidden source: typename Ty}}
> ```
> 
> This would give the user more relevant information than just dropping the 
> notes. (I have no idea if I'm asking for something incredibly difficult but I 
> was thinking we could use the declaration printer to print this information 
> out to the diagnostic in these cases.)

I made an attempt at this, and I think I like it. It does have a bit of novelty 
in terms of how it generates appropriate errors though.

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


[llvm] [libcxx] [clang-tools-extra] [clang] [FIX] Fix the function isctype failed in arm64-big-endian (PR #73200)

2023-11-29 Thread via cfe-commits

https://github.com/W-50243 updated 
https://github.com/llvm/llvm-project/pull/73200

>From ebc84bed665494dde9dbef956a0383ff79cb3d0c Mon Sep 17 00:00:00 2001
From: W-50243 
Date: Thu, 23 Nov 2023 11:02:24 +0800
Subject: [PATCH] [FIX] Fix the function isctype failed in arm64-big-endian

---
 libcxx/include/__locale | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libcxx/include/__locale b/libcxx/include/__locale
index b1502dd71edadf6..ef56135f2f1d45e 100644
--- a/libcxx/include/__locale
+++ b/libcxx/include/__locale
@@ -384,7 +384,7 @@ public:
 static const mask punct  = _ISpunct;
 static const mask xdigit = _ISxdigit;
 static const mask blank  = _ISblank;
-#if defined(__mips__)
+#if defined(__mips__) || (BYTE_ORDER == BIG_ENDIAN)
 static const mask __regex_word = static_cast(_ISbit(15));
 #else
 static const mask __regex_word = 0x80;

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


[clang] [llvm] [clang-tools-extra] [Clang][Sema] Don't say "is declared here" for invalid template locations (PR #71264)

2023-11-29 Thread Justin Bogner via cfe-commits

bogner wrote:

> That's a lot of repeated code. Should we have a "NoteTemplateLocation" 
> function(s) of some sort that would do the check and the diag as appropriate?

Makes sense to me, and also makes @AaronBallman's idea of emitting notes 
referring to the external source a little easier. Done in the latest update.

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


[clang] 5237193 - [NFC] Fix typos in comments

2023-11-29 Thread Phoebe Wang via cfe-commits

Author: Phoebe Wang
Date: 2023-11-19T10:14:34+08:00
New Revision: 5237193b87721134541f228e28edfd544a9c8ac8

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

LOG: [NFC] Fix typos in comments

Added: 


Modified: 
clang/lib/CodeGen/CodeGenFunction.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 64521ce7182eee6..2199d7b58fb96e6 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -495,12 +495,12 @@ void CodeGenFunction::FinishFunction(SourceLocation 
EndLoc) {
   if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
 LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
 
-  // Add the required-vector-width attribute. This contains the max width from:
+  // Add the min-legal-vector-width attribute. This contains the max width 
from:
   // 1. min-vector-width attribute used in the source program.
   // 2. Any builtins used that have a vector width specified.
   // 3. Values passed in and out of inline assembly.
   // 4. Width of vector arguments and return types for this function.
-  // 5. Width of vector aguments and return types for functions called by this
+  // 5. Width of vector arguments and return types for functions called by this
   //function.
   if (getContext().getTargetInfo().getTriple().isX86())
 CurFn->addFnAttr("min-legal-vector-width",



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


[llvm] [clang] [clang-tools-extra] [Clang][Sema] Don't say "is declared here" for invalid template locations (PR #71264)

2023-11-29 Thread Justin Bogner via cfe-commits

https://github.com/bogner updated 
https://github.com/llvm/llvm-project/pull/71264

>From cab6bcd73081fcbe9807adbf60b345f8d9e654e4 Mon Sep 17 00:00:00 2001
From: Justin Bogner 
Date: Fri, 3 Nov 2023 18:59:49 -0700
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.5
---
 clang/lib/Sema/SemaDecl.cpp   |   2 +-
 clang/lib/Sema/SemaDeclCXX.cpp|   3 +-
 clang/lib/Sema/SemaInit.cpp   |   3 +-
 clang/lib/Sema/SemaLambda.cpp |   3 +-
 clang/lib/Sema/SemaTemplate.cpp   | 123 --
 clang/lib/Sema/SemaType.cpp   |   3 +-
 .../test/SemaHLSL/BuiltIns/vector-errors.hlsl |   5 -
 7 files changed, 89 insertions(+), 53 deletions(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 396566a8f10a9b7..a86c428c9121abf 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -5929,7 +5929,7 @@ Sema::GetNameFromUnqualifiedId(const UnqualifiedId ) 
{
   Diag(Name.StartLocation,
diag::err_deduction_guide_name_not_class_template)
 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
-  if (Template)
+  if (Template && Template->getLocation().isValid())
 Diag(Template->getLocation(), diag::note_template_decl_here);
   return DeclarationNameInfo();
 }
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 397b7a00e453126..de5cc07f5d42865 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -11462,7 +11462,8 @@ bool Sema::CheckDeductionGuideDeclarator(Declarator , 
QualType ,
   GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
   << GuidedTemplateDecl;
-Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
+if (GuidedTemplateDecl->getLocation().isValid())
+  Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
   }
 
   auto  = D.getMutableDeclSpec();
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index ed02d3580f34f9a..0952b065d56b58e 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10575,7 +10575,8 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
  diag::err_deduced_non_class_template_specialization_type)
   << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
 if (auto *TD = TemplateName.getAsTemplateDecl())
-  Diag(TD->getLocation(), diag::note_template_decl_here);
+  if (TD->getLocation().isValid())
+Diag(TD->getLocation(), diag::note_template_decl_here);
 return QualType();
   }
 
diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index ca09b0481bcac76..603b7465323e237 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -1444,7 +1444,8 @@ void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer 
,
   for (const auto  : Intro.Captures) {
 if (Capture.Id == TP->getIdentifier()) {
   Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
-  Diag(TP->getLocation(), diag::note_template_param_here);
+  if (TP->getLocation().isValid())
+Diag(TP->getLocation(), diag::note_template_param_here);
 }
   }
 }
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index ee354862212803f..1a6eaa196db09be 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -872,7 +872,7 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation 
PointOfInstantiation,
   Note = diag::note_explicit_instantiation_here;
 }
   }
-  if (Note) // Diagnostics were emitted.
+  if (Note && Pattern->getLocation().isValid()) // Diagnostics were emitted.
 Diag(Pattern->getLocation(), *Note);
 
   // In general, Instantiation isn't marked invalid to get more than one
@@ -899,7 +899,8 @@ void Sema::DiagnoseTemplateParameterShadow(SourceLocation 
Loc, Decl *PrevDecl) {
   unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
  : diag::err_template_param_shadow;
   Diag(Loc, DiagId) << cast(PrevDecl)->getDeclName();
-  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
+  if (PrevDecl->getLocation().isValid())
+Diag(PrevDecl->getLocation(), diag::note_template_param_here);
 }
 
 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
@@ -4434,7 +4435,8 @@ static void checkMoreSpecializedThanPrimary(Sema , 
PartialSpecDecl *Partial) {
   << SFINAEArgString;
   }
 
-  S.Diag(Template->getLocation(), diag::note_template_decl_here);
+  if (Template->getLocation().isValid())
+

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

2023-11-29 Thread Nikolas Klauser via cfe-commits

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


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

2023-11-29 Thread Nikolas Klauser via cfe-commits

philnik777 wrote:

@shafik See 
https://discourse.llvm.org/t/rfc-allow-c-11-lambdas-in-c-03-as-an-extension/75262

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


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

2023-11-29 Thread Nikolas Klauser via cfe-commits

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


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

2023-11-29 Thread Shafik Yaghmour via cfe-commits

shafik wrote:

> Was there an RFC asking the community about exposing lambdas in pre C++11 
> modes? This is a sufficiently large language extension that we probably 
> should verify if we haven't already. I believe this is a conforming extension 
> (I can't think of a circumstance under which we'd take correct C++98 code and 
> treat it differently), but I don't think it's as simple as you've done here. 
> For example, `noexcept` is a C++11-ism and can appear on a lambda. 
> `constexpr` as well, trailing return types, etc. So we'd need a better 
> understanding of what features of lambdas you intend to enable and just how 
> much of the syntax you expect to work in older modes.

Also generic lambdas is probably a big one to think about as well. 

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


[clang] [Driver] Support -mcmodel= for LoongArch (PR #72514)

2023-11-29 Thread Lu Weining via cfe-commits

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


[clang] 1296d20 - [Driver] Support -mcmodel= for LoongArch (#72514)

2023-11-29 Thread via cfe-commits

Author: Lu Weining
Date: 2023-11-30T14:08:45+08:00
New Revision: 1296d20adfb0978afe38d67efab9818079d870ca

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

LOG: [Driver] Support -mcmodel= for LoongArch (#72514)

7e42545 rejects unsupported mcmodel options, but normal/medium/extreme
should be supported models for LoongArch according to [gcc
document](https://gcc.gnu.org/onlinedocs/gcc/LoongArch-Options.html).

The mappings among `gcc`, `clang driver`, `clang cc1` and `LLVM (i.e.
llc --code-model=)` are:

| gcc  |  clang driver |  clang cc1   |LLVM|
| -  | -- | - | -- |
| normal|  normal |   small|small|
| medium  | medium |   medium|medium |
| extreme  | extreme |  large | large |

Link: https://reviews.llvm.org/D150522

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/mcmodel.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 2d73f42772a29dc..d2b8fea2e9b8e62 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5756,6 +5756,18 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   if (CM == "large" && RelocationModel != llvm::Reloc::Static)
 D.Diag(diag::err_drv_argument_only_allowed_with)
 << A->getAsString(Args) << "-fno-pic";
+} else if (Triple.isLoongArch()) {
+  if (CM == "extreme" &&
+  Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false))
+D.Diag(diag::err_drv_argument_not_allowed_with)
+<< A->getAsString(Args) << "-fplt";
+  Ok = CM == "normal" || CM == "medium" || CM == "extreme";
+  // Convert to LLVM recognizable names.
+  if (Ok)
+CM = llvm::StringSwitch(CM)
+ .Case("normal", "small")
+ .Case("extreme", "large")
+ .Default(CM);
 } else if (Triple.isPPC64() || Triple.isOSAIX()) {
   Ok = CM == "small" || CM == "medium" || CM == "large";
 } else if (Triple.isRISCV()) {

diff  --git a/clang/test/Driver/mcmodel.c b/clang/test/Driver/mcmodel.c
index d8a41b0f5abd9aa..1eb6ae16ff472d9 100644
--- a/clang/test/Driver/mcmodel.c
+++ b/clang/test/Driver/mcmodel.c
@@ -15,6 +15,14 @@
 // RUN: not %clang -### -c --target=aarch64 -mcmodel=medium %s 2>&1 | 
FileCheck --check-prefix=ERR-MEDIUM %s
 // RUN: not %clang -### -c --target=aarch64 -mcmodel=kernel %s 2>&1 | 
FileCheck --check-prefix=ERR-KERNEL %s
 // RUN: not %clang --target=aarch64_32-linux -### -S -mcmodel=small %s 2>&1 | 
FileCheck --check-prefix=ERR-AARCH64_32 %s
+// RUN: %clang --target=loongarch64 -### -S -mcmodel=normal %s 2>&1 | 
FileCheck --check-prefix=SMALL %s
+// RUN: %clang --target=loongarch64 -### -S -mcmodel=medium %s 2>&1 | 
FileCheck --check-prefix=MEDIUM %s
+// RUN: %clang --target=loongarch64 -### -S -mcmodel=extreme %s 2>&1 | 
FileCheck --check-prefix=LARGE %s
+// RUN: not %clang --target=loongarch64 -### -S -mcmodel=tiny %s 2>&1 | 
FileCheck --check-prefix=ERR-TINY %s
+// RUN: not %clang --target=loongarch64 -### -S -mcmodel=small %s 2>&1 | 
FileCheck --check-prefix=ERR-SMALL %s
+// RUN: not %clang --target=loongarch64 -### -S -mcmodel=kernel %s 2>&1 | 
FileCheck --check-prefix=ERR-KERNEL %s
+// RUN: not %clang --target=loongarch64 -### -S -mcmodel=large %s 2>&1 | 
FileCheck --check-prefix=ERR-LARGE %s
+// RUN: not %clang --target=loongarch64 -### -S -mcmodel=extreme -fplt %s 2>&1 
| FileCheck --check-prefix=ERR-LOONGARCH64-PLT-EXTREME %s
 
 // TINY: "-mcmodel=tiny"
 // SMALL: "-mcmodel=small"
@@ -25,9 +33,14 @@
 
 // INVALID: error: unsupported argument 'lager' to option '-mcmodel=' for 
target '{{.*}}'
 
+// ERR-TINY:   error: unsupported argument 'tiny' to option '-mcmodel=' for 
target '{{.*}}'
+// ERR-SMALL:  error: unsupported argument 'small' to option '-mcmodel=' for 
target '{{.*}}'
 // ERR-MEDIUM: error: unsupported argument 'medium' to option '-mcmodel=' for 
target '{{.*}}'
 // ERR-KERNEL: error: unsupported argument 'kernel' to option '-mcmodel=' for 
target '{{.*}}'
 // ERR-LARGE:  error: unsupported argument 'large' to option '-mcmodel=' for 
target '{{.*}}'
 
 // AARCH64-PIC-LARGE: error: invalid argument '-mcmodel=large' only allowed 
with '-fno-pic'
 // ERR-AARCH64_32: error: unsupported argument 'small' to option '-mcmodel=' 
for target 'aarch64_32-unknown-linux'
+
+// ERR-LOONGARCH64-PLT-LARGE: error: invalid argument '-mcmodel=large' not 
allowed with '-fplt'
+// ERR-LOONGARCH64-PLT-EXTREME: error: invalid argument '-mcmodel=extreme' not 
allowed with '-fplt'



___
cfe-commits mailing list

[clang] [Driver] Support -mcmodel= for LoongArch (PR #72514)

2023-11-29 Thread via cfe-commits

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

LGTM

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


[clang] [Clang] Eagerly instantiate used constexpr function upon definition. (PR #73463)

2023-11-29 Thread Shafik Yaghmour via cfe-commits

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

Thank you, LGTM

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


[clang] [Clang][Lex] Fix parsing of nested requirement to prevent flowing off the end of token stream (PR #73691)

2023-11-29 Thread Shafik Yaghmour via cfe-commits

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


[clang] 0233a13 - [Clang][Lex] Fix parsing of nested requirement to prevent flowing off the end of token stream (#73691)

2023-11-29 Thread via cfe-commits

Author: Shafik Yaghmour
Date: 2023-11-29T21:03:32-08:00
New Revision: 0233a1306b240850cbf9f4783a20c36f967d9697

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

LOG: [Clang][Lex] Fix parsing of nested requirement to prevent flowing off the 
end of token stream (#73691)

Currently when parsing a nested requirement we attempt to balance parens
if we have a parameter list. This will fail in some cases of ill-formed
code and keep going until we fall off the token stream and crash. This
fixes the hand parsing by using SkipUntil which will properly flag if we
don't find the expected tokens.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Parse/ParseExprCXX.cpp
clang/test/Parser/cxx2a-concepts-requires-expr.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2ee946af32bf197..8d2b60dd75acfee 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -790,6 +790,9 @@ Bug Fixes to C++ Support
   completes (except deduction guides). Fixes:
   (`#59827 `_)
 
+- Fix crash when parsing nested requirement. Fixes:
+  (`#73112 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

diff  --git a/clang/lib/Parse/ParseExprCXX.cpp 
b/clang/lib/Parse/ParseExprCXX.cpp
index 79db094e098f8e6..8b86db1bb8fc5d5 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -3635,10 +3635,12 @@ ExprResult Parser::ParseRequiresExpression() {
   auto Res = TryParseParameterDeclarationClause();
   if (Res != TPResult::False) {
 // Skip to the closing parenthesis
-// FIXME: Don't traverse these tokens twice (here and in
-//  TryParseParameterDeclarationClause).
 unsigned Depth = 1;
 while (Depth != 0) {
+  bool FoundParen = SkipUntil(tok::l_paren, tok::r_paren,
+  SkipUntilFlags::StopBeforeMatch);
+  if (!FoundParen)
+break;
   if (Tok.is(tok::l_paren))
 Depth++;
   else if (Tok.is(tok::r_paren))

diff  --git a/clang/test/Parser/cxx2a-concepts-requires-expr.cpp 
b/clang/test/Parser/cxx2a-concepts-requires-expr.cpp
index a18a54c7fad0690..971591afb08dba2 100644
--- a/clang/test/Parser/cxx2a-concepts-requires-expr.cpp
+++ b/clang/test/Parser/cxx2a-concepts-requires-expr.cpp
@@ -160,3 +160,11 @@ template 
 requires requires {
  typename BitInt; // ok
 } using r44 = void;
+
+namespace GH73112 {
+void f() {
+requires { requires(int; } // expected-error {{expected ')'}} \
+   // expected-error {{expected expression}} \
+   // expected-note {{to match this '('}}
+}
+}



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


[clang] [Driver] Support -mcmodel= for LoongArch (PR #72514)

2023-11-29 Thread Zhao Jiazhong via cfe-commits

zjiaz wrote:

FWIW, `mcmodel=medium` option is used in [chromium's build config 
file](https://source.chromium.org/chromium/chromium/src/+/main:build/config/compiler/BUILD.gn;l=1451?q=mcmodel=chromium%2Fchromium%2Fsrc:build%2F),
 and now chromium's llvm toolchain has been affected by this issue:
> clang++: error: unsupported argument 'medium' to option '-mcmodel=' for 
> target 'loongarch64-unknown-linux-gnu'

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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread Emilia Kond via cfe-commits

https://github.com/rymiel updated 
https://github.com/llvm/llvm-project/pull/73886

>From 95e2a2ee5d901d79430cb9b9468e1af8215b334f Mon Sep 17 00:00:00 2001
From: Emilia Kond 
Date: Thu, 30 Nov 2023 03:30:48 +0200
Subject: [PATCH 1/2] [clang-format] Don't skip stringizing when determining
 brace kind

PR #69473 introduced skipping PP directives when determining the brace
kind of an lbrace. However, it did so by skipping to the end of the line
when encountering a hash character. This means it also skipped to the
end of line when encountering a macro stringizing operator, which, unlike
PP directives, don't have effect until the end of line.

This led to cases where the rbrace could be completely skipped if it was
on the same line as a stringizing operator.

This patch skips hash characters if we're already in a PP directive, as
you can't define a macro inside of a macro

Fixes https://github.com/llvm/llvm-project/issues/72662
---
 clang/lib/Format/UnwrappedLineParser.cpp  |  2 +-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 16 
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index a5a4419b98239e6..5f574dfeafc874b 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -496,7 +496,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 do {
   NextTok = Tokens->getNextToken();
 } while (NextTok->is(tok::comment));
-while (NextTok->is(tok::hash)) {
+while (NextTok->is(tok::hash) && !Line->InPPDirective) {
   NextTok = Tokens->getNextToken();
   do {
 NextTok = Tokens->getNextToken();
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index bc734573ce0cb4d..8ad6a585d004593 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1851,6 +1851,22 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsTrailingReturnArrow) {
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) {
+  auto Tokens = annotate("#define Foo(Bar) \\\n"
+ "  { \\\n"
+ "#Bar \\\n"
+ "  }\n");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+
+  Tokens = annotate("#define Foo(Bar) \\\n"
+"  { #Bar }\n");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacros) {
   // '__attribute__' has special handling.
   auto Tokens = annotate("__attribute__(X) void Foo(void);");

>From 3037f808b23cc27f984a846bb1f9ef5cc2cd3a71 Mon Sep 17 00:00:00 2001
From: Emilia Kond 
Date: Thu, 30 Nov 2023 04:47:31 +0200
Subject: [PATCH 2/2] Apply suggestions from Owen's review

---
 clang/lib/Format/UnwrappedLineParser.cpp  | 2 +-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 5f574dfeafc874b..9a9a16a3caaca8b 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -496,7 +496,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 do {
   NextTok = Tokens->getNextToken();
 } while (NextTok->is(tok::comment));
-while (NextTok->is(tok::hash) && !Line->InPPDirective) {
+while (NextTok->is(tok::hash) && !Line->InMacroBody) {
   NextTok = Tokens->getNextToken();
   do {
 NextTok = Tokens->getNextToken();
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 8ad6a585d004593..65b1f0f4b576598 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1855,13 +1855,13 @@ TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) {
   auto Tokens = annotate("#define Foo(Bar) \\\n"
  "  { \\\n"
  "#Bar \\\n"
- "  }\n");
+ "  }");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_BRACE_KIND(Tokens[6], BK_Block);
   EXPECT_BRACE_KIND(Tokens[9], BK_Block);
 
   Tokens = annotate("#define Foo(Bar) \\\n"
-"  { #Bar }\n");
+"  { #Bar }");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_BRACE_KIND(Tokens[6], BK_Block);
   EXPECT_BRACE_KIND(Tokens[9], BK_Block);

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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread Emilia Kond via cfe-commits


@@ -1851,6 +1851,22 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsTrailingReturnArrow) {
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) {
+  auto Tokens = annotate("#define Foo(Bar) \\\n"
+ "  { \\\n"
+ "#Bar \\\n"
+ "  }\n");

rymiel wrote:

Sorry, no, it was a leftover from other testing, thank you for catching it

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


[clang] [clang-offload-bundler] Add support for -check-input-archive (PR #73709)

2023-11-29 Thread Jacob Lambert via cfe-commits

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


[clang] 3cf1909 - [clang-offload-bundler] Add support for -check-input-archive (#73709)

2023-11-29 Thread via cfe-commits

Author: Jacob Lambert
Date: 2023-11-29T18:39:17-08:00
New Revision: 3cf190974a37d18c7bd6f52b9588f4104e8e96f0

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

LOG: [clang-offload-bundler] Add support for -check-input-archive (#73709)

In this patch, we add support for checking a heterogeneous archive. We
also significantly improve the clang-offload-bundler documentation.

Added: 


Modified: 
clang/docs/ClangOffloadBundler.rst
clang/include/clang/Driver/OffloadBundler.h
clang/lib/Driver/OffloadBundler.cpp
clang/test/Driver/clang-offload-bundler-asserts-on.c
clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp

Removed: 




diff  --git a/clang/docs/ClangOffloadBundler.rst 
b/clang/docs/ClangOffloadBundler.rst
index 1e21d3e7264d5c3..1d163db1a9a63bc 100644
--- a/clang/docs/ClangOffloadBundler.rst
+++ b/clang/docs/ClangOffloadBundler.rst
@@ -30,58 +30,139 @@ includes an ``init`` function that will use the runtime 
corresponding to the
 offload kind (see :ref:`clang-offload-kind-table`) to load the offload code
 objects appropriate to the devices present when the host program is executed.
 
+:program:`clang-offload-bundler` is located in
+`clang/tools/clang-offload-bundler`.
+
+.. code-block:: console
+
+  $ clang-offload-bundler -help
+  OVERVIEW: A tool to bundle several input files of the specified type 
+  referring to the same source file but 
diff erent targets into a single
+  one. The resulting file can also be unbundled into 
diff erent files by
+  this tool if -unbundle is provided.
+
+  USAGE: clang-offload-bundler [options]
+
+  OPTIONS:
+
+  Generic Options:
+
+--help  - Display available options (--help-hidden for 
more)
+--help-list - Display list of available options 
(--help-list-hidden for more)
+--version   - Display the version of this program
+
+  clang-offload-bundler options:
+
+--###   - Print any external commands that are to be 
executed instead of actually executing them - for testing purposes.
+--allow-missing-bundles - Create empty files if bundles are missing when 
unbundling.
+--bundle-align=   - Alignment of bundle for binary files
+--check-input-archive   - Check if input heterogeneous archive is valid in 
terms of TargetID rules.
+--inputs=   - [,...]
+--list  - List bundle IDs in the bundled file.
+--outputs=  - [,...]
+--targets=  - [-,...]
+--type= - Type of the files to be bundled/unbundled.
+  Current supported types are:
+i   - cpp-output
+ii  - c++-cpp-output
+cui - cuda/hip-output
+d   - dependency
+ll  - llvm
+bc  - llvm-bc
+s   - assembler
+o   - object
+a   - archive of bundled files
+gch - precompiled-header
+ast - clang AST file
+--unbundle  - Unbundle bundled file into several output files.
+
+Usage
+=
+
+This tool can be used as follows for bundling:
+
+::
+
+  clang-offload-bundler -targets=triple1,triple2 -type=ii 
-inputs=a.triple1.ii,a.triple2.ii -outputs=a.ii
+
+or, it can be used as follows for unbundling:
+
+::
+
+  clang-offload-bundler -targets=triple1,triple2 -type=ii 
-outputs=a.triple1.ii,a.triple2.ii -inputs=a.ii -unbundle
+
+
 Supported File Formats
 ==
-Several text and binary file formats are supported for bundling/unbundling. See
-:ref:`supported-file-formats-table` for a list of currently supported formats.
+
+Multiple text and binary file formats are supported for bundling/unbundling. 
See
+:ref:`supported-file-formats-table` for a list of currently supported input
+formats. Use the ``File Type`` column to determine the value to pass to the
+``--type`` option based on the type of input files while bundling/unbundling.
 
   .. table:: Supported File Formats
  :name: supported-file-formats-table
 
- +++-+
- | File Format| File Extension | Text/Binary |
- +++=+
- | CPP output |i   | Text|
- +++-+
- | C++ CPP output |   ii   | Text|
- +++-+
- | CUDA/HIP output|   cui  | Text|
- +++-+
- | 

[openmp] [llvm] [mlir] [clang] [OpenMP] Introduce the KernelLaunchEnvironment as implicit argument (PR #70401)

2023-11-29 Thread via cfe-commits

ronlieb wrote:

> performance degradation observed for this patch on trunk build : hpc2021 8 
> mpi210's reference run 518.tealeaf 10.8% 534.hpgmg 7.3%

both of these benchmarks which exhibited performance regressions, contain 
reductions.

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


[llvm] [clang] [clang][DependencyScanner] Remove unused -ivfsoverlay files (PR #73734)

2023-11-29 Thread Jan Svoboda via cfe-commits

jansvoboda11 wrote:

I'm not thrilled by the chosen implementation strategy. Disabling tracking 
during parts of header search does not sound obviously correct to me. Module 
map search can have subtle side-effects, and I wouldn't be suprised if this 
feature was affected by one. That said, I haven't been able to come up with a 
case where this would yield incorrect results.

An alternative implementation I'd be more confident in would be to grab the set 
of files we know affect the compilation (built on top of 
`ASTWriter::collectNonAffectingInputFiles()`) and call 
`FileManager::getOptionalFileRef()` with their 
`FileEntryRef::getNameAsRequested()`.

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


[llvm] [clang] [clang][DependencyScanner] Remove unused -ivfsoverlay files (PR #73734)

2023-11-29 Thread Jan Svoboda via cfe-commits

jansvoboda11 wrote:

We set `RedirectingFileSystem::HasBeenUsed` to `true` while implicitly 
compiling one module, but then hand off the same VFS object to implicit compile 
of another module. This will cause all modules discovered later to incorrectly 
inherit that bit from previous modules. This will also introduce 
non-determinism based on the TU that reached a module first (and which modules 
it imported on the way). Here's a test case:
```
// This test checks that VFS usage doesn't leak between modules.

// RUN: rm -rf %t && split-file %s %t
// RUN: sed -e "s|DIR|%/t|g" %t/build/cdb.json.in > %t/build/cdb.json
// RUN: sed -e "s|DIR|%/t|g" %t/build/vfs.yaml.in > %t/build/vfs.yaml
// RUN: clang-scan-deps -compilation-database %t/build/cdb.json \
// RUN:   -format experimental-full --optimize-args=vfs > %t/deps.json
// RUN: cat %t/deps.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t

// CHECK:  {
// CHECK-NEXT:   "modules": [
// CHECK-NEXT: {
// CHECK-NEXT:   "clang-module-deps": [
// CHECK-NEXT: {
// CHECK-NEXT:   "context-hash": "{{.*}}",
// CHECK-NEXT:   "module-name": "B"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT:   "context-hash": "{{.*}}",
// CHECK-NEXT:   "module-name": "C"
// CHECK-NEXT: }
// CHECK-NEXT:   ],
// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/moduleA/module.modulemap",
// CHECK-NEXT:   "command-line": [
// Module A needs the VFS overlay because its dependency, module B, needs it.
// CHECK:  "-ivfsoverlay"
// CHECK-NEXT: "[[PREFIX]]/build/vfs.yaml"
// CHECK:],
// CHECK-NEXT:   "context-hash": "{{.*}}",
// CHECK-NEXT:   "file-deps": [
// CHECK:],
// CHECK-NEXT:   "name": "A"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT:   "clang-module-deps": [],
// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/moduleB/module.modulemap",
// CHECK-NEXT:   "command-line": [
// Module B needs the VFS overlay because it provides the header referred to by 
the module map.
// CHECK:  "-ivfsoverlay"
// CHECK-NEXT: "[[PREFIX]]/build/vfs.yaml"
// CHECK:],
// CHECK-NEXT:   "context-hash": "{{.*}}",
// CHECK-NEXT:   "file-deps": [
// CHECK:],
// CHECK-NEXT:   "name": "B"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT:   "clang-module-deps": [],
// CHECK-NEXT:   "clang-modulemap-file": 
"[[PREFIX]]/moduleC/module.modulemap",
// CHECK-NEXT:   "command-line": [
// Module C doesn't need the VFS overlay.
// CHECK-NOT:  "-ivfsoverlay"
// CHECK:],
// CHECK-NEXT:   "context-hash": "{{.*}}",
// CHECK-NEXT:   "file-deps": [
// CHECK:],
// CHECK-NEXT:   "name": "C"
// CHECK-NEXT: }
// CHECK-NEXT:   ],
// CHECK-NEXT:   "translation-units": [
// CHECK:]
// CHECK:  }

//--- build/cdb.json.in
[{
  "directory": "DIR",
  "command": "clang -c DIR/tu.m -I DIR/moduleA -I DIR/moduleB -I DIR/moduleC 
-fmodules -fmodules-cache-path=DIR/cache -fimplicit-module-maps -ivfsoverlay 
DIR/build/vfs.yaml",
  "file": "DIR/tu.m"
}]

//--- build/vfs.yaml.in
{
  "version": 0,
  "case-sensitive": "false",
  "roots": [
{
  "contents": [
{
  "external-contents": "DIR/build/B.h",
  "name": "B.h",
  "type": "file"
}
  ],
  "name": "DIR/moduleB",
  "type": "directory"
}
  ]
}

//--- tu.m
@import A;

//--- moduleA/module.modulemap
module A { header "A.h" }
//--- moduleA/A.h
@import B;
@import C;

//--- moduleB/module.modulemap
module B { header "B.h" }
//--- build/B.h

//--- moduleC/module.modulemap
module C { header "C.h" }
//--- moduleC/C.h
```

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


[lldb] [clang] [libc] [libcxxabi] [libunwind] [llvm] [flang] [libcxx] [lld] [clang-tools-extra] [compiler-rt] [PowerPC] Combine sub within setcc back to sext (PR #66978)

2023-11-29 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/66978

>From 2a7b9be6cd0705590c85c51b35ea99fe053aaf47 Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Wed, 6 Sep 2023 16:16:34 +0800
Subject: [PATCH 1/4] [PowerPC] Combine sub within setcc back to sext

---
 llvm/lib/Target/PowerPC/PPCISelLowering.cpp | 37 +-
 llvm/test/CodeGen/PowerPC/setcc-to-sub.ll   | 42 +
 2 files changed, 69 insertions(+), 10 deletions(-)

diff --git a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp 
b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
index f4e3531980d165f..4659ebef35ecf62 100644
--- a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
@@ -14407,15 +14407,18 @@ SDValue 
PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
   ShiftCst);
 }
 
-SDValue PPCTargetLowering::combineSetCC(SDNode *N,
-DAGCombinerInfo ) const {
-  assert(N->getOpcode() == ISD::SETCC &&
- "Should be called with a SETCC node");
+SDValue PPCTargetLowering::combineSetCC(SDNode *N, DAGCombinerInfo ) const 
{
+  assert(N->getOpcode() == ISD::SETCC && "Should be called with a SETCC node");
 
   ISD::CondCode CC = cast(N->getOperand(2))->get();
+  SDValue LHS = N->getOperand(0);
+  SDValue RHS = N->getOperand(1);
+  SDLoc DL(N);
+  SelectionDAG  = DCI.DAG;
+  EVT VT = N->getValueType(0);
+  EVT OpVT = LHS.getValueType();
+
   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
-SDValue LHS = N->getOperand(0);
-SDValue RHS = N->getOperand(1);
 
 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
@@ -14426,15 +14429,29 @@ SDValue PPCTargetLowering::combineSetCC(SDNode *N,
 // x != 0-y --> x+y != 0
 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
 RHS.hasOneUse()) {
-  SDLoc DL(N);
-  SelectionDAG  = DCI.DAG;
-  EVT VT = N->getValueType(0);
-  EVT OpVT = LHS.getValueType();
   SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
   return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
 }
   }
 
+  // Combine (a-2^(M-1)) => sext(trunc(a, M), 64)
+  if (CC == ISD::SETULT && LHS.getOpcode() == ISD::ADD && OpVT == MVT::i64 &&
+  isa(RHS) && isa(LHS.getOperand(1))) {
+uint64_t ShiftVal =
+~(cast(LHS.getOperand(1))->getZExtValue()) + 1;
+uint64_t CmpVal = ~(cast(RHS)->getZExtValue()) + 1;
+if (isPowerOf2_64(ShiftVal) && ShiftVal << 1 == CmpVal) {
+  unsigned DestBits = Log2_64(CmpVal);
+  if (DestBits == 8 || DestBits == 16 || DestBits == 32) {
+SDValue Conv =
+DAG.getSExtOrTrunc(DAG.getSExtOrTrunc(LHS.getOperand(0), DL,
+  MVT::getIntegerVT(DestBits)),
+   DL, OpVT);
+return DAG.getSetCC(DL, VT, LHS.getOperand(0), Conv, ISD::SETNE);
+  }
+}
+  }
+
   return DAGCombineTruncBoolExt(N, DCI);
 }
 
diff --git a/llvm/test/CodeGen/PowerPC/setcc-to-sub.ll 
b/llvm/test/CodeGen/PowerPC/setcc-to-sub.ll
index 13c629b6349450c..ce75b77eed29666 100644
--- a/llvm/test/CodeGen/PowerPC/setcc-to-sub.ll
+++ b/llvm/test/CodeGen/PowerPC/setcc-to-sub.ll
@@ -89,6 +89,48 @@ entry:
   ret i1 %cmp.i5
 }
 
+define zeroext i1 @test5(i64 %a) {
+; CHECK-LABEL: test5:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:extsw 4, 3
+; CHECK-NEXT:xor 3, 3, 4
+; CHECK-NEXT:addic 4, 3, -1
+; CHECK-NEXT:subfe 3, 4, 3
+; CHECK-NEXT:blr
+entry:
+  %0 = add i64 %a, -2147483648
+  %cmp = icmp ult i64 %0, -4294967296
+  ret i1 %cmp
+}
+
+define zeroext i1 @test6(i64 %a) {
+; CHECK-LABEL: test6:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:extsh 4, 3
+; CHECK-NEXT:xor 3, 3, 4
+; CHECK-NEXT:addic 4, 3, -1
+; CHECK-NEXT:subfe 3, 4, 3
+; CHECK-NEXT:blr
+entry:
+  %0 = add i64 %a, -32768
+  %cmp = icmp ult i64 %0, -65536
+  ret i1 %cmp
+}
+
+define zeroext i1 @test7(i64 %a) {
+; CHECK-LABEL: test7:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:extsb 4, 3
+; CHECK-NEXT:xor 3, 3, 4
+; CHECK-NEXT:addic 4, 3, -1
+; CHECK-NEXT:subfe 3, 4, 3
+; CHECK-NEXT:blr
+entry:
+  %0 = add i64 %a, -128
+  %cmp = icmp ult i64 %0, -256
+  ret i1 %cmp
+}
+
 !1 = !{!2, !2, i64 0}
 !2 = !{!"int", !3, i64 0}
 !3 = !{!"omnipotent char", !4, i64 0}

>From fbb7e6362d6223f8e0ee6014e000c1cc5ae6e777 Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Wed, 6 Sep 2023 16:16:34 +0800
Subject: [PATCH 2/4] [PowerPC] Combine sub within setcc back to sext

---
 llvm/lib/Target/PowerPC/PPCISelLowering.cpp | 37 +-
 llvm/test/CodeGen/PowerPC/setcc-to-sub.ll   | 42 +
 2 files changed, 69 insertions(+), 10 deletions(-)

diff --git a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp 
b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
index f4e3531980d165f..4659ebef35ecf62 

[clang] [Driver] Make ELF -nopie specific to OpenBSD (PR #72578)

2023-11-29 Thread Mike Hommey via cfe-commits

glandium wrote:

Weirdly, this leads to `warning: argument unused during compilation: '-nopie'` 
rather than `error: unknown argument: '-nopie'`

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


[libunwind] [libunwind][WebAssembly] Omit unused parts of libunwind.cpp for Wasm (PR #73196)

2023-11-29 Thread Heejin Ahn via cfe-commits

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


[libunwind] e88a2f1 - [libunwind][WebAssembly] Omit unused parts of libunwind.cpp for Wasm (#73196)

2023-11-29 Thread via cfe-commits

Author: Heejin Ahn
Date: 2023-11-29T18:03:58-08:00
New Revision: e88a2f123fa4843ae3782377668cf5741acc9121

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

LOG: [libunwind][WebAssembly] Omit unused parts of libunwind.cpp for Wasm 
(#73196)

Wasm doesn't use most of that file; Wasm does not allow access of system
registers and those functionalities are provided from the VM.

Added: 


Modified: 
libunwind/src/libunwind.cpp

Removed: 




diff  --git a/libunwind/src/libunwind.cpp b/libunwind/src/libunwind.cpp
index 1bd18659b7860c0..cd610377b63de8d 100644
--- a/libunwind/src/libunwind.cpp
+++ b/libunwind/src/libunwind.cpp
@@ -26,7 +26,7 @@
 #include 
 #endif
 
-#if !defined(__USING_SJLJ_EXCEPTIONS__)
+#if !defined(__USING_SJLJ_EXCEPTIONS__) || !defined(__USING_WASM_EXCEPTIONS__)
 #include "AddressSpace.hpp"
 #include "UnwindCursor.hpp"
 
@@ -347,7 +347,8 @@ void __unw_remove_dynamic_eh_frame_section(unw_word_t 
eh_frame_start) {
 }
 
 #endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
-#endif // !defined(__USING_SJLJ_EXCEPTIONS__)
+#endif // !defined(__USING_SJLJ_EXCEPTIONS__) ||
+   // !defined(__USING_WASM_EXCEPTIONS__)
 
 #ifdef __APPLE__
 



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


[libunwind] [libunwind][WebAssembly] Omit unused parts of libunwind.cpp for Wasm (PR #73196)

2023-11-29 Thread Heejin Ahn via cfe-commits

aheejin wrote:

I think the CI failures are unrelated. Merging.

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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread Owen Pan via cfe-commits


@@ -1851,6 +1851,22 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsTrailingReturnArrow) {
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) {
+  auto Tokens = annotate("#define Foo(Bar) \\\n"
+ "  { \\\n"
+ "#Bar \\\n"
+ "  }\n");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+
+  Tokens = annotate("#define Foo(Bar) \\\n"
+"  { #Bar }\n");

owenca wrote:

Ditto.

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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread Owen Pan via cfe-commits


@@ -1851,6 +1851,22 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsTrailingReturnArrow) {
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) {
+  auto Tokens = annotate("#define Foo(Bar) \\\n"
+ "  { \\\n"
+ "#Bar \\\n"
+ "  }\n");

owenca wrote:

Do we need the newline?

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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread Owen Pan via cfe-commits


@@ -496,7 +496,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 do {
   NextTok = Tokens->getNextToken();
 } while (NextTok->is(tok::comment));
-while (NextTok->is(tok::hash)) {
+while (NextTok->is(tok::hash) && !Line->InPPDirective) {

owenca wrote:

```suggestion
while (NextTok->is(tok::hash) && !Line->InMacroBody) {
```
To be precise?

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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Emilia Kond (rymiel)


Changes

PR #69473 introduced skipping PP directives when determining the brace 
kind of an lbrace. However, it did so by skipping to the end of the line when 
encountering a hash character. This means it also skipped to the end of line 
when encountering a macro stringizing operator, which, unlike PP directives, 
don't have effect until the end of line.

This led to cases where the rbrace could be completely skipped if it was on the 
same line as a stringizing operator.

This patch skips hash characters if we're already in a PP directive, as you 
can't define a macro inside of a macro

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

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


2 Files Affected:

- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+1-1) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+16) 


``diff
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index a5a4419b98239e6..5f574dfeafc874b 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -496,7 +496,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 do {
   NextTok = Tokens->getNextToken();
 } while (NextTok->is(tok::comment));
-while (NextTok->is(tok::hash)) {
+while (NextTok->is(tok::hash) && !Line->InPPDirective) {
   NextTok = Tokens->getNextToken();
   do {
 NextTok = Tokens->getNextToken();
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index bc734573ce0cb4d..8ad6a585d004593 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1851,6 +1851,22 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsTrailingReturnArrow) {
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) {
+  auto Tokens = annotate("#define Foo(Bar) \\\n"
+ "  { \\\n"
+ "#Bar \\\n"
+ "  }\n");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+
+  Tokens = annotate("#define Foo(Bar) \\\n"
+"  { #Bar }\n");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacros) {
   // '__attribute__' has special handling.
   auto Tokens = annotate("__attribute__(X) void Foo(void);");

``




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


[clang] [clang-format] Don't skip stringizing when determining brace kind (PR #73886)

2023-11-29 Thread Emilia Kond via cfe-commits

https://github.com/rymiel created 
https://github.com/llvm/llvm-project/pull/73886

PR #69473 introduced skipping PP directives when determining the brace kind of 
an lbrace. However, it did so by skipping to the end of the line when 
encountering a hash character. This means it also skipped to the end of line 
when encountering a macro stringizing operator, which, unlike PP directives, 
don't have effect until the end of line.

This led to cases where the rbrace could be completely skipped if it was on the 
same line as a stringizing operator.

This patch skips hash characters if we're already in a PP directive, as you 
can't define a macro inside of a macro

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

>From 95e2a2ee5d901d79430cb9b9468e1af8215b334f Mon Sep 17 00:00:00 2001
From: Emilia Kond 
Date: Thu, 30 Nov 2023 03:30:48 +0200
Subject: [PATCH] [clang-format] Don't skip stringizing when determining brace
 kind

PR #69473 introduced skipping PP directives when determining the brace
kind of an lbrace. However, it did so by skipping to the end of the line
when encountering a hash character. This means it also skipped to the
end of line when encountering a macro stringizing operator, which, unlike
PP directives, don't have effect until the end of line.

This led to cases where the rbrace could be completely skipped if it was
on the same line as a stringizing operator.

This patch skips hash characters if we're already in a PP directive, as
you can't define a macro inside of a macro

Fixes https://github.com/llvm/llvm-project/issues/72662
---
 clang/lib/Format/UnwrappedLineParser.cpp  |  2 +-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 16 
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index a5a4419b98239e6..5f574dfeafc874b 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -496,7 +496,7 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
 do {
   NextTok = Tokens->getNextToken();
 } while (NextTok->is(tok::comment));
-while (NextTok->is(tok::hash)) {
+while (NextTok->is(tok::hash) && !Line->InPPDirective) {
   NextTok = Tokens->getNextToken();
   do {
 NextTok = Tokens->getNextToken();
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index bc734573ce0cb4d..8ad6a585d004593 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1851,6 +1851,22 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsTrailingReturnArrow) {
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandHashInMacro) {
+  auto Tokens = annotate("#define Foo(Bar) \\\n"
+ "  { \\\n"
+ "#Bar \\\n"
+ "  }\n");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+
+  Tokens = annotate("#define Foo(Bar) \\\n"
+"  { #Bar }\n");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_BRACE_KIND(Tokens[6], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacros) {
   // '__attribute__' has special handling.
   auto Tokens = annotate("__attribute__(X) void Foo(void);");

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


[clang] [clang][NFC] Refactor expected directives in C++ DRs 1-99 (PR #73879)

2023-11-29 Thread Vlad Serebrennikov via cfe-commits


@@ -80,14 +86,21 @@ namespace dr5 { // dr5: 3.1
 
 namespace dr7 { // dr7: 3.4
   class A { public: ~A(); };
-  class B : virtual private A {}; // expected-note 2 {{declared private here}}
-  class C : public B {} c; // expected-error 2 {{inherited virtual base class 
'A' has private destructor}} \
-   // expected-note {{implicit default constructor for 
'dr7::C' first required here}} \
-   // expected-note {{implicit destructor for 'dr7::C' 
first required here}}
+  class B : virtual private A {}; // #dr7-B
+  class C : public B {} c; // #dr7-C
+  // expected-error@#dr7-C {{inherited virtual base class 'A' has private 
destructor}}
+  // expected-note@#dr7-C {{in implicit default constructor for 'dr7::C' first 
required here}}
+  // expected-note@#dr7-B {{declared private here}}

Endilll wrote:

I had a thought of naming those markers `dr7-struct-C`, but decided to 
prioritize shorter markers. If you find this more accessible, we can do it this 
way.

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


[clang] [clang][NFC] Refactor expected directives in C++ DRs 1-99 (PR #73879)

2023-11-29 Thread Shafik Yaghmour via cfe-commits


@@ -80,14 +86,21 @@ namespace dr5 { // dr5: 3.1
 
 namespace dr7 { // dr7: 3.4
   class A { public: ~A(); };
-  class B : virtual private A {}; // expected-note 2 {{declared private here}}
-  class C : public B {} c; // expected-error 2 {{inherited virtual base class 
'A' has private destructor}} \
-   // expected-note {{implicit default constructor for 
'dr7::C' first required here}} \
-   // expected-note {{implicit destructor for 'dr7::C' 
first required here}}
+  class B : virtual private A {}; // #dr7-B
+  class C : public B {} c; // #dr7-C
+  // expected-error@#dr7-C {{inherited virtual base class 'A' has private 
destructor}}
+  // expected-note@#dr7-C {{in implicit default constructor for 'dr7::C' first 
required here}}
+  // expected-note@#dr7-B {{declared private here}}

shafik wrote:

I have to say, it is kind of messing with me that we have `-C` before `-B` but 
I then realized that `B` and `C` are the class names here and don't imply some 
sort of ordering.

I wanted to point that out in case others also felt that way.

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


[clang] [clang][NFC] Refactor expected directives in C++ DRs 1-99 (PR #73879)

2023-11-29 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

I think I mostly like this direction.

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


[clang] [clang][NFC] Refactor expected directives in C++ DRs 1-99 (PR #73879)

2023-11-29 Thread Shafik Yaghmour via cfe-commits

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


[clang] [Clang][Lex] Fix parsing of nested requirement to prevent flowing off the end of token stream (PR #73691)

2023-11-29 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik updated 
https://github.com/llvm/llvm-project/pull/73691

>From 21d6bbdd1f8676e51b053ec3dd9020270e6b929e Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Tue, 28 Nov 2023 11:20:12 -0800
Subject: [PATCH] [Clang][Lex] Fix parsing of nested requirement to prevent
 flowing off the end of token stream

Currently when parsing a nested requirement we attempt to balance parens if we
have a parameter list. This will fail in some cases of ill-formed code and keep
going until we fall off the token stream and crash. This fixes the hand parsing
by using SkipUntil which will properly flag if we don't find the expected
tokens.

Fixes: https://github.com/llvm/llvm-project/issues/73112
---
 clang/docs/ReleaseNotes.rst| 3 +++
 clang/lib/Parse/ParseExprCXX.cpp   | 6 --
 clang/test/Parser/cxx2a-concepts-requires-expr.cpp | 8 
 3 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7c909ac3cab6419..f8abc44743da09c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -783,6 +783,9 @@ Bug Fixes to C++ Support
   completes (except deduction guides). Fixes:
   (`#59827 `_)
 
+- Fix crash when parsing nested requirement. Fixes:
+  (`#73112 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp
index 79db094e098f8e6..8b86db1bb8fc5d5 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -3635,10 +3635,12 @@ ExprResult Parser::ParseRequiresExpression() {
   auto Res = TryParseParameterDeclarationClause();
   if (Res != TPResult::False) {
 // Skip to the closing parenthesis
-// FIXME: Don't traverse these tokens twice (here and in
-//  TryParseParameterDeclarationClause).
 unsigned Depth = 1;
 while (Depth != 0) {
+  bool FoundParen = SkipUntil(tok::l_paren, tok::r_paren,
+  SkipUntilFlags::StopBeforeMatch);
+  if (!FoundParen)
+break;
   if (Tok.is(tok::l_paren))
 Depth++;
   else if (Tok.is(tok::r_paren))
diff --git a/clang/test/Parser/cxx2a-concepts-requires-expr.cpp 
b/clang/test/Parser/cxx2a-concepts-requires-expr.cpp
index a18a54c7fad0690..971591afb08dba2 100644
--- a/clang/test/Parser/cxx2a-concepts-requires-expr.cpp
+++ b/clang/test/Parser/cxx2a-concepts-requires-expr.cpp
@@ -160,3 +160,11 @@ template 
 requires requires {
  typename BitInt; // ok
 } using r44 = void;
+
+namespace GH73112 {
+void f() {
+requires { requires(int; } // expected-error {{expected ')'}} \
+   // expected-error {{expected expression}} \
+   // expected-note {{to match this '('}}
+}
+}

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


[clang] [clang][NFC] Refactor expected directives in C++ DRs 1-99 (PR #73879)

2023-11-29 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

I'm putting this NFC for a review, because that's the direction I'd like our DR 
test suite to take. If it goes well, I'll go on and refactor the rest of the 
test suite in this manner.

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


[clang] [libcxx] [clang-tools-extra] [flang] [compiler-rt] [lld] [llvm] [lldb] [libc] Fix clang to recognize new C23 modifiers %w and %wf when printing (PR #71771)

2023-11-29 Thread via cfe-commits

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

>From 06c4cf02dfb4b20c8349c5f3c7209276f6d56edf Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Thu, 9 Nov 2023 02:21:46 +
Subject: [PATCH 1/3] Fix clang to recognize new C23 modifiers %w and %wf when
 printing

---
 clang/include/clang/AST/FormatString.h | 16 +++-
 clang/lib/AST/FormatString.cpp | 52 +-
 clang/lib/AST/PrintfFormatString.cpp   | 19 ++
 clang/test/Sema/format-strings-ms.c| 28 ++
 4 files changed, 112 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index 5c4ad9baaef608c..6a886854650f1d9 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -81,8 +81,10 @@ class LengthModifier {
 AsLongDouble, // 'L'
 AsAllocate,   // for '%as', GNU extension to C90 scanf
 AsMAllocate,  // for '%ms', GNU extension to scanf
-AsWide,   // 'w' (MSVCRT, like l but only for c, C, s, S, or Z
-AsWideChar = AsLong // for '%ls', only makes sense for printf
+AsWide,   // 'w' (1. MSVCRT, like l but only for c, C, s, S, or Z on 
windows
+  // 2. for b, d, i, o, u, x, or X when a size followed(like 
8, 16, 32 or 64)
+AsWideFast,   // 'wf' (for b, d, i, o, u, x, or X)
+AsWideChar = AsLong, // for '%ls', only makes sense for printf
   };
 
   LengthModifier()
@@ -417,6 +419,7 @@ class FormatSpecifier {
   ///  http://www.opengroup.org/onlinepubs/009695399/functions/printf.html
   bool UsesPositionalArg;
   unsigned argIndex;
+  unsigned size;
 public:
   FormatSpecifier(bool isPrintf)
 : CS(isPrintf), VectorNumElts(false),
@@ -460,6 +463,15 @@ class FormatSpecifier {
 FieldWidth = Amt;
   }
 
+  void setSize(unsigned s) {
+size = s;
+  }
+
+  unsigned getSize() const {
+return size;
+  }
+
+
   bool usesPositionalArg() const { return UsesPositionalArg; }
 
   bool hasValidLengthModifier(const TargetInfo ,
diff --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index e0c9e18cfe3a243..ebc136e780717e4 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -286,7 +286,33 @@ 
clang::analyze_format_string::ParseLengthModifier(FormatSpecifier ,
   lmKind = LengthModifier::AsInt3264;
   break;
 case 'w':
-  lmKind = LengthModifier::AsWide; ++I; break;
+  ++I;
+  if (I == E) return false;
+  if (*I == 'f') {
+lmKind = LengthModifier::AsWideFast;
+++I;
+  } else {
+lmKind = LengthModifier::AsWide;
+  }
+
+  if (I == E) return false;
+  int s = 0;
+  while (unsigned(*I - '0') <= 9) {
+s = 10 * s + unsigned(*I - '0');
+++I;
+  }
+
+  // s == 0 is MSVCRT case, like l but only for c, C, s, S, or Z on windows
+  // s != 0 for b, d, i, o, u, x, or X when a size followed(like 8, 16, 32 
or 64)
+  if (s != 0) {
+std::set supported_list {8, 16, 32, 64};
+if (supported_list.count(s) == 0) {
+  return false;
+}
+FS.setSize(s);
+  }
+
+  break;
   }
   LengthModifier lm(lmPosition, lmKind);
   FS.setLengthModifier(lm);
@@ -703,6 +729,8 @@ analyze_format_string::LengthModifier::toString() const {
 return "m";
   case AsWide:
 return "w";
+  case AsWideFast:
+return "wf";
   case None:
 return "";
   }
@@ -970,6 +998,27 @@ bool FormatSpecifier::hasValidLengthModifier(const 
TargetInfo ,
 case ConversionSpecifier::SArg:
 case ConversionSpecifier::ZArg:
   return Target.getTriple().isOSMSVCRT();
+case ConversionSpecifier::bArg:
+case ConversionSpecifier::dArg:
+case ConversionSpecifier::iArg:
+case ConversionSpecifier::oArg:
+case ConversionSpecifier::uArg:
+case ConversionSpecifier::xArg:
+case ConversionSpecifier::XArg:
+  return true;
+default:
+  return false;
+  }
+case LengthModifier::AsWideFast:
+  switch (CS.getKind()) {
+case ConversionSpecifier::bArg:
+case ConversionSpecifier::dArg:
+case ConversionSpecifier::iArg:
+case ConversionSpecifier::oArg:
+case ConversionSpecifier::uArg:
+case ConversionSpecifier::xArg:
+case ConversionSpecifier::XArg:
+  return true;
 default:
   return false;
   }
@@ -996,6 +1045,7 @@ bool FormatSpecifier::hasStandardLengthModifier() const {
 case LengthModifier::AsInt3264:
 case LengthModifier::AsInt64:
 case LengthModifier::AsWide:
+case LengthModifier::AsWideFast:
 case LengthModifier::AsShortLong: // ???
   return false;
   }
diff --git a/clang/lib/AST/PrintfFormatString.cpp 
b/clang/lib/AST/PrintfFormatString.cpp
index f0b9d0ecaf23461..4b9111e8bcf509a 100644
--- a/clang/lib/AST/PrintfFormatString.cpp
+++ 

[clang] [clang][NFC] Refactor expected directives in C++ DRs 1-99 (PR #73879)

2023-11-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

This patch converts (almost) every expected directive in 
`test/CXX/drs/dr0xx.cpp` into either `@-1` form (when directive immediately 
follow the line diagnostic is pointing out to), or `@#marker` form 
(when directive is placed away from the line diagnostic is pointing out to). It 
also converts directive to match exactly one diagnostic, as opposed to matching 
multiple. Error messages are expanded to exactly match compiler output. `#if 
__cplusplus` guarding directives are replaced with respective prefixes (e.g. 
`since-cxx17`).

All aforementioned changes serve a purpose of making it easier to reconstruct 
expected compiler output, which should also make it a bit easier to grasp the 
gist of those already non-trivial tests due to their nature of testing corner 
cases of the language.

---

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


1 Files Affected:

- (modified) clang/test/CXX/drs/dr0xx.cpp (+496-290) 


``diff
diff --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp
index 1210c7a834e5970..e79ce6daf2655c5 100644
--- a/clang/test/CXX/drs/dr0xx.cpp
+++ b/clang/test/CXX/drs/dr0xx.cpp
@@ -1,9 +1,9 @@
-// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -Wno-bind-to-temporary-copy
-// RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
-// RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
-// RUN: %clang_cc1 -std=c++17 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
-// RUN: %clang_cc1 -std=c++20 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
-// RUN: %clang_cc1 -std=c++23 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++98 %s -verify=expected,cxx98,cxx98-14 -fexceptions 
-fcxx-exceptions -pedantic-errors -Wno-bind-to-temporary-copy
+// RUN: %clang_cc1 -std=c++11 %s 
-verify=expected,since-cxx11,cxx98-14,cxx11-14 -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++14 %s 
-verify=expected,since-cxx11,cxx98-14,cxx11-14 -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++17 %s -verify=expected,since-cxx11,since-cxx17 
-fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++20 %s -verify=expected,since-cxx11,since-cxx17 
-fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx11,since-cxx17 
-fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
 
 namespace dr1 { // dr1: no
   namespace X { extern "C" void dr1_f(int a = 1); }
@@ -26,9 +26,11 @@ namespace dr1 { // dr1: no
   namespace X {
 void z(int);
   }
-  void X::z(int = 1) {} // expected-note {{previous}}
+  void X::z(int = 1) {} // #dr1-z
   namespace X {
-void z(int = 1); // expected-error {{redefinition of default argument}}
+void z(int = 1);
+// expected-error@-1 {{redefinition of default argument}}
+// expected-note@#dr1-z {{previous definition is here}}
   }
 
   void i(int = 1);
@@ -50,17 +52,21 @@ namespace dr1 { // dr1: no
 
 namespace dr3 { // dr3: yes
   template struct A {};
-  template void f(T) { A a; } // expected-note {{implicit 
instantiation}}
+  template void f(T) { A a; } // #dr3-f-T
   template void f(int);
-  template<> struct A {}; // expected-error {{explicit specialization of 
'dr3::A' after instantiation}}
+  template<> struct A {};
+  // expected-error@-1 {{explicit specialization of 'dr3::A' after 
instantiation}}
+  // expected-note@#dr3-f-T {{implicit instantiation first required here}}
 }
 
 namespace dr4 { // dr4: yes
   extern "C" {
 static void dr4_f(int) {}
 static void dr4_f(float) {}
-void dr4_g(int) {} // expected-note {{previous}}
-void dr4_g(float) {} // expected-error {{conflicting types}}
+void dr4_g(int) {} // #dr4-g-int
+void dr4_g(float) {}
+// expected-error@-1 {{conflicting types for 'dr4_g'}}
+// expected-note@#dr4-g-int {{previous definition is here}}
   }
 }
 
@@ -80,14 +86,21 @@ namespace dr5 { // dr5: 3.1
 
 namespace dr7 { // dr7: 3.4
   class A { public: ~A(); };
-  class B : virtual private A {}; // expected-note 2 {{declared private here}}
-  class C : public B {} c; // expected-error 2 {{inherited virtual base class 
'A' has private destructor}} \
-   // expected-note {{implicit default constructor for 
'dr7::C' first required here}} \
-   // expected-note {{implicit destructor for 'dr7::C' 
first required here}}
+  class B : virtual private A {}; // #dr7-B
+  

[clang] [clang][NFC] Refactor expected directives in C++ DRs 1-99 (PR #73879)

2023-11-29 Thread Vlad Serebrennikov via cfe-commits

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

This patch converts (almost) every expected directive in 
`test/CXX/drs/dr0xx.cpp` into either `@-1` form (when directive immediately 
follow the line diagnostic is pointing out to), or `@#` form (when 
directive is placed away from the line diagnostic is pointing out to). It also 
converts directive to match exactly one diagnostic, as opposed to matching 
multiple. Error messages are expanded to exactly match compiler output. `#if 
__cplusplus` guarding directives are replaced with respective prefixes (e.g. 
`since-cxx17`).

All aforementioned changes serve a purpose of making it easier to reconstruct 
expected compiler output, which should also make it a bit easier to grasp the 
gist of those already non-trivial tests due to their nature of testing corner 
cases of the language.

>From d34fde4c1ac3fda1260da75d621d481edcb3eaba Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Thu, 30 Nov 2023 03:25:01 +0300
Subject: [PATCH] [clang][NFC] Refactor expected directives in C++ DRs 1-99

This patch converts (almost) every expected directive in 
`test/CXX/drs/dr0xx.cpp` into either `@-1` form (when directive immediately 
follow the line diagnostic is pointing out to), or `@#` form (when 
directive is placed away from the line diagnostic is pointing out to). It also 
converts directive to match exactly one diagnostic, as opposed to matching 
multiple. Error messages are expanded to exactly match compiler output. `#if 
__cplusplus` guarding directives are replaced with respective prefixes (e.g. 
`since-cxx17`).

All aforementioned changes serve a purpose of making it easier to reconstruct 
expected compiler output, which should also make it a bit easier to grasp the 
gist of those already non-trivial tests due to their nature of testing corner 
cases of the language.
---
 clang/test/CXX/drs/dr0xx.cpp | 786 ++-
 1 file changed, 496 insertions(+), 290 deletions(-)

diff --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp
index 1210c7a834e5970..e79ce6daf2655c5 100644
--- a/clang/test/CXX/drs/dr0xx.cpp
+++ b/clang/test/CXX/drs/dr0xx.cpp
@@ -1,9 +1,9 @@
-// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -Wno-bind-to-temporary-copy
-// RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
-// RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
-// RUN: %clang_cc1 -std=c++17 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
-// RUN: %clang_cc1 -std=c++20 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
-// RUN: %clang_cc1 -std=c++23 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++98 %s -verify=expected,cxx98,cxx98-14 -fexceptions 
-fcxx-exceptions -pedantic-errors -Wno-bind-to-temporary-copy
+// RUN: %clang_cc1 -std=c++11 %s 
-verify=expected,since-cxx11,cxx98-14,cxx11-14 -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++14 %s 
-verify=expected,since-cxx11,cxx98-14,cxx11-14 -fexceptions -fcxx-exceptions 
-pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++17 %s -verify=expected,since-cxx11,since-cxx17 
-fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++20 %s -verify=expected,since-cxx11,since-cxx17 
-fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
+// RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx11,since-cxx17 
-fexceptions -fcxx-exceptions -pedantic-errors -triple %itanium_abi_triple
 
 namespace dr1 { // dr1: no
   namespace X { extern "C" void dr1_f(int a = 1); }
@@ -26,9 +26,11 @@ namespace dr1 { // dr1: no
   namespace X {
 void z(int);
   }
-  void X::z(int = 1) {} // expected-note {{previous}}
+  void X::z(int = 1) {} // #dr1-z
   namespace X {
-void z(int = 1); // expected-error {{redefinition of default argument}}
+void z(int = 1);
+// expected-error@-1 {{redefinition of default argument}}
+// expected-note@#dr1-z {{previous definition is here}}
   }
 
   void i(int = 1);
@@ -50,17 +52,21 @@ namespace dr1 { // dr1: no
 
 namespace dr3 { // dr3: yes
   template struct A {};
-  template void f(T) { A a; } // expected-note {{implicit 
instantiation}}
+  template void f(T) { A a; } // #dr3-f-T
   template void f(int);
-  template<> struct A {}; // expected-error {{explicit specialization of 
'dr3::A' after instantiation}}
+  template<> struct A {};
+  // expected-error@-1 {{explicit specialization of 'dr3::A' after 
instantiation}}
+  // expected-note@#dr3-f-T {{implicit instantiation first required here}}
 }
 
 namespace dr4 { // dr4: yes
   extern "C" {
 static void dr4_f(int) {}
 static 

[clang] [flang] [lldb] [lld] [libcxx] [compiler-rt] [llvm] [clang-tools-extra] [libc] Fix clang to recognize new C23 modifiers %w and %wf when printing (PR #71771)

2023-11-29 Thread via cfe-commits


@@ -286,7 +286,33 @@ 
clang::analyze_format_string::ParseLengthModifier(FormatSpecifier ,
   lmKind = LengthModifier::AsInt3264;
   break;
 case 'w':
-  lmKind = LengthModifier::AsWide; ++I; break;
+  ++I;
+  if (I == E) return false;
+  if (*I == 'f') {
+lmKind = LengthModifier::AsWideFast;
+++I;
+  } else {
+lmKind = LengthModifier::AsWide;
+  }
+
+  if (I == E) return false;
+  int s = 0;
+  while (unsigned(*I - '0') <= 9) {
+s = 10 * s + unsigned(*I - '0');
+++I;
+  }
+
+  // s == 0 is MSVCRT case, like l but only for c, C, s, S, or Z on windows
+  // s != 0 for b, d, i, o, u, x, or X when a size followed(like 8, 16, 32 
or 64)
+  if (s != 0) {
+std::set supported_list {8, 16, 32, 64};

enh-google wrote:

> So I think we should probably err on the side of specifying all the 
> bit-widths we specify in stdint.h.

as a libc maintainer (who happens to have done a survey of the other libcs on 
this specific bit of C23 functionality, when zijunzhao was implementing it for 
bionic :-) ), i'd argue the opposite: none of bionic, glibc, musl, FreeBSD, and 
Apple's fork of FreeBSD libc supports these weird sizes[1]. nor does any 
hardware i'm aware of. i'd actually argue that the llvm stdint.h change that 
added these types should be reverted[2]. (presumably someone who knows the llvm 
code better can check whether it's possible for clang to ever actually define 
`__INT48_TYPE__` and its non-power-of-two friends? if there really _is_ such an 
architecture, we could at least get a useful code comment in stdint.h out of 
it!)

as for the diagnostics, i'd argue (a) it doesn't make sense having this be 
libc-specific (like, for example, the existing "do math functions set errno?" 
configuration) since every libc in use would have the same "no, we don't 
support 48-bit ints" setting and (b) saying "well, 56-bit ints _might_ be a 
thing in theory, so we'll punt and leave it to be runtime error" isn't very 
helpful in a world where it will always be a runtime error.

___
1. to be fair, a couple of them still don't implement %w at all. at the risk of 
making more work for zijunzhao, if you were going to teach clang about 
different libc versions, _that_ would at least be useful (for those targets 
that include a version in them): "which version of Android/iOS first had %b?" 
etc. if i'm using %b but targeting a version that didn't have it, that's a 
useful compile-time warning, at least as long as anyone's targeting old-enough 
versions. (and, full disclosure: for Android that's the same as %w: they're 
both new in this year's release --- 
https://android.googlesource.com/platform/bionic/+/HEAD/docs/status.md)
2. personally, i don't feel like the commit message on the change that 
introduced this stuff to stdint.h motivated it at all. i suspect if llvm hadn't 
still been an academic project back then, that change would never have been 
accepted in the first place!

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


[clang] [clang-format] Option to ignore macro definitions (PR #70338)

2023-11-29 Thread Owen Pan via cfe-commits


@@ -1157,7 +1157,15 @@ void UnwrappedLineParser::parsePPDefine() {
   // guard processing above, and changes preprocessing nesting.
   FormatTok->Tok.setKind(tok::identifier);
   FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
-  nextToken();
+
+  if (Style.SkipMacroDefinitionBody) {
+do {
+  nextToken();
+} while (!eof());
+  } else {
+nextToken();
+  }

owenca wrote:

Instead, we can simply mark the tokens `Finalized` (after `Line->InMacroBody` 
is set to `true` below) so that the continuation indenter can be left alone.

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


[clang] [Clang] Generate the GEP instead of adding AST nodes (PR #73730)

2023-11-29 Thread Eli Friedman via cfe-commits


@@ -956,42 +958,112 @@ static llvm::Value 
*getArrayIndexingBound(CodeGenFunction ,
   return nullptr;
 }
 
-const Expr *
-CodeGenFunction::BuildCountedByFieldExpr(const Expr *Base,
- const ValueDecl *CountedByVD) {
+namespace {
+
+/// \p MemberExprBaseVisitor returns the base \p DeclRefExpr of a field access.
+class MemberExprBaseVisitor
+: public StmtVisitor {
+  const RecordDecl *ExpectedRD;
+
+  bool IsExpectedRecordDecl(const Expr *E) const {
+QualType Ty = E->getType();
+if (Ty->isPointerType())
+  Ty = Ty->getPointeeType();
+return ExpectedRD == Ty->getAsRecordDecl();
+  }
+
+public:
+  MemberExprBaseVisitor(const RecordDecl *ExpectedRD)
+  : ExpectedRD(ExpectedRD) { }
+
+  
//======//
+  //Visitor Methods
+  
//======//
+
+  // Note: if we build C++ support for counted_by, then we'll have to handle
+  // horrors like this:
+  //
+  // struct S {
+  //   int x, y;
+  //   int blah[] __attribute__((counted_by(x)));
+  // } s;
+  //
+  // int foo(int index, int val) {
+  //   int (S::*IHatePMDs)[] = ::blah;
+  //   (s.*IHatePMDs)[index] = val;
+  // }
+
+  Expr *Visit(Expr *E) {
+return StmtVisitor::Visit(E);
+  }
+
+  Expr *VisitCastExpr(CastExpr *E) {
+return IsExpectedRecordDecl(E) ? E : Visit(E->getSubExpr());
+  }
+  Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
+return IsExpectedRecordDecl(E) ? E : nullptr;
+  }
+  Expr *VisitDeclRefExpr(DeclRefExpr *E) {
+return IsExpectedRecordDecl(E) ? E : nullptr;
+  }
+  Expr *VisitMemberExpr(MemberExpr *E) {
+Expr *Res = Visit(E->getBase());
+return !Res && IsExpectedRecordDecl(E) ? E : Res;
+  }
+  Expr *VisitParenExpr(ParenExpr *E) {
+return IsExpectedRecordDecl(E) ? E : Visit(E->getSubExpr());
+  }
+
+  Expr *VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
+return Visit(E->getBase());
+  }
+  Expr *VisitImplicitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
+  Expr *VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
+};
+
+} // end anonymous namespace
+
+llvm::Value *
+CodeGenFunction::EmitCountedByFieldExpr(const Expr *Base,
+const ValueDecl *CountedByVD) {
+  const DeclContext *DC = CountedByVD->getLexicalDeclContext();
+  const auto *CountedByRD = cast(DC);
+
   // Find the outer struct expr (i.e. p in p->a.b.c.d).
-  Expr *CountedByExpr = const_cast(Base)->IgnoreParenImpCasts();
-
-  // Work our way up the expression until we reach the DeclRefExpr.
-  while (!isa(CountedByExpr))
-if (const auto *ME = dyn_cast(CountedByExpr))
-  CountedByExpr = ME->getBase()->IgnoreParenImpCasts();
-
-  // Add back an implicit cast to create the required pr-value.
-  CountedByExpr = ImplicitCastExpr::Create(
-  getContext(), CountedByExpr->getType(), CK_LValueToRValue, CountedByExpr,
-  nullptr, VK_PRValue, FPOptionsOverride());
-
-  if (const auto *IFD = dyn_cast(CountedByVD)) {
-// The counted_by field is inside an anonymous struct / union. The
-// IndirectFieldDecl has the correct order of FieldDecls to build this
-// easily. (Yay!)
-for (NamedDecl *ND : IFD->chain()) {
-  auto *VD = cast(ND);
-  CountedByExpr =
-  MemberExpr::CreateImplicit(getContext(), CountedByExpr,
- CountedByExpr->getType()->isPointerType(),
- VD, VD->getType(), VK_LValue, 
OK_Ordinary);
-}
-  } else {
-CountedByExpr = MemberExpr::CreateImplicit(
-getContext(), const_cast(CountedByExpr),
-CountedByExpr->getType()->isPointerType(),
-const_cast(CountedByVD), CountedByVD->getType(), 
VK_LValue,
-OK_Ordinary);
+  Expr *CountedByExpr =
+  MemberExprBaseVisitor(CountedByRD).Visit(const_cast(Base));
+  if (!CountedByExpr)
+return nullptr;
+
+  llvm::Value *Res = nullptr;
+  if (CountedByExpr->getType()->isPointerType())
+Res = EmitPointerWithAlignment(CountedByExpr).getPointer();

efriedma-quic wrote:

We generally don't track previously emitted values for an Expr.  I think you'd 
want to change CodeGenFunction::EmitArraySubscriptExpr to have a special 
codepath for emitting array subscripts with a counted_by bound.  (While you're 
computing/emitting indexing for the counted_by field, you can also emit the 
indexing for the array itself at the same time.  So we just skip the code that 
would normally emit the base, and just use the base computed by your code 
instead.)

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


[clang] [Clang] Generate the GEP instead of adding AST nodes (PR #73730)

2023-11-29 Thread Eli Friedman via cfe-commits


@@ -956,42 +958,112 @@ static llvm::Value 
*getArrayIndexingBound(CodeGenFunction ,
   return nullptr;
 }
 
-const Expr *
-CodeGenFunction::BuildCountedByFieldExpr(const Expr *Base,
- const ValueDecl *CountedByVD) {
+namespace {
+
+/// \p MemberExprBaseVisitor returns the base \p DeclRefExpr of a field access.
+class MemberExprBaseVisitor
+: public StmtVisitor {
+  const RecordDecl *ExpectedRD;
+
+  bool IsExpectedRecordDecl(const Expr *E) const {
+QualType Ty = E->getType();
+if (Ty->isPointerType())
+  Ty = Ty->getPointeeType();
+return ExpectedRD == Ty->getAsRecordDecl();
+  }
+
+public:
+  MemberExprBaseVisitor(const RecordDecl *ExpectedRD)
+  : ExpectedRD(ExpectedRD) { }
+
+  
//======//
+  //Visitor Methods
+  
//======//
+
+  // Note: if we build C++ support for counted_by, then we'll have to handle
+  // horrors like this:
+  //
+  // struct S {
+  //   int x, y;
+  //   int blah[] __attribute__((counted_by(x)));
+  // } s;
+  //
+  // int foo(int index, int val) {
+  //   int (S::*IHatePMDs)[] = ::blah;
+  //   (s.*IHatePMDs)[index] = val;
+  // }
+
+  Expr *Visit(Expr *E) {
+return StmtVisitor::Visit(E);
+  }
+
+  Expr *VisitCastExpr(CastExpr *E) {

efriedma-quic wrote:

Did you mean to have codepaths for both CastExpr and ImplicitCastExpr?

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


[clang] [Clang] Generate the GEP instead of adding AST nodes (PR #73730)

2023-11-29 Thread Eli Friedman via cfe-commits


@@ -956,42 +958,112 @@ static llvm::Value 
*getArrayIndexingBound(CodeGenFunction ,
   return nullptr;
 }
 
-const Expr *
-CodeGenFunction::BuildCountedByFieldExpr(const Expr *Base,
- const ValueDecl *CountedByVD) {
+namespace {
+
+/// \p MemberExprBaseVisitor returns the base \p DeclRefExpr of a field access.
+class MemberExprBaseVisitor
+: public StmtVisitor {
+  const RecordDecl *ExpectedRD;
+
+  bool IsExpectedRecordDecl(const Expr *E) const {
+QualType Ty = E->getType();
+if (Ty->isPointerType())
+  Ty = Ty->getPointeeType();
+return ExpectedRD == Ty->getAsRecordDecl();
+  }
+
+public:
+  MemberExprBaseVisitor(const RecordDecl *ExpectedRD)
+  : ExpectedRD(ExpectedRD) { }
+
+  
//======//
+  //Visitor Methods
+  
//======//
+
+  // Note: if we build C++ support for counted_by, then we'll have to handle
+  // horrors like this:
+  //
+  // struct S {
+  //   int x, y;
+  //   int blah[] __attribute__((counted_by(x)));
+  // } s;
+  //
+  // int foo(int index, int val) {
+  //   int (S::*IHatePMDs)[] = ::blah;
+  //   (s.*IHatePMDs)[index] = val;
+  // }
+
+  Expr *Visit(Expr *E) {
+return StmtVisitor::Visit(E);
+  }
+
+  Expr *VisitCastExpr(CastExpr *E) {
+return IsExpectedRecordDecl(E) ? E : Visit(E->getSubExpr());
+  }
+  Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
+return IsExpectedRecordDecl(E) ? E : nullptr;
+  }
+  Expr *VisitDeclRefExpr(DeclRefExpr *E) {
+return IsExpectedRecordDecl(E) ? E : nullptr;
+  }
+  Expr *VisitMemberExpr(MemberExpr *E) {
+Expr *Res = Visit(E->getBase());
+return !Res && IsExpectedRecordDecl(E) ? E : Res;
+  }
+  Expr *VisitParenExpr(ParenExpr *E) {
+return IsExpectedRecordDecl(E) ? E : Visit(E->getSubExpr());
+  }
+
+  Expr *VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
+return Visit(E->getBase());
+  }
+  Expr *VisitImplicitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
+  Expr *VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
+};
+
+} // end anonymous namespace
+
+llvm::Value *
+CodeGenFunction::EmitCountedByFieldExpr(const Expr *Base,
+const ValueDecl *CountedByVD) {
+  const DeclContext *DC = CountedByVD->getLexicalDeclContext();
+  const auto *CountedByRD = cast(DC);
+
   // Find the outer struct expr (i.e. p in p->a.b.c.d).
-  Expr *CountedByExpr = const_cast(Base)->IgnoreParenImpCasts();
-
-  // Work our way up the expression until we reach the DeclRefExpr.
-  while (!isa(CountedByExpr))
-if (const auto *ME = dyn_cast(CountedByExpr))
-  CountedByExpr = ME->getBase()->IgnoreParenImpCasts();
-
-  // Add back an implicit cast to create the required pr-value.
-  CountedByExpr = ImplicitCastExpr::Create(
-  getContext(), CountedByExpr->getType(), CK_LValueToRValue, CountedByExpr,
-  nullptr, VK_PRValue, FPOptionsOverride());
-
-  if (const auto *IFD = dyn_cast(CountedByVD)) {
-// The counted_by field is inside an anonymous struct / union. The
-// IndirectFieldDecl has the correct order of FieldDecls to build this
-// easily. (Yay!)
-for (NamedDecl *ND : IFD->chain()) {
-  auto *VD = cast(ND);
-  CountedByExpr =
-  MemberExpr::CreateImplicit(getContext(), CountedByExpr,
- CountedByExpr->getType()->isPointerType(),
- VD, VD->getType(), VK_LValue, 
OK_Ordinary);
-}
-  } else {
-CountedByExpr = MemberExpr::CreateImplicit(
-getContext(), const_cast(CountedByExpr),
-CountedByExpr->getType()->isPointerType(),
-const_cast(CountedByVD), CountedByVD->getType(), 
VK_LValue,
-OK_Ordinary);
+  Expr *CountedByExpr =
+  MemberExprBaseVisitor(CountedByRD).Visit(const_cast(Base));
+  if (!CountedByExpr)
+return nullptr;
+
+  llvm::Value *Res = nullptr;
+  if (CountedByExpr->getType()->isPointerType())
+Res = EmitPointerWithAlignment(CountedByExpr).getPointer();

efriedma-quic wrote:

Oo, I should have spotted this earlier.  EmitPointerWithAlignment/EmitLValue is 
going to repeat any side-effects of the expression in question.  You can't emit 
an expression twice, in general.

So for the array bounds sanitizer case, I think this needs to be integrated a 
bit more tightly with the expression emission.  (Not sure about the object_size 
case.)

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


[clang] [Clang] Generate the GEP instead of adding AST nodes (PR #73730)

2023-11-29 Thread Eli Friedman via cfe-commits


@@ -956,42 +958,112 @@ static llvm::Value 
*getArrayIndexingBound(CodeGenFunction ,
   return nullptr;
 }
 
-const Expr *
-CodeGenFunction::BuildCountedByFieldExpr(const Expr *Base,
- const ValueDecl *CountedByVD) {
+namespace {
+
+/// \p MemberExprBaseVisitor returns the base \p DeclRefExpr of a field access.
+class MemberExprBaseVisitor
+: public StmtVisitor {
+  const RecordDecl *ExpectedRD;
+
+  bool IsExpectedRecordDecl(const Expr *E) const {
+QualType Ty = E->getType();
+if (Ty->isPointerType())
+  Ty = Ty->getPointeeType();
+return ExpectedRD == Ty->getAsRecordDecl();
+  }
+
+public:
+  MemberExprBaseVisitor(const RecordDecl *ExpectedRD)
+  : ExpectedRD(ExpectedRD) { }
+
+  
//======//
+  //Visitor Methods
+  
//======//
+
+  // Note: if we build C++ support for counted_by, then we'll have to handle
+  // horrors like this:
+  //
+  // struct S {
+  //   int x, y;
+  //   int blah[] __attribute__((counted_by(x)));
+  // } s;
+  //
+  // int foo(int index, int val) {
+  //   int (S::*IHatePMDs)[] = ::blah;
+  //   (s.*IHatePMDs)[index] = val;
+  // }
+
+  Expr *Visit(Expr *E) {
+return StmtVisitor::Visit(E);
+  }
+
+  Expr *VisitCastExpr(CastExpr *E) {
+return IsExpectedRecordDecl(E) ? E : Visit(E->getSubExpr());
+  }
+  Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
+return IsExpectedRecordDecl(E) ? E : nullptr;
+  }
+  Expr *VisitDeclRefExpr(DeclRefExpr *E) {
+return IsExpectedRecordDecl(E) ? E : nullptr;
+  }
+  Expr *VisitMemberExpr(MemberExpr *E) {
+Expr *Res = Visit(E->getBase());
+return !Res && IsExpectedRecordDecl(E) ? E : Res;

efriedma-quic wrote:

The recursion here doesn't look right.  Silly example:

```
struct S { struct S *p; int count; int[] values; }
int f(int idx, struct S *p) {
  return p->p->values[idx];
}
```

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


[clang] bf2e05c - [clang][NFC] Fill in historical data on when C++ DR 1-99 were fixed

2023-11-29 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2023-11-30T02:25:15+03:00
New Revision: bf2e05c7fbc739cd9b9086163303f846ee2806d2

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

LOG: [clang][NFC] Fill in historical data on when C++ DR 1-99 were fixed

Added: 


Modified: 
clang/test/CXX/drs/dr0xx.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp
index 5a127ff4f4164e1..1210c7a834e5970 100644
--- a/clang/test/CXX/drs/dr0xx.cpp
+++ b/clang/test/CXX/drs/dr0xx.cpp
@@ -64,7 +64,7 @@ namespace dr4 { // dr4: yes
   }
 }
 
-namespace dr5 { // dr5: yes
+namespace dr5 { // dr5: 3.1
   struct A {} a;
   struct B {
 B(const A&);
@@ -78,7 +78,7 @@ namespace dr5 { // dr5: yes
   const C c = e;
 }
 
-namespace dr7 { // dr7: yes
+namespace dr7 { // dr7: 3.4
   class A { public: ~A(); };
   class B : virtual private A {}; // expected-note 2 {{declared private here}}
   class C : public B {} c; // expected-error 2 {{inherited virtual base class 
'A' has private destructor}} \
@@ -114,7 +114,7 @@ namespace dr8 { // dr8: dup 45
   A::T *A::g() { return 0; }
 }
 
-namespace dr9 { // dr9: yes
+namespace dr9 { // dr9: 2.8
   struct B {
   protected:
 int m; // expected-note {{here}}
@@ -175,7 +175,7 @@ namespace dr13 { // dr13: no
   int a4 = h(g);
 }
 
-namespace dr14 { // dr14: yes
+namespace dr14 { // dr14: 3.4
   namespace X { extern "C" int dr14_f(); }
   namespace Y { extern "C" int dr14_f(); }
   using namespace X;
@@ -201,7 +201,7 @@ namespace dr15 { // dr15: yes
   template void f(int = 0); // expected-error {{default arguments 
cannot be added}}
 }
 
-namespace dr16 { // dr16: yes
+namespace dr16 { // dr16: 2.8
   class A { // expected-note {{here}}
 void f(); // expected-note {{here}}
 friend class C;
@@ -230,7 +230,7 @@ namespace dr17 { // dr17: yes
 
 // dr18: sup 577
 
-namespace dr19 { // dr19: yes
+namespace dr19 { // dr19: 3.1
   struct A {
 int n; // expected-note {{here}}
   };
@@ -243,7 +243,7 @@ namespace dr19 { // dr19: yes
   };
 }
 
-namespace dr20 { // dr20: yes
+namespace dr20 { // dr20: 2.8
   class X {
   public:
 X();
@@ -254,7 +254,7 @@ namespace dr20 { // dr20: yes
   X x = f(); // expected-error {{private}}
 }
 
-namespace dr21 { // dr21: yes
+namespace dr21 { // dr21: 3.4
   template struct A;
   struct X {
 template friend struct A; // expected-error {{default 
template argument not permitted on a friend template}}
@@ -398,7 +398,7 @@ namespace dr30 { // dr30: sup 468 c++11
 #endif
 }
 
-namespace dr31 { // dr31: yes
+namespace dr31 { // dr31: 2.8
   class X {
   private:
 void operator delete(void*); // expected-note {{here}}
@@ -410,7 +410,7 @@ namespace dr31 { // dr31: yes
 
 // dr32: na
 
-namespace dr33 { // dr33: yes
+namespace dr33 { // dr33: 9
   namespace X { struct S; void f(void (*)(S)); } // expected-note {{candidate}}
   namespace Y { struct T; void f(void (*)(T)); } // expected-note {{candidate}}
   void g(X::S);
@@ -667,7 +667,7 @@ namespace dr48 { // dr48: yes
   const int  = S::o;
 }
 
-namespace dr49 { // dr49: yes
+namespace dr49 { // dr49: 2.8
   template struct A {}; // expected-note 0-2{{here}}
   int k;
 #if __has_feature(cxx_constexpr)
@@ -703,7 +703,7 @@ namespace dr50 { // dr50: yes
   X *u = dynamic_cast(p); // expected-error {{incomplete}}
 }
 
-namespace dr51 { // dr51: yes
+namespace dr51 { // dr51: 2.8
   struct A {};
   struct B : A {};
   struct S {
@@ -713,9 +713,7 @@ namespace dr51 { // dr51: yes
   A  = s;
 }
 
-namespace dr52 { // dr52: yes
-  struct A { int n; }; // expected-note {{here}}
-  struct B : private A {} b; // expected-note 2{{private}}
+namespace dr52 { // dr52: 2.8
   // FIXME: This first diagnostic is very strangely worded, and seems to be 
bogus.
   int k = b.A::n; // expected-error {{'A' is a private member of 'dr52::A'}}
   // expected-error@-1 {{cannot cast 'struct B' to its private base}}
@@ -726,7 +724,7 @@ namespace dr53 { // dr53: yes
   enum E { e } x = static_cast(n);
 }
 
-namespace dr54 { // dr54: yes
+namespace dr54 { // dr54: 2.8
   struct A { int a; } a;
   struct V { int v; } v;
   struct B : private A, virtual V { int b; } b; // expected-note 6{{private 
here}}
@@ -777,7 +775,7 @@ namespace dr56 { // dr56: yes
   };
 }
 
-namespace dr58 { // dr58: yes
+namespace dr58 { // dr58: 3.1
   // FIXME: Ideally, we should have a CodeGen test for this.
 #if __cplusplus >= 201103L
   enum E1 { E1_0 = 0, E1_1 = 1 };
@@ -834,7 +832,7 @@ namespace dr60 { // dr60: yes
   int  = f(k);
 }
 
-namespace dr61 { // dr61: yes
+namespace dr61 { // dr61: 3.4
   struct X {
 static void f();
   } x;
@@ -849,7 +847,7 @@ namespace dr61 { // dr61: yes
   void (*r)() = y.f; // expected-error {{cannot create a non-constant pointer 

[clang] [clang][DependencyScanner] Include the working directory in the context hash (PR #73719)

2023-11-29 Thread Juergen Ributzka via cfe-commits

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

LGTM

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


[clang] [Clang] Generate the GEP instead of adding AST nodes (PR #73730)

2023-11-29 Thread Bill Wendling via cfe-commits

bwendling wrote:

Okay. With the latest commit, I handle some of the weird accesses. As it turns 
out, looking at `isArrow()` for a `MemberExpr` isn't going to work, because 
it'll happen with ordinary accesses:

```
ImplicitCastExpr 0x564fa8c3fd48 'int *' 
`-MemberExpr 0x564fa8c3fcf8 'int[]' lvalue .arr 0x564fa8c2f488
  `-MemberExpr 0x564fa8c3fcc8 'struct S' lvalue ->s 0x564fa8c3f928
`-ImplicitCastExpr 0x564fa8c3fcb0 'struct SS *' 
  `-DeclRefExpr 0x564fa8c3fc90 'struct SS *' lvalue ParmVar 0x564fa8c3fab8 
's' 'struct SS *'
; ModuleID = '/home/morbo/llvm/ugh.c'
```

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


[clang] c6d7072 - [clang][CodeGen] Emit annotations for function declarations. (#66716)

2023-11-29 Thread via cfe-commits

Author: Brendan Dahl
Date: 2023-11-29T15:13:30-08:00
New Revision: c6d70722b49db01914d5f64cc86ea5ed609ad9fd

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

LOG: [clang][CodeGen] Emit annotations for function declarations. (#66716)

Previously, annotations were only emitted for function definitions. With
this change annotations are also emitted for declarations. Also,
emitting function annotations is now deferred until the end so that the
most up to date declaration is used which will have any inherited
annotations.

Added: 
clang/test/CodeGen/annotations-decl-use-decl.c
clang/test/CodeGen/annotations-decl-use-define.c
clang/test/CodeGen/annotations-declaration.c
clang/test/CodeGenCXX/attr-annotate-constructor.cpp
clang/test/CodeGenCXX/attr-annotate-destructor.cpp

Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/test/CodeGen/annotations-global.c
clang/test/CodeGenCXX/attr-annotate.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 3225c984768657a..6cb308e5a759701 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -699,6 +699,7 @@ void CodeGenModule::checkAliases() {
 void CodeGenModule::clear() {
   DeferredDeclsToEmit.clear();
   EmittedDeferredDecls.clear();
+  DeferredAnnotations.clear();
   if (OpenMPRuntime)
 OpenMPRuntime->clear();
 }
@@ -3165,6 +3166,13 @@ void CodeGenModule::EmitVTablesOpportunistically() {
 }
 
 void CodeGenModule::EmitGlobalAnnotations() {
+  for (const auto& [MangledName, VD] : DeferredAnnotations) {
+llvm::GlobalValue *GV = GetGlobalValue(MangledName);
+if (GV)
+  AddGlobalAnnotations(VD, GV);
+  }
+  DeferredAnnotations.clear();
+
   if (Annotations.empty())
 return;
 
@@ -3678,6 +3686,14 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
 
   // Ignore declarations, they will be emitted on their first use.
   if (const auto *FD = dyn_cast(Global)) {
+// Update deferred annotations with the latest declaration if the function
+// function was already used or defined.
+if (FD->hasAttr()) {
+  StringRef MangledName = getMangledName(GD);
+  if (GetGlobalValue(MangledName))
+DeferredAnnotations[MangledName] = FD;
+}
+
 // Forward declarations are emitted lazily on first use.
 if (!FD->doesThisDeclarationHaveABody()) {
   if (!FD->doesDeclarationForceExternallyVisibleDefinition())
@@ -4462,6 +4478,11 @@ llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
   llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  Entry ? StringRef() : MangledName, ());
 
+  // Store the declaration associated with this function so it is potentially
+  // updated by further declarations or definitions and emitted at the end.
+  if (D && D->hasAttr())
+DeferredAnnotations[MangledName] = cast(D);
+
   // If we already created a function with the same mangled name (but 
diff erent
   // type) before, take its name and add it to the list of functions to be
   // replaced with F at the end of CodeGen.
@@ -5748,8 +5769,6 @@ void 
CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
 AddGlobalCtor(Fn, CA->getPriority());
   if (const DestructorAttr *DA = D->getAttr())
 AddGlobalDtor(Fn, DA->getPriority(), true);
-  if (D->hasAttr())
-AddGlobalAnnotations(D, Fn);
   if (getLangOpts().OpenMP && D->hasAttr())
 getOpenMPRuntime().emitDeclareTargetFunction(D, GV);
 }

diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index e81edc979c208b1..ec34680fd3f7e6e 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -431,6 +431,10 @@ class CodeGenModule : public CodeGenTypeCache {
   /// Global annotations.
   std::vector Annotations;
 
+  // Store deferred function annotations so they can be emitted at the end with
+  // most up to date ValueDecl that will have all the inherited annotations.
+  llvm::DenseMap DeferredAnnotations;
+
   /// Map used to get unique annotation strings.
   llvm::StringMap AnnotationStrings;
 

diff  --git a/clang/test/CodeGen/annotations-decl-use-decl.c 
b/clang/test/CodeGen/annotations-decl-use-decl.c
new file mode 100644
index 000..f43ba91a34d876f
--- /dev/null
+++ b/clang/test/CodeGen/annotations-decl-use-decl.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
+
+// Test annotation attributes are still emitted when the function is used 
before
+// it is defined with annotations.
+
+void foo(void);
+void *xxx = (void*)foo;
+void __attribute__((annotate("bar"))) foo();
+
+// CHECK: target triple
+// CHECK-DAG: private unnamed_addr constant [4 x i8] 

[clang] [clang][CodeGen] Emit annotations for function declarations. (PR #66716)

2023-11-29 Thread Eli Friedman via cfe-commits

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


[clang] [Clang] Implement P2864R2 Remove Deprecated Arithmetic Conversion on… (PR #73105)

2023-11-29 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

Actually that is more like a quick fix, we can live with it. More proper way 
would be simply to split those tests into pre-c++20 and universal.

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


[clang] [Clang] Implement P2864R2 Remove Deprecated Arithmetic Conversion on… (PR #73105)

2023-11-29 Thread via cfe-commits

cor3ntin wrote:

@PiotrZSL You beat me to it, thanks a lot!

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


[clang] [clang][DependencyScanner] Include the working directory in the context hash (PR #73719)

2023-11-29 Thread Ben Langmuir via cfe-commits

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


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


[clang] [clang-offload-bundler] Add support for -check-input-archive (PR #73709)

2023-11-29 Thread Jacob Lambert via cfe-commits

https://github.com/lamb-j updated 
https://github.com/llvm/llvm-project/pull/73709

>From 995706601f9f4aed021a9003ad79ca3e7e1d18af Mon Sep 17 00:00:00 2001
From: Jacob Lambert 
Date: Tue, 28 Nov 2023 14:42:11 -0800
Subject: [PATCH 1/7] [clang-offload-bundler] Add support for
 -check-input-archive

In this patch, we add support for checking a heterogeneous archive.
We also significantly improve the clang-offload-bundler documentation.
---
 clang/docs/ClangOffloadBundler.rst| 297 +++---
 clang/include/clang/Driver/OffloadBundler.h   |   2 +-
 clang/lib/Driver/OffloadBundler.cpp   |  94 +-
 .../ClangOffloadBundler.cpp   |  19 ++
 4 files changed, 358 insertions(+), 54 deletions(-)

diff --git a/clang/docs/ClangOffloadBundler.rst 
b/clang/docs/ClangOffloadBundler.rst
index 1e21d3e7264d5c3..1fcfde011e46e2f 100644
--- a/clang/docs/ClangOffloadBundler.rst
+++ b/clang/docs/ClangOffloadBundler.rst
@@ -30,58 +30,139 @@ includes an ``init`` function that will use the runtime 
corresponding to the
 offload kind (see :ref:`clang-offload-kind-table`) to load the offload code
 objects appropriate to the devices present when the host program is executed.
 
+:program:`clang-offload-bundler` is located in
+`clang/tools/clang-offload-bundler`.
+
+.. code-block:: console
+
+  $ clang-offload-bundler -help
+  OVERVIEW: A tool to bundle several input files of the specified type 
+  referring to the same source file but different targets into a single
+  one. The resulting file can also be unbundled into different files by
+  this tool if -unbundle is provided.
+
+  USAGE: clang-offload-bundler [options]
+
+  OPTIONS:
+
+  Generic Options:
+
+--help  - Display available options (--help-hidden for 
more)
+--help-list - Display list of available options 
(--help-list-hidden for more)
+--version   - Display the version of this program
+
+  clang-offload-bundler options:
+
+--###   - Print any external commands that are to be 
executed instead of actually executing them - for testing purposes.
+--allow-missing-bundles - Create empty files if bundles are missing when 
unbundling.
+--bundle-align=   - Alignment of bundle for binary files
+--check-input-archive   - Check if input heterogeneous archive is valid in 
terms of TargetID rules.
+--inputs=   - [,...]
+--list  - List bundle IDs in the bundled file.
+--outputs=  - [,...]
+--targets=  - [-,...]
+--type= - Type of the files to be bundled/unbundled.
+  Current supported types are:
+i   - cpp-output
+ii  - c++-cpp-output
+cui - cuda/hip-output
+d   - dependency
+ll  - llvm
+bc  - llvm-bc
+s   - assembler
+o   - object
+a   - archive of bundled files
+gch - precompiled-header
+ast - clang AST file
+--unbundle  - Unbundle bundled file into several output files.
+
+Usage
+=
+
+This tool can be used as follows for bundling:
+
+::
+
+  clang-offload-bundler -targets=triple1,triple2 -type=ii 
-inputs=a.triple1.ii,a.triple2.ii -outputs=a.ii
+
+or, it can be used as follows for unbundling:
+
+::
+
+  clang-offload-bundler -targets=triple1,triple2 -type=ii 
-outputs=a.triple1.ii,a.triple2.ii -inputs=a.ii -unbundle
+
+
 Supported File Formats
 ==
-Several text and binary file formats are supported for bundling/unbundling. See
-:ref:`supported-file-formats-table` for a list of currently supported formats.
+
+Multiple text and binary file formats are supported for bundling/unbundling. 
See
+:ref:`supported-file-formats-table` for a list of currently supported input
+formats. Use the ``File Type`` column to determine the value to pass to the
+``--type`` option based on the type of input files while bundling/unbundling.
 
   .. table:: Supported File Formats
  :name: supported-file-formats-table
 
- +++-+
- | File Format| File Extension | Text/Binary |
- +++=+
- | CPP output |i   | Text|
- +++-+
- | C++ CPP output |   ii   | Text|
- +++-+
- | CUDA/HIP output|   cui  | Text|
- +++-+
- | Dependency |d   | Text|
- +++-+
- | LLVM   |   ll   | 

[clang] [clang][CodeGen] Emit annotations for function declarations. (PR #66716)

2023-11-29 Thread Brendan Dahl via cfe-commits

brendandahl wrote:

@efriedma-quic missed your comment. I don't have commit access. Can you merge 
for me?

Thanks!

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


[clang-tools-extra] fc19424 - [clang-tidy][NFC] Fix bugprone-suspicious-enum-usage tests

2023-11-29 Thread Piotr Zegar via cfe-commits

Author: Piotr Zegar
Date: 2023-11-29T22:53:59Z
New Revision: fc19424d1d6d0df20e1734610a8e80a8e5158009

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

LOG: [clang-tidy][NFC] Fix bugprone-suspicious-enum-usage tests

Fixes failure in tests from a bugprone-suspicious-enum-usage check
by limiting those test to C++17 only to make CI green.
Tests were broken by change introduced in pull request #73105

Added: 


Modified: 

clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage-strict.cpp

clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage.cpp

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage-strict.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage-strict.cpp
index 405dec22eea77c8..ec214945539ebf9 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage-strict.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage-strict.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s bugprone-suspicious-enum-usage %t -- 
-config="{CheckOptions: {bugprone-suspicious-enum-usage.StrictMode: true}}" --
+// RUN: %check_clang_tidy -std=c++17 %s bugprone-suspicious-enum-usage %t -- 
-config="{CheckOptions: {bugprone-suspicious-enum-usage.StrictMode: true}}" --
 
 enum A {
   A = 1,
@@ -71,7 +71,7 @@ int trigger() {
   unsigned p = R;
   PP pp = Q;
   p |= pp;
-  
+
   enum X x = Z;
   p = x | Z;
   return 0;

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage.cpp
index 257c82e88f9a3dd..de7eb989bd2d4ef 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-enum-usage.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s bugprone-suspicious-enum-usage %t -- 
-config="{CheckOptions: {bugprone-suspicious-enum-usage.StrictMode: false}}" --
+// RUN: %check_clang_tidy -std=c++17 %s bugprone-suspicious-enum-usage %t -- 
-config="{CheckOptions: {bugprone-suspicious-enum-usage.StrictMode: false}}"
 
 enum Empty {
 };
@@ -79,7 +79,7 @@ int dont_trigger() {
   int d = c | H, e = b * a;
   a = B | C;
   b = X | Z;
-  
+
   if (Tuesday != Monday + 1 ||
   Friday - Thursday != 1 ||
   Sunday + Wednesday == (Sunday | Wednesday))



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


[clang] [Clang] Generate the GEP instead of adding AST nodes (PR #73730)

2023-11-29 Thread Bill Wendling via cfe-commits

bwendling wrote:

> I agree users probably shouldn't be doing that... but given it compiles your 
> code should handle it gracefully. (It should just be a matter of making sure 
> you don't recurse too deeply through the "base".)

*nods* However, the code it generates might not be what they want...but I'll 
try my best.

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


[llvm] [clang] [clang-tools-extra] [C API] Add getters for Target Extension Types to C API (PR #71291)

2023-11-29 Thread Benji Smith via cfe-commits

https://github.com/Benjins updated 
https://github.com/llvm/llvm-project/pull/71291

>From 12e5ec3c0727d58bf8d91f673c3facd974f98c54 Mon Sep 17 00:00:00 2001
From: Benji Smith <6193112+benj...@users.noreply.github.com>
Date: Sat, 4 Nov 2023 11:57:20 -0400
Subject: [PATCH 1/4] [C API] Add getters for Target Extension Types to C API

These types were added in LLVM-16, and the C API supports constructing them,
but not getting information back from them

This change adds getters for them to the C API, updates the echo test to be
able to clone Target Extension Types, and adds some usage of them to the
echo.ll test to confirm that they work
---
 llvm/include/llvm-c/Core.h| 33 +++
 llvm/lib/IR/Core.cpp  | 32 ++
 llvm/test/Bindings/llvm-c/echo.ll | 17 ++
 llvm/tools/llvm-c-test/echo.cpp   | 38 +--
 4 files changed, 118 insertions(+), 2 deletions(-)

diff --git a/llvm/include/llvm-c/Core.h b/llvm/include/llvm-c/Core.h
index 4fc88b2b64eacea..2d95f198f64958f 100644
--- a/llvm/include/llvm-c/Core.h
+++ b/llvm/include/llvm-c/Core.h
@@ -1654,6 +1654,39 @@ LLVMTypeRef LLVMTargetExtTypeInContext(LLVMContextRef C, 
const char *Name,
unsigned *IntParams,
unsigned IntParamCount);
 
+/**
+ * Obtain the name for this target extension type
+ */
+const char *LLVMGetTargetExtTypeName(LLVMTypeRef TargetExtTy);
+
+/**
+ * Obtain the number of type parameters for this target extension type
+ */
+unsigned LLVMCountTargetExtTypeTypeParams(LLVMTypeRef TargetExtTy);
+
+/**
+ * Obtain the values of a target extension type's type parameters, output to
+ * the passed-in pointer. The pointer should have enough space for all type
+ * params for the given target extension type
+ *
+ * @see LLVMCountTargetExtTypeTypeParams
+ */
+void LLVMGetTargetExtTypeTypeParams(LLVMTypeRef TargetExtTy, LLVMTypeRef 
*Dest);
+
+/**
+ * Obtain the number of int parameters for this target extension type
+ */
+unsigned LLVMCountTargetExtTypeIntParams(LLVMTypeRef TargetExtTy);
+
+/**
+ * Obtain the int values of a target extension type's int parameters, output to
+ * the passed-in pointer. The pointer should have enough space for all int
+ * params for the given target extension type
+ *
+ * @see LLVMCountTargetExtTypeIntParams
+ */
+void LLVMGetTargetExtTypeIntParams(LLVMTypeRef TargetExtTy, unsigned *Dest);
+
 /**
  * @}
  */
diff --git a/llvm/lib/IR/Core.cpp b/llvm/lib/IR/Core.cpp
index 076d1089582fe7e..eb1cda55288e334 100644
--- a/llvm/lib/IR/Core.cpp
+++ b/llvm/lib/IR/Core.cpp
@@ -924,6 +924,38 @@ LLVMTypeRef LLVMTargetExtTypeInContext(LLVMContextRef C, 
const char *Name,
   TargetExtType::get(*unwrap(C), Name, TypeParamArray, IntParamArray));
 }
 
+const char *LLVMGetTargetExtTypeName(LLVMTypeRef TargetExtTy) {
+  TargetExtType *Type = unwrap(TargetExtTy);
+  return Type->getName().data();
+}
+
+unsigned LLVMCountTargetExtTypeTypeParams(LLVMTypeRef TargetExtTy) {
+  TargetExtType *Type = unwrap(TargetExtTy);
+  return Type->getNumTypeParameters();
+}
+
+void LLVMGetTargetExtTypeTypeParams(LLVMTypeRef TargetExtTy,
+LLVMTypeRef *Dest) {
+  TargetExtType *Type = unwrap(TargetExtTy);
+
+  for (unsigned int i = 0; i < Type->getNumTypeParameters(); i++) {
+Dest[i] = wrap(Type->getTypeParameter(i));
+  }
+}
+
+unsigned LLVMCountTargetExtTypeIntParams(LLVMTypeRef TargetExtTy) {
+  TargetExtType *Type = unwrap(TargetExtTy);
+  return Type->getNumIntParameters();
+}
+
+void LLVMGetTargetExtTypeIntParams(LLVMTypeRef TargetExtTy, unsigned *Dest) {
+  TargetExtType *Type = unwrap(TargetExtTy);
+
+  for (unsigned int i = 0; i < Type->getNumIntParameters(); i++) {
+Dest[i] = Type->getIntParameter(i);
+  }
+}
+
 /*===-- Operations on values 
--===*/
 
 /*--.. Operations on all values 
--*/
diff --git a/llvm/test/Bindings/llvm-c/echo.ll 
b/llvm/test/Bindings/llvm-c/echo.ll
index 5daa238bfb8e533..e62670424112d51 100644
--- a/llvm/test/Bindings/llvm-c/echo.ll
+++ b/llvm/test/Bindings/llvm-c/echo.ll
@@ -66,6 +66,23 @@ define void @types() {
   ret void
 }
 
+; Target extension types:
+define target("target.ext.1") @target_ext_01(target("target.ext.1") %0) {
+   ret target("target.ext.1") %0
+}
+
+define target("target.ext.2", i8, i1) @target_ext_02(target("target.ext.2", 
i8, i1) %0) {
+   ret target("target.ext.2", i8, i1) %0
+}
+
+define target("target.ext.3", 7) @target_ext_03(target("target.ext.3", 7) %0) {
+   ret target("target.ext.3", 7) %0
+}
+
+define target("target.ext.4", i1, i32, 7) 
@target_ext_04(target("target.ext.4", i1, i32, 7) %0) {
+   ret target("target.ext.4", i1, i32, 7) %0
+}
+
 define i32 @iops(i32 %a, i32 %b) {
   %1 = add i32 %a, %b
   %2 = mul i32 %a, %1
diff --git a/llvm/tools/llvm-c-test/echo.cpp 

[openmp] [clang] [OpenMP] Avoid initializing the KernelLaunchEnvironment if possible (PR #73864)

2023-11-29 Thread Johannes Doerfert via cfe-commits

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


[clang] fae233c - [OpenMP] Avoid initializing the KernelLaunchEnvironment if possible (#73864)

2023-11-29 Thread via cfe-commits

Author: Johannes Doerfert
Date: 2023-11-29T14:49:13-08:00
New Revision: fae233c63f93b4b6f9693685abe6c7d24393682f

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

LOG: [OpenMP] Avoid initializing the KernelLaunchEnvironment if possible 
(#73864)

If we don't have a team reduction we don't need a kernel launch
environment (for now). In that case we can avoid the cost.

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
openmp/libomptarget/plugins-nextgen/common/src/PluginInterface.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index 7ddc67e8a04ab64..5b9dbbf7e83a968 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -804,7 +804,9 @@ void CGOpenMPRuntimeGPU::emitKernelDeinit(CodeGenFunction 
,
   CGM.getTypes().ConvertTypeForMem(StaticTy);
   const auto  = CGM.getModule().getDataLayout();
   uint64_t ReductionDataSize =
-  DL.getTypeAllocSize(LLVMReductionsBufferTy).getFixedValue();
+  TeamsReductions.empty()
+  ? 0
+  : DL.getTypeAllocSize(LLVMReductionsBufferTy).getFixedValue();
   CGBuilderTy  = CGF.Builder;
   OMPBuilder.createTargetDeinit(Bld, ReductionDataSize,
 C.getLangOpts().OpenMPCUDAReductionBufNum);

diff  --git 
a/openmp/libomptarget/plugins-nextgen/common/src/PluginInterface.cpp 
b/openmp/libomptarget/plugins-nextgen/common/src/PluginInterface.cpp
index 477e0cad06fd50a..2ba9aca9e141a4d 100644
--- a/openmp/libomptarget/plugins-nextgen/common/src/PluginInterface.cpp
+++ b/openmp/libomptarget/plugins-nextgen/common/src/PluginInterface.cpp
@@ -464,6 +464,10 @@ GenericKernelTy::getKernelLaunchEnvironment(
   if (isCtorOrDtor() || RecordReplay.isReplaying())
 return nullptr;
 
+  if (!KernelEnvironment.Configuration.ReductionDataSize ||
+  !KernelEnvironment.Configuration.ReductionBufferLength)
+return reinterpret_cast(~0);
+
   // TODO: Check if the kernel needs a launch environment.
   auto AllocOrErr = GenericDevice.dataAlloc(sizeof(KernelLaunchEnvironmentTy),
 /*HostPtr=*/nullptr,
@@ -478,8 +482,7 @@ GenericKernelTy::getKernelLaunchEnvironment(
   /// async data transfer.
   auto  = (*AsyncInfoWrapper).KernelLaunchEnvironment;
   LocalKLE = KernelLaunchEnvironment;
-  if (KernelEnvironment.Configuration.ReductionDataSize &&
-  KernelEnvironment.Configuration.ReductionBufferLength) {
+  {
 auto AllocOrErr = GenericDevice.dataAlloc(
 KernelEnvironment.Configuration.ReductionDataSize *
 KernelEnvironment.Configuration.ReductionBufferLength,



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


[clang] [Clang] Generate the GEP instead of adding AST nodes (PR #73730)

2023-11-29 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

I agree users probably shouldn't be doing that... but given it compiles your 
code should handle it gracefully.  (It should just be a matter of making sure 
you don't recurse too deeply through the "base".)

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


[clang] [clang][OpenMP] Fix missing DI for __kmpc_global_thread_num (PR #73856)

2023-11-29 Thread Joseph Huber via cfe-commits

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

AFAIK this is the correct way to set debug information for something that 
doesn't have a valid source location like a lot of generated OpenMP calls.

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


[clang] [Clang] Implement P2864R2 Remove Deprecated Arithmetic Conversion on… (PR #73105)

2023-11-29 Thread via cfe-commits

dyung wrote:

@cor3ntin Your commit seems to be causing 2 test failures in the 
clang-tools-extra tests, can you try to fix them or revert if you need time to 
investigate?

https://lab.llvm.org/buildbot/#/builders/139/builds/54467

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


[libunwind] be811d1 - [libc++] Run picolibc tests with qemu

2023-11-29 Thread Louis Dionne via cfe-commits

Author: Michael Platings
Date: 2023-11-29T17:21:08-05:00
New Revision: be811d1617654e46f4f4daa82259ae4fad4c8e6a

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

LOG: [libc++] Run picolibc tests with qemu

This patch actually runs the tests for picolibc behind an emulator,
removing a few workarounds and increasing coverage.

Differential Revision: https://reviews.llvm.org/D155521

Added: 


Modified: 
libcxx/cmake/caches/Armv7M-picolibc.cmake
libcxx/docs/index.rst
libcxx/test/configs/armv7m-picolibc-libc++.cfg.in
libcxx/test/libcxx/selftest/dsl/dsl.sh.py
libcxx/test/libcxx/selftest/pass.cpp/run-error.pass.cpp
libcxx/test/libcxx/selftest/pass.mm/run-error.pass.mm
libcxx/test/libcxx/selftest/stdin-is-piped.sh.cpp
libcxx/test/std/algorithms/alg.sorting/alg.sort/sort/sort.pass.cpp

libcxx/test/std/diagnostics/syserr/syserr.errcat/syserr.errcat.objects/generic_category.pass.cpp

libcxx/test/std/diagnostics/syserr/syserr.errcat/syserr.errcat.objects/system_category.pass.cpp

libcxx/test/std/input.output/iostream.objects/narrow.stream.objects/cerr.sh.cpp

libcxx/test/std/input.output/iostream.objects/narrow.stream.objects/cin.sh.cpp

libcxx/test/std/input.output/iostream.objects/narrow.stream.objects/clog.sh.cpp

libcxx/test/std/input.output/iostream.objects/narrow.stream.objects/cout.sh.cpp

libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp

libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp

libcxx/test/std/localization/locale.categories/category.ctype/facet.ctype.special/facet.ctype.char.statics/classic_table.pass.cpp

libcxx/test/std/localization/locale.categories/category.numeric/locale.nm.put/facet.num.put.members/put_long_double.pass.cpp

libcxx/test/std/numerics/rand/rand.dist/rand.dist.bern/rand.dist.bern.bin/eval.PR44847.pass.cpp
libcxx/test/std/time/time.clock/time.clock.file/now.pass.cpp
libcxxabi/test/configs/armv7m-picolibc-libc++abi.cfg.in
libunwind/test/configs/armv7m-picolibc-libunwind.cfg.in
libunwind/test/libunwind_02.pass.cpp

Removed: 




diff  --git a/libcxx/cmake/caches/Armv7M-picolibc.cmake 
b/libcxx/cmake/caches/Armv7M-picolibc.cmake
index 6ed1866a50845fe..9f8863943444b65 100644
--- a/libcxx/cmake/caches/Armv7M-picolibc.cmake
+++ b/libcxx/cmake/caches/Armv7M-picolibc.cmake
@@ -29,6 +29,8 @@ set(LIBCXX_ENABLE_STATIC ON CACHE BOOL "")
 set(LIBCXX_ENABLE_THREADS OFF CACHE BOOL "")
 set(LIBCXX_ENABLE_WIDE_CHARACTERS OFF CACHE BOOL "")
 set(LIBCXX_INCLUDE_BENCHMARKS OFF CACHE BOOL "")
+# Long tests are prohibitively slow when run via emulation.
+set(LIBCXX_TEST_PARAMS "long_tests=False" CACHE STRING "")
 set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "")
 set(LIBUNWIND_ENABLE_SHARED OFF CACHE BOOL "")
 set(LIBUNWIND_ENABLE_STATIC ON CACHE BOOL "")
@@ -36,3 +38,4 @@ set(LIBUNWIND_ENABLE_THREADS OFF CACHE BOOL "")
 set(LIBUNWIND_IS_BAREMETAL ON CACHE BOOL "")
 set(LIBUNWIND_REMEMBER_HEAP_ALLOC ON CACHE BOOL "")
 set(LIBUNWIND_USE_COMPILER_RT ON CACHE BOOL "")
+find_program(QEMU_SYSTEM_ARM qemu-system-arm)

diff  --git a/libcxx/docs/index.rst b/libcxx/docs/index.rst
index 7bb5512beb1f1fc..e8b4a95dbcffae1 100644
--- a/libcxx/docs/index.rst
+++ b/libcxx/docs/index.rst
@@ -133,7 +133,7 @@ Linux i386, x86_64, arm, arm64  Only 
glibc-2.24 and later and no
 Android 5.0+  i386, x86_64, arm, arm64
 Windows   i386, x86_64  Both MSVC and MinGW style 
environments, ABI in MSVC environments is :doc:`unstable 
`
 AIX 7.2TL5+   powerpc, powerpc64
-Embedded (picolibc)   arm   Support for building with 
picolibc is currently work-in-progress
+Embedded (picolibc)   arm
 = = 
 
 Generally speaking, libc++ should work on any platform that provides a fairly 
complete

diff  --git a/libcxx/test/configs/armv7m-picolibc-libc++.cfg.in 
b/libcxx/test/configs/armv7m-picolibc-libc++.cfg.in
index c0d23f136475eba..a39d43aec96aa4a 100644
--- a/libcxx/test/configs/armv7m-picolibc-libc++.cfg.in
+++ b/libcxx/test/configs/armv7m-picolibc-libc++.cfg.in
@@ -26,10 +26,16 @@ config.substitutions.append(('%{link_flags}',
 ' -Wl,--defsym=__ram_size=0x100'
 ' -Wl,--defsym=__stack_size=0x1000'
 ))
+
+config.executor = (
+'@LIBCXX_SOURCE_DIR@/utils/qemu_baremetal.py'
+' --qemu @QEMU_SYSTEM_ARM@'
+' --machine mps2-an385'
+' --cpu cortex-m3')
 config.substitutions.append(('%{exec}',
-'true' # TODO use qemu-system-arm
+'%{executor}'
+' --execdir %T'
 ))
-config.available_features.add('libcxx-fake-executor')
 
 import os, site
 

[clang] [clang] Avoid recalculating TBAA base type info (PR #73264)

2023-11-29 Thread Eli Friedman via cfe-commits


@@ -418,14 +418,20 @@ llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) {
 return nullptr;
 
   const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
-  if (llvm::MDNode *N = BaseTypeMetadataCache[Ty])
-return N;
 
-  // Note that the following helper call is allowed to add new nodes to the
-  // cache, which invalidates all its previously obtained iterators. So we
-  // first generate the node for the type and then add that node to the cache.
+  // nullptr is a valid value in the cache, so use find rather than []
+  auto I = BaseTypeMetadataCache.find(Ty);
+  if (I != BaseTypeMetadataCache.end())
+return I->second;
+
+  // First calculate the metadata, before recomputing the insertion point, as
+  // the helper can recursively call us.
   llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty);
-  return BaseTypeMetadataCache[Ty] = TypeNode;
+  LLVM_ATTRIBUTE_UNUSED auto inserted =
+  BaseTypeMetadataCache.try_emplace(Ty, TypeNode);

efriedma-quic wrote:

Please just use "insert" when you're dealing with trivially constructible types.

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


[clang] [clang] Avoid recalculating TBAA base type info (PR #73264)

2023-11-29 Thread Eli Friedman via cfe-commits

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


[clang] [clang] Avoid recalculating TBAA base type info (PR #73264)

2023-11-29 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

LGTM with one minor comment

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


[clang] [Clang] Implement P2308R1 - Template Parameter Initialization. (PR #73103)

2023-11-29 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/73103

>From 074d18d3805b067a5442bea94816d01319a29083 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Wed, 22 Nov 2023 11:43:07 +0100
Subject: [PATCH 1/5] [Clang] Implement P2308R1 - Template Parameter
 Initialization.

https://wiki.edg.com/pub/Wg21kona2023/StrawPolls/p2308r1.html

This implements P2308R1 as a DR and resolves CWG2459, CWG2450
and CWG2049.
---
 clang/docs/ReleaseNotes.rst   |  3 +
 clang/include/clang/Sema/Sema.h   |  4 +
 clang/lib/Parse/ParseTemplate.cpp | 11 ++-
 clang/lib/Sema/SemaOverload.cpp   |  9 ++
 clang/lib/Sema/SemaTemplate.cpp   | 96 ---
 clang/test/CXX/drs/dr20xx.cpp |  8 ++
 clang/test/CXX/drs/dr24xx.cpp | 32 +++
 .../SemaTemplate/temp_arg_nontype_cxx20.cpp   |  6 +-
 .../SemaTemplate/temp_arg_nontype_cxx2c.cpp   | 74 ++
 clang/www/cxx_dr_status.html  |  6 +-
 clang/www/cxx_status.html |  2 +-
 11 files changed, 208 insertions(+), 43 deletions(-)
 create mode 100644 clang/test/CXX/drs/dr24xx.cpp
 create mode 100644 clang/test/SemaTemplate/temp_arg_nontype_cxx2c.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2ee946af32bf197..dfeaae404ce63d5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -184,6 +184,9 @@ C++2c Feature Support
 
 - Implemented `P2864R2 Remove Deprecated Arithmetic Conversion on Enumerations 
From C++26 `_.
 
+- Implemented `P2361R6 Template parameter initialization 
`_.
+  This change is applied as a DR in all language modes.
+
 
 Resolutions to C++ Defect Reports
 ^
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e75a8bdb1fc72ff..937fcb3ce6079d7 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3932,6 +3932,10 @@ class Sema final {
   APValue , CCEKind CCE,
   NamedDecl *Dest = nullptr);
 
+  ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T,
+ APValue , CCEKind CCE,
+ bool RequireInt);
+
   /// Abstract base class used to perform a contextual implicit
   /// conversion from an expression to any type passing a filter.
   class ContextualImplicitConverter {
diff --git a/clang/lib/Parse/ParseTemplate.cpp 
b/clang/lib/Parse/ParseTemplate.cpp
index f556d0e6d4f8b6e..64fe4d50bba27bf 100644
--- a/clang/lib/Parse/ParseTemplate.cpp
+++ b/clang/lib/Parse/ParseTemplate.cpp
@@ -1062,8 +1062,7 @@ Parser::ParseNonTypeTemplateParameter(unsigned Depth, 
unsigned Position) {
   ++CurTemplateDepthTracker;
   EnterExpressionEvaluationContext ConstantEvaluated(
   Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
-  DefaultArg =
-  Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
+  DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseInitializer());
   if (DefaultArg.isInvalid())
 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
 }
@@ -1582,6 +1581,8 @@ ParsedTemplateArgument 
Parser::ParseTemplateTemplateArgument() {
 /// constant-expression
 /// type-id
 /// id-expression
+/// braced-init-list  [C++26, DR]
+///
 ParsedTemplateArgument Parser::ParseTemplateArgument() {
   // C++ [temp.arg]p2:
   //   In a template-argument, an ambiguity between a type-id and an
@@ -1619,8 +1620,12 @@ ParsedTemplateArgument Parser::ParseTemplateArgument() {
   }
 
   // Parse a non-type template argument.
+  ExprResult ExprArg;
   SourceLocation Loc = Tok.getLocation();
-  ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
+  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
+ExprArg = ParseBraceInitializer();
+  else
+ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
   if (ExprArg.isInvalid() || !ExprArg.get()) {
 return ParsedTemplateArgument();
   }
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 3a3e9234469d393..e2ca2a0cfb89433 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -6226,6 +6226,15 @@ ExprResult Sema::CheckConvertedConstantExpression(Expr 
*From, QualType T,
   return R;
 }
 
+ExprResult Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T,
+ APValue ,
+ Sema::CCEKind CCE,
+ bool RequireInt) {
+
+  APValue PreNarrowingValue;
+  return ::EvaluateConvertedConstantExpression(*this, E, T, Value, CCE,
+  

[clang] Refactor ASTContext::getDeclAlign() (NFC) (PR #72977)

2023-11-29 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

LGTM

See 
https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements
 for the rules on use/don't use braces.  A single multi-line statement is sort 
of on the edge; I tend to prefer braces in that case, but you can go either way.

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


[clang] [clang][CodeGen] Emit atomic IR instead of libcalls for misaligned po… (PR #73176)

2023-11-29 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

As a historical note, when I first wrote the support for atomics, it was under 
a model where LLVM IR only modeled legal atomics, and clang lowered illegal 
atomics to libcalls.  This was changed a few years later to generalize atomics 
in LLVM IR to support arbitrary atomic ops lowered to libcalls.  But there are 
still a few inconsistencies resulting from this, I think.

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


[clang] [mlir] [compiler-rt] [flang] [llvm] [clang-tools-extra] [clang][CodeGen] Handle template parameter objects with explicit address spaces (PR #69266)

2023-11-29 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

The concept makes sense, but I think the code should be inside 
CodeGenModule::GetAddrOfTemplateParamObject?  I think all users of the function 
want a value in the correct address-space.

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


[clang] [Clang][OpenMP] Bug #69214 fix (PR #73861)

2023-11-29 Thread via cfe-commits

https://github.com/lwshanbd created 
https://github.com/llvm/llvm-project/pull/73861

Fix #69214.
In `emitOMPSimdRegion`, the `EmitOMPPrivateLoopCounters` should be after 
`EmitOMPPrivateClause`.

>From 9eb00076c22197f223649b420994176a170a2671 Mon Sep 17 00:00:00 2001
From: Baodi Shan 
Date: Wed, 29 Nov 2023 16:26:33 -0500
Subject: [PATCH] [Clang][OpenMP] Bug #69214 fix

---
 clang/lib/CodeGen/CGStmtOpenMP.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp 
b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index 478d6dbf9ca81d9..fb27d90265360df 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -2562,9 +2562,9 @@ static void emitOMPSimdRegion(CodeGenFunction , const 
OMPLoopDirective ,
   (void)CGF.EmitOMPLinearClauseInit(S);
   {
 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
+CGF.EmitOMPPrivateClause(S, LoopScope);
 CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
 CGF.EmitOMPLinearClause(S, LoopScope);
-CGF.EmitOMPPrivateClause(S, LoopScope);
 CGF.EmitOMPReductionClauseInit(S, LoopScope);
 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
 CGF, S, CGF.EmitLValue(S.getIterationVariable()));

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


[clang] 97e7926 - [혀헽헿] changes introduced through rebase

2023-11-29 Thread Jon Roelofs via cfe-commits

Author: Jon Roelofs
Date: 2023-11-29T13:57:10-08:00
New Revision: 97e7926f25d81fb6c6d87202f721c2e2cf6198f5

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

LOG: [혀헽헿] changes introduced through rebase

Created using spr 1.3.4

[skip ci]

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td
clang/test/CodeGen/ifunc.c
llvm/docs/LangRef.rst
llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 4c4c4eb606fb0dc..5e85ec52a4634e5 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5408,9 +5408,9 @@ considered inline.
 Not all targets support this attribute. ELF target support depends on both the
 linker and runtime linker, and is available in at least lld 4.0 and later,
 binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later.
-MachO targets support it, but with slightly 
diff erent semantics: the resolver is
-run at first call, instead of at load time by the runtime linker. Targets other
-than ELF and MachO currently do not support this attribute.
+Mach-O targets support it, but with slightly 
diff erent semantics: the resolver
+is run at first call, instead of at load time by the runtime linker. Targets
+other than ELF and Mach-O currently do not support this attribute.
   }];
 }
 

diff  --git a/clang/test/CodeGen/ifunc.c b/clang/test/CodeGen/ifunc.c
index 99d60dc0ea85dbd..a29b500e80bd50b 100644
--- a/clang/test/CodeGen/ifunc.c
+++ b/clang/test/CodeGen/ifunc.c
@@ -3,9 +3,13 @@
 // RUN: %clang_cc1 -triple i386-unknown-linux-gnu -fsanitize=thread -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=SAN
 // RUN: %clang_cc1 -triple i386-unknown-linux-gnu -fsanitize=address -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=SAN
 // RUN: %clang_cc1 -triple i386-unknown-linux-gnu -fsanitize=memory -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=SAN
+// RUN: %clang_cc1 -triple arm64-apple-macosx -emit-llvm -o - %s | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-apple-macosx -emit-llvm -o - %s | FileCheck 
%s
+// RUN: %clang_cc1 -triple arm64-apple-macosx -O2 -emit-llvm -o - %s | 
FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-apple-macosx -O2 -emit-llvm -o - %s | 
FileCheck %s
+// RUN: %clang_cc1 -triple arm64-apple-macosx -fsanitize=thread -O2 -emit-llvm 
-o - %s | FileCheck %s --check-prefix=MACSAN
 // RUN: %clang_cc1 -triple x86_64-apple-macosx -fsanitize=thread -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=MACSAN
+// RUN: %clang_cc1 -triple arm64-apple-macosx -fsanitize=address -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=MACSAN
 // RUN: %clang_cc1 -triple x86_64-apple-macosx -fsanitize=address -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=MACSAN
 
 int foo(int) __attribute__ ((ifunc("foo_ifunc")));

diff  --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index cb222e979db29d4..fece4ac7f127d6b 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -937,7 +937,7 @@ IFuncs, like as aliases, don't create any new data or func. 
They are just a new
 symbol that is resolved at runtime by calling a resolver function.
 
 On ELF platforms, IFuncs are resolved by the dynamic linker at load time. On
-MachO platforms, they are lowered in terms of ``.symbol_resolver``s, which
+Mach-O platforms, they are lowered in terms of ``.symbol_resolver``s, which
 lazily resolve the callee the first time they are called.
 
 IFunc may have an optional :ref:`linkage type ` and an optional

diff  --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp 
b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index b4ac0a70e7fde9c..aaa7693c61f0e85 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -2321,7 +2321,7 @@ bool AsmPrinter::doFinalization(Module ) {
   }
 
   // IFuncs must come before deubginfo in case the backend decides to emit them
-  // as actual functions, since on MachO targets, we cannot create regular
+  // as actual functions, since on Mach-O targets, we cannot create regular
   // sections after DWARF.
   for (const auto  : M.ifuncs())
 emitGlobalIFunc(M, IFunc);



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


[clang] ecbfa04 - [혀헽헿] changes introduced through rebase

2023-11-29 Thread Jon Roelofs via cfe-commits

Author: Jon Roelofs
Date: 2023-11-29T13:57:04-08:00
New Revision: ecbfa0495147d255964d8beeb89c8d8d80ec74a1

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

LOG: [혀헽헿] changes introduced through rebase

Created using spr 1.3.4

[skip ci]

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td
clang/test/CodeGen/ifunc.c
llvm/docs/LangRef.rst
llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 4c4c4eb606fb0dc..5e85ec52a4634e5 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5408,9 +5408,9 @@ considered inline.
 Not all targets support this attribute. ELF target support depends on both the
 linker and runtime linker, and is available in at least lld 4.0 and later,
 binutils 2.20.1 and later, glibc v2.11.1 and later, and FreeBSD 9.1 and later.
-MachO targets support it, but with slightly 
diff erent semantics: the resolver is
-run at first call, instead of at load time by the runtime linker. Targets other
-than ELF and MachO currently do not support this attribute.
+Mach-O targets support it, but with slightly 
diff erent semantics: the resolver
+is run at first call, instead of at load time by the runtime linker. Targets
+other than ELF and Mach-O currently do not support this attribute.
   }];
 }
 

diff  --git a/clang/test/CodeGen/ifunc.c b/clang/test/CodeGen/ifunc.c
index 99d60dc0ea85dbd..a29b500e80bd50b 100644
--- a/clang/test/CodeGen/ifunc.c
+++ b/clang/test/CodeGen/ifunc.c
@@ -3,9 +3,13 @@
 // RUN: %clang_cc1 -triple i386-unknown-linux-gnu -fsanitize=thread -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=SAN
 // RUN: %clang_cc1 -triple i386-unknown-linux-gnu -fsanitize=address -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=SAN
 // RUN: %clang_cc1 -triple i386-unknown-linux-gnu -fsanitize=memory -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=SAN
+// RUN: %clang_cc1 -triple arm64-apple-macosx -emit-llvm -o - %s | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-apple-macosx -emit-llvm -o - %s | FileCheck 
%s
+// RUN: %clang_cc1 -triple arm64-apple-macosx -O2 -emit-llvm -o - %s | 
FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-apple-macosx -O2 -emit-llvm -o - %s | 
FileCheck %s
+// RUN: %clang_cc1 -triple arm64-apple-macosx -fsanitize=thread -O2 -emit-llvm 
-o - %s | FileCheck %s --check-prefix=MACSAN
 // RUN: %clang_cc1 -triple x86_64-apple-macosx -fsanitize=thread -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=MACSAN
+// RUN: %clang_cc1 -triple arm64-apple-macosx -fsanitize=address -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=MACSAN
 // RUN: %clang_cc1 -triple x86_64-apple-macosx -fsanitize=address -O2 
-emit-llvm -o - %s | FileCheck %s --check-prefix=MACSAN
 
 int foo(int) __attribute__ ((ifunc("foo_ifunc")));

diff  --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index cb222e979db29d4..fece4ac7f127d6b 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -937,7 +937,7 @@ IFuncs, like as aliases, don't create any new data or func. 
They are just a new
 symbol that is resolved at runtime by calling a resolver function.
 
 On ELF platforms, IFuncs are resolved by the dynamic linker at load time. On
-MachO platforms, they are lowered in terms of ``.symbol_resolver``s, which
+Mach-O platforms, they are lowered in terms of ``.symbol_resolver``s, which
 lazily resolve the callee the first time they are called.
 
 IFunc may have an optional :ref:`linkage type ` and an optional

diff  --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp 
b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index b4ac0a70e7fde9c..aaa7693c61f0e85 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -2321,7 +2321,7 @@ bool AsmPrinter::doFinalization(Module ) {
   }
 
   // IFuncs must come before deubginfo in case the backend decides to emit them
-  // as actual functions, since on MachO targets, we cannot create regular
+  // as actual functions, since on Mach-O targets, we cannot create regular
   // sections after DWARF.
   for (const auto  : M.ifuncs())
 emitGlobalIFunc(M, IFunc);



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


[llvm] [clang] [CUDA][HIP] Improve variable registration with the new driver (PR #73177)

2023-11-29 Thread Yaxun Liu via cfe-commits


@@ -63,6 +63,12 @@ class CGCUDARuntime {
   OffloadGlobalSurfaceEntry = 0x2,
   /// Mark the entry as a texture variable.
   OffloadGlobalTextureEntry = 0x3,
+  /// Mark the entry as being extern.
+  OffloadGlobalExtern = 0x4,

yxsamliu wrote:

once people start to use these enums, it is difficult to change them since it 
will break binary backward compatibility

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


  1   2   3   4   5   >