[clang] [clang] Support -Wa, options -mmsa and -mno-msa (PR #99615)

2024-08-08 Thread Fangrui Song via cfe-commits

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

.

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


[clang] [llvm] Add length builtins and length HLSL function to DirectX Backend (PR #101256)

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

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


[clang] [clang][deps] Only bypass scanning VFS for the module cache (PR #88800)

2024-08-08 Thread Jan Svoboda via cfe-commits

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

>From e1aed43691bc02fe6d775c68908182289f2727c0 Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Thu, 11 Apr 2024 14:44:55 -0700
Subject: [PATCH 1/2] [clang][deps] Only bypass scanning VFS for the module
 cache

The scanning VFS doesn't cache stat failures of paths with no extension. This 
was originally implemented to avoid caching the non-existence of the modules 
cache directory that the modular scanner will eventually create if it does not 
exist.

However, this prevents caching of the non-existence of all directories and 
notably also header files from the standard C++ library, which can lead to 
sub-par performance.

This patch adds an API to the scanning VFS that allows clients to configure 
path prefix for which to bypass the scanning VFS and use the underlying VFS 
directly.
---
 .../DependencyScanningFilesystem.h| 13 
 .../DependencyScanningFilesystem.cpp  | 16 --
 .../DependencyScanningWorker.cpp  | 32 ---
 .../DependencyScanningFilesystemTest.cpp  | 27 
 4 files changed, 67 insertions(+), 21 deletions(-)

diff --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index f7b4510d7f7beb..d12814e7c9253e 100644
--- 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -353,6 +353,12 @@ class DependencyScanningWorkerFilesystem
 
   std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
 
+  /// Make it so that no paths bypass this VFS.
+  void resetBypassedPathPrefix() { BypassedPathPrefix.reset(); }
+  /// Set the prefix for paths that should bypass this VFS and go straight to
+  /// the underlying VFS.
+  void setBypassedPathPrefix(StringRef Prefix) { BypassedPathPrefix = Prefix; }
+
   /// Returns entry for the given filename.
   ///
   /// Attempts to use the local and shared caches first, then falls back to
@@ -450,12 +456,19 @@ class DependencyScanningWorkerFilesystem
 getUnderlyingFS().print(OS, Type, IndentLevel + 1);
   }
 
+  /// Whether this path should bypass this VFS and go straight to the 
underlying
+  /// VFS.
+  bool shouldBypass(StringRef Path) const;
+
   /// The global cache shared between worker threads.
   DependencyScanningFilesystemSharedCache &SharedCache;
   /// The local cache is used by the worker thread to cache file system queries
   /// locally instead of querying the global cache every time.
   DependencyScanningFilesystemLocalCache LocalCache;
 
+  /// Prefix of paths that should go straight to the underlying VFS.
+  std::optional BypassedPathPrefix;
+
   /// The working directory to use for making relative paths absolute before
   /// using them for cache lookups.
   llvm::ErrorOr WorkingDirForCacheLookup;
diff --git 
a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
index 0cab17a3424406..4d738e4bea41a6 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -201,11 +201,8 @@ const CachedRealPath 
&DependencyScanningFilesystemSharedCache::CacheShard::
   return *StoredRealPath;
 }
 
-static bool shouldCacheStatFailures(StringRef Filename) {
-  StringRef Ext = llvm::sys::path::extension(Filename);
-  if (Ext.empty())
-return false; // This may be the module cache directory.
-  return true;
+bool DependencyScanningWorkerFilesystem::shouldBypass(StringRef Path) const {
+  return BypassedPathPrefix && Path.starts_with(*BypassedPathPrefix);
 }
 
 DependencyScanningWorkerFilesystem::DependencyScanningWorkerFilesystem(
@@ -244,8 +241,6 @@ DependencyScanningWorkerFilesystem::computeAndStoreResult(
   llvm::ErrorOr Stat =
   getUnderlyingFS().status(OriginalFilename);
   if (!Stat) {
-if (!shouldCacheStatFailures(OriginalFilename))
-  return Stat.getError();
 const auto &Entry =
 getOrEmplaceSharedEntryForFilename(FilenameForLookup, Stat.getError());
 return insertLocalEntryForFilename(FilenameForLookup, Entry);
@@ -291,7 +286,7 @@ DependencyScanningWorkerFilesystem::status(const Twine 
&Path) {
   SmallString<256> OwnedFilename;
   StringRef Filename = Path.toStringRef(OwnedFilename);
 
-  if (Filename.ends_with(".pcm"))
+  if (shouldBypass(Filename))
 return getUnderlyingFS().status(Path);
 
   llvm::ErrorOr Result = getOrCreateFileSystemEntry(Filename);
@@ -362,7 +357,7 @@ DependencyScanningWorkerFilesystem::openFileForRead(const 
Twine &Path) {
   SmallString<256> OwnedFilename;
   StringRef Filename = Path.toStringRef(OwnedFilename);
 
-  if (Filename.ends_with(".pcm"))
+  if (shouldBypass(Filename))
 return getUnderl

[clang] [clang][deps] Only bypass scanning VFS for the module cache (PR #88800)

2024-08-08 Thread Jan Svoboda via cfe-commits

jansvoboda11 wrote:

@aganea Rebased, added tests and a prep-patch: 
https://github.com/llvm/llvm-project/pull/102540.

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


[clang] [attributes][-Wunsafe-buffer-usage] Support adding unsafe_buffer_usage attribute to struct fields (PR #101585)

2024-08-08 Thread Malavika Samak via cfe-commits


@@ -0,0 +1,113 @@
+// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage \
+// RUN:-fsafe-buffer-usage-suggestions -verify %s
+
+using size_t = __typeof(sizeof(int));
+
+namespace std {
+  class type_info;
+  class bad_cast;
+  class bad_typeid;
+
+  template  class span {
+
+  private:
+T *elements;
+size_t size_;
+
+  public:
+span(T *, size_t){}
+
+constexpr T* data() const noexcept {
+  return elements;
+}
+
+constexpr size_t size() const noexcept {
+  return size_;
+}
+
+  };
+}
+
+struct A {
+[[clang::unsafe_buffer_usage]]
+int *ptr;
+
+size_t sz;
+};
+
+struct B {
+   A a;
+ 
+   [[clang::unsafe_buffer_usage]]
+   int buf[];
+};
+
+union Union {
+  [[clang::unsafe_buffer_usage]]
+  int *ptr1;
+
+  int ptr2;
+};
+
+struct C {
+  Union ptr; 
+};
+
+struct D { 
+  [[clang::unsafe_buffer_usage]]
+  int *ptr, *ptr2;
+
+  [[clang::unsafe_buffer_usage]]
+  int buf[10];
+ 
+  size_t sz;
+  
+};
+
+void foo(int *ptr);
+
+void foo_safe(std::span sp);
+
+void test_attribute_union(C c) {
+  int *p = c.ptr.ptr1; //expected-warning{{field ptr1 prone to unsafe buffer 
manipulation}}
+
+  // TODO: Warn here about the field
+  int address = c.ptr.ptr2;
+}
+
+int* test_atribute_struct(A a) {
+   int b = *(a.ptr); //expected-warning{{field ptr prone to unsafe buffer 
manipulation}}
+   a.sz++;
+   // expected-warning@+1{{unsafe pointer arithmetic}}
+   return a.ptr++; //expected-warning{{field ptr prone to unsafe buffer 
manipulation}}
+}
+
+void test_attribute_field_deref_chain(B b) {
+  int *ptr = b.a.ptr;//expected-warning{{field ptr prone to unsafe buffer 
manipulation}} 
+  foo(b.buf); //expected-warning{{field buf prone to unsafe buffer 
manipulation}}
+}
+
+void test_safe_writes(std::span sp) {
+  A a;
+  // TODO: We should not warn for safe assignments from hardened types

malavikasamak wrote:

Now that we have allowed the attribute to be added to all record fields 
irrespective of their type, such a special handling for pointers seems strange. 
Will remove the comment in the next version. We can file a GitHub issue if we 
decide otherwise in the future.  

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


[clang] [attributes][-Wunsafe-buffer-usage] Support adding unsafe_buffer_usage attribute to struct fields (PR #101585)

2024-08-08 Thread Malavika Samak via cfe-commits


@@ -926,22 +926,27 @@ class CArrayToPtrAssignmentGadget : public FixableGadget {
 /// A call of a function or method that performs unchecked buffer operations
 /// over one of its pointer parameters.
 class UnsafeBufferUsageAttrGadget : public WarningGadget {
-  constexpr static const char *const OpTag = "call_expr";
-  const CallExpr *Op;
+  constexpr static const char *const OpTag = "attr_expr";
+  const Expr *Op;
 
 public:
   UnsafeBufferUsageAttrGadget(const MatchFinder::MatchResult &Result)
   : WarningGadget(Kind::UnsafeBufferUsageAttr),
-Op(Result.Nodes.getNodeAs(OpTag)) {}
+Op(Result.Nodes.getNodeAs(OpTag)) {}
 
   static bool classof(const Gadget *G) {
 return G->getKind() == Kind::UnsafeBufferUsageAttr;
   }
 
   static Matcher matcher() {
+auto HasUnsafeFielDecl =
+member(fieldDecl(hasAttr(attr::UnsafeBufferUsage)));
+
 auto HasUnsafeFnDecl =
 callee(functionDecl(hasAttr(attr::UnsafeBufferUsage)));
-return stmt(callExpr(HasUnsafeFnDecl).bind(OpTag));
+
+return stmt(expr(anyOf(callExpr(HasUnsafeFnDecl).bind(OpTag),

malavikasamak wrote:

Fixing in the next version.

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


[clang] [attributes][-Wunsafe-buffer-usage] Support adding unsafe_buffer_usage attribute to struct fields (PR #101585)

2024-08-08 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak updated 
https://github.com/llvm/llvm-project/pull/101585

>From 1ecd91c03f6de92153809402b10f99e5f649787f Mon Sep 17 00:00:00 2001
From: MalavikaSamak 
Date: Thu, 1 Aug 2024 11:01:36 -0700
Subject: [PATCH 1/3] [-Wunsafe-buffer-usage] Support adding
 unsafe_buffer_usage aatribute to struct fields.

---
 clang/include/clang/Basic/Attr.td |   2 +-
 clang/include/clang/Basic/AttrDocs.td |  45 +--
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +-
 clang/lib/Analysis/UnsafeBufferUsage.cpp  |  17 ++-
 clang/lib/Sema/AnalysisBasedWarnings.cpp  |  13 +-
 .../warn-unsafe-buffer-usage-field-attr.cpp   | 113 ++
 6 files changed, 176 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-unsafe-buffer-usage-field-attr.cpp

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4825979a974d22..2cc21d67ddffb2 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4447,7 +4447,7 @@ def ReleaseHandle : InheritableParamAttr {
 
 def UnsafeBufferUsage : InheritableAttr {
   let Spellings = [Clang<"unsafe_buffer_usage">];
-  let Subjects = SubjectList<[Function]>;
+  let Subjects = SubjectList<[Function, Field]>;
   let Documentation = [UnsafeBufferUsageDocs];
 }
 
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 99738812c81579..a52e3dd68a0ce2 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6763,15 +6763,18 @@ attribute requires a string literal argument to 
identify the handle being releas
 def UnsafeBufferUsageDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
-The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions
-that need to be avoided as they are prone to buffer overflows. It is designed 
to
-work together with the off-by-default compiler warning 
``-Wunsafe-buffer-usage``
-to help codebases transition away from raw pointer based buffer management,
-in favor of safer abstractions such as C++20 ``std::span``. The attribute 
causes
-``-Wunsafe-buffer-usage`` to warn on every use of the function, and it may
-enable ``-Wunsafe-buffer-usage`` to emit automatic fix-it hints
-which would help the user replace such unsafe functions with safe
-alternatives, though the attribute can be used even when the fix can't be 
automated.
+The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions 
or
+struct fields that are buffers, that must to be avoided as they are prone to 
+buffer overflows. It is designed to work together with the off-by-default 
compiler 
+warning ``-Wunsafe-buffer-usage``to help codebases transition away from raw 
pointer 
+based buffer management, in favor of safer abstractions such as C++20 
``std::span``. 
+The attribute causes ``-Wunsafe-buffer-usage`` to warn on every use of the 
function or 
+the field it is attached to, and it may enable ``-Wunsafe-buffer-usage`` to 
emit 
+automatic fix-it hints which would help the user replace the use of unsafe 
+functions(/fields) with safe alternatives, though the attribute can be used 
even when 
+the fix can't be automated.
+
+Attribute attached to functions:
 
 The attribute does not suppress ``-Wunsafe-buffer-usage`` inside the function
 to which it is attached. These warnings still need to be addressed.
@@ -6835,6 +6838,30 @@ the proper solution would be to create a different 
function (possibly
 an overload of ``baz()``) that accepts a safe container like ``bar()``,
 and then use the attribute on the original ``baz()`` to help the users
 update their code to use the new function.
+
+Attribute attached to fields:
+
+The attribute should only be attached to struct fields, if the fields can not 
be
+updated to a safe type with bounds check, such as std::span. In other words, 
the
+buffers prone to unsafe accesses should always be updated to use safe 
containers/views
+and attaching the attribute must be last resort when such an update is 
infeasible. 
+
+The attribute can be placed on individual fields or a set of them as shown 
below.  
+.. code-block:: c++
+
+  struct A {
+[[clang::unsafe_buffer_usage]]
+int *ptr1;
+  
+[[clang::unsafe_buffer_usage]]
+int *ptr2, buf[10];
+
+size_t sz;
+  };
+
+Here, every read/write to the fields ptr1, ptr2 and buf will trigger a warning 
that the
+field is marked unsafe due to unsafe-buffer operations on it.
+
   }];
 }
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 810abe4f23e31e..b0428d28667a51 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12371,7 +12371,8 @@ def warn_unsafe_buffer_variable : Warning<
   InGroup, DefaultIgnore;
 def warn_unsafe_buffer_operation : Warning<
   "%select{unsafe pointer operation|unsaf

[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Bill Wendling via cfe-commits


@@ -4248,6 +4248,22 @@ bool CompilerInvocation::ParseLangArgs(LangOptions 
&Opts, ArgList &Args,
   Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
   }
 
+  if (auto *A = Args.getLastArg(OPT_fsanitize_overflow_pattern_exclusion_EQ)) {
+for (int i = 0, n = A->getNumValues(); i != n; ++i) {
+  StringRef Value = A->getValue(i);
+  if (Value == "none")
+Opts.OverflowPatternExclusionMask |= LangOptionsBase::None;

bwendling wrote:

This seems counter-intuitive. Shouldn't this be an assignment instead?

```c
Opts.OverflowPatternExclusionMask = LangOptionsBase::None;
```

Or is that not the behavior you want?

Also, look up `StringSwitch`, which does the same as these if-then statements, 
but in the LLVM way. :-)

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Bill Wendling via cfe-commits


@@ -0,0 +1,83 @@
+// Check for potential false positives from patterns that _almost_ match 
classic overflow-dependent or overflow-prone code patterns

bwendling wrote:

In general, I think it's expected the RUN lines will be first and any comments 
about the test can come afterwards. It allows the comments to be set out more 
prominently. (Here and the next testcase.)

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Bill Wendling via cfe-commits


@@ -555,6 +570,11 @@ class LangOptions : public LangOptionsBase {
   /// The default stream kind used for HIP kernel launching.
   GPUDefaultStreamKind GPUDefaultStream;
 
+  /// Which overflow patterns should be excluded from sanitizer instrumentation
+  int OverflowPatternExclusionMask = 0;

bwendling wrote:

Use an `unsigned int` here.

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Bill Wendling via cfe-commits


@@ -2877,6 +2888,17 @@ ScalarExprEmitter::EmitScalarPrePostIncDec(const 
UnaryOperator *E, LValue LV,
   } else if (type->isIntegerType()) {
 QualType promotedType;
 bool canPerformLossyDemotionCheck = false;
+
+// Is the pattern "while (i--)" and overflow exclusion?
+bool disableSanitizer =

bwendling wrote:

This is difficult to read. I know it's nice to have it all in one big 
conditional, but it'd be more readable if split up a bit.

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Bill Wendling via cfe-commits


@@ -293,6 +293,40 @@ To silence reports from unsigned integer overflow, you can 
set
 ``-fsanitize-recover=unsigned-integer-overflow``, is particularly useful for
 providing fuzzing signal without blowing up logs.
 
+Disabling instrumentation for common overflow patterns
+--
+
+There are certain overflow-dependent or overflow-prone code patterns which
+produce a lot of noise for integer overflow/truncation sanitizers. To disable
+instrumentation for these common patterns one should use
+``-fsanitize-overflow-pattern-exclusion=``.
+
+Currently, this option supports three pervasive overflow-dependent code idioms:

bwendling wrote:

It might be useful to add "titles" to each example here. Something like:

```txt
``negated-unsigned-const``

.. code-block:: c++

/// -fsanitize-overflow-pattern-exclusion=negated-unsigned-const
 ...
```


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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Bill Wendling via cfe-commits


@@ -293,6 +293,40 @@ To silence reports from unsigned integer overflow, you can 
set
 ``-fsanitize-recover=unsigned-integer-overflow``, is particularly useful for
 providing fuzzing signal without blowing up logs.
 
+Disabling instrumentation for common overflow patterns
+--
+
+There are certain overflow-dependent or overflow-prone code patterns which
+produce a lot of noise for integer overflow/truncation sanitizers. To disable
+instrumentation for these common patterns one should use
+``-fsanitize-overflow-pattern-exclusion=``.
+
+Currently, this option supports three pervasive overflow-dependent code idioms:
+
+.. code-block:: c++
+
+/// -fsanitize-overflow-pattern-exclusion=negated-unsigned-const
+unsigned long foo = -1UL; // No longer causes a negation overflow warning
+unsigned long bar = -2UL; // and so on...
+
+.. code-block:: c++
+
+/// -fsanitize-overflow-pattern-exclusion=post-decr-while
+unsigned char count = 16;
+while (count--) { /* ... */ } // No longer causes 
unsigned-integer-overflow sanitizer to trip
+
+.. code-block:: c++
+
+/// -fsanitize-overflow-pattern-exclusion=add-overflow-test
+if (base + offset < base) { /* ... */ } // The pattern of `a + b < a`, and 
other re-orderings,
+// won't be instrumented (same for 
signed types)
+
+Negated unsigned constants, post-decrements in a while loop condition and

bwendling wrote:

This first line could go to the first paragraph?

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


[clang] [clang][modules] Enable built-in modules for the upcoming Apple releases (PR #102239)

2024-08-08 Thread Ian Anderson via cfe-commits

ian-twilightcoder wrote:

/cherry-pick 961639962251de7428c3fe93fa17cfa6ab3c561a 
0f1361baf650641a59aaa1710d7a0b7b02f2e56d

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


[clang] [libcxx] [clang] Reland: Instantiate concepts with sugared template arguments (PR #101782)

2024-08-08 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

This change makes the following code no longer compile:
```
#include 
#include 

template 
concept CompatibleIter = std::contiguous_iterator;

template 
class span {
  public:
  template 
requires(CompatibleIter)
  constexpr span(It first, int count) noexcept {

  }
};

void foo(int n) {
  int vla[n];
  span s(vla, n);
}
```
```
$ clang++  span.cpp -c -std=c++20
span.cpp:18:11: warning: variable length arrays in C++ are a Clang extension 
[-Wvla-cxx-extension]
   18 |   int vla[n];
  |   ^
span.cpp:18:11: note: function parameter 'n' with unknown value cannot be used 
in a constant expression
span.cpp:17:14: note: declared here
   17 | void foo(int n) {
  |  ^
span.cpp:19:19: error: no matching constructor for initialization of 
'span'
   19 |   span s(vla, n);
  |   ^ ~~
span.cpp:12:13: note: candidate template ignored: constraints not satisfied 
[with It = int *]
   12 |   constexpr span(It first, int count) noexcept {
  | ^
span.cpp:11:14: note: because 'CompatibleIter' evaluated to 
false
   11 | requires(CompatibleIter)
  |  ^
span.cpp:5:26: note: because 'int *' does not satisfy 'contiguous_iterator'
5 | concept CompatibleIter = std::contiguous_iterator;
  |  ^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/bits/iterator_concepts.h:697:35:
 note: because 'int *' does not satisfy 'random_access_iterator'
  697 | concept contiguous_iterator = random_access_iterator<_Iter>
  |   ^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/bits/iterator_concepts.h:681:38:
 note: because 'int *' does not satisfy 'bidirectional_iterator'
  681 | concept random_access_iterator = bidirectional_iterator<_Iter>
  |  ^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/bits/iterator_concepts.h:671:38:
 note: because 'int *' does not satisfy 'forward_iterator'
  671 | concept bidirectional_iterator = forward_iterator<_Iter>
  |  ^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/bits/iterator_concepts.h:666:32:
 note: because 'int *' does not satisfy 'input_iterator'
  666 | concept forward_iterator = input_iterator<_Iter>
  |^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/bits/iterator_concepts.h:655:30:
 note: because 'int *' does not satisfy 'input_or_output_iterator'
  655 | concept input_iterator = input_or_output_iterator<_Iter>
  |  ^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/bits/iterator_concepts.h:635:5:
 note: because 'int *' does not satisfy 'weakly_incrementable'
  635 | && weakly_incrementable<_Iter>;
  |^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/bits/iterator_concepts.h:619:36:
 note: because 'int *' does not satisfy 'movable'
  619 | concept weakly_incrementable = movable<_Iter>
  |^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/concepts:265:10: 
note: because 'assignable_from' evaluated to false
  265 |   && assignable_from<_Tp&, _Tp> && swappable<_Tp>;
  |  ^
/usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/concepts:143:44: 
note: because 'same_as' would be invalid
  143 | { __lhs = static_cast<_Rhs&&>(__rhs) } -> same_as<_Lhs>;
  |   ^
span.cpp:8:7: note: candidate constructor (the implicit copy constructor) not 
viable: requires 1 argument, but 2 were provided
8 | class span {
  |   ^~~~
span.cpp:8:7: note: candidate constructor (the implicit move constructor) not 
viable: requires 1 argument, but 2 were provided
8 | class span {
  |   ^~~~
1 warning and 1 error generated.
```

Can you revert it if it takes a while to fix?

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


[clang] [llvm] [Clang] C++20 Coroutines: Introduce Frontend Attribute [[clang::coro_await_elidable]] (PR #99282)

2024-08-08 Thread Yuxuan Chen via cfe-commits

https://github.com/yuxuanchen1997 updated 
https://github.com/llvm/llvm-project/pull/99282

>From 5578fde5d3225b24d5e8b140f2654ed8075eec92 Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Tue, 4 Jun 2024 23:22:00 -0700
Subject: [PATCH] [Clang] Introduce [[clang::coro_await_elidable]]

---
 clang/docs/ReleaseNotes.rst   |  3 +
 clang/include/clang/AST/Expr.h|  3 +
 clang/include/clang/AST/Stmt.h|  5 +-
 clang/include/clang/Basic/Attr.td |  8 ++
 clang/include/clang/Basic/AttrDocs.td | 33 ++-
 clang/lib/AST/Expr.cpp|  2 +
 clang/lib/CodeGen/CGBlocks.cpp|  5 +-
 clang/lib/CodeGen/CGCUDARuntime.cpp   |  5 +-
 clang/lib/CodeGen/CGCUDARuntime.h |  8 +-
 clang/lib/CodeGen/CGCXXABI.h  | 10 +--
 clang/lib/CodeGen/CGClass.cpp | 16 ++--
 clang/lib/CodeGen/CGExpr.cpp  | 55 
 clang/lib/CodeGen/CGExprCXX.cpp   | 60 +++--
 clang/lib/CodeGen/CodeGenFunction.h   | 64 --
 clang/lib/CodeGen/ItaniumCXXABI.cpp   | 16 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp | 18 ++--
 clang/lib/Sema/SemaCoroutine.cpp  | 24 -
 clang/test/CodeGenCoroutines/Inputs/utility.h | 13 +++
 .../CodeGenCoroutines/coro-await-elidable.cpp | 87 +++
 ...a-attribute-supported-attributes-list.test |  1 +
 llvm/include/llvm/Bitcode/LLVMBitCodes.h  |  1 +
 llvm/include/llvm/IR/Attributes.td|  3 +
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp |  2 +
 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp |  2 +
 llvm/lib/Transforms/Utils/CodeExtractor.cpp   |  1 +
 25 files changed, 335 insertions(+), 110 deletions(-)
 create mode 100644 clang/test/CodeGenCoroutines/Inputs/utility.h
 create mode 100644 clang/test/CodeGenCoroutines/coro-await-elidable.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a4a862ccba2128..1ca1247ed069cf 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -136,6 +136,9 @@ Attribute Changes in Clang
 - The ``hybrid_patchable`` attribute is now supported on ARM64EC targets. It 
can be used to specify
   that a function requires an additional x86-64 thunk, which may be patched at 
runtime.
 
+- Introduced a new attribute ``[[clang::coro_await_elidable]]`` on coroutine 
return types
+  to express elideability at call sites where the coroutine is co_awaited as a 
prvalue.
+
 Improvements to Clang's diagnostics
 ---
 
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 5b813bfc2faf90..83985499e6eba7 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -2991,6 +2991,9 @@ class CallExpr : public Expr {
 
   bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
 
+  bool isCoroMustElide() const { return CallExprBits.IsCoroMustElide; }
+  void setCoroMustElide(bool V = true) { CallExprBits.IsCoroMustElide = V; }
+
   Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
   const Decl *getCalleeDecl() const {
 return getCallee()->getReferencedDeclOfCallee();
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index bbd7634bcc3bfb..acdb9070ded0f1 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -561,8 +561,11 @@ class alignas(void *) Stmt {
 LLVM_PREFERRED_TYPE(bool)
 unsigned HasFPFeatures : 1;
 
+/// True if the call expression is a must-elide call to a coroutine.
+unsigned IsCoroMustElide : 1;
+
 /// Padding used to align OffsetToTrailingObjects to a byte multiple.
-unsigned : 24 - 3 - NumExprBits;
+unsigned : 24 - 4 - NumExprBits;
 
 /// The offset in bytes from the this pointer to the start of the
 /// trailing objects belonging to CallExpr. Intentionally byte sized
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 8ac2079099c854..d2f6d72342bdc7 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1220,6 +1220,14 @@ def CoroDisableLifetimeBound : InheritableAttr {
   let SimpleHandler = 1;
 }
 
+def CoroAwaitElidable : InheritableAttr {
+  let Spellings = [Clang<"coro_await_elidable">];
+  let Subjects = SubjectList<[CXXRecord]>;
+  let LangOpts = [CPlusPlus];
+  let Documentation = [CoroAwaitElidableDoc];
+  let SimpleHandler = 1;
+}
+
 // OSObject-based attributes.
 def OSConsumed : InheritableParamAttr {
   let Spellings = [Clang<"os_consumed">];
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 94c284fc731589..cdfece7ba20abf 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -8147,6 +8147,38 @@ but do not pass them to the underlying coroutine or pass 
them by value.
 }];
 }
 
+def CoroAwaitElidable

[clang] [llvm] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout (PR #102521)

2024-08-08 Thread Joel E. Denny via cfe-commits

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


[clang] [llvm] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout (PR #102521)

2024-08-08 Thread Joel E. Denny via cfe-commits

https://github.com/jdenny-ornl updated 
https://github.com/llvm/llvm-project/pull/102521

>From 6546428805b52f1b6f350193ab08ff027892710f Mon Sep 17 00:00:00 2001
From: "Joel E. Denny" 
Date: Thu, 8 Aug 2024 15:02:04 -0400
Subject: [PATCH 1/4] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout

When working on very busy systems, check-offload frequently fails many
tests with this diagnostic:

```
clang: error: cannot determine amdgcn architecture: 
/tmp/llvm/build/bin/amdgpu-arch: Child timed out: ; consider passing it via 
'-march'
```

The timeout is 10 seconds.  This patch accepts the environment
variable `CLANG_TOOL_CHAIN_PROGRAM_WAIT` to increase it.

It should be documented somewhere.  Any suggestions on where?
---
 clang/lib/Driver/ToolChain.cpp | 10 +-
 clang/lib/Driver/ToolChains/AMDGPU.cpp |  3 ++-
 clang/lib/Driver/ToolChains/Cuda.cpp   |  3 ++-
 llvm/utils/lit/lit/TestingConfig.py|  1 +
 4 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 2d50c2cbbc881c..04b281e1bb10cd 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -40,6 +40,7 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
 #include "llvm/Support/VersionTuple.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/TargetParser/AArch64TargetParser.h"
@@ -105,7 +106,7 @@ ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
 
 llvm::Expected>
 ToolChain::executeToolChainProgram(StringRef Executable,
-   unsigned SecondsToWait) const {
+   unsigned DefaultSecondsToWait) const {
   llvm::SmallString<64> OutputFile;
   llvm::sys::fs::createTemporaryFile("toolchain-program", "txt", OutputFile);
   llvm::FileRemover OutputRemover(OutputFile.c_str());
@@ -116,6 +117,13 @@ ToolChain::executeToolChainProgram(StringRef Executable,
   };
 
   std::string ErrorMessage;
+  int SecondsToWait = DefaultSecondsToWait;
+  if (std::optional Str =
+  llvm::sys::Process::GetEnv("CLANG_TOOL_CHAIN_PROGRAM_WAIT")) {
+int Val = std::atoi(Str->c_str());
+if (Val > 0)
+  SecondsToWait = Val;
+  }
   if (llvm::sys::ExecuteAndWait(Executable, {}, {}, Redirects, SecondsToWait,
 /*MemoryLimit=*/0, &ErrorMessage))
 return llvm::createStringError(std::error_code(),
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index aa8f9197cfabc3..4ed366d21f5c43 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -899,7 +899,8 @@ AMDGPUToolChain::getSystemGPUArchs(const ArgList &Args) 
const {
   else
 Program = GetProgramPath("amdgpu-arch");
 
-  auto StdoutOrErr = executeToolChainProgram(Program, /*SecondsToWait=*/10);
+  auto StdoutOrErr = executeToolChainProgram(Program,
+ /*DefaultSecondsToWait=*/10);
   if (!StdoutOrErr)
 return StdoutOrErr.takeError();
 
diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 17c952c808f725..104217eaf5d849 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -804,7 +804,8 @@ NVPTXToolChain::getSystemGPUArchs(const ArgList &Args) 
const {
   else
 Program = GetProgramPath("nvptx-arch");
 
-  auto StdoutOrErr = executeToolChainProgram(Program, /*SecondsToWait=*/10);
+  auto StdoutOrErr = executeToolChainProgram(Program,
+ /*DefaultSecondsToWait=*/10);
   if (!StdoutOrErr)
 return StdoutOrErr.takeError();
 
diff --git a/llvm/utils/lit/lit/TestingConfig.py 
b/llvm/utils/lit/lit/TestingConfig.py
index eb9f8de2a7f960..06713429d06b4b 100644
--- a/llvm/utils/lit/lit/TestingConfig.py
+++ b/llvm/utils/lit/lit/TestingConfig.py
@@ -26,6 +26,7 @@ def fromdefaults(litConfig):
 "SYSTEMROOT",
 "TERM",
 "CLANG",
+"CLANG_TOOL_CHAIN_PROGRAM_WAIT",
 "LLDB",
 "LD_PRELOAD",
 "LLVM_SYMBOLIZER_PATH",

>From 711cf93741ba618c7ee8051190b18bba938121fa Mon Sep 17 00:00:00 2001
From: "Joel E. Denny" 
Date: Thu, 8 Aug 2024 16:21:28 -0400
Subject: [PATCH 2/4] Apply reviewer suggestion

---
 clang/include/clang/Basic/DiagnosticDriverKinds.td | 3 ++-
 clang/lib/Driver/ToolChain.cpp | 2 ++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 3d8240f8357b40..05642f803d07de 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -99,7 +99,8 @@ def warn_drv_amdgpu_cov6: Warning<
   " use at your own risk">;
 def err_drv_undetermined_gpu_arch : Error<
  

[clang] [llvm] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout (PR #102521)

2024-08-08 Thread Joseph Huber via cfe-commits

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


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


[clang] [llvm] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout (PR #102521)

2024-08-08 Thread Joel E. Denny via cfe-commits


@@ -99,7 +99,8 @@ def warn_drv_amdgpu_cov6: Warning<
   " use at your own risk">;
 def err_drv_undetermined_gpu_arch : Error<
   "cannot determine %0 architecture: %1; consider passing it via "
-  "'%2'">;
+  "'%2' or increasing the tool timeout using the environment variable "
+  "'CLANG_TOOL_CHAIN_PROGRAM_WAIT' (in secs, <=0 is inifinite)">;

jdenny-ornl wrote:

Applied.

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


[clang] [llvm] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout (PR #102521)

2024-08-08 Thread Joel E. Denny via cfe-commits


@@ -116,6 +117,15 @@ ToolChain::executeToolChainProgram(StringRef Executable,
   };
 
   std::string ErrorMessage;
+  int SecondsToWait = DefaultSecondsToWait;
+  if (std::optional Str =
+  llvm::sys::Process::GetEnv("CLANG_TOOL_CHAIN_PROGRAM_WAIT")) {
+int Val = std::atoi(Str->c_str());
+if (Val > 0)
+  SecondsToWait = Val;
+else
+  SecondsToWait = 0; // infinite

jdenny-ornl wrote:

Applied.  Thanks.

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


[clang] [attributes][-Wunsafe-buffer-usage] Support adding unsafe_buffer_usage attribute to struct fields (PR #101585)

2024-08-08 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak updated 
https://github.com/llvm/llvm-project/pull/101585

>From 1ecd91c03f6de92153809402b10f99e5f649787f Mon Sep 17 00:00:00 2001
From: MalavikaSamak 
Date: Thu, 1 Aug 2024 11:01:36 -0700
Subject: [PATCH 1/4] [-Wunsafe-buffer-usage] Support adding
 unsafe_buffer_usage aatribute to struct fields.

---
 clang/include/clang/Basic/Attr.td |   2 +-
 clang/include/clang/Basic/AttrDocs.td |  45 +--
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +-
 clang/lib/Analysis/UnsafeBufferUsage.cpp  |  17 ++-
 clang/lib/Sema/AnalysisBasedWarnings.cpp  |  13 +-
 .../warn-unsafe-buffer-usage-field-attr.cpp   | 113 ++
 6 files changed, 176 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-unsafe-buffer-usage-field-attr.cpp

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4825979a974d22..2cc21d67ddffb2 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4447,7 +4447,7 @@ def ReleaseHandle : InheritableParamAttr {
 
 def UnsafeBufferUsage : InheritableAttr {
   let Spellings = [Clang<"unsafe_buffer_usage">];
-  let Subjects = SubjectList<[Function]>;
+  let Subjects = SubjectList<[Function, Field]>;
   let Documentation = [UnsafeBufferUsageDocs];
 }
 
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 99738812c81579..a52e3dd68a0ce2 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6763,15 +6763,18 @@ attribute requires a string literal argument to 
identify the handle being releas
 def UnsafeBufferUsageDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
-The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions
-that need to be avoided as they are prone to buffer overflows. It is designed 
to
-work together with the off-by-default compiler warning 
``-Wunsafe-buffer-usage``
-to help codebases transition away from raw pointer based buffer management,
-in favor of safer abstractions such as C++20 ``std::span``. The attribute 
causes
-``-Wunsafe-buffer-usage`` to warn on every use of the function, and it may
-enable ``-Wunsafe-buffer-usage`` to emit automatic fix-it hints
-which would help the user replace such unsafe functions with safe
-alternatives, though the attribute can be used even when the fix can't be 
automated.
+The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions 
or
+struct fields that are buffers, that must to be avoided as they are prone to 
+buffer overflows. It is designed to work together with the off-by-default 
compiler 
+warning ``-Wunsafe-buffer-usage``to help codebases transition away from raw 
pointer 
+based buffer management, in favor of safer abstractions such as C++20 
``std::span``. 
+The attribute causes ``-Wunsafe-buffer-usage`` to warn on every use of the 
function or 
+the field it is attached to, and it may enable ``-Wunsafe-buffer-usage`` to 
emit 
+automatic fix-it hints which would help the user replace the use of unsafe 
+functions(/fields) with safe alternatives, though the attribute can be used 
even when 
+the fix can't be automated.
+
+Attribute attached to functions:
 
 The attribute does not suppress ``-Wunsafe-buffer-usage`` inside the function
 to which it is attached. These warnings still need to be addressed.
@@ -6835,6 +6838,30 @@ the proper solution would be to create a different 
function (possibly
 an overload of ``baz()``) that accepts a safe container like ``bar()``,
 and then use the attribute on the original ``baz()`` to help the users
 update their code to use the new function.
+
+Attribute attached to fields:
+
+The attribute should only be attached to struct fields, if the fields can not 
be
+updated to a safe type with bounds check, such as std::span. In other words, 
the
+buffers prone to unsafe accesses should always be updated to use safe 
containers/views
+and attaching the attribute must be last resort when such an update is 
infeasible. 
+
+The attribute can be placed on individual fields or a set of them as shown 
below.  
+.. code-block:: c++
+
+  struct A {
+[[clang::unsafe_buffer_usage]]
+int *ptr1;
+  
+[[clang::unsafe_buffer_usage]]
+int *ptr2, buf[10];
+
+size_t sz;
+  };
+
+Here, every read/write to the fields ptr1, ptr2 and buf will trigger a warning 
that the
+field is marked unsafe due to unsafe-buffer operations on it.
+
   }];
 }
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 810abe4f23e31e..b0428d28667a51 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12371,7 +12371,8 @@ def warn_unsafe_buffer_variable : Warning<
   InGroup, DefaultIgnore;
 def warn_unsafe_buffer_operation : Warning<
   "%select{unsafe pointer operation|unsaf

[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread Bill Wendling via cfe-commits

https://github.com/bwendling created 
https://github.com/llvm/llvm-project/pull/102549

The __builtin_get_counted_by builtin is used on a flexible array
pointer and returns a pointer to the "counted_by" attribute's COUNT
argument, which is a field in the same non-anonymous struct as the
flexible array member. This is useful for automatically setting the
count field without needing the programmer's intervention. Otherwise
it's possible to get this anti-pattern:

  ptr = alloc(, COUNT);
  ptr->FAM[9] = 37; /* <<< Sanitizer will complain */
  ptr->count = COUNT;

>From 7ba43ae2b737fbd868848a23b58b3965f8d36ce1 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Tue, 6 Aug 2024 17:49:01 -0700
Subject: [PATCH 1/7] [WIP][Clang] Add __builtin_get_counted_by builtin

The __builtin_get_counted_by builtin is used on a flexible array
pointer and returns a pointer to the "counted_by" attribute's COUNT
argument, which is a field in the same non-anonymous struct as the
flexible array member. This is useful for automatically setting the
count field without needing the programmer's intervention. Otherwise
it's possible to get this anti-pattern:

  ptr = alloc(, COUNT);
  ptr->FAM[9] = 37; /* <<< Sanitizer will complain */
  ptr->count = COUNT;
---
 clang/include/clang/Basic/Builtins.td |  6 
 clang/lib/CodeGen/CGBuiltin.cpp   | 22 
 clang/lib/CodeGen/CGExpr.cpp  | 29 +---
 clang/lib/CodeGen/CodeGenFunction.h   |  4 +++
 clang/lib/Sema/SemaExpr.cpp   | 49 +--
 5 files changed, 96 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index b025a7681bfac3..254cd157d5f9d0 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4774,3 +4774,9 @@ def ArithmeticFence : LangBuiltin<"ALL_LANGUAGES"> {
   let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
+
+def GetCountedBy : Builtin {
+  let Spellings = ["__builtin_get_counted_by"];
+  let Attributes = [NoThrow];
+  let Prototype = "size_t*(void*)";
+}
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 51d1162c6e403c..859249be72c07e 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3563,6 +3563,28 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
  /*EmittedE=*/nullptr, IsDynamic));
   }
+  case Builtin::BI__builtin_get_counted_by: {
+llvm::Value *Result = nullptr;
+
+if (const MemberExpr *ME =
+dyn_cast(E->getArg(0)->IgnoreImpCasts())) {
+  bool IsFlexibleArrayMember = ME->isFlexibleArrayMemberLike(
+  getContext(), getLangOpts().getStrictFlexArraysLevel(),
+  /*IgnoreTemplateOrMacroSubstitution=*/false);
+
+  // TODO: Probably have to handle horrible casting crap here.
+
+  // FIXME: Emit a diagnostic?
+  if (!ME->HasSideEffects(getContext()) && IsFlexibleArrayMember &&
+  ME->getMemberDecl()->getType()->isCountAttributedType()) {
+const FieldDecl *FAMDecl = dyn_cast(ME->getMemberDecl());
+if (const FieldDecl *CountFD = FindCountedByField(FAMDecl))
+  Result = GetCountedByFieldExprGEP(ME, FAMDecl, CountFD);
+  }
+}
+
+return RValue::get(Result);
+  }
   case Builtin::BI__builtin_prefetch: {
 Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
 // FIXME: Technically these constants should of type 'int', yes?
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index a1dce741c78a11..55cd95c08e3ffc 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1100,15 +1100,7 @@ static bool getGEPIndicesToField(CodeGenFunction &CGF, 
const RecordDecl *RD,
   return false;
 }
 
-/// This method is typically called in contexts where we can't generate
-/// side-effects, like in __builtin_dynamic_object_size. When finding
-/// expressions, only choose those that have either already been emitted or can
-/// be loaded without side-effects.
-///
-/// - \p FAMDecl: the \p Decl for the flexible array member. It may not be
-///   within the top-level struct.
-/// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
-llvm::Value *CodeGenFunction::EmitLoadOfCountedByField(
+llvm::Value *CodeGenFunction::GetCountedByFieldExprGEP(
 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
   const RecordDecl *RD = 
CountDecl->getParent()->getOuterLexicalRecordContext();
 
@@ -1141,12 +1133,25 @@ llvm::Value *CodeGenFunction::EmitLoadOfCountedByField(
 return nullptr;
 
   Indices.push_back(Builder.getInt32(0));
-  Res = Builder.CreateInBoundsGEP(
+  return Builder.CreateInBoundsGEP(
   ConvertType(QualType(RD->getTypeForDecl(), 0)), Res,
   RecInd

[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Bill Wendling (bwendling)


Changes

The __builtin_get_counted_by builtin is used on a flexible array
pointer and returns a pointer to the "counted_by" attribute's COUNT
argument, which is a field in the same non-anonymous struct as the
flexible array member. This is useful for automatically setting the
count field without needing the programmer's intervention. Otherwise
it's possible to get this anti-pattern:

  ptr = alloc(, COUNT);
  ptr->FAM[9] = 37; /* <<< Sanitizer will complain */
  ptr->count = COUNT;

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


7 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.td (+6) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+60) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+17-12) 
- (modified) clang/lib/CodeGen/CodeGenFunction.h (+4) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+87-2) 
- (added) clang/test/CodeGen/builtin-get-counted-by.c (+83) 
- (added) clang/test/Sema/builtin-get-counted-by.c (+22) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index b025a7681bfac..254cd157d5f9d 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4774,3 +4774,9 @@ def ArithmeticFence : LangBuiltin<"ALL_LANGUAGES"> {
   let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
+
+def GetCountedBy : Builtin {
+  let Spellings = ["__builtin_get_counted_by"];
+  let Attributes = [NoThrow];
+  let Prototype = "size_t*(void*)";
+}
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index d1af7fde157b6..58fc0dfe45e1b 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -27,6 +27,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/OSLog.h"
 #include "clang/AST/OperationKinds.h"
+#include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
@@ -2536,6 +2537,45 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+namespace {
+
+/// MemberExprVisitor - Find the MemberExpr through all of the casts, array
+/// subscripts, and unary ops. This intentionally avoids all of them because
+/// we're interested only in the MemberExpr to check if it's a flexible array
+/// member.
+class MemberExprVisitor
+: public ConstStmtVisitor {
+public:
+  
//======//
+  //Visitor Methods
+  
//======//
+
+  const Expr *Visit(const Expr *E) {
+return ConstStmtVisitor::Visit(E);
+  }
+  const Expr *VisitStmt(const Stmt *S) { return nullptr; }
+
+  const Expr *VisitMemberExpr(const MemberExpr *E) { return E; }
+
+  const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
+return Visit(E->getBase());
+  }
+  const Expr *VisitCastExpr(const CastExpr *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitParenExpr(const ParenExpr *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitUnaryAddrOf(const clang::UnaryOperator *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitUnaryDeref(const clang::UnaryOperator *E) {
+return Visit(E->getSubExpr());
+  }
+};
+
+} // anonymous namespace
+
 RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned 
BuiltinID,
 const CallExpr *E,
 ReturnValueSlot ReturnValue) {
@@ -3563,6 +3603,26 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
  /*EmittedE=*/nullptr, IsDynamic));
   }
+  case Builtin::BI__builtin_get_counted_by: {
+llvm::Value *Result = llvm::ConstantPointerNull::get(
+cast(ConvertType(E->getType(;
+
+if (const Expr *Ptr = MemberExprVisitor().Visit(E->getArg(0))) {
+  const MemberExpr *ME = cast(Ptr);
+  bool IsFlexibleArrayMember = ME->isFlexibleArrayMemberLike(
+  getContext(), getLangOpts().getStrictFlexArraysLevel(),
+  /*IgnoreTemplateOrMacroSubstitution=*/false);
+
+  if (!ME->HasSideEffects(getContext()) && IsFlexibleArrayMember &&
+  ME->getMemberDecl()->getType()->isCountAttributedType()) {
+const FieldDecl *FAMDecl = dyn_cast(ME->getMemberDecl());
+if (const FieldDecl *CountFD = FindCountedByField(FAMDecl))
+  Result = GetCountedByFieldExprGEP(ME, FAMDecl, CountFD);
+  }
+}
+
+return RValue::get(Result);
+  }
   case Builtin::BI__builtin_prefetch: {
 Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
 // FIXME: Tech

[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread Bill Wendling via cfe-commits

bwendling wrote:

@kees

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


[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread via cfe-commits

github-actions[bot] wrote:

⚠️ We detected that you are using a GitHub private e-mail address to contribute 
to the repo. Please turn off [Keep my email addresses 
private](https://github.com/settings/emails) setting in your account. See 
[LLVM 
Discourse](https://discourse.llvm.org/t/hidden-emails-on-github-should-we-do-something-about-it)
 for more information.

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


[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread Bill Wendling via cfe-commits

bwendling wrote:

There's still some cleanup to do. Firstly, the code to get the `MemberExpr` for 
the flexible array member. It's sloppy.

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


[clang] [libcxx] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/102551

This reverts commit 748371183ae769bfb485f1e7466a864bf1db93d5.

Reverted due to both regression reported on PR and #102253

>From cce965741a7496f792e3f94f47ae5acba06c4c39 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 8 Aug 2024 20:18:01 -0300
Subject: [PATCH] Revert "[clang] Reland: Instantiate concepts with sugared
 template arguments (#101782)"

This reverts commit 748371183ae769bfb485f1e7466a864bf1db93d5.

Reverted due to both regression reported on PR and #102253
---
 clang/docs/ReleaseNotes.rst  |  5 ++---
 clang/include/clang/Sema/Template.h  |  6 +++---
 clang/lib/Sema/SemaConcept.cpp   | 11 ---
 clang/lib/Sema/SemaExprCXX.cpp   |  5 +++--
 clang/lib/Sema/SemaTemplate.cpp  | 10 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp | 16 
 clang/lib/Serialization/ASTReaderDecl.cpp|  2 +-
 clang/test/AST/ast-dump-concepts.cpp | 10 --
 .../expr.prim.req/compound-requirement.cpp   | 10 +-
 .../expr.prim.req/nested-requirement.cpp |  2 +-
 .../expr.prim.req/simple-requirement.cpp |  4 ++--
 .../expr.prim/expr.prim.req/type-requirement.cpp | 12 ++--
 .../temp/temp.constr/temp.constr.normal/p1.cpp   |  2 +-
 clang/test/CXX/temp/temp.param/p10-2a.cpp|  4 ++--
 .../SemaTemplate/concepts-recursive-inst.cpp | 12 ++--
 clang/test/SemaTemplate/concepts.cpp |  4 ++--
 .../SemaTemplate/instantiate-requires-expr.cpp   | 16 +++-
 clang/test/SemaTemplate/pr52970.cpp  |  2 +-
 .../cpp17_iterator_concepts.verify.cpp   |  2 +-
 19 files changed, 60 insertions(+), 75 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb0a1b25e51c2a..7beef7be0e6a53 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -75,8 +75,8 @@ sections with improvements to Clang's support for those 
languages.
 
 C++ Language Changes
 
-- Allow single element access of GCC vector/ext_vector_type object to be 
-  constant expression. Supports the `V.xyzw` syntax and other tidbits 
+- Allow single element access of GCC vector/ext_vector_type object to be
+  constant expression. Supports the `V.xyzw` syntax and other tidbits
   as seen in OpenCL. Selecting multiple elements is left as a future work.
 
 C++17 Feature Support
@@ -166,7 +166,6 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
 - -Wdangling-assignment-gsl is enabled by default.
-- Clang now does a better job preserving the template arguments as written 
when specializing concepts.
 - Clang now always preserves the template arguments as written used
   to specialize template type aliases.
 
diff --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index d616865afe807e..0340c23fd170d6 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -234,8 +234,7 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args,
-   bool Final = false) {
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
   assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
  "Replacing in an empty list?");
 
@@ -247,7 +246,8 @@ enum class TemplateSubstitutionKind : char {
 TemplateArgumentLists[0].Args = Args;
   } else {
 --NumRetainedOuterLevels;
-TemplateArgumentLists.push_back({{AssociatedDecl, Final}, Args});
+TemplateArgumentLists.push_back(
+{{AssociatedDecl, /*Final=*/false}, Args});
   }
 }
 
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e34..d1e62fb5cee623 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -414,8 +414,7 @@ DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID 
&ID,
   E->Profile(ID, S.Context, /*Canonical=*/true);
   for (const auto &List : MLTAL)
 for (const auto &TemplateArg : List.Args)
-  S.Context.getCanonicalTemplateArgument(TemplateArg)
-  .Profile(ID, S.Context);
+  TemplateArg.Profile(ID, S.Context);
 
   // Note that we have to do this with our own collection, because there are
   // times where a constraint-expression check can cause us to need to evaluate
@@ -643,8 +642,8 @@ bool Sema::CheckConstraintSatisfac

[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff bb7143f6669345825c214b26fbe336857f4bf523 
197cd1c945c4b1c5cdd38d07f6ed5dd2baa96ab2 --extensions cpp,h,c -- 
clang/test/CodeGen/builtin-get-counted-by.c 
clang/test/Sema/builtin-get-counted-by.c clang/lib/CodeGen/CGBuiltin.cpp 
clang/lib/CodeGen/CGExpr.cpp clang/lib/CodeGen/CodeGenFunction.h 
clang/lib/Sema/SemaExpr.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 58fc0dfe45..de46c538fd 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3610,8 +3610,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 if (const Expr *Ptr = MemberExprVisitor().Visit(E->getArg(0))) {
   const MemberExpr *ME = cast(Ptr);
   bool IsFlexibleArrayMember = ME->isFlexibleArrayMemberLike(
-  getContext(), getLangOpts().getStrictFlexArraysLevel(),
-  /*IgnoreTemplateOrMacroSubstitution=*/false);
+  getContext(), getLangOpts().getStrictFlexArraysLevel(),
+  /*IgnoreTemplateOrMacroSubstitution=*/false);
 
   if (!ME->HasSideEffects(getContext()) && IsFlexibleArrayMember &&
   ME->getMemberDecl()->getType()->isCountAttributedType()) {
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 33bc71d621..3b80bcfd3a 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6656,8 +6656,8 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, 
SourceLocation LParenLoc,
 if (const Expr *Ptr = MemberExprVisitor().Visit(ArgExprs[0])) {
   const MemberExpr *ME = cast(Ptr);
   bool IsFlexibleArrayMember = ME->isFlexibleArrayMemberLike(
-  Context, getLangOpts().getStrictFlexArraysLevel(),
-  /*IgnoreTemplateOrMacroSubstitution=*/false);
+  Context, getLangOpts().getStrictFlexArraysLevel(),
+  /*IgnoreTemplateOrMacroSubstitution=*/false);
 
   if (!ME->HasSideEffects(Context) && IsFlexibleArrayMember &&
   ME->getMemberDecl()->getType()->isCountAttributedType()) {

``




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


[clang] [libcxx] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Matheus Izvekov (mizvekov)


Changes

This reverts commit 748371183ae769bfb485f1e7466a864bf1db93d5.

Reverted due to both regression reported on PR and #102253

---

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


19 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2-3) 
- (modified) clang/include/clang/Sema/Template.h (+3-3) 
- (modified) clang/lib/Sema/SemaConcept.cpp (+4-7) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (+3-2) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+5-5) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+8-8) 
- (modified) clang/lib/Serialization/ASTReaderDecl.cpp (+1-1) 
- (modified) clang/test/AST/ast-dump-concepts.cpp (+4-6) 
- (modified) 
clang/test/CXX/expr/expr.prim/expr.prim.req/compound-requirement.cpp (+5-5) 
- (modified) clang/test/CXX/expr/expr.prim/expr.prim.req/nested-requirement.cpp 
(+1-1) 
- (modified) clang/test/CXX/expr/expr.prim/expr.prim.req/simple-requirement.cpp 
(+2-2) 
- (modified) clang/test/CXX/expr/expr.prim/expr.prim.req/type-requirement.cpp 
(+6-6) 
- (modified) clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp (+1-1) 
- (modified) clang/test/CXX/temp/temp.param/p10-2a.cpp (+2-2) 
- (modified) clang/test/SemaTemplate/concepts-recursive-inst.cpp (+6-6) 
- (modified) clang/test/SemaTemplate/concepts.cpp (+2-2) 
- (modified) clang/test/SemaTemplate/instantiate-requires-expr.cpp (+3-13) 
- (modified) clang/test/SemaTemplate/pr52970.cpp (+1-1) 
- (modified) libcxx/test/libcxx/algorithms/cpp17_iterator_concepts.verify.cpp 
(+1-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb0a1b25e51c2a..7beef7be0e6a53 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -75,8 +75,8 @@ sections with improvements to Clang's support for those 
languages.
 
 C++ Language Changes
 
-- Allow single element access of GCC vector/ext_vector_type object to be 
-  constant expression. Supports the `V.xyzw` syntax and other tidbits 
+- Allow single element access of GCC vector/ext_vector_type object to be
+  constant expression. Supports the `V.xyzw` syntax and other tidbits
   as seen in OpenCL. Selecting multiple elements is left as a future work.
 
 C++17 Feature Support
@@ -166,7 +166,6 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
 - -Wdangling-assignment-gsl is enabled by default.
-- Clang now does a better job preserving the template arguments as written 
when specializing concepts.
 - Clang now always preserves the template arguments as written used
   to specialize template type aliases.
 
diff --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index d616865afe807e..0340c23fd170d6 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -234,8 +234,7 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args,
-   bool Final = false) {
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
   assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
  "Replacing in an empty list?");
 
@@ -247,7 +246,8 @@ enum class TemplateSubstitutionKind : char {
 TemplateArgumentLists[0].Args = Args;
   } else {
 --NumRetainedOuterLevels;
-TemplateArgumentLists.push_back({{AssociatedDecl, Final}, Args});
+TemplateArgumentLists.push_back(
+{{AssociatedDecl, /*Final=*/false}, Args});
   }
 }
 
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e34..d1e62fb5cee623 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -414,8 +414,7 @@ DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID 
&ID,
   E->Profile(ID, S.Context, /*Canonical=*/true);
   for (const auto &List : MLTAL)
 for (const auto &TemplateArg : List.Args)
-  S.Context.getCanonicalTemplateArgument(TemplateArg)
-  .Profile(ID, S.Context);
+  TemplateArg.Profile(ID, S.Context);
 
   // Note that we have to do this with our own collection, because there are
   // times where a constraint-expression check can cause us to need to evaluate
@@ -643,8 +642,8 @@ bool Sema::CheckConstraintSatisfaction(
   // here.
   llvm::SmallVector FlattenedArgs;
   for (auto List : TemplateArgsLists)
-for (const TemplateArgument &Arg : List.Args)
-  Fla

[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread Bill Wendling via cfe-commits

https://github.com/bwendling updated 
https://github.com/llvm/llvm-project/pull/102549

>From 7ba43ae2b737fbd868848a23b58b3965f8d36ce1 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Tue, 6 Aug 2024 17:49:01 -0700
Subject: [PATCH 1/8] [WIP][Clang] Add __builtin_get_counted_by builtin

The __builtin_get_counted_by builtin is used on a flexible array
pointer and returns a pointer to the "counted_by" attribute's COUNT
argument, which is a field in the same non-anonymous struct as the
flexible array member. This is useful for automatically setting the
count field without needing the programmer's intervention. Otherwise
it's possible to get this anti-pattern:

  ptr = alloc(, COUNT);
  ptr->FAM[9] = 37; /* <<< Sanitizer will complain */
  ptr->count = COUNT;
---
 clang/include/clang/Basic/Builtins.td |  6 
 clang/lib/CodeGen/CGBuiltin.cpp   | 22 
 clang/lib/CodeGen/CGExpr.cpp  | 29 +---
 clang/lib/CodeGen/CodeGenFunction.h   |  4 +++
 clang/lib/Sema/SemaExpr.cpp   | 49 +--
 5 files changed, 96 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index b025a7681bfac3..254cd157d5f9d0 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4774,3 +4774,9 @@ def ArithmeticFence : LangBuiltin<"ALL_LANGUAGES"> {
   let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
+
+def GetCountedBy : Builtin {
+  let Spellings = ["__builtin_get_counted_by"];
+  let Attributes = [NoThrow];
+  let Prototype = "size_t*(void*)";
+}
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 51d1162c6e403c..859249be72c07e 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3563,6 +3563,28 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
  /*EmittedE=*/nullptr, IsDynamic));
   }
+  case Builtin::BI__builtin_get_counted_by: {
+llvm::Value *Result = nullptr;
+
+if (const MemberExpr *ME =
+dyn_cast(E->getArg(0)->IgnoreImpCasts())) {
+  bool IsFlexibleArrayMember = ME->isFlexibleArrayMemberLike(
+  getContext(), getLangOpts().getStrictFlexArraysLevel(),
+  /*IgnoreTemplateOrMacroSubstitution=*/false);
+
+  // TODO: Probably have to handle horrible casting crap here.
+
+  // FIXME: Emit a diagnostic?
+  if (!ME->HasSideEffects(getContext()) && IsFlexibleArrayMember &&
+  ME->getMemberDecl()->getType()->isCountAttributedType()) {
+const FieldDecl *FAMDecl = dyn_cast(ME->getMemberDecl());
+if (const FieldDecl *CountFD = FindCountedByField(FAMDecl))
+  Result = GetCountedByFieldExprGEP(ME, FAMDecl, CountFD);
+  }
+}
+
+return RValue::get(Result);
+  }
   case Builtin::BI__builtin_prefetch: {
 Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
 // FIXME: Technically these constants should of type 'int', yes?
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index a1dce741c78a11..55cd95c08e3ffc 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1100,15 +1100,7 @@ static bool getGEPIndicesToField(CodeGenFunction &CGF, 
const RecordDecl *RD,
   return false;
 }
 
-/// This method is typically called in contexts where we can't generate
-/// side-effects, like in __builtin_dynamic_object_size. When finding
-/// expressions, only choose those that have either already been emitted or can
-/// be loaded without side-effects.
-///
-/// - \p FAMDecl: the \p Decl for the flexible array member. It may not be
-///   within the top-level struct.
-/// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
-llvm::Value *CodeGenFunction::EmitLoadOfCountedByField(
+llvm::Value *CodeGenFunction::GetCountedByFieldExprGEP(
 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
   const RecordDecl *RD = 
CountDecl->getParent()->getOuterLexicalRecordContext();
 
@@ -1141,12 +1133,25 @@ llvm::Value *CodeGenFunction::EmitLoadOfCountedByField(
 return nullptr;
 
   Indices.push_back(Builder.getInt32(0));
-  Res = Builder.CreateInBoundsGEP(
+  return Builder.CreateInBoundsGEP(
   ConvertType(QualType(RD->getTypeForDecl(), 0)), Res,
   RecIndicesTy(llvm::reverse(Indices)), "..counted_by.gep");
+}
 
-  return Builder.CreateAlignedLoad(ConvertType(CountDecl->getType()), Res,
-   getIntAlign(), "..counted_by.load");
+/// This method is typically called in contexts where we can't generate
+/// side-effects, like in __builtin_dynamic_object_size. When finding
+/// expressions, only choose those that have either already been emitted or can
+/// be loaded without side-effects.
+///
+/// 

[clang] [llvm] [LLVM][PassBuilder] Extend the function signature of callback for optimizer pipeline extension point (PR #100953)

2024-08-08 Thread Shilei Tian via cfe-commits

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


[clang] [llvm] [LLVM][PassBuilder] Extend the function signature of callback for optimizer pipeline extension point (PR #100953)

2024-08-08 Thread Shilei Tian via cfe-commits

shiltian wrote:

This PR is no longer needed. We decided to move the `AMDGPUAttributorPass` to 
full LTO.

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


[clang] [llvm] [MC] Emit a jump table size section (PR #101962)

2024-08-08 Thread Fangrui Song via cfe-commits

MaskRay wrote:

Conventionally, `.debug_*` sections are reserved for DWARF, even without 
official standards.
GNU strip's default behavior --strip-all, emulated by llvm-objcopy's 
--strip-all-gnu option, is roughly to remove non-SHF_ALLOC sections that are 
not debug.
The `.llvm` prefix holds no special meaning.

When designing new sections, we should not adapt to the --strip-all-gnu 
behavior.

Jump tables exhibit diverse structures. For instance, consider 
llvm/test/CodeGen/ARM/jump-table-tbh.ll and Mach-O's .data_region.


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


[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

I'd expect some kind of diagnostic when the specified field doesn't have a 
corresponding counted_by field.

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


[clang] [llvm] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout (PR #102521)

2024-08-08 Thread Joel E. Denny via cfe-commits

https://github.com/jdenny-ornl updated 
https://github.com/llvm/llvm-project/pull/102521

>From 6546428805b52f1b6f350193ab08ff027892710f Mon Sep 17 00:00:00 2001
From: "Joel E. Denny" 
Date: Thu, 8 Aug 2024 15:02:04 -0400
Subject: [PATCH 1/5] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout

When working on very busy systems, check-offload frequently fails many
tests with this diagnostic:

```
clang: error: cannot determine amdgcn architecture: 
/tmp/llvm/build/bin/amdgpu-arch: Child timed out: ; consider passing it via 
'-march'
```

The timeout is 10 seconds.  This patch accepts the environment
variable `CLANG_TOOL_CHAIN_PROGRAM_WAIT` to increase it.

It should be documented somewhere.  Any suggestions on where?
---
 clang/lib/Driver/ToolChain.cpp | 10 +-
 clang/lib/Driver/ToolChains/AMDGPU.cpp |  3 ++-
 clang/lib/Driver/ToolChains/Cuda.cpp   |  3 ++-
 llvm/utils/lit/lit/TestingConfig.py|  1 +
 4 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 2d50c2cbbc881c..04b281e1bb10cd 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -40,6 +40,7 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
 #include "llvm/Support/VersionTuple.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/TargetParser/AArch64TargetParser.h"
@@ -105,7 +106,7 @@ ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
 
 llvm::Expected>
 ToolChain::executeToolChainProgram(StringRef Executable,
-   unsigned SecondsToWait) const {
+   unsigned DefaultSecondsToWait) const {
   llvm::SmallString<64> OutputFile;
   llvm::sys::fs::createTemporaryFile("toolchain-program", "txt", OutputFile);
   llvm::FileRemover OutputRemover(OutputFile.c_str());
@@ -116,6 +117,13 @@ ToolChain::executeToolChainProgram(StringRef Executable,
   };
 
   std::string ErrorMessage;
+  int SecondsToWait = DefaultSecondsToWait;
+  if (std::optional Str =
+  llvm::sys::Process::GetEnv("CLANG_TOOL_CHAIN_PROGRAM_WAIT")) {
+int Val = std::atoi(Str->c_str());
+if (Val > 0)
+  SecondsToWait = Val;
+  }
   if (llvm::sys::ExecuteAndWait(Executable, {}, {}, Redirects, SecondsToWait,
 /*MemoryLimit=*/0, &ErrorMessage))
 return llvm::createStringError(std::error_code(),
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index aa8f9197cfabc3..4ed366d21f5c43 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -899,7 +899,8 @@ AMDGPUToolChain::getSystemGPUArchs(const ArgList &Args) 
const {
   else
 Program = GetProgramPath("amdgpu-arch");
 
-  auto StdoutOrErr = executeToolChainProgram(Program, /*SecondsToWait=*/10);
+  auto StdoutOrErr = executeToolChainProgram(Program,
+ /*DefaultSecondsToWait=*/10);
   if (!StdoutOrErr)
 return StdoutOrErr.takeError();
 
diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 17c952c808f725..104217eaf5d849 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -804,7 +804,8 @@ NVPTXToolChain::getSystemGPUArchs(const ArgList &Args) 
const {
   else
 Program = GetProgramPath("nvptx-arch");
 
-  auto StdoutOrErr = executeToolChainProgram(Program, /*SecondsToWait=*/10);
+  auto StdoutOrErr = executeToolChainProgram(Program,
+ /*DefaultSecondsToWait=*/10);
   if (!StdoutOrErr)
 return StdoutOrErr.takeError();
 
diff --git a/llvm/utils/lit/lit/TestingConfig.py 
b/llvm/utils/lit/lit/TestingConfig.py
index eb9f8de2a7f960..06713429d06b4b 100644
--- a/llvm/utils/lit/lit/TestingConfig.py
+++ b/llvm/utils/lit/lit/TestingConfig.py
@@ -26,6 +26,7 @@ def fromdefaults(litConfig):
 "SYSTEMROOT",
 "TERM",
 "CLANG",
+"CLANG_TOOL_CHAIN_PROGRAM_WAIT",
 "LLDB",
 "LD_PRELOAD",
 "LLVM_SYMBOLIZER_PATH",

>From 711cf93741ba618c7ee8051190b18bba938121fa Mon Sep 17 00:00:00 2001
From: "Joel E. Denny" 
Date: Thu, 8 Aug 2024 16:21:28 -0400
Subject: [PATCH 2/5] Apply reviewer suggestion

---
 clang/include/clang/Basic/DiagnosticDriverKinds.td | 3 ++-
 clang/lib/Driver/ToolChain.cpp | 2 ++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 3d8240f8357b40..05642f803d07de 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -99,7 +99,8 @@ def warn_drv_amdgpu_cov6: Warning<
   " use at your own risk">;
 def err_drv_undetermined_gpu_arch : Error<
  

[clang] [llvm] Revert "demangle function names in trace files (#87626)" (PR #102274)

2024-08-08 Thread Fangrui Song via cfe-commits

MaskRay wrote:

> @tru @nikic @MaskRay should this be backported to 19 release branch?

Thanks for asking:) I think so. Invoked the cherry-pick command at 
https://github.com/llvm/llvm-project/issues/10#issuecomment-2276883290

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


[clang] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread Matheus Izvekov via cfe-commits

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

>From c70e98cef58982fd7afb896fe08ebacc8b752009 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 8 Aug 2024 20:18:01 -0300
Subject: [PATCH] Revert "[clang] Reland: Instantiate concepts with sugared
 template arguments (#101782)"

This reverts commit 748371183ae769bfb485f1e7466a864bf1db93d5.

Reverted due to both regression reported on PR and #102253
---
 clang/docs/ReleaseNotes.rst  |  5 ++---
 clang/include/clang/Sema/Template.h  |  6 +++---
 clang/lib/Sema/SemaConcept.cpp   | 11 ---
 clang/lib/Sema/SemaExprCXX.cpp   |  5 +++--
 clang/lib/Sema/SemaTemplate.cpp  | 10 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp | 16 
 clang/lib/Serialization/ASTReaderDecl.cpp|  2 +-
 clang/test/AST/ast-dump-concepts.cpp | 10 --
 .../expr.prim.req/compound-requirement.cpp   | 10 +-
 .../expr.prim.req/nested-requirement.cpp |  2 +-
 .../expr.prim.req/simple-requirement.cpp |  4 ++--
 .../expr.prim/expr.prim.req/type-requirement.cpp | 12 ++--
 .../temp/temp.constr/temp.constr.normal/p1.cpp   |  2 +-
 clang/test/CXX/temp/temp.param/p10-2a.cpp|  4 ++--
 .../SemaTemplate/concepts-recursive-inst.cpp | 12 ++--
 clang/test/SemaTemplate/concepts.cpp |  4 ++--
 .../SemaTemplate/instantiate-requires-expr.cpp   | 16 +++-
 clang/test/SemaTemplate/pr52970.cpp  |  2 +-
 18 files changed, 59 insertions(+), 74 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb0a1b25e51c2a..7beef7be0e6a53 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -75,8 +75,8 @@ sections with improvements to Clang's support for those 
languages.
 
 C++ Language Changes
 
-- Allow single element access of GCC vector/ext_vector_type object to be 
-  constant expression. Supports the `V.xyzw` syntax and other tidbits 
+- Allow single element access of GCC vector/ext_vector_type object to be
+  constant expression. Supports the `V.xyzw` syntax and other tidbits
   as seen in OpenCL. Selecting multiple elements is left as a future work.
 
 C++17 Feature Support
@@ -166,7 +166,6 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
 - -Wdangling-assignment-gsl is enabled by default.
-- Clang now does a better job preserving the template arguments as written 
when specializing concepts.
 - Clang now always preserves the template arguments as written used
   to specialize template type aliases.
 
diff --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index d616865afe807e..0340c23fd170d6 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -234,8 +234,7 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args,
-   bool Final = false) {
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
   assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
  "Replacing in an empty list?");
 
@@ -247,7 +246,8 @@ enum class TemplateSubstitutionKind : char {
 TemplateArgumentLists[0].Args = Args;
   } else {
 --NumRetainedOuterLevels;
-TemplateArgumentLists.push_back({{AssociatedDecl, Final}, Args});
+TemplateArgumentLists.push_back(
+{{AssociatedDecl, /*Final=*/false}, Args});
   }
 }
 
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e34..d1e62fb5cee623 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -414,8 +414,7 @@ DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID 
&ID,
   E->Profile(ID, S.Context, /*Canonical=*/true);
   for (const auto &List : MLTAL)
 for (const auto &TemplateArg : List.Args)
-  S.Context.getCanonicalTemplateArgument(TemplateArg)
-  .Profile(ID, S.Context);
+  TemplateArg.Profile(ID, S.Context);
 
   // Note that we have to do this with our own collection, because there are
   // times where a constraint-expression check can cause us to need to evaluate
@@ -643,8 +642,8 @@ bool Sema::CheckConstraintSatisfaction(
   // here.
   llvm::SmallVector FlattenedArgs;
   for (auto List : TemplateArgsLists)
-for (const TemplateArgument &Arg : List.Args)
-  FlattenedArgs.emplace_back(Con

[clang] [compiler-rt] [llvm] [PAC][AArch64] Support init/fini array signing (PR #96478)

2024-08-08 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

There's some followup discussion suggesting a different IR representation at 
https://github.com/llvm/llvm-project/pull/102199#discussion_r1706094411 .  

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


[clang] [llvm] [Clang] C++20 Coroutines: Introduce Frontend Attribute [[clang::coro_await_elidable]] (PR #99282)

2024-08-08 Thread Yuxuan Chen via cfe-commits

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


[clang] [llvm] [Clang] C++20 Coroutines: Introduce Frontend Attribute [[clang::coro_await_elidable]] (PR #99282)

2024-08-08 Thread Yuxuan Chen via cfe-commits

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


[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread Bill Wendling via cfe-commits

bwendling wrote:

> I'd expect some kind of diagnostic when the specified field doesn't have a 
> corresponding counted_by field.

So there's a complication with that. The use case for this builtin is to 
automatically set the `count` field during allocation in the Linux kernel. (It 
could be used elsewhere, but Linux is why we're doing this now.) From my 
understanding, @kees wants to have a way to get the `count` field without 
having to change the allocator's prototype. (Is that correct?) That's not 
currently possible, or at least we haven't found a way to do it yet.

The idea is to do something like:

```c
#define kmalloc(type, COUNT) ({ \
  ... \
  if (__builtin_get_counted_by(__p->FAM)) \
*__builtin_get_counted_by(__p->FAM) = COUNT; \
  __p; \
})
```

We want the builtin to return a `nullptr` for this reason (because Clang 
doesn't have a `__builtin_has_attribute` builtin). But also we can use the same 
`kmalloc` for all allocations and not have to have one special `kmalloc` for a 
FAM that uses `counted_by` and one for every other allocation.

As you can see, this builtin has a very limited utility. Obviously, one 
wouldn't write:

```c
*__builtin_get_counted_by(ptr->FAM) = 42;
```

when using `ptr->count = 42` is far easier.

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


[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

2024-08-08 Thread Bill Wendling via cfe-commits

https://github.com/bwendling updated 
https://github.com/llvm/llvm-project/pull/102549

>From 7ba43ae2b737fbd868848a23b58b3965f8d36ce1 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Tue, 6 Aug 2024 17:49:01 -0700
Subject: [PATCH 1/9] [WIP][Clang] Add __builtin_get_counted_by builtin

The __builtin_get_counted_by builtin is used on a flexible array
pointer and returns a pointer to the "counted_by" attribute's COUNT
argument, which is a field in the same non-anonymous struct as the
flexible array member. This is useful for automatically setting the
count field without needing the programmer's intervention. Otherwise
it's possible to get this anti-pattern:

  ptr = alloc(, COUNT);
  ptr->FAM[9] = 37; /* <<< Sanitizer will complain */
  ptr->count = COUNT;
---
 clang/include/clang/Basic/Builtins.td |  6 
 clang/lib/CodeGen/CGBuiltin.cpp   | 22 
 clang/lib/CodeGen/CGExpr.cpp  | 29 +---
 clang/lib/CodeGen/CodeGenFunction.h   |  4 +++
 clang/lib/Sema/SemaExpr.cpp   | 49 +--
 5 files changed, 96 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index b025a7681bfac..254cd157d5f9d 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4774,3 +4774,9 @@ def ArithmeticFence : LangBuiltin<"ALL_LANGUAGES"> {
   let Attributes = [CustomTypeChecking, Constexpr];
   let Prototype = "void(...)";
 }
+
+def GetCountedBy : Builtin {
+  let Spellings = ["__builtin_get_counted_by"];
+  let Attributes = [NoThrow];
+  let Prototype = "size_t*(void*)";
+}
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 51d1162c6e403..859249be72c07 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3563,6 +3563,28 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
  /*EmittedE=*/nullptr, IsDynamic));
   }
+  case Builtin::BI__builtin_get_counted_by: {
+llvm::Value *Result = nullptr;
+
+if (const MemberExpr *ME =
+dyn_cast(E->getArg(0)->IgnoreImpCasts())) {
+  bool IsFlexibleArrayMember = ME->isFlexibleArrayMemberLike(
+  getContext(), getLangOpts().getStrictFlexArraysLevel(),
+  /*IgnoreTemplateOrMacroSubstitution=*/false);
+
+  // TODO: Probably have to handle horrible casting crap here.
+
+  // FIXME: Emit a diagnostic?
+  if (!ME->HasSideEffects(getContext()) && IsFlexibleArrayMember &&
+  ME->getMemberDecl()->getType()->isCountAttributedType()) {
+const FieldDecl *FAMDecl = dyn_cast(ME->getMemberDecl());
+if (const FieldDecl *CountFD = FindCountedByField(FAMDecl))
+  Result = GetCountedByFieldExprGEP(ME, FAMDecl, CountFD);
+  }
+}
+
+return RValue::get(Result);
+  }
   case Builtin::BI__builtin_prefetch: {
 Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
 // FIXME: Technically these constants should of type 'int', yes?
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index a1dce741c78a1..55cd95c08e3ff 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1100,15 +1100,7 @@ static bool getGEPIndicesToField(CodeGenFunction &CGF, 
const RecordDecl *RD,
   return false;
 }
 
-/// This method is typically called in contexts where we can't generate
-/// side-effects, like in __builtin_dynamic_object_size. When finding
-/// expressions, only choose those that have either already been emitted or can
-/// be loaded without side-effects.
-///
-/// - \p FAMDecl: the \p Decl for the flexible array member. It may not be
-///   within the top-level struct.
-/// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
-llvm::Value *CodeGenFunction::EmitLoadOfCountedByField(
+llvm::Value *CodeGenFunction::GetCountedByFieldExprGEP(
 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
   const RecordDecl *RD = 
CountDecl->getParent()->getOuterLexicalRecordContext();
 
@@ -1141,12 +1133,25 @@ llvm::Value *CodeGenFunction::EmitLoadOfCountedByField(
 return nullptr;
 
   Indices.push_back(Builder.getInt32(0));
-  Res = Builder.CreateInBoundsGEP(
+  return Builder.CreateInBoundsGEP(
   ConvertType(QualType(RD->getTypeForDecl(), 0)), Res,
   RecIndicesTy(llvm::reverse(Indices)), "..counted_by.gep");
+}
 
-  return Builder.CreateAlignedLoad(ConvertType(CountDecl->getType()), Res,
-   getIntAlign(), "..counted_by.load");
+/// This method is typically called in contexts where we can't generate
+/// side-effects, like in __builtin_dynamic_object_size. When finding
+/// expressions, only choose those that have either already been emitted or can
+/// be loaded without side-effects.
+///
+/// - \p F

[clang] [clang][DebugInfo] Don't mark structured bindings as artificial (PR #100355)

2024-08-08 Thread Michael Buch via cfe-commits

https://github.com/Michael137 updated 
https://github.com/llvm/llvm-project/pull/100355

>From 2b1255de05856e4c79f58d3e4071384ba80a881d Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Thu, 18 Jul 2024 16:26:16 -0500
Subject: [PATCH 1/3] [clang][Sema] Don't mark VarDecls of bindings in
 tuple-like decompositions as implicit

---
 clang/lib/AST/DeclCXX.cpp |  1 -
 clang/lib/Sema/SemaDeclCXX.cpp|  1 -
 .../debug-info-structured-binding.cpp | 36 ++--
 .../ASTMatchers/ASTMatchersTraversalTest.cpp  | 57 +++
 4 files changed, 88 insertions(+), 7 deletions(-)

diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index 72d68f39a97a5..2c22f42a5e0a8 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -3327,7 +3327,6 @@ VarDecl *BindingDecl::getHoldingVar() const {
 return nullptr;
 
   auto *VD = cast(DRE->getDecl());
-  assert(VD->isImplicit() && "holding var for binding decl not implicit");
   return VD;
 }
 
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index f24912cde275a..f4cc1fc4583aa 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -1316,7 +1316,6 @@ static bool checkTupleLikeDecomposition(Sema &S,
 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
 RefVD->setTSCSpec(Src->getTSCSpec());
-RefVD->setImplicit();
 if (Src->isInlineSpecified())
   RefVD->setInlineSpecified();
 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
diff --git a/clang/test/CodeGenCXX/debug-info-structured-binding.cpp 
b/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
index c88a5cdaa20e7..4a3126a36598d 100644
--- a/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
+++ b/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
@@ -5,20 +5,46 @@
 // CHECK: #dbg_declare(ptr %{{[0-9]+}}, ![[VAR_2:[0-9]+]], 
!DIExpression(DW_OP_plus_uconst, 4),
 // CHECK: #dbg_declare(ptr %{{[0-9]+}}, ![[VAR_3:[0-9]+]], 
!DIExpression(DW_OP_deref),
 // CHECK: #dbg_declare(ptr %{{[0-9]+}}, ![[VAR_4:[0-9]+]], 
!DIExpression(DW_OP_deref, DW_OP_plus_uconst, 4),
+// CHECK: #dbg_declare(ptr %z1, ![[VAR_5:[0-9]+]], !DIExpression()
+// CHECK: #dbg_declare(ptr %z2, ![[VAR_6:[0-9]+]], !DIExpression()
 // CHECK: ![[VAR_0]] = !DILocalVariable(name: "a"
-// CHECK: ![[VAR_1]] = !DILocalVariable(name: "x1"
-// CHECK: ![[VAR_2]] = !DILocalVariable(name: "y1"
-// CHECK: ![[VAR_3]] = !DILocalVariable(name: "x2"
-// CHECK: ![[VAR_4]] = !DILocalVariable(name: "y2"
+// CHECK: ![[VAR_1]] = !DILocalVariable(name: "x1", scope: !{{[0-9]+}}, file: 
!{{[0-9]+}}, line: {{[0-9]+}}, type: !{{[0-9]+}})
+// CHECK: ![[VAR_2]] = !DILocalVariable(name: "y1", scope: !{{[0-9]+}}, file: 
!{{[0-9]+}}, line: {{[0-9]+}}, type: !{{[0-9]+}})
+// CHECK: ![[VAR_3]] = !DILocalVariable(name: "x2", scope: !{{[0-9]+}}, file: 
!{{[0-9]+}}, line: {{[0-9]+}}, type: !{{[0-9]+}})
+// CHECK: ![[VAR_4]] = !DILocalVariable(name: "y2", scope: !{{[0-9]+}}, file: 
!{{[0-9]+}}, line: {{[0-9]+}}, type: !{{[0-9]+}})
+// CHECK: ![[VAR_5]] = !DILocalVariable(name: "z1", scope: !{{[0-9]+}}, file: 
!{{[0-9]+}}, line: {{[0-9]+}}, type: !{{[0-9]+}})
+// CHECK: ![[VAR_6]] = !DILocalVariable(name: "z2", scope: !{{[0-9]+}}, file: 
!{{[0-9]+}}, line: {{[0-9]+}}, type: !{{[0-9]+}})
 
 struct A {
   int x;
   int y;
 };
 
+struct B {
+  int w;
+  int z;
+  template int get();
+  template<> int get<0>() { return w; }
+  template<> int get<1>() { return z; }
+};
+
+namespace std {
+template struct tuple_size {
+};
+template<>
+struct tuple_size {
+static constexpr int value = 2;
+};
+
+template struct tuple_element {};
+template<> struct tuple_element<0, B> { using type = int; };
+template<> struct tuple_element<1, B> { using type = int; };
+}
+
 int f() {
   A a{10, 20};
   auto [x1, y1] = a;
   auto &[x2, y2] = a;
-  return x1 + y1 + x2 + y2;
+  auto [z1, z2] = B{1, 2};
+  return x1 + y1 + x2 + y2 + z1 + z2;
 }
diff --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 47a71134d5027..06ac07cb12509 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3163,6 +3163,63 @@ void foo()
 matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
  true, {"-std=c++17"}));
   }
+
+  Code = R"cpp(
+struct Pair
+{
+int x, y;
+};
+
+// Note: these utilities are required to force binding to tuple like structure
+namespace std
+{
+template 
+struct tuple_size
+{
+};
+
+template <>
+struct tuple_size
+{
+static constexpr unsigned value = 2;
+};
+
+template 
+struct tuple_element
+{
+using type = int;
+};
+
+};
+
+template 
+int &&get(Pair &&p);
+
+void decompTuple()
+{
+  

[clang] [llvm] [IR] Add method to GlobalVariable to change type of initializer. (PR #102553)

2024-08-08 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic created 
https://github.com/llvm/llvm-project/pull/102553

With opaque pointers, nothing directly uses the value type, so we can mutate it 
if we want.  This avoid doing a complicated RAUW dance.

>From f3151c0b623881ca29d4c965f93cf5aa0714d32e Mon Sep 17 00:00:00 2001
From: Eli Friedman 
Date: Thu, 8 Aug 2024 16:55:17 -0700
Subject: [PATCH] [IR] Add method to GlobalVariable to change type of
 initializer.

With opaque pointers, nothing directly uses the value type, so we can
mutate it if we want.  This avoid doing a complicated RAUW dance.
---
 clang/lib/CodeGen/CGDecl.cpp  | 28 +--
 llvm/include/llvm/IR/GlobalVariable.h | 10 --
 llvm/lib/IR/Globals.cpp   |  6 ++
 3 files changed, 15 insertions(+), 29 deletions(-)

diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index c3251bb5ab565..efc9e4a6d3b3d 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -370,38 +370,12 @@ CodeGenFunction::AddInitializerToStaticVarDecl(const 
VarDecl &D,
   assert(VarSize == CstSize && "Emitted constant has unexpected size");
 #endif
 
-  // The initializer may differ in type from the global. Rewrite
-  // the global to match the initializer.  (We have to do this
-  // because some types, like unions, can't be completely represented
-  // in the LLVM type system.)
-  if (GV->getValueType() != Init->getType()) {
-llvm::GlobalVariable *OldGV = GV;
-
-GV = new llvm::GlobalVariable(
-CGM.getModule(), Init->getType(), OldGV->isConstant(),
-OldGV->getLinkage(), Init, "",
-/*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
-OldGV->getType()->getPointerAddressSpace());
-GV->setVisibility(OldGV->getVisibility());
-GV->setDSOLocal(OldGV->isDSOLocal());
-GV->setComdat(OldGV->getComdat());
-
-// Steal the name of the old global
-GV->takeName(OldGV);
-
-// Replace all uses of the old global with the new global
-OldGV->replaceAllUsesWith(GV);
-
-// Erase the old global, since it is no longer used.
-OldGV->eraseFromParent();
-  }
-
   bool NeedsDtor =
   D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
 
   GV->setConstant(
   D.getType().isConstantStorage(getContext(), true, !NeedsDtor));
-  GV->setInitializer(Init);
+  GV->replaceInitializer(Init);
 
   emitter.finalize(GV);
 
diff --git a/llvm/include/llvm/IR/GlobalVariable.h 
b/llvm/include/llvm/IR/GlobalVariable.h
index bcaf8e91432ba..0736c300de72f 100644
--- a/llvm/include/llvm/IR/GlobalVariable.h
+++ b/llvm/include/llvm/IR/GlobalVariable.h
@@ -147,10 +147,16 @@ class GlobalVariable : public GlobalObject, public 
ilist_node {
 return static_cast(Op<0>().get());
   }
   /// setInitializer - Sets the initializer for this global variable, removing
-  /// any existing initializer if InitVal==NULL.  If this GV has type T*, the
-  /// initializer must have type T.
+  /// any existing initializer if InitVal==NULL. The initializer must have the
+  /// type getValueType().
   void setInitializer(Constant *InitVal);
 
+  /// replaceInitializer - Sets the initializer for this global variable, and
+  /// sets the value type of the global to the type of the initializer. The
+  /// initializer must not be null.  This may affect the global's alignment if
+  /// it isn't explicitly set.
+  void replaceInitializer(Constant *InitVal);
+
   /// If the value is a global constant, its value is immutable throughout the
   /// runtime execution of the program.  Assigning a value into the constant
   /// leads to undefined behavior.
diff --git a/llvm/lib/IR/Globals.cpp b/llvm/lib/IR/Globals.cpp
index cc37d7371cce3..2bc69cdb712b0 100644
--- a/llvm/lib/IR/Globals.cpp
+++ b/llvm/lib/IR/Globals.cpp
@@ -503,6 +503,12 @@ void GlobalVariable::setInitializer(Constant *InitVal) {
   }
 }
 
+void GlobalVariable::replaceInitializer(Constant *InitVal) {
+  assert(InitVal && "Can't compute type of null initializer");
+  ValueType = InitVal->getType();
+  setInitializer(InitVal);
+}
+
 /// Copy all additional attributes (those not needed to create a 
GlobalVariable)
 /// from the GlobalVariable Src to this one.
 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {

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


[clang] [llvm] [IR] Add method to GlobalVariable to change type of initializer. (PR #102553)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Eli Friedman (efriedma-quic)


Changes

With opaque pointers, nothing directly uses the value type, so we can mutate it 
if we want.  This avoid doing a complicated RAUW dance.

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


3 Files Affected:

- (modified) clang/lib/CodeGen/CGDecl.cpp (+1-27) 
- (modified) llvm/include/llvm/IR/GlobalVariable.h (+8-2) 
- (modified) llvm/lib/IR/Globals.cpp (+6) 


``diff
diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index c3251bb5ab565..efc9e4a6d3b3d 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -370,38 +370,12 @@ CodeGenFunction::AddInitializerToStaticVarDecl(const 
VarDecl &D,
   assert(VarSize == CstSize && "Emitted constant has unexpected size");
 #endif
 
-  // The initializer may differ in type from the global. Rewrite
-  // the global to match the initializer.  (We have to do this
-  // because some types, like unions, can't be completely represented
-  // in the LLVM type system.)
-  if (GV->getValueType() != Init->getType()) {
-llvm::GlobalVariable *OldGV = GV;
-
-GV = new llvm::GlobalVariable(
-CGM.getModule(), Init->getType(), OldGV->isConstant(),
-OldGV->getLinkage(), Init, "",
-/*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
-OldGV->getType()->getPointerAddressSpace());
-GV->setVisibility(OldGV->getVisibility());
-GV->setDSOLocal(OldGV->isDSOLocal());
-GV->setComdat(OldGV->getComdat());
-
-// Steal the name of the old global
-GV->takeName(OldGV);
-
-// Replace all uses of the old global with the new global
-OldGV->replaceAllUsesWith(GV);
-
-// Erase the old global, since it is no longer used.
-OldGV->eraseFromParent();
-  }
-
   bool NeedsDtor =
   D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
 
   GV->setConstant(
   D.getType().isConstantStorage(getContext(), true, !NeedsDtor));
-  GV->setInitializer(Init);
+  GV->replaceInitializer(Init);
 
   emitter.finalize(GV);
 
diff --git a/llvm/include/llvm/IR/GlobalVariable.h 
b/llvm/include/llvm/IR/GlobalVariable.h
index bcaf8e91432ba..0736c300de72f 100644
--- a/llvm/include/llvm/IR/GlobalVariable.h
+++ b/llvm/include/llvm/IR/GlobalVariable.h
@@ -147,10 +147,16 @@ class GlobalVariable : public GlobalObject, public 
ilist_node {
 return static_cast(Op<0>().get());
   }
   /// setInitializer - Sets the initializer for this global variable, removing
-  /// any existing initializer if InitVal==NULL.  If this GV has type T*, the
-  /// initializer must have type T.
+  /// any existing initializer if InitVal==NULL. The initializer must have the
+  /// type getValueType().
   void setInitializer(Constant *InitVal);
 
+  /// replaceInitializer - Sets the initializer for this global variable, and
+  /// sets the value type of the global to the type of the initializer. The
+  /// initializer must not be null.  This may affect the global's alignment if
+  /// it isn't explicitly set.
+  void replaceInitializer(Constant *InitVal);
+
   /// If the value is a global constant, its value is immutable throughout the
   /// runtime execution of the program.  Assigning a value into the constant
   /// leads to undefined behavior.
diff --git a/llvm/lib/IR/Globals.cpp b/llvm/lib/IR/Globals.cpp
index cc37d7371cce3..2bc69cdb712b0 100644
--- a/llvm/lib/IR/Globals.cpp
+++ b/llvm/lib/IR/Globals.cpp
@@ -503,6 +503,12 @@ void GlobalVariable::setInitializer(Constant *InitVal) {
   }
 }
 
+void GlobalVariable::replaceInitializer(Constant *InitVal) {
+  assert(InitVal && "Can't compute type of null initializer");
+  ValueType = InitVal->getType();
+  setInitializer(InitVal);
+}
+
 /// Copy all additional attributes (those not needed to create a 
GlobalVariable)
 /// from the GlobalVariable Src to this one.
 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {

``




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


[clang] [llvm] [IR] Add method to GlobalVariable to change type of initializer. (PR #102553)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-ir

Author: Eli Friedman (efriedma-quic)


Changes

With opaque pointers, nothing directly uses the value type, so we can mutate it 
if we want.  This avoid doing a complicated RAUW dance.

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


3 Files Affected:

- (modified) clang/lib/CodeGen/CGDecl.cpp (+1-27) 
- (modified) llvm/include/llvm/IR/GlobalVariable.h (+8-2) 
- (modified) llvm/lib/IR/Globals.cpp (+6) 


``diff
diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index c3251bb5ab565..efc9e4a6d3b3d 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -370,38 +370,12 @@ CodeGenFunction::AddInitializerToStaticVarDecl(const 
VarDecl &D,
   assert(VarSize == CstSize && "Emitted constant has unexpected size");
 #endif
 
-  // The initializer may differ in type from the global. Rewrite
-  // the global to match the initializer.  (We have to do this
-  // because some types, like unions, can't be completely represented
-  // in the LLVM type system.)
-  if (GV->getValueType() != Init->getType()) {
-llvm::GlobalVariable *OldGV = GV;
-
-GV = new llvm::GlobalVariable(
-CGM.getModule(), Init->getType(), OldGV->isConstant(),
-OldGV->getLinkage(), Init, "",
-/*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
-OldGV->getType()->getPointerAddressSpace());
-GV->setVisibility(OldGV->getVisibility());
-GV->setDSOLocal(OldGV->isDSOLocal());
-GV->setComdat(OldGV->getComdat());
-
-// Steal the name of the old global
-GV->takeName(OldGV);
-
-// Replace all uses of the old global with the new global
-OldGV->replaceAllUsesWith(GV);
-
-// Erase the old global, since it is no longer used.
-OldGV->eraseFromParent();
-  }
-
   bool NeedsDtor =
   D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
 
   GV->setConstant(
   D.getType().isConstantStorage(getContext(), true, !NeedsDtor));
-  GV->setInitializer(Init);
+  GV->replaceInitializer(Init);
 
   emitter.finalize(GV);
 
diff --git a/llvm/include/llvm/IR/GlobalVariable.h 
b/llvm/include/llvm/IR/GlobalVariable.h
index bcaf8e91432ba..0736c300de72f 100644
--- a/llvm/include/llvm/IR/GlobalVariable.h
+++ b/llvm/include/llvm/IR/GlobalVariable.h
@@ -147,10 +147,16 @@ class GlobalVariable : public GlobalObject, public 
ilist_node {
 return static_cast(Op<0>().get());
   }
   /// setInitializer - Sets the initializer for this global variable, removing
-  /// any existing initializer if InitVal==NULL.  If this GV has type T*, the
-  /// initializer must have type T.
+  /// any existing initializer if InitVal==NULL. The initializer must have the
+  /// type getValueType().
   void setInitializer(Constant *InitVal);
 
+  /// replaceInitializer - Sets the initializer for this global variable, and
+  /// sets the value type of the global to the type of the initializer. The
+  /// initializer must not be null.  This may affect the global's alignment if
+  /// it isn't explicitly set.
+  void replaceInitializer(Constant *InitVal);
+
   /// If the value is a global constant, its value is immutable throughout the
   /// runtime execution of the program.  Assigning a value into the constant
   /// leads to undefined behavior.
diff --git a/llvm/lib/IR/Globals.cpp b/llvm/lib/IR/Globals.cpp
index cc37d7371cce3..2bc69cdb712b0 100644
--- a/llvm/lib/IR/Globals.cpp
+++ b/llvm/lib/IR/Globals.cpp
@@ -503,6 +503,12 @@ void GlobalVariable::setInitializer(Constant *InitVal) {
   }
 }
 
+void GlobalVariable::replaceInitializer(Constant *InitVal) {
+  assert(InitVal && "Can't compute type of null initializer");
+  ValueType = InitVal->getType();
+  setInitializer(InitVal);
+}
+
 /// Copy all additional attributes (those not needed to create a 
GlobalVariable)
 /// from the GlobalVariable Src to this one.
 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {

``




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


[clang] [llvm] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout (PR #102521)

2024-08-08 Thread Joel E. Denny via cfe-commits

jdenny-ornl wrote:

FWIW, on one of my test systems that's currently very busy, check-offload 
consistently fails with amdgpu-arch timeouts.  However, the following so far 
makes it consistently succeed:

```
$ CLANG_TOOLCHAIN_PROGRAM_TIMEOUT=60 ninja check-offload
```

Previously, I've decreased lit parallelism to avoid the timeouts, but it hasn't 
worked consistently, and it slows down the test suite.


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


[clang] [Clang][Sema] Fix mismatch of out-of-line definition of template class (PR #102554)

2024-08-08 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky created 
https://github.com/llvm/llvm-project/pull/102554

Skip adding template instantiation arguments when the declaration is a nested 
class template when instantiating constraint expression.
attempt to fix https://github.com/llvm/llvm-project/issues/102320

>From 0080b8743a1186d0463e1ff7af73a2a8776b66f1 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Fri, 9 Aug 2024 08:19:09 +0800
Subject: [PATCH] [Clang][Sema] Fix mismatch of out-of-line definition of
 template class

---
 clang/docs/ReleaseNotes.rst |  1 +
 clang/lib/Sema/SemaConcept.cpp  |  3 ++-
 clang/test/SemaCXX/PR102320.cpp | 18 ++
 3 files changed, 21 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/SemaCXX/PR102320.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb0a1b25e51c2..ffc7e34f1166f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -212,6 +212,7 @@ Bug Fixes to C++ Support
 - Clang now preserves the unexpanded flag in a lambda transform used for pack 
expansion. (#GH56852), (#GH85667),
   (#GH99877).
 - Fixed a bug when diagnosing ambiguous explicit specializations of 
constrained member functions.
+- Fix a bug in out-of-line definition of constrained class template nested in 
a class template. (GH102320).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e3..016dd90b9e95e 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -951,7 +951,8 @@ static const Expr 
*SubstituteConstraintExpressionWithoutSatisfaction(
   DeclInfo.getDecl(), DeclInfo.getLexicalDeclContext(), /*Final=*/false,
   /*Innermost=*/std::nullopt,
   /*RelativeToPrimary=*/true,
-  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
+  /*Pattern=*/nullptr,
+  !isa_and_present(DeclInfo.getDecl()),
   /*SkipForSpecialization*/ false);
 
   if (MLTAL.getNumSubstitutedLevels() == 0)
diff --git a/clang/test/SemaCXX/PR102320.cpp b/clang/test/SemaCXX/PR102320.cpp
new file mode 100644
index 0..56973875c7b95
--- /dev/null
+++ b/clang/test/SemaCXX/PR102320.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+// expected-no-diagnostics
+
+template
+concept Constrained = true;
+
+template 
+class C
+{
+template
+class D;
+};
+
+template 
+template 
+class C::D
+{
+};

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


[clang] [Clang][Sema] Fix mismatch of out-of-line definition of template class (PR #102554)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Qizhi Hu (jcsxky)


Changes

Skip adding template instantiation arguments when the declaration is a nested 
class template when instantiating constraint expression.
attempt to fix https://github.com/llvm/llvm-project/issues/102320

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1) 
- (modified) clang/lib/Sema/SemaConcept.cpp (+2-1) 
- (added) clang/test/SemaCXX/PR102320.cpp (+18) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb0a1b25e51c2a..ffc7e34f1166fd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -212,6 +212,7 @@ Bug Fixes to C++ Support
 - Clang now preserves the unexpanded flag in a lambda transform used for pack 
expansion. (#GH56852), (#GH85667),
   (#GH99877).
 - Fixed a bug when diagnosing ambiguous explicit specializations of 
constrained member functions.
+- Fix a bug in out-of-line definition of constrained class template nested in 
a class template. (GH102320).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e34..016dd90b9e95e2 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -951,7 +951,8 @@ static const Expr 
*SubstituteConstraintExpressionWithoutSatisfaction(
   DeclInfo.getDecl(), DeclInfo.getLexicalDeclContext(), /*Final=*/false,
   /*Innermost=*/std::nullopt,
   /*RelativeToPrimary=*/true,
-  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
+  /*Pattern=*/nullptr,
+  !isa_and_present(DeclInfo.getDecl()),
   /*SkipForSpecialization*/ false);
 
   if (MLTAL.getNumSubstitutedLevels() == 0)
diff --git a/clang/test/SemaCXX/PR102320.cpp b/clang/test/SemaCXX/PR102320.cpp
new file mode 100644
index 00..56973875c7b953
--- /dev/null
+++ b/clang/test/SemaCXX/PR102320.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+// expected-no-diagnostics
+
+template
+concept Constrained = true;
+
+template 
+class C
+{
+template
+class D;
+};
+
+template 
+template 
+class C::D
+{
+};

``




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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Justin Stitt via cfe-commits

https://github.com/JustinStitt updated 
https://github.com/llvm/llvm-project/pull/100272

>From 154d3505ab13275086b3dffed67bcdcac52f79a3 Mon Sep 17 00:00:00 2001
From: Justin Stitt 
Date: Tue, 23 Jul 2024 20:21:49 +
Subject: [PATCH 1/8] implement idiom exclusions

Add flag `-fno-sanitize-overflow-idioms` which disables integer
overflow/truncation sanitizer instrumentation for common
overflow-dependent code patterns.

Signed-off-by: Justin Stitt 
---
 clang/include/clang/AST/Expr.h|   5 +
 clang/include/clang/Basic/LangOptions.def |   2 +
 clang/include/clang/Driver/Options.td |  10 ++
 clang/include/clang/Driver/SanitizerArgs.h|   1 +
 clang/lib/AST/Expr.cpp|  53 +++
 clang/lib/CodeGen/CGExprScalar.cpp|  26 +++-
 clang/lib/Driver/SanitizerArgs.cpp|   7 +
 clang/lib/Driver/ToolChains/Clang.cpp |   7 +
 .../CodeGen/overflow-idiom-exclusion-fp.c |  77 ++
 clang/test/CodeGen/overflow-idiom-exclusion.c | 141 ++
 10 files changed, 327 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/overflow-idiom-exclusion-fp.c
 create mode 100644 clang/test/CodeGen/overflow-idiom-exclusion.c

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 5b813bfc2faf9..c329ee061cf00 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -3860,6 +3860,7 @@ class CStyleCastExpr final
 class BinaryOperator : public Expr {
   enum { LHS, RHS, END_EXPR };
   Stmt *SubExprs[END_EXPR];
+  bool isOverflowIdiom;
 
 public:
   typedef BinaryOperatorKind Opcode;
@@ -4018,6 +4019,10 @@ class BinaryOperator : public Expr {
 return isShiftAssignOp(getOpcode());
   }
 
+  bool ignoreOverflowSanitizers() const {
+return isOverflowIdiom;
+  }
+
   /// Return true if a binary operator using the specified opcode and operands
   /// would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
   /// integer to a pointer.
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 0035092ce0d86..4619e2d8c4fb7 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -400,6 +400,8 @@ VALUE_LANGOPT(TrivialAutoVarInitMaxSize, 32, 0,
  "stop trivial automatic variable initialization if var size 
exceeds the specified size (in bytes). Must be greater than 0.")
 ENUM_LANGOPT(SignedOverflowBehavior, SignedOverflowBehaviorTy, 2, 
SOB_Undefined,
  "signed integer overflow handling")
+LANGOPT(IgnoreNegationOverflow, 1, 0, "ignore overflow caused by negation")
+LANGOPT(SanitizeOverflowIdioms, 1, 1, "enable instrumentation for common 
overflow idioms")
 ENUM_LANGOPT(ThreadModel  , ThreadModelKind, 2, ThreadModelKind::POSIX, 
"Thread Model")
 
 BENIGN_LANGOPT(ArrowDepth, 32, 256,
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c8c56dbb51b28..f253f7535776b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2558,6 +2558,16 @@ defm sanitize_stats : BoolOption<"f", "sanitize-stats",
   "Disable">,
   BothFlags<[], [ClangOption], " sanitizer statistics gathering.">>,
   Group;
+defm sanitize_overflow_idioms : BoolFOption<"sanitize-overflow-idioms",
+  LangOpts<"SanitizeOverflowIdioms">, DefaultTrue,
+  PosFlag,
+  NegFlag,
+  BothFlags<[], [ClangOption], " the instrumentation of common overflow 
idioms">>;
+defm sanitize_negation_overflow : BoolFOption<"sanitize-negation-overflow",
+  LangOpts<"IgnoreNegationOverflow">, DefaultFalse,
+  PosFlag,
+  NegFlag,
+  BothFlags<[], [ClangOption], " integer overflow sanitizer instrumentation 
for negation">>;
 def fsanitize_thread_memory_access : Flag<["-"], 
"fsanitize-thread-memory-access">,
  Group,
  HelpText<"Enable memory access 
instrumentation in ThreadSanitizer (default)">;
diff --git a/clang/include/clang/Driver/SanitizerArgs.h 
b/clang/include/clang/Driver/SanitizerArgs.h
index 47ef175302679..291739e1221d9 100644
--- a/clang/include/clang/Driver/SanitizerArgs.h
+++ b/clang/include/clang/Driver/SanitizerArgs.h
@@ -64,6 +64,7 @@ class SanitizerArgs {
   // True if cross-dso CFI support if provided by the system (i.e. Android).
   bool ImplicitCfiRuntime = false;
   bool NeedsMemProfRt = false;
+  bool SanitizeOverflowIdioms = true;
   bool HwasanUseAliases = false;
   llvm::AsanDetectStackUseAfterReturnMode AsanUseAfterReturn =
   llvm::AsanDetectStackUseAfterReturnMode::Invalid;
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 9d5b8167d0ee6..c07560c92100d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -4759,6 +4759,54 @@ ParenListExpr *ParenListExpr::CreateEmpty(const 
ASTContext &Ctx,
   return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
 }
 
+namespace {
+/// Certa

[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Justin Stitt via cfe-commits


@@ -4248,6 +4248,22 @@ bool CompilerInvocation::ParseLangArgs(LangOptions 
&Opts, ArgList &Args,
   Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
   }
 
+  if (auto *A = Args.getLastArg(OPT_fsanitize_overflow_pattern_exclusion_EQ)) {
+for (int i = 0, n = A->getNumValues(); i != n; ++i) {
+  StringRef Value = A->getValue(i);
+  if (Value == "none")
+Opts.OverflowPatternExclusionMask |= LangOptionsBase::None;

JustinStitt wrote:

resolved with 4b3efbb41ff86eeff15671b1d876e1ef6a58a536

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Justin Stitt via cfe-commits


@@ -0,0 +1,83 @@
+// Check for potential false positives from patterns that _almost_ match 
classic overflow-dependent or overflow-prone code patterns

JustinStitt wrote:

resolved in 4b3efbb41ff86eeff15671b1d876e1ef6a58a536

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Justin Stitt via cfe-commits


@@ -293,6 +293,40 @@ To silence reports from unsigned integer overflow, you can 
set
 ``-fsanitize-recover=unsigned-integer-overflow``, is particularly useful for
 providing fuzzing signal without blowing up logs.
 
+Disabling instrumentation for common overflow patterns
+--
+
+There are certain overflow-dependent or overflow-prone code patterns which
+produce a lot of noise for integer overflow/truncation sanitizers. To disable
+instrumentation for these common patterns one should use
+``-fsanitize-overflow-pattern-exclusion=``.
+
+Currently, this option supports three pervasive overflow-dependent code idioms:

JustinStitt wrote:

thanks. resolved in 4b3efbb41ff86eeff15671b1d876e1ef6a58a536

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Justin Stitt via cfe-commits


@@ -555,6 +570,11 @@ class LangOptions : public LangOptionsBase {
   /// The default stream kind used for HIP kernel launching.
   GPUDefaultStreamKind GPUDefaultStream;
 
+  /// Which overflow patterns should be excluded from sanitizer instrumentation
+  int OverflowPatternExclusionMask = 0;

JustinStitt wrote:

gotcha, resolved with 4b3efbb41ff86eeff15671b1d876e1ef6a58a536

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Justin Stitt via cfe-commits


@@ -293,6 +293,40 @@ To silence reports from unsigned integer overflow, you can 
set
 ``-fsanitize-recover=unsigned-integer-overflow``, is particularly useful for
 providing fuzzing signal without blowing up logs.
 
+Disabling instrumentation for common overflow patterns
+--
+
+There are certain overflow-dependent or overflow-prone code patterns which
+produce a lot of noise for integer overflow/truncation sanitizers. To disable
+instrumentation for these common patterns one should use
+``-fsanitize-overflow-pattern-exclusion=``.
+
+Currently, this option supports three pervasive overflow-dependent code idioms:
+
+.. code-block:: c++
+
+/// -fsanitize-overflow-pattern-exclusion=negated-unsigned-const
+unsigned long foo = -1UL; // No longer causes a negation overflow warning
+unsigned long bar = -2UL; // and so on...
+
+.. code-block:: c++
+
+/// -fsanitize-overflow-pattern-exclusion=post-decr-while
+unsigned char count = 16;
+while (count--) { /* ... */ } // No longer causes 
unsigned-integer-overflow sanitizer to trip
+
+.. code-block:: c++
+
+/// -fsanitize-overflow-pattern-exclusion=add-overflow-test
+if (base + offset < base) { /* ... */ } // The pattern of `a + b < a`, and 
other re-orderings,
+// won't be instrumented (same for 
signed types)
+
+Negated unsigned constants, post-decrements in a while loop condition and

JustinStitt wrote:

right, that reads better. thanks!

resolved with 4b3efbb41ff86eeff15671b1d876e1ef6a58a536

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Justin Stitt via cfe-commits


@@ -2877,6 +2888,17 @@ ScalarExprEmitter::EmitScalarPrePostIncDec(const 
UnaryOperator *E, LValue LV,
   } else if (type->isIntegerType()) {
 QualType promotedType;
 bool canPerformLossyDemotionCheck = false;
+
+// Is the pattern "while (i--)" and overflow exclusion?
+bool disableSanitizer =

JustinStitt wrote:

You're right. I split up the logic into a new method in 
4b3efbb41ff86eeff15671b1d876e1ef6a58a536

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


[clang] [Clang] Overflow Pattern Exclusions (PR #100272)

2024-08-08 Thread Justin Stitt via cfe-commits

JustinStitt wrote:

@bwendling I tried to address all your feedback points with 
4b3efbb41ff86eeff15671b1d876e1ef6a58a536 Let me know how that looks 👍 

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


[clang] [llvm] [Clang] Add env var for nvptx-arch/amdgpu-arch timeout (PR #102521)

2024-08-08 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> FWIW, on one of my test systems that's currently very busy, check-offload 
> consistently fails with amdgpu-arch timeouts. However, the following so far 
> makes it consistently succeed:
> 
> ```
> $ CLANG_TOOLCHAIN_PROGRAM_TIMEOUT=60 ninja check-offload
> ```
> 
> Previously, I've decreased lit parallelism to avoid the timeouts, but it 
> hasn't worked consistently, and it slows down the test suite.

Possibly worth increasing it to a minute then, this is basically just a last 
ditch effort to prevent builds from hanging forever. I've had it happen 
personally where either the CUDA or AMDGPU drivers were stuck, and when I tried 
to rebuild `libc` `ninja` just hung indefinitely and it took me awhile to 
figure out why.

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


[clang] [llvm] [IR] Add method to GlobalVariable to change type of initializer. (PR #102553)

2024-08-08 Thread John McCall via cfe-commits

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

Well, this is wonderful, thank you. LGTM.

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


[clang] [clang-tools-extra] [lldb] [clang] Reland: Instantiate alias templates with sugar (PR #101858)

2024-08-08 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

> or if we would implement a `TypeAliasTemplateSpecializationDecl` only for the 
> benefit of external resugarers.

It is not only valuable to external resugarers. Another point that warrants an 
introduction of it is for unevaluated lambdas. These lambdas e.g. appearing as 
part of the `using Alias = decltype(lambda)` could carry a requires expression 
and thus evaluating it requires the recovery of the instantiating template 
arguments for the type alias, which isn't a quite natural thing without such a 
Decl. I have improved some of these situations through an on-stack 
InstantiatingTemplate to help to inspect the template arguments; however, that 
approach is somewhat cumbersome and still couldn't extend to other scenarios 
e.g. mangling these lambdas. 
(https://github.com/llvm/llvm-project/issues/97024. We need a correct 
DeclContext for the lambda, yet a `TypeAliasTemplateDecl` isn't a DeclContext, 
unfortunately.)


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


[clang] Reland [C++20] [Modules] [Itanium ABI] Generate the vtable in the mod… (PR #102287)

2024-08-08 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

Although there is an issue report in 
https://github.com/llvm/llvm-project/issues/98021. But it looks like an 
existing issue and the previous "fix" is just a "coincidence". So I don't think 
this is a regression and I like to backport this.

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


[clang] Reland [C++20] [Modules] [Itanium ABI] Generate the vtable in the mod… (PR #102287)

2024-08-08 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

/cherry-pick 847f9cb0e868c8ec34f9aa86fdf846f8c4e0388b

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


[clang] Reland [C++20] [Modules] [Itanium ABI] Generate the vtable in the mod… (PR #102287)

2024-08-08 Thread via cfe-commits

llvmbot wrote:

/pull-request llvm/llvm-project#102561

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


[clang] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

(It's #102353)

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


[clang] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread Matheus Izvekov via cfe-commits

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


[clang] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

> (It's #102353)

Updated, thanks for the correction.

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


[clang] 00139ae - Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (#102551)

2024-08-08 Thread via cfe-commits

Author: Matheus Izvekov
Date: 2024-08-08T23:38:08-03:00
New Revision: 00139ae1bc0ae855ebe9c8991f480b382bbc4308

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

LOG: Revert "[clang] Reland: Instantiate concepts with sugared template 
arguments (#101782)" (#102551)

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Template.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/test/AST/ast-dump-concepts.cpp
clang/test/CXX/expr/expr.prim/expr.prim.req/compound-requirement.cpp
clang/test/CXX/expr/expr.prim/expr.prim.req/nested-requirement.cpp
clang/test/CXX/expr/expr.prim/expr.prim.req/simple-requirement.cpp
clang/test/CXX/expr/expr.prim/expr.prim.req/type-requirement.cpp
clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
clang/test/CXX/temp/temp.param/p10-2a.cpp
clang/test/SemaTemplate/concepts-recursive-inst.cpp
clang/test/SemaTemplate/concepts.cpp
clang/test/SemaTemplate/instantiate-requires-expr.cpp
clang/test/SemaTemplate/pr52970.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb0a1b25e51c2..7beef7be0e6a5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -75,8 +75,8 @@ sections with improvements to Clang's support for those 
languages.
 
 C++ Language Changes
 
-- Allow single element access of GCC vector/ext_vector_type object to be 
-  constant expression. Supports the `V.xyzw` syntax and other tidbits 
+- Allow single element access of GCC vector/ext_vector_type object to be
+  constant expression. Supports the `V.xyzw` syntax and other tidbits
   as seen in OpenCL. Selecting multiple elements is left as a future work.
 
 C++17 Feature Support
@@ -166,7 +166,6 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
 - -Wdangling-assignment-gsl is enabled by default.
-- Clang now does a better job preserving the template arguments as written 
when specializing concepts.
 - Clang now always preserves the template arguments as written used
   to specialize template type aliases.
 

diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index d616865afe807..0340c23fd170d 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -234,8 +234,7 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args,
-   bool Final = false) {
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
   assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
  "Replacing in an empty list?");
 
@@ -247,7 +246,8 @@ enum class TemplateSubstitutionKind : char {
 TemplateArgumentLists[0].Args = Args;
   } else {
 --NumRetainedOuterLevels;
-TemplateArgumentLists.push_back({{AssociatedDecl, Final}, Args});
+TemplateArgumentLists.push_back(
+{{AssociatedDecl, /*Final=*/false}, Args});
   }
 }
 

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d4c9d044985e3..d1e62fb5cee62 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -414,8 +414,7 @@ DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID 
&ID,
   E->Profile(ID, S.Context, /*Canonical=*/true);
   for (const auto &List : MLTAL)
 for (const auto &TemplateArg : List.Args)
-  S.Context.getCanonicalTemplateArgument(TemplateArg)
-  .Profile(ID, S.Context);
+  TemplateArg.Profile(ID, S.Context);
 
   // Note that we have to do this with our own collection, because there are
   // times where a constraint-expression check can cause us to need to evaluate
@@ -643,8 +642,8 @@ bool Sema::CheckConstraintSatisfaction(
   // here.
   llvm::SmallVector FlattenedArgs;
   for (auto List : TemplateArgsLists)
-for (const TemplateArgument &Arg : List.Args)
-  FlattenedArgs.emplace_back(Context.getCanonicalTemplateArgument(Arg));
+FlattenedArgs.insert(FlattenedArgs.end(), List.Args.begin(),
+ List.Args.end());
 
   llvm::FoldingSetNodeID ID;
   ConstraintSatisfaction::Profile(ID,

[clang] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread Matheus Izvekov via cfe-commits

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


[clang] [Clang][Sema] Fix mismatch of out-of-line definition of template class (PR #102554)

2024-08-08 Thread Younan Zhang via cfe-commits

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


[clang] [Clang][Sema] Fix mismatch of out-of-line definition of template class (PR #102554)

2024-08-08 Thread Younan Zhang via cfe-commits

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

I'm sorry but this approach doesn't make sense to me.

I have to say that I self-assigned the issue hours before this patch (I don't 
know when you started working on it because you haven't explained anything 
either), and that means I'll look into that recently since I've also been 
working on another similar case for template packs. Submitting a (especially 
unreasonable fix) PR without asking first seems to be very impolite behavior.

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


[clang] [Clang][Sema] Fix mismatch of out-of-line definition of template class (PR #102554)

2024-08-08 Thread Younan Zhang via cfe-commits


@@ -951,7 +951,8 @@ static const Expr 
*SubstituteConstraintExpressionWithoutSatisfaction(
   DeclInfo.getDecl(), DeclInfo.getLexicalDeclContext(), /*Final=*/false,
   /*Innermost=*/std::nullopt,
   /*RelativeToPrimary=*/true,
-  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
+  /*Pattern=*/nullptr,
+  !isa_and_present(DeclInfo.getDecl()),

zyn0217 wrote:

This looks wrong: With the flag disabled, we wouldn't correctly collect 
template arguments for the outer class template in this case. Having collected 
nothing for the other hand side's constraint expression doesn't mean we should 
do the same for the primary declaration.

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


[clang] [Clang][Interp] Fix display of syntactically-invalid note for member function calls (PR #102170)

2024-08-08 Thread via cfe-commits

https://github.com/yronglin updated 
https://github.com/llvm/llvm-project/pull/102170

>From f14464c0734776cd79a2fbd93cec94e815276009 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Fri, 9 Aug 2024 01:22:29 +0800
Subject: [PATCH 1/2] [Clang][Interp] Fix display of syntactically-invalid note
 for member function calls

Signed-off-by: yronglin 
---
 clang/lib/AST/Interp/InterpFrame.cpp  | 30 ++-
 clang/lib/AST/Interp/Source.cpp   |  2 +-
 .../AST/Interp/constexpr-frame-describe.cpp   | 83 +++
 clang/test/AST/Interp/constexpr-nqueens.cpp   |  2 +-
 clang/test/AST/Interp/lambda.cpp  |  2 +-
 clang/test/AST/Interp/records.cpp |  6 +-
 6 files changed, 114 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/AST/Interp/constexpr-frame-describe.cpp

diff --git a/clang/lib/AST/Interp/InterpFrame.cpp 
b/clang/lib/AST/Interp/InterpFrame.cpp
index 83784db91f4f3..27108f957305f 100644
--- a/clang/lib/AST/Interp/InterpFrame.cpp
+++ b/clang/lib/AST/Interp/InterpFrame.cpp
@@ -18,6 +18,7 @@
 #include "Program.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/ExprCXX.h"
 
 using namespace clang;
 using namespace clang::interp;
@@ -169,11 +170,32 @@ void InterpFrame::describe(llvm::raw_ostream &OS) const {
   F && (F->isBuiltin() || F->isLambdaStaticInvoker()))
 return;
 
+  const Expr *CallExpr = Caller->getExpr(getRetPC());
   const FunctionDecl *F = getCallee();
-  if (const auto *M = dyn_cast(F);
-  M && M->isInstance() && !isa(F)) {
-print(OS, This, S.getCtx(), S.getCtx().getRecordType(M->getParent()));
-OS << "->";
+  bool IsMemberCall = isa(F) && !isa(F) &&
+  cast(F)->isImplicitObjectMemberFunction();
+  if (Func->hasThisPointer() && IsMemberCall) {
+if (const auto *MCE = dyn_cast_if_present(CallExpr)) {
+  const Expr *Object = MCE->getImplicitObjectArgument();
+  Object->printPretty(OS, /*Helper=*/nullptr,
+  S.getCtx().getPrintingPolicy(),
+  /*Indentation=*/0);
+  if (Object->getType()->isPointerType())
+OS << "->";
+  else
+OS << ".";
+} else if (const auto *OCE =
+   dyn_cast_if_present(CallExpr)) {
+  OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
+  S.getCtx().getPrintingPolicy(),
+  /*Indentation=*/0);
+  OS << ".";
+} else if (const auto *M = dyn_cast(F)) {
+  print(OS, This, S.getCtx(),
+S.getCtx().getLValueReferenceType(
+S.getCtx().getRecordType(M->getParent(;
+  OS << ".";
+}
   }
 
   F->getNameForDiagnostic(OS, S.getCtx().getPrintingPolicy(),
diff --git a/clang/lib/AST/Interp/Source.cpp b/clang/lib/AST/Interp/Source.cpp
index 45cd0ad4fd427..77796b00ca52c 100644
--- a/clang/lib/AST/Interp/Source.cpp
+++ b/clang/lib/AST/Interp/Source.cpp
@@ -41,7 +41,7 @@ const Expr *SourceInfo::asExpr() const {
 const Expr *SourceMapper::getExpr(const Function *F, CodePtr PC) const {
   if (const Expr *E = getSource(F, PC).asExpr())
 return E;
-  llvm::report_fatal_error("missing source expression");
+  return nullptr;
 }
 
 SourceLocation SourceMapper::getLocation(const Function *F, CodePtr PC) const {
diff --git a/clang/test/AST/Interp/constexpr-frame-describe.cpp 
b/clang/test/AST/Interp/constexpr-frame-describe.cpp
new file mode 100644
index 0..fe698362e3d9b
--- /dev/null
+++ b/clang/test/AST/Interp/constexpr-frame-describe.cpp
@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected,both %s
+// RUN: %clang_cc1 -std=c++20 -fexperimental-new-constant-interpreter 
-fsyntax-only -verify=ref,both %s
+
+
+struct Foo {
+constexpr void zomg() const { (void)(1 / 0); } // both-error {{constant 
expression}} \
+  both-warning {{division 
by zero}} \
+  both-note 2{{division by 
zero}}
+};
+
+struct S {
+constexpr S() {}
+constexpr bool operator==(const S&) const { // both-error {{never produces 
a constant expression}}
+  return 1 / 0; // both-warning {{division by zero}} \
+   both-note 3{{division by zero}}
+}
+
+constexpr bool heh() const {
+auto F = new Foo();
+F->zomg(); // both-note {{in call to 'F->zomg()'}}
+delete F;
+return false;
+}
+};
+
+constexpr S s;
+
+static_assert(s.heh()); // both-error {{constant expression}} \
+   both-note {{in call to 's.heh()'}}
+
+constexpr S s2;
+constexpr const S *sptr = &s;
+constexpr const S *sptr2 = &s2;
+static_assert(s == s2); // both-error {{constant expression}} \
+   both-note {{in call to 's.operator==(s2)'}}
+static_assert(*sptr == *sptr2); // both-error {{constant expression}} \
+   both-note {{in ca

[clang] [Clang][Interp] Fix display of syntactically-invalid note for member function calls (PR #102170)

2024-08-08 Thread via cfe-commits


@@ -46,7 +46,7 @@ constexpr int div(int a, int b) {
 return a / b; // both-note {{division by zero}}
   };
 
-  return f(); // expected-note {{in call to '&f->operator()()'}} \
+  return f(); // expected-note {{in call to 'f.operator()()'}} \

yronglin wrote:

Done~

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


[clang] [clang][ASTMatcher] Add `matchesString` for `StringLiteral` which matches literals on given `RegExp` (PR #102152)

2024-08-08 Thread via cfe-commits

https://github.com/Gitspike updated 
https://github.com/llvm/llvm-project/pull/102152

>From c062124cacf5caef4fcc57816c35250005fd32eb Mon Sep 17 00:00:00 2001
From: hehouhua 
Date: Wed, 7 Aug 2024 11:55:30 +0800
Subject: [PATCH 1/2] [clang][ASTMatcher] Add matches for StringLiteral which
 matches literals on given RegExp

Add Matcher matchesString.
---
 clang/docs/LibASTMatchersReference.html   | 14 +++
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/include/clang/ASTMatchers/ASTMatchers.h | 24 +++
 clang/lib/ASTMatchers/Dynamic/Registry.cpp|  1 +
 .../ASTMatchers/ASTMatchersNarrowingTest.cpp  | 19 +++
 5 files changed, 60 insertions(+)

diff --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index a16b9c44ef0eab..77b789b1ec4b94 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -5582,6 +5582,20 @@ Narrowing Matchers
 
 
 
+MatcherStringLiteral>matchesStringStringRef RegExp, 
Regex::RegexFlags Flags = NoFlags
+Matches string 
literals that contain a substring matched by the given RegExp
+
+Example matches "foo" and "foobar" but not "bar"
+  (matcher = stringLiteral(matchesString("foo.*")))
+  const char* a = "foo";
+  const char* b = "foobar";
+  const char* c = "bar";
+
+Usable as: Matcher
+
+
+
+
 MatcherStringLiteral>hasSizeunsigned N
 Matches nodes that have the 
specified size.
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7beef7be0e6a53..760d566eabe9e3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -307,6 +307,8 @@ AST Matchers
 - Fixed an issue with the `hasName` and `hasAnyName` matcher when matching
   inline namespaces with an enclosing namespace of the same name.
 
+Add `matchesString` for `StringLiteral` which matches literals on given 
`RegExp`.
+
 clang-format
 
 
diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index ca44c3ee085654..bff415294c4561 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -3116,6 +3116,30 @@ AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
   return RegExp->match(FullNameString);
 }
 
+/// Matches string literals that contain a substring matched by the given 
RegExp.
+///
+/// Example matches "foo" and "foobar" but not "bar"
+///   (matcher = stringLiteral(matchesString("foo.*")))
+/// \code
+///   const char* a = "foo";
+///   const char* b = "foobar";
+///   const char* c = "bar";
+/// \endcode
+///
+/// Usable as: Matcher
+AST_MATCHER_REGEX(StringLiteral, matchesString, RegExp) {
+  constexpr unsigned StringLength = 64;
+  SmallString Str;
+  llvm::raw_svector_ostream OS(Str);
+  Node.outputString(OS);
+  StringRef OSRef = OS.str();
+  if (OSRef.size() < 2U) {
+return false;
+  }
+  OSRef = OSRef.substr(1, OSRef.size() - 2);
+  return RegExp->match(OSRef);
+}
+
 /// Matches overloaded operator names.
 ///
 /// Matches overloaded operator names specified in strings without the
diff --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 2c75e6beb74301..a3a2515d86be70 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -125,6 +125,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER_OVERLOAD(equals);
 
   REGISTER_REGEX_MATCHER(isExpansionInFileMatching);
+  REGISTER_REGEX_MATCHER(matchesString);
   REGISTER_REGEX_MATCHER(matchesName);
   REGISTER_REGEX_MATCHER(matchesSelector);
 
diff --git a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
index 611e1f9ba5327c..ff9684fb54b266 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2503,6 +2503,25 @@ TEST_P(ASTMatchersTest, IsDelegatingConstructor) {
   cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(1;
 }
 
+TEST_P(ASTMatchersTest, MatchesString) {
+  StatementMatcher Literal = stringLiteral(matchesString("foo.*"));
+  EXPECT_TRUE(matches("const char* a = \"foo\";", Literal));
+  EXPECT_TRUE(matches("const char* b = \"foobar\";", Literal));
+  EXPECT_TRUE(matches("const char* b = \"fo\"\"obar\";", Literal));
+  EXPECT_TRUE(notMatches("const char* c = \"bar\";", Literal));
+  // test embedded nulls
+  StatementMatcher Literal2 = stringLiteral(matchesString("bar"));
+  EXPECT_TRUE(matches("const char* b = \"foo\\0bar\";", Literal2));
+  EXPECT_TRUE(notMatches("const char* b = \"foo\\0b\\0ar\";", Literal2));
+  // test prefix
+  if (!GetParam().isCXX20OrLater()) {
+return;
+  }
+  EXPECT_TRUE(matches("const wchar_t* a = L\"foo\";", Literal));
+  EXPECT_TRUE(ma

[clang] [Clang][Interp] Fix display of syntactically-invalid note for member function calls (PR #102170)

2024-08-08 Thread via cfe-commits

yronglin wrote:

> LGTM otherwise. The CI currently fails on Windows, but that looks like it's 
> using an old version of the test?

Thanks! Some local changes were missed last time and were not committed.

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


[clang] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread Fangrui Song via cfe-commits

MaskRay wrote:

The description specifies "Reverted due to both regression reported on PR and 
https://github.com/llvm/llvm-project/issues/102353"; but somehow the commit 
message does not include the reason.
(I just tried to look at reverts without reasons and remind the authors.)

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


[clang] Revert "[clang] Reland: Instantiate concepts with sugared template arguments (#101782)" (PR #102551)

2024-08-08 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

> The description specifies "Reverted due to both regression reported on PR and 
> https://github.com/llvm/llvm-project/issues/102353"; but somehow the commit 
> message does not include the reason.
> 
> (I just tried to look at reverts without reasons and remind the authors.)

I don't understand how that happened either. I merged through the iPhone GitHub 
App, for what it's worth, and I didn't edit the commit message before 
confirming.

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


[clang] [C++20] [Modules] Emit Errors when compiling a non-module source as module (PR #102565)

2024-08-08 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 created 
https://github.com/llvm/llvm-project/pull/102565

Close https://github.com/llvm/llvm-project/issues/101398

The root cause of the issue is that I removed the codes before and failed to 
recognize it in time and this was not found for a long time due to it only 
crashes with invalid codes.

>From f55262aa35a53a5f01de6a29c21d7f584244ca13 Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Fri, 9 Aug 2024 11:31:59 +0800
Subject: [PATCH] [C++20] [Modules] Emit Errors when compiling a non-module
 source as module

Close https://github.com/llvm/llvm-project/issues/101398

The root cause of the issue is that I removed the codes before and
failed to recognize it in time and this was not found for a long time
due to it only crashes with invalid codes.
---
 clang/include/clang/Basic/DiagnosticSemaKinds.td |  2 ++
 clang/lib/Sema/Sema.cpp  | 12 
 .../dcl.dcl/dcl.module/dcl.module.interface/p1.cppm  |  4 +++-
 clang/test/Modules/pr101398.cppm |  5 +
 4 files changed, 22 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Modules/pr101398.cppm

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 5cdf36660b2a66..554dbaff2ce0d8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11693,6 +11693,8 @@ def err_module_not_defined : Error<
 def err_module_redeclaration : Error<
   "translation unit contains multiple module declarations">;
 def note_prev_module_declaration : Note<"previous module declaration is here">;
+def err_module_declaration_missing : Error<
+  "missing 'export module' declaration in module interface unit">;
 def err_module_declaration_missing_after_global_module_introducer : Error<
   "missing 'module' declaration at end of global module fragment "
   "introduced here">;
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 19d8692ee64849..633b8220ffbf11 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1272,6 +1272,18 @@ void Sema::ActOnEndOfTranslationUnit() {
Module::ExplicitGlobalModuleFragment) {
 Diag(ModuleScopes.back().BeginLoc,
  diag::err_module_declaration_missing_after_global_module_introducer);
+  } else if (getLangOpts().getCompilingModule() ==
+ LangOptions::CMK_ModuleInterface &&
+ // We can't use ModuleScopes here since ModuleScopes is always
+ // empty if we're compiling the BMI.
+ !getASTContext().getCurrentNamedModule()) {
+// If we are building a module interface unit, we should have seen the
+// module declaration.
+//
+// FIXME: Make a better guess as to where to put the module declaration.
+Diag(getSourceManager().getLocForStartOfFile(
+ getSourceManager().getMainFileID()),
+ diag::err_module_declaration_missing);
   }
 
   // Now we can decide whether the modules we're building need an initializer.
diff --git 
a/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm 
b/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
index 1a01ffac0154ae..84ef85126c369a 100644
--- a/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
+++ b/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++20 %s -verify -o /dev/null
+// RUN: %clang_cc1 -std=c++20 %s -verify -emit-module-interface -o /dev/null
 // RUN: %clang_cc1 -std=c++20 %s -DINTERFACE -verify -emit-module-interface -o 
%t
 // RUN: %clang_cc1 -std=c++20 %s -DIMPLEMENTATION -verify -fmodule-file=A=%t 
-o /dev/null
 //
@@ -15,6 +15,8 @@ module A; // #module-decl
   // expected-error@-2 {{missing 'export' specifier in module declaration 
while building module interface}}
   #define INTERFACE
  #endif
+#else // Not in a module
+// expected-error@* {{missing 'export module' declaration in module interface 
unit}}
 #endif
 
 #ifndef INTERFACE
diff --git a/clang/test/Modules/pr101398.cppm b/clang/test/Modules/pr101398.cppm
new file mode 100644
index 00..843d0ce84fdce3
--- /dev/null
+++ b/clang/test/Modules/pr101398.cppm
@@ -0,0 +1,5 @@
+// RUN: mkdir -p %t
+// RUN: %clang -std=c++20 -xc++-module %s -Xclang -verify --precompile -o 
%t/tmp.pcm
+// not modules
+
+// expected-error@* {{missing 'export module' declaration in module interface 
unit}}

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


[clang] [C++20] [Modules] Emit Errors when compiling a non-module source as module (PR #102565)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-modules

Author: Chuanqi Xu (ChuanqiXu9)


Changes

Close https://github.com/llvm/llvm-project/issues/101398

The root cause of the issue is that I removed the codes before and failed to 
recognize it in time and this was not found for a long time due to it only 
crashes with invalid codes.

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


4 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2) 
- (modified) clang/lib/Sema/Sema.cpp (+12) 
- (modified) 
clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm (+3-1) 
- (added) clang/test/Modules/pr101398.cppm (+5) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 5cdf36660b2a66..554dbaff2ce0d8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11693,6 +11693,8 @@ def err_module_not_defined : Error<
 def err_module_redeclaration : Error<
   "translation unit contains multiple module declarations">;
 def note_prev_module_declaration : Note<"previous module declaration is here">;
+def err_module_declaration_missing : Error<
+  "missing 'export module' declaration in module interface unit">;
 def err_module_declaration_missing_after_global_module_introducer : Error<
   "missing 'module' declaration at end of global module fragment "
   "introduced here">;
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 19d8692ee64849..633b8220ffbf11 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1272,6 +1272,18 @@ void Sema::ActOnEndOfTranslationUnit() {
Module::ExplicitGlobalModuleFragment) {
 Diag(ModuleScopes.back().BeginLoc,
  diag::err_module_declaration_missing_after_global_module_introducer);
+  } else if (getLangOpts().getCompilingModule() ==
+ LangOptions::CMK_ModuleInterface &&
+ // We can't use ModuleScopes here since ModuleScopes is always
+ // empty if we're compiling the BMI.
+ !getASTContext().getCurrentNamedModule()) {
+// If we are building a module interface unit, we should have seen the
+// module declaration.
+//
+// FIXME: Make a better guess as to where to put the module declaration.
+Diag(getSourceManager().getLocForStartOfFile(
+ getSourceManager().getMainFileID()),
+ diag::err_module_declaration_missing);
   }
 
   // Now we can decide whether the modules we're building need an initializer.
diff --git 
a/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm 
b/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
index 1a01ffac0154ae..84ef85126c369a 100644
--- a/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
+++ b/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++20 %s -verify -o /dev/null
+// RUN: %clang_cc1 -std=c++20 %s -verify -emit-module-interface -o /dev/null
 // RUN: %clang_cc1 -std=c++20 %s -DINTERFACE -verify -emit-module-interface -o 
%t
 // RUN: %clang_cc1 -std=c++20 %s -DIMPLEMENTATION -verify -fmodule-file=A=%t 
-o /dev/null
 //
@@ -15,6 +15,8 @@ module A; // #module-decl
   // expected-error@-2 {{missing 'export' specifier in module declaration 
while building module interface}}
   #define INTERFACE
  #endif
+#else // Not in a module
+// expected-error@* {{missing 'export module' declaration in module interface 
unit}}
 #endif
 
 #ifndef INTERFACE
diff --git a/clang/test/Modules/pr101398.cppm b/clang/test/Modules/pr101398.cppm
new file mode 100644
index 00..843d0ce84fdce3
--- /dev/null
+++ b/clang/test/Modules/pr101398.cppm
@@ -0,0 +1,5 @@
+// RUN: mkdir -p %t
+// RUN: %clang -std=c++20 -xc++-module %s -Xclang -verify --precompile -o 
%t/tmp.pcm
+// not modules
+
+// expected-error@* {{missing 'export module' declaration in module interface 
unit}}

``




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


[clang] [Clang][Sema] Fix mismatch of out-of-line definition of template class (PR #102554)

2024-08-08 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

> I'm sorry but this approach doesn't make sense to me.
> 
> I have to say that I self-assigned the issue hours before this patch (I don't 
> know when you started working on it because you haven't explained anything 
> either), and that means I'll look into that recently since I've also been 
> working on another similar case for template packs. Submitting a (especially 
> unreasonable fix) PR without asking first seems to be very impolite behavior.

I am so sorry for that. Since I had been working on this issue yesterday and I 
didn't notice that you have assigned it to yourself as I didn't refresh my web 
page. Feel free to submit your solution if you have a better approach. I will 
close this PR later. Again, sorry for that and I will do better next time. 
Thanks for your remind!

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


[clang] [Clang][Sema] Fix mismatch of out-of-line definition of template class (PR #102554)

2024-08-08 Thread Qizhi Hu via cfe-commits


@@ -951,7 +951,8 @@ static const Expr 
*SubstituteConstraintExpressionWithoutSatisfaction(
   DeclInfo.getDecl(), DeclInfo.getLexicalDeclContext(), /*Final=*/false,
   /*Innermost=*/std::nullopt,
   /*RelativeToPrimary=*/true,
-  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
+  /*Pattern=*/nullptr,
+  !isa_and_present(DeclInfo.getDecl()),

jcsxky wrote:

By the way, I don't think we always need outer arguments since the depth of the 
`TemplateTypeParmType` in `ConceptSpecializationExpr` is 1 (not 0).

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


[clang] [Clang][Sema] Fix mismatch of out-of-line definition of template class (PR #102554)

2024-08-08 Thread Qizhi Hu via cfe-commits

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


[clang] [clang][ASTMatcher] Add `matchesString` for `StringLiteral` which matches literals on given `RegExp` (PR #102152)

2024-08-08 Thread via cfe-commits

https://github.com/Gitspike updated 
https://github.com/llvm/llvm-project/pull/102152

>From ff2e7f928b7f29a89de20aeb0df2e718a5290759 Mon Sep 17 00:00:00 2001
From: hehouhua 
Date: Wed, 7 Aug 2024 11:55:30 +0800
Subject: [PATCH 1/3] [clang][ASTMatcher] Add matches for StringLiteral which
 matches literals on given RegExp

Add Matcher matchesString.
---
 clang/docs/LibASTMatchersReference.html   | 14 +++
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/include/clang/ASTMatchers/ASTMatchers.h | 24 +++
 clang/lib/ASTMatchers/Dynamic/Registry.cpp|  1 +
 .../ASTMatchers/ASTMatchersNarrowingTest.cpp  | 19 +++
 5 files changed, 60 insertions(+)

diff --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index a16b9c44ef0eab..77b789b1ec4b94 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -5582,6 +5582,20 @@ Narrowing Matchers
 
 
 
+MatcherStringLiteral>matchesStringStringRef RegExp, 
Regex::RegexFlags Flags = NoFlags
+Matches string 
literals that contain a substring matched by the given RegExp
+
+Example matches "foo" and "foobar" but not "bar"
+  (matcher = stringLiteral(matchesString("foo.*")))
+  const char* a = "foo";
+  const char* b = "foobar";
+  const char* c = "bar";
+
+Usable as: Matcher
+
+
+
+
 MatcherStringLiteral>hasSizeunsigned N
 Matches nodes that have the 
specified size.
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7beef7be0e6a53..760d566eabe9e3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -307,6 +307,8 @@ AST Matchers
 - Fixed an issue with the `hasName` and `hasAnyName` matcher when matching
   inline namespaces with an enclosing namespace of the same name.
 
+Add `matchesString` for `StringLiteral` which matches literals on given 
`RegExp`.
+
 clang-format
 
 
diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index ca44c3ee085654..bff415294c4561 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -3116,6 +3116,30 @@ AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
   return RegExp->match(FullNameString);
 }
 
+/// Matches string literals that contain a substring matched by the given 
RegExp.
+///
+/// Example matches "foo" and "foobar" but not "bar"
+///   (matcher = stringLiteral(matchesString("foo.*")))
+/// \code
+///   const char* a = "foo";
+///   const char* b = "foobar";
+///   const char* c = "bar";
+/// \endcode
+///
+/// Usable as: Matcher
+AST_MATCHER_REGEX(StringLiteral, matchesString, RegExp) {
+  constexpr unsigned StringLength = 64;
+  SmallString Str;
+  llvm::raw_svector_ostream OS(Str);
+  Node.outputString(OS);
+  StringRef OSRef = OS.str();
+  if (OSRef.size() < 2U) {
+return false;
+  }
+  OSRef = OSRef.substr(1, OSRef.size() - 2);
+  return RegExp->match(OSRef);
+}
+
 /// Matches overloaded operator names.
 ///
 /// Matches overloaded operator names specified in strings without the
diff --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 2c75e6beb74301..a3a2515d86be70 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -125,6 +125,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER_OVERLOAD(equals);
 
   REGISTER_REGEX_MATCHER(isExpansionInFileMatching);
+  REGISTER_REGEX_MATCHER(matchesString);
   REGISTER_REGEX_MATCHER(matchesName);
   REGISTER_REGEX_MATCHER(matchesSelector);
 
diff --git a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
index 611e1f9ba5327c..ff9684fb54b266 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2503,6 +2503,25 @@ TEST_P(ASTMatchersTest, IsDelegatingConstructor) {
   cxxConstructorDecl(isDelegatingConstructor(), parameterCountIs(1;
 }
 
+TEST_P(ASTMatchersTest, MatchesString) {
+  StatementMatcher Literal = stringLiteral(matchesString("foo.*"));
+  EXPECT_TRUE(matches("const char* a = \"foo\";", Literal));
+  EXPECT_TRUE(matches("const char* b = \"foobar\";", Literal));
+  EXPECT_TRUE(matches("const char* b = \"fo\"\"obar\";", Literal));
+  EXPECT_TRUE(notMatches("const char* c = \"bar\";", Literal));
+  // test embedded nulls
+  StatementMatcher Literal2 = stringLiteral(matchesString("bar"));
+  EXPECT_TRUE(matches("const char* b = \"foo\\0bar\";", Literal2));
+  EXPECT_TRUE(notMatches("const char* b = \"foo\\0b\\0ar\";", Literal2));
+  // test prefix
+  if (!GetParam().isCXX20OrLater()) {
+return;
+  }
+  EXPECT_TRUE(matches("const wchar_t* a = L\"foo\";", Literal));
+  EXPECT_TRUE(ma

[clang] [WIP][Clang] Add __builtin_get_counted_by builtin (PR #102549)

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

kees wrote:

> > I'd expect some kind of diagnostic when the specified field doesn't have a 
> > corresponding counted_by field.
> 
> So there's a complication with that. The use case for this builtin is to 
> automatically set the `count` field during allocation in the Linux kernel. 
> (It could be used elsewhere, but Linux is why we're doing this now.) From my 
> understanding, @kees wants to have a way to get the `count` field without 
> having to change the allocator's prototype. (Is that correct?) That's not 
> currently possible, or at least we haven't found a way to do it yet.

Yup, that's correct. There needs to be a way to programmatically determine what 
the "counter" variable is so that we don't have to create a separate (and 
ultimately redundant) allocator API for FAM structs that use "counted_by". It 
could be entirely automatic. Some more background details are here:

https://lore.kernel.org/lkml/20240807235433.work.317-k...@kernel.org/

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


[clang-tools-extra] 5297b75 - clang-tidy: readability-redundant-smartptr-get does not remove (#97964) (#100177)

2024-08-08 Thread via cfe-commits

Author: akshaykumars614
Date: 2024-08-09T00:55:15-04:00
New Revision: 5297b750e54dafe16cc13f24b8d5478214e83682

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

LOG: clang-tidy: readability-redundant-smartptr-get does not remove (#97964) 
(#100177)

added a check to remove '->' if exists

added testcase and modified Release Notes

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/readability/redundant-smartptr-get.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
index 8837ac16e8828..be52af77ae0a5 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
@@ -164,6 +164,10 @@ void RedundantSmartptrGetCheck::check(const 
MatchFinder::MatchResult &Result) {
   StringRef SmartptrText = Lexer::getSourceText(
   CharSourceRange::getTokenRange(Smartptr->getSourceRange()),
   *Result.SourceManager, getLangOpts());
+  // Check if the last two characters are "->" and remove them
+  if (SmartptrText.ends_with("->")) {
+SmartptrText = SmartptrText.drop_back(2);
+  }
   // Replace foo->get() with *foo, and foo.get() with foo.
   std::string Replacement = Twine(IsPtrToPtr ? "*" : "", SmartptrText).str();
   diag(GetCall->getBeginLoc(), "redundant get() call on smart pointer")

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 642ad39cc0c1c..b72d109b3d393 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -104,6 +104,10 @@ New check aliases
 Changes in existing checks
 ^^
 
+- Improved :doc:`readability-redundant-smartptr-get
+  ` check to
+  remove `->`, when reduntant `get()` is removed.
+
 Removed checks
 ^^
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-smartptr-get.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-smartptr-get.cpp
index 01f12b6bfe6ea..ec4ca4cb79484 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-smartptr-get.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-smartptr-get.cpp
@@ -20,6 +20,23 @@ struct shared_ptr {
   explicit operator bool() const noexcept;
 };
 
+template 
+struct vector {
+  vector();
+  bool operator==(const vector& other) const;
+  bool operator!=(const vector& other) const;
+  unsigned long size() const;
+  bool empty() const;
+
+  using iterator = T*;
+
+  iterator begin();
+  iterator end();
+
+  T* data;
+  unsigned long sz;
+};
+
 }  // namespace std
 
 struct Bar {
@@ -235,3 +252,34 @@ void Negative() {
   if (MACRO(x) == nullptr)
 ;
 }
+
+void test_redundant_get() {
+  std::vector> v;
+  auto f = [](int) {};
+  for (auto i = v.begin(); i != v.end(); ++i) {
+f(*i->get());
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: redundant get() call
+// CHECK-FIXES: f(**i);
+  }
+}
+
+struct Inner {
+  int a;
+  int *getValue()  { return &a; }
+};
+
+struct Example {
+  Inner inner;
+  Inner* get() { return &inner; }
+  int *getValue()  { return inner.getValue(); }
+};
+
+void test_redundant_get_with_member() {
+  std::vector> v;
+  auto f = [](int) {};
+  for (auto i = v.begin(); i != v.end(); ++i) {
+f(*(*i).get()->get()->getValue());
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: redundant get() call
+// CHECK-FIXES: f(**i->get()->getValue());
+ }
+}



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


[clang] Fix a unit test input file (PR #102567)

2024-08-08 Thread Ian Anderson via cfe-commits

https://github.com/ian-twilightcoder created 
https://github.com/llvm/llvm-project/pull/102567

I forgot to update the version info in the SDKSettings file when I updated it 
to the real version relevant to the test. The version in the SDKSettings file 
isn't actually used for anything in the test, but might as well have realistic 
values.

>From 23f2ad9507fb6a8edb0f2194448e0eb2ac8c2652 Mon Sep 17 00:00:00 2001
From: Ian Anderson 
Date: Thu, 8 Aug 2024 21:54:40 -0700
Subject: [PATCH] Fix a unit test input file

I forgot to update the version info in the SDKSettings file when I updated it 
to the real version relevant to the test. The version in the SDKSettings file 
isn't actually used for anything in the test, but might as well have realistic 
values.
---
 clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json 
b/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
index 77b70e1a83c19c..ced45d5c219962 100644
--- a/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
+++ b/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
@@ -1 +1 @@
-{"Version":"990.0", "MaximumDeploymentTarget": "99.0.99"}
+{"Version":"15.0", "MaximumDeploymentTarget": "15.0.99"}

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


[clang-tools-extra] clang-tidy: readability-redundant-smartptr-get does not remove (#97964) (PR #100177)

2024-08-08 Thread via cfe-commits

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


[clang] Fix a unit test input file (PR #102567)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ian Anderson (ian-twilightcoder)


Changes

I forgot to update the version info in the SDKSettings file when I updated it 
to the real version relevant to the test. The version in the SDKSettings file 
isn't actually used for anything in the test, but might as well have realistic 
values.

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


1 Files Affected:

- (modified) clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json (+1-1) 


``diff
diff --git a/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json 
b/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
index 77b70e1a83c19c..ced45d5c219962 100644
--- a/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
+++ b/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
@@ -1 +1 @@
-{"Version":"990.0", "MaximumDeploymentTarget": "99.0.99"}
+{"Version":"15.0", "MaximumDeploymentTarget": "15.0.99"}

``




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


[clang] Fix a unit test input file (PR #102567)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Ian Anderson (ian-twilightcoder)


Changes

I forgot to update the version info in the SDKSettings file when I updated it 
to the real version relevant to the test. The version in the SDKSettings file 
isn't actually used for anything in the test, but might as well have realistic 
values.

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


1 Files Affected:

- (modified) clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json (+1-1) 


``diff
diff --git a/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json 
b/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
index 77b70e1a83c19c..ced45d5c219962 100644
--- a/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
+++ b/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
@@ -1 +1 @@
-{"Version":"990.0", "MaximumDeploymentTarget": "99.0.99"}
+{"Version":"15.0", "MaximumDeploymentTarget": "15.0.99"}

``




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


[clang] Fix a unit test input file (PR #102567)

2024-08-08 Thread Ian Anderson via cfe-commits

https://github.com/ian-twilightcoder updated 
https://github.com/llvm/llvm-project/pull/102567

>From 4bc7053e1383e6aa9e1a60017be296e305b8da5a Mon Sep 17 00:00:00 2001
From: Ian Anderson 
Date: Thu, 8 Aug 2024 21:54:40 -0700
Subject: [PATCH] Fix a unit test input file

I forgot to update the version info in the SDKSettings file when I updated it 
to the real version relevant to the test.
---
 clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json 
b/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
index 77b70e1a83c19c..ced45d5c219962 100644
--- a/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
+++ b/clang/test/Driver/Inputs/MacOSX15.0.sdk/SDKSettings.json
@@ -1 +1 @@
-{"Version":"990.0", "MaximumDeploymentTarget": "99.0.99"}
+{"Version":"15.0", "MaximumDeploymentTarget": "15.0.99"}

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


[clang] Fix a unit test input file (PR #102567)

2024-08-08 Thread Ian Anderson via cfe-commits

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


[clang] [RFC] Add clang atomic control options and pragmas (PR #102569)

2024-08-08 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-hlsl

@llvm/pr-subscribers-coroutines

Author: Yaxun (Sam) Liu (yxsamliu)


Changes

This RFC proposes the addition of an atomic pragma to Clang, designed to 
provide a more flexible mechanism for users to specify how atomic operations 
should be handled during the lowering process in LLVM IR. Currently, the 
atomicrmw instruction in LLVM IR can be lowered to either atomic instructions 
or CAS loops, depending on whether the target supports atomic instructions for 
a specific operation type or alignment. However, there are cases where the 
decision-making process for lowering an atomicrmw instruction cannot be fully 
expressed by the existing IR.

For instance, consider a scenario where a floating-point atomic add instruction 
does not conform to IEEE denormal mode requirements on a particular subtarget. 
Even though this non-conformance exists, users might still prefer the 
corresponding IR to be lowered to atomic instructions if they are unconcerned 
about denormal mode. This means that the backend needs to be informed through 
IR whether to ignore the floating-point denormal mode during the lowering 
process. Another example involves an atomic instruction that may not function 
correctly for specific memory types, such as memory accessed through PCIe, 
which only supports atomic integer add, exchange, or compare-and-swap 
operations. To ensure correct and efficient lowering of atomicrmw instructions, 
the backend must be aware of the memory type involved.

To convey this necessary information to the backend, we propose adding 
target-specific metadata to atomicrmw instructions in IR. Since this 
information is provided by users, a flexible mechanism is needed to allow them 
to specify these details in the source code. To achieve this, we introduce a 
pragma in the format of This pragma allows users to specify one, two, or all 
three options and must be placed at the beginning of a compound statement. The 
pragma can also be nested, with inner pragmas overriding the options specified 
in outer compound statements or the target's default options. These options 
will then determine the target-specific metadata added to atomic instructions 
in the IR.

In addition to the pragma, a new compiler option is introduced: 
-fatomic=no_remote_memory:{on|off},no_fine_grained_memory:{on|off},ignore_denormal_mode{on|off}.
 This compiler option allows users to override the target's default options 
through the Clang driver and front end.

The design of this atomic pragma and the associated compiler options are 
intended to be target-neutral, enabling potential reuse across different 
targets. While a target might choose not to emit metadata for some or all of 
these options, or might add new options to the pragma, the overall design is 
inspired by Clang's floating-point pragma, which conveys extra information to 
the backend about how floating-point instructions should be lowered. 
Importantly, the metadata introduced by this pragma in the IR can be dropped 
without affecting the correctness of the program, as it is primarily intended 
to improve performance.

In terms of implementation, the atomic pragma is represented in the AST by 
trailing data in CompoundStmt. The parser in Clang maintains an atomic options 
stack in Sema, which is updated whenever the atomic pragma is encountered. When 
a CompoundStmt is created, it includes the current atomic options. RAII is 
employed to save and restore atomic options when transitioning between outer 
and inner CompoundStmts.

During code generation in Clang, the CodeGenModule maintains the current atomic 
options, which are used to emit the relevant metadata for atomic instructions. 
As with the parsing phase, RAII is used to manage the saving and restoring of 
atomic options when entering and exiting nested CompoundStmts. This ensures 
that the correct metadata is generated in the IR, reflecting the user's 
specified options accurately.

---

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


47 Files Affected:

- (modified) clang/include/clang/AST/Stmt.h (+38-4) 
- (modified) clang/include/clang/AST/TextNodeDumper.h (+1) 
- (added) clang/include/clang/Basic/AtomicOptions.def (+19) 
- (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+7) 
- (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (+9) 
- (modified) clang/include/clang/Basic/LangOptions.h (+167) 
- (modified) clang/include/clang/Basic/PragmaKinds.h (+7) 
- (modified) clang/include/clang/Basic/TargetInfo.h (+6) 
- (modified) clang/include/clang/Basic/TokenKinds.def (+2) 
- (modified) clang/include/clang/Driver/Options.td (+8) 
- (modified) clang/include/clang/Parse/Parser.h (+5) 
- (modified) clang/include/clang/Sema/Sema.h (+36-2) 
- (modified) clang/lib/AST/ASTImporter.cpp (+4-1) 
- (modified) clang/lib/AST/Stmt.cpp (+16-7) 
- (modified) clang/lib/AST/StmtPrinter.cpp (+23) 
- (modi

[clang] [RFC] Add clang atomic control options and pragmas (PR #102569)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Yaxun (Sam) Liu (yxsamliu)


Changes

This RFC proposes the addition of an atomic pragma to Clang, designed to 
provide a more flexible mechanism for users to specify how atomic operations 
should be handled during the lowering process in LLVM IR. Currently, the 
atomicrmw instruction in LLVM IR can be lowered to either atomic instructions 
or CAS loops, depending on whether the target supports atomic instructions for 
a specific operation type or alignment. However, there are cases where the 
decision-making process for lowering an atomicrmw instruction cannot be fully 
expressed by the existing IR.

For instance, consider a scenario where a floating-point atomic add instruction 
does not conform to IEEE denormal mode requirements on a particular subtarget. 
Even though this non-conformance exists, users might still prefer the 
corresponding IR to be lowered to atomic instructions if they are unconcerned 
about denormal mode. This means that the backend needs to be informed through 
IR whether to ignore the floating-point denormal mode during the lowering 
process. Another example involves an atomic instruction that may not function 
correctly for specific memory types, such as memory accessed through PCIe, 
which only supports atomic integer add, exchange, or compare-and-swap 
operations. To ensure correct and efficient lowering of atomicrmw instructions, 
the backend must be aware of the memory type involved.

To convey this necessary information to the backend, we propose adding 
target-specific metadata to atomicrmw instructions in IR. Since this 
information is provided by users, a flexible mechanism is needed to allow them 
to specify these details in the source code. To achieve this, we introduce a 
pragma in the format of This pragma allows users to specify one, two, or all 
three options and must be placed at the beginning of a compound statement. The 
pragma can also be nested, with inner pragmas overriding the options specified 
in outer compound statements or the target's default options. These options 
will then determine the target-specific metadata added to atomic instructions 
in the IR.

In addition to the pragma, a new compiler option is introduced: 
-fatomic=no_remote_memory:{on|off},no_fine_grained_memory:{on|off},ignore_denormal_mode{on|off}.
 This compiler option allows users to override the target's default options 
through the Clang driver and front end.

The design of this atomic pragma and the associated compiler options are 
intended to be target-neutral, enabling potential reuse across different 
targets. While a target might choose not to emit metadata for some or all of 
these options, or might add new options to the pragma, the overall design is 
inspired by Clang's floating-point pragma, which conveys extra information to 
the backend about how floating-point instructions should be lowered. 
Importantly, the metadata introduced by this pragma in the IR can be dropped 
without affecting the correctness of the program, as it is primarily intended 
to improve performance.

In terms of implementation, the atomic pragma is represented in the AST by 
trailing data in CompoundStmt. The parser in Clang maintains an atomic options 
stack in Sema, which is updated whenever the atomic pragma is encountered. When 
a CompoundStmt is created, it includes the current atomic options. RAII is 
employed to save and restore atomic options when transitioning between outer 
and inner CompoundStmts.

During code generation in Clang, the CodeGenModule maintains the current atomic 
options, which are used to emit the relevant metadata for atomic instructions. 
As with the parsing phase, RAII is used to manage the saving and restoring of 
atomic options when entering and exiting nested CompoundStmts. This ensures 
that the correct metadata is generated in the IR, reflecting the user's 
specified options accurately.

---

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


47 Files Affected:

- (modified) clang/include/clang/AST/Stmt.h (+38-4) 
- (modified) clang/include/clang/AST/TextNodeDumper.h (+1) 
- (added) clang/include/clang/Basic/AtomicOptions.def (+19) 
- (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+7) 
- (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (+9) 
- (modified) clang/include/clang/Basic/LangOptions.h (+167) 
- (modified) clang/include/clang/Basic/PragmaKinds.h (+7) 
- (modified) clang/include/clang/Basic/TargetInfo.h (+6) 
- (modified) clang/include/clang/Basic/TokenKinds.def (+2) 
- (modified) clang/include/clang/Driver/Options.td (+8) 
- (modified) clang/include/clang/Parse/Parser.h (+5) 
- (modified) clang/include/clang/Sema/Sema.h (+36-2) 
- (modified) clang/lib/AST/ASTImporter.cpp (+4-1) 
- (modified) clang/lib/AST/Stmt.cpp (+16-7) 
- (modified) clang/lib/AST/StmtPrinter.cpp (+23) 
- (modified) clang/lib/AST/Text

[clang] [RFC] Add clang atomic control options and pragmas (PR #102569)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis

Author: Yaxun (Sam) Liu (yxsamliu)


Changes

This RFC proposes the addition of an atomic pragma to Clang, designed to 
provide a more flexible mechanism for users to specify how atomic operations 
should be handled during the lowering process in LLVM IR. Currently, the 
atomicrmw instruction in LLVM IR can be lowered to either atomic instructions 
or CAS loops, depending on whether the target supports atomic instructions for 
a specific operation type or alignment. However, there are cases where the 
decision-making process for lowering an atomicrmw instruction cannot be fully 
expressed by the existing IR.

For instance, consider a scenario where a floating-point atomic add instruction 
does not conform to IEEE denormal mode requirements on a particular subtarget. 
Even though this non-conformance exists, users might still prefer the 
corresponding IR to be lowered to atomic instructions if they are unconcerned 
about denormal mode. This means that the backend needs to be informed through 
IR whether to ignore the floating-point denormal mode during the lowering 
process. Another example involves an atomic instruction that may not function 
correctly for specific memory types, such as memory accessed through PCIe, 
which only supports atomic integer add, exchange, or compare-and-swap 
operations. To ensure correct and efficient lowering of atomicrmw instructions, 
the backend must be aware of the memory type involved.

To convey this necessary information to the backend, we propose adding 
target-specific metadata to atomicrmw instructions in IR. Since this 
information is provided by users, a flexible mechanism is needed to allow them 
to specify these details in the source code. To achieve this, we introduce a 
pragma in the format of This pragma allows users to specify one, two, or all 
three options and must be placed at the beginning of a compound statement. The 
pragma can also be nested, with inner pragmas overriding the options specified 
in outer compound statements or the target's default options. These options 
will then determine the target-specific metadata added to atomic instructions 
in the IR.

In addition to the pragma, a new compiler option is introduced: 
-fatomic=no_remote_memory:{on|off},no_fine_grained_memory:{on|off},ignore_denormal_mode{on|off}.
 This compiler option allows users to override the target's default options 
through the Clang driver and front end.

The design of this atomic pragma and the associated compiler options are 
intended to be target-neutral, enabling potential reuse across different 
targets. While a target might choose not to emit metadata for some or all of 
these options, or might add new options to the pragma, the overall design is 
inspired by Clang's floating-point pragma, which conveys extra information to 
the backend about how floating-point instructions should be lowered. 
Importantly, the metadata introduced by this pragma in the IR can be dropped 
without affecting the correctness of the program, as it is primarily intended 
to improve performance.

In terms of implementation, the atomic pragma is represented in the AST by 
trailing data in CompoundStmt. The parser in Clang maintains an atomic options 
stack in Sema, which is updated whenever the atomic pragma is encountered. When 
a CompoundStmt is created, it includes the current atomic options. RAII is 
employed to save and restore atomic options when transitioning between outer 
and inner CompoundStmts.

During code generation in Clang, the CodeGenModule maintains the current atomic 
options, which are used to emit the relevant metadata for atomic instructions. 
As with the parsing phase, RAII is used to manage the saving and restoring of 
atomic options when entering and exiting nested CompoundStmts. This ensures 
that the correct metadata is generated in the IR, reflecting the user's 
specified options accurately.

---

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


47 Files Affected:

- (modified) clang/include/clang/AST/Stmt.h (+38-4) 
- (modified) clang/include/clang/AST/TextNodeDumper.h (+1) 
- (added) clang/include/clang/Basic/AtomicOptions.def (+19) 
- (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+7) 
- (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (+9) 
- (modified) clang/include/clang/Basic/LangOptions.h (+167) 
- (modified) clang/include/clang/Basic/PragmaKinds.h (+7) 
- (modified) clang/include/clang/Basic/TargetInfo.h (+6) 
- (modified) clang/include/clang/Basic/TokenKinds.def (+2) 
- (modified) clang/include/clang/Driver/Options.td (+8) 
- (modified) clang/include/clang/Parse/Parser.h (+5) 
- (modified) clang/include/clang/Sema/Sema.h (+36-2) 
- (modified) clang/lib/AST/ASTImporter.cpp (+4-1) 
- (modified) clang/lib/AST/Stmt.cpp (+16-7) 
- (modified) clang/lib/AST/StmtPrinter.cpp (+23) 
- (modified) clang/lib/AST/Te

[clang] [RFC] Add clang atomic control options and pragmas (PR #102569)

2024-08-08 Thread Yaxun Liu via cfe-commits

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


[clang] [hmaptool] Fix for empty prefixes and suffixes (PR #102571)

2024-08-08 Thread Shoaib Meenai via cfe-commits

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

The previous logic could fail in some edge cases.


>From 28297fc4e0b3b21990f1d614115b8eb946989479 Mon Sep 17 00:00:00 2001
From: Shoaib Meenai 
Date: Wed, 13 Dec 2023 18:59:25 -0800
Subject: [PATCH] [hmaptool] Fix for empty prefixes and suffixes

The previous logic could fail in some edge cases.
---
 clang/utils/hmaptool/hmaptool | 7 +--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/clang/utils/hmaptool/hmaptool b/clang/utils/hmaptool/hmaptool
index d7754632b162bf..aa400e3dd64e93 100755
--- a/clang/utils/hmaptool/hmaptool
+++ b/clang/utils/hmaptool/hmaptool
@@ -192,8 +192,11 @@ def action_write(name, args):
 
 key_idx = len(strtable)
 strtable += key + '\0'
-prefix = os.path.dirname(value) + '/'
-suffix = os.path.basename(value)
+prefix, suffix = os.path.split(value)
+# This guarantees that prefix + suffix == value in all cases, 
including when
+# prefix is empty or contains a trailing slash or suffix is empty 
(hence the use
+# of `len(value) - len(suffix)` instead of just `-len(suffix)`.
+prefix += value[len(prefix) : len(value) - len(suffix)]
 prefix_idx = len(strtable)
 strtable += prefix + '\0'
 suffix_idx = len(strtable)

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


[clang] [hmaptool] Fix for empty prefixes and suffixes (PR #102571)

2024-08-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Shoaib Meenai (smeenai)


Changes

The previous logic could fail in some edge cases.


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


1 Files Affected:

- (modified) clang/utils/hmaptool/hmaptool (+5-2) 


``diff
diff --git a/clang/utils/hmaptool/hmaptool b/clang/utils/hmaptool/hmaptool
index d7754632b162b..aa400e3dd64e9 100755
--- a/clang/utils/hmaptool/hmaptool
+++ b/clang/utils/hmaptool/hmaptool
@@ -192,8 +192,11 @@ def action_write(name, args):
 
 key_idx = len(strtable)
 strtable += key + '\0'
-prefix = os.path.dirname(value) + '/'
-suffix = os.path.basename(value)
+prefix, suffix = os.path.split(value)
+# This guarantees that prefix + suffix == value in all cases, 
including when
+# prefix is empty or contains a trailing slash or suffix is empty 
(hence the use
+# of `len(value) - len(suffix)` instead of just `-len(suffix)`.
+prefix += value[len(prefix) : len(value) - len(suffix)]
 prefix_idx = len(strtable)
 strtable += prefix + '\0'
 suffix_idx = len(strtable)

``




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


[clang] be66c50 - [C++20] [Modules] Emit Errors when compiling a non-module source as module (#102565)

2024-08-08 Thread via cfe-commits

Author: Chuanqi Xu
Date: 2024-08-09T13:39:24+08:00
New Revision: be66c506c7fd6fdb7363f724075d02ca0d35713a

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

LOG: [C++20] [Modules] Emit Errors when compiling a non-module source as module 
(#102565)

Close https://github.com/llvm/llvm-project/issues/101398

The root cause of the issue is that I removed the codes before and
failed to recognize it in time and this was not found for a long time
due to it only crashes with invalid codes.

Added: 
clang/test/Modules/pr101398.cppm

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/Sema.cpp
clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 5cdf36660b2a66..554dbaff2ce0d8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11693,6 +11693,8 @@ def err_module_not_defined : Error<
 def err_module_redeclaration : Error<
   "translation unit contains multiple module declarations">;
 def note_prev_module_declaration : Note<"previous module declaration is here">;
+def err_module_declaration_missing : Error<
+  "missing 'export module' declaration in module interface unit">;
 def err_module_declaration_missing_after_global_module_introducer : Error<
   "missing 'module' declaration at end of global module fragment "
   "introduced here">;

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 19d8692ee64849..633b8220ffbf11 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1272,6 +1272,18 @@ void Sema::ActOnEndOfTranslationUnit() {
Module::ExplicitGlobalModuleFragment) {
 Diag(ModuleScopes.back().BeginLoc,
  diag::err_module_declaration_missing_after_global_module_introducer);
+  } else if (getLangOpts().getCompilingModule() ==
+ LangOptions::CMK_ModuleInterface &&
+ // We can't use ModuleScopes here since ModuleScopes is always
+ // empty if we're compiling the BMI.
+ !getASTContext().getCurrentNamedModule()) {
+// If we are building a module interface unit, we should have seen the
+// module declaration.
+//
+// FIXME: Make a better guess as to where to put the module declaration.
+Diag(getSourceManager().getLocForStartOfFile(
+ getSourceManager().getMainFileID()),
+ diag::err_module_declaration_missing);
   }
 
   // Now we can decide whether the modules we're building need an initializer.

diff  --git 
a/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm 
b/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
index 1a01ffac0154ae..84ef85126c369a 100644
--- a/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
+++ b/clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++20 %s -verify -o /dev/null
+// RUN: %clang_cc1 -std=c++20 %s -verify -emit-module-interface -o /dev/null
 // RUN: %clang_cc1 -std=c++20 %s -DINTERFACE -verify -emit-module-interface -o 
%t
 // RUN: %clang_cc1 -std=c++20 %s -DIMPLEMENTATION -verify -fmodule-file=A=%t 
-o /dev/null
 //
@@ -15,6 +15,8 @@ module A; // #module-decl
   // expected-error@-2 {{missing 'export' specifier in module declaration 
while building module interface}}
   #define INTERFACE
  #endif
+#else // Not in a module
+// expected-error@* {{missing 'export module' declaration in module interface 
unit}}
 #endif
 
 #ifndef INTERFACE

diff  --git a/clang/test/Modules/pr101398.cppm 
b/clang/test/Modules/pr101398.cppm
new file mode 100644
index 00..843d0ce84fdce3
--- /dev/null
+++ b/clang/test/Modules/pr101398.cppm
@@ -0,0 +1,5 @@
+// RUN: mkdir -p %t
+// RUN: %clang -std=c++20 -xc++-module %s -Xclang -verify --precompile -o 
%t/tmp.pcm
+// not modules
+
+// expected-error@* {{missing 'export module' declaration in module interface 
unit}}



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


[clang] [C++20] [Modules] Emit Errors when compiling a non-module source as module (PR #102565)

2024-08-08 Thread Chuanqi Xu via cfe-commits

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


  1   2   3   4   5   >