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

2024-06-16 Thread Vikram Hegde via cfe-commits


@@ -0,0 +1,65 @@
+; RUN: llc -stop-after=amdgpu-isel -mtriple=amdgcn-- -mcpu=gfx1100 
-verify-machineinstrs -o - %s | FileCheck --check-prefixes=CHECK,ISEL %s
+
+; CHECK-LABEL: name:basic_readfirstlane_i64
+;   CHECK:[[TOKEN:%[0-9]+]]{{[^ ]*}} = CONVERGENCECTRL_ANCHOR

vikramRH wrote:

Makes sense, updated.

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits


@@ -372,6 +382,34 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+llvm::StringRef getLambdaCaptureName(const LambdaCapture ) {
+  if (Capture.capturesVariable())
+return Capture.getCapturedVar()->getName();
+  if (Capture.capturesThis())
+return llvm::StringRef{"this"};
+  return llvm::StringRef{"unknown"};

zyn0217 wrote:

Can we handle all the capture kinds here? I was expecting otherwise an assert 
or an `llvm_unreachable` here rather than printing "unknown".

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits


@@ -281,7 +281,7 @@ struct TextDocumentEdit {
   /// The text document to change.
   VersionedTextDocumentIdentifier textDocument;
 
-   /// The edits to be applied.
+  /// The edits to be applied.

zyn0217 wrote:

Ditto. Unrelated blank changes. Please revert changes here and below.

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits


@@ -1458,13 +1463,66 @@ TEST(TypeHints, DefaultTemplateArgs) {
 struct A {};
 A foo();
 auto $var[[var]] = foo();
-A bar[1];
+A baz;
+A bar[1]{};

zyn0217 wrote:

Why there's an empty initializer? Can you revert it?

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits


@@ -504,10 +503,10 @@ struct FragmentCompiler {
   auto Fast = isFastTidyCheck(Str);
   if (!Fast.has_value()) {
 diag(Warning,
- llvm::formatv(
- "Latency of clang-tidy check '{0}' is not known. "
- "It will only run if ClangTidy.FastCheckFilter is Loose or 
None",
- Str)
+ llvm::formatv("Latency of clang-tidy check '{0}' is not known. "
+   "It will only run if ClangTidy.FastCheckFilter is "
+   "Loose or None",
+   Str)

zyn0217 wrote:

Please don't sneak in unrelated format changes in one patch.

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits


@@ -1568,7 +1626,7 @@ TEST(TypeHints, SubstTemplateParameterAliases) {
   )cpp";
 
   llvm::StringRef VectorIntPtr = R"cpp(
-vector array;
+vector $init[[array]];

zyn0217 wrote:

Will the range ever be used somewhere?

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits


@@ -372,6 +382,34 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+llvm::StringRef getLambdaCaptureName(const LambdaCapture ) {
+  if (Capture.capturesVariable())
+return Capture.getCapturedVar()->getName();
+  if (Capture.capturesThis())
+return llvm::StringRef{"this"};
+  return llvm::StringRef{"unknown"};
+}
+
+template 
+std::string joinAndTruncate(R &, size_t MaxLength,
+P &) {
+  std::string Out;
+  bool IsFirst = true;
+  for (auto & : Range) {
+if (!IsFirst)
+  Out.append(", ");
+else
+  IsFirst = false;

zyn0217 wrote:

nit: 1. We don't usually append to a string; instead, we use 
`llvm::raw_string_ostream`. 2. This whole thing can be simplified by 
[`llvm::ListSeparator`](https://github.com/llvm/llvm-project/blob/ef18986b2033a44e69b7c3553a356e9037ac1413/llvm/include/llvm/ADT/StringExtras.h#L507-L529)

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits


@@ -755,12 +807,34 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
   bool NameHint = shouldHintName(Args[I], Name);
   bool ReferenceHint = shouldHintReference(Params[I], ForwardedParams[I]);
 
+  bool IsDefault = isa(Args[I]);
+  HasNonDefaultArgs |= !IsDefault;
+  if (Cfg.InlayHints.DefaultArguments && IsDefault) {
+auto SourceText = Lexer::getSourceText(
+CharSourceRange::getTokenRange(Params[I]->getDefaultArgRange()),
+Callee.Decl->getASTContext().getSourceManager(),
+Callee.Decl->getASTContext().getLangOpts());

zyn0217 wrote:

You don't have to query `Decl::getASTContext()` for the ASTContext, we have one 
in `InlayHintVisitor`.

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 commented:

My two cents:

While I appreciate the value of inspecting more semantic information about 
lambdas, I still have mixed feelings about user experience.

Admittedly, presenting implicitly captured variables provides users with 
insight into ODR-used variables, but I'm unsure about our strategy: We would 
probably end up showing too many hints inside the lambda capture, which would 
visually elongate the lambda header and distract users from reading.

Indeed, we have a configuration entry to restrict the length, but I feel that's 
insufficient (Although we're baking it with TypeNameLimit currently, which is 
also inappropriate). For example, a user might have a lambda capturing several 
variables named in single letters e.g. a-z. As a result, we probably eventually 
display `[&: a, b, c, d, e, f, g, ...](...)`, which is IMO too spammy.

That said, I wonder if we can implement the capture stuff in hovers instead. 
>From what I can think of, we present something e.g.
```cpp
// implicitly captured by reference/copy:
int a;
std::string s;
...
```
when user hovers over the capture defaults.

(I don't have a strong opinion on the hints for default arguments. It would 
also be great to hear @HighCommander4 and @kadircet's input.)

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits


@@ -15,9 +15,12 @@
 #include "support/Context.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 #include 
+#include 

zyn0217 wrote:

What are these headers for?

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Younan Zhang via cfe-commits

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


[clang] [clang][analyzer] use unqualified canonical type during merging equivalence class (PR #95729)

2024-06-16 Thread Balazs Benics via cfe-commits

https://github.com/steakhal commented:

Awesome. I have one remark though.
It would be nice to see tests that does not depend on the errno, as this 
eqclass merging is a major vore feature, unlike the errno modeling which is an 
optional feature. If have something in mind, you could add that test in 
addition you already propose.

Again, cool stuff!

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


[clang] [llvm] [Clang][Coroutines] Improve CoroElide with [[clang::coro_structured_concurrency]] attribute for C++ (PR #94693)

2024-06-16 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> Thanks for the feedback. This patch is the first iteration to model this idea 
> as quickly as I can. In general, I agree with your comments.
> 
> > * I feel the name containing `concurrency` is not proper
> 
> The name is bikesheddable as always. I was also thinking around the line of 
> `[[clang::coro_inplace_awaitable_task]]`.
> 
> > * Every time we add or change IR related to coroutines, we need to update 
> > https://llvm.org/docs/Coroutines.html. So that we can understand the 
> > semantics of the proposed `llvm.coro.safe.elide` much easier.
> 
> Will do once we agree on a design.

It would be helpful for reviewers to understand the design ahead of time. For 
example, I can't be sure I understand your design 100% right now.

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


[clang] [llvm] [Clang][Coroutines] Improve CoroElide with [[clang::coro_structured_concurrency]] attribute for C++ (PR #94693)

2024-06-16 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> Thanks for the feedback. This patch is the first iteration to model this idea 
> as quickly as I can. In general, I agree with your comments.
> 
> > * I feel the name containing `concurrency` is not proper
> 
> The name is bikesheddable as always. I was also thinking around the line of 
> `[[clang::coro_inplace_awaitable_task]]`.
> 
> > * Every time we add or change IR related to coroutines, we need to update 
> > https://llvm.org/docs/Coroutines.html. So that we can understand the 
> > semantics of the proposed `llvm.coro.safe.elide` much easier.
> 
> Will do once we agree on a design.
> 
> > * I'd like to add a new effect to the attribute to always inline (or an 
> > inline hint) every such callee function. Note that this won't be part of 
> > semantics but the implementation details.
> 
> This is a good suggestion for the scope of another PR.
> 
> > * What I prefer is to add a middle end function attribute (must-coro-elide) 
> > and apply this attribute and (always inline attribute) to the calls
> 
> Do you mean the caller or the callee? I think both, right?

To calls. We can add attribute to calls instead of functions.

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


[clang] [llvm] [Clang][Coroutines] Improve CoroElide with [[clang::coro_structured_concurrency]] attribute for C++ (PR #94693)

2024-06-16 Thread Yuxuan Chen via cfe-commits

yuxuanchen1997 wrote:

> What I prefer is to add a middle end function attribute (must-coro-elide) and 
> apply this attribute and (always inline attribute) to the calls:

Actually this might be problematic. The same coroutine called in different 
contexts (e.g. one coroutine that is also attributed, another is a coroutine 
that does not follow the semantics of the said attribute) can have different 
elidability. We need to attribute the actual emitted `CallInst`/`InvokeInst` 
from the `CallExpr` in FE. 

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


[clang] [llvm] [Clang][Coroutines] Improve CoroElide with [[clang::coro_structured_concurrency]] attribute for C++ (PR #94693)

2024-06-16 Thread Yuxuan Chen via cfe-commits

yuxuanchen1997 wrote:

Thanks for the feedback. This patch is the first iteration to model this idea 
as quickly as I can. In general, I agree with your comments. 

> * I feel the name containing `concurrency` is not proper

The name is bikesheddable as always. I was also thinking around the line of 
`[[clang::coro_inplace_awaitable_task]]`.

> * Every time we add or change IR related to coroutines, we need to update 
> https://llvm.org/docs/Coroutines.html. So that we can understand the 
> semantics of the proposed `llvm.coro.safe.elide` much easier.

Will do once we agree on a design. 

> * I'd like to add a new effect to the attribute to always inline (or an 
> inline hint) every such callee function. Note that this won't be part of 
> semantics but the implementation details.

This is a good suggestion for the scope of another PR. 

> * What I prefer is to add a middle end function attribute (must-coro-elide) 
> and apply this attribute and (always inline attribute) to the calls

Do you mean the caller or the callee? I think both, right? 

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


[clang] [llvm] [Clang][Coroutines] Improve CoroElide with [[clang::coro_structured_concurrency]] attribute for C++ (PR #94693)

2024-06-16 Thread Yuxuan Chen via cfe-commits

yuxuanchen1997 wrote:

Thanks for the feedback. This patch is the first iteration to model this idea 
as quickly as I can. In general I agree with your comments

> * I feel the name containing `concurrency` is not proper

The name is bikesheddable as always. I was also thinking around the line of 
`[[clang::coro_inplace_awaitable_task]]`.

> * Every time we add or change IR related to coroutines, we need to update 
> https://llvm.org/docs/Coroutines.html. So that we can understand the 
> semantics of the proposed `llvm.coro.safe.elide` much easier.

Will do once we agree on a design. 

> * I'd like to add a new effect to the attribute to always inline (or an 
> inline hint) every such callee function. Note that this won't be part of 
> semantics but the implementation details.

This is a good suggestion for the scope of another PR. 

> * What I prefer is to add a middle end function attribute (must-coro-elide) 
> and apply this attribute and (always inline attribute) to the calls

Do you mean the caller or the callee? I think both, right? 

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


[clang] [Serialization] Use specialized decl hash function for GlobalDeclID (PR #95730)

2024-06-16 Thread Chuanqi Xu via cfe-commits

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


[clang] [Serialization] Use specialized decl hash function for GlobalDeclID (PR #95730)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Chuanqi Xu (ChuanqiXu9)


Changes

See the comment:
https://github.com/llvm/llvm-project/pull/92083#issuecomment-2168121729

After the patch, https://github.com/llvm/llvm-project/pull/92083, the lower 32 
bits of DeclID can be the same commonly. This may produce many collisions. It 
will be best to change the default hash implementation for uint64_t. But sent 
this one as a quick workaround.

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


1 Files Affected:

- (modified) clang/include/clang/AST/DeclID.h (+5-1) 


``diff
diff --git a/clang/include/clang/AST/DeclID.h b/clang/include/clang/AST/DeclID.h
index 32d2ed41a374a..4ad7afb463b18 100644
--- a/clang/include/clang/AST/DeclID.h
+++ b/clang/include/clang/AST/DeclID.h
@@ -230,7 +230,11 @@ template <> struct DenseMapInfo {
   }
 
   static unsigned getHashValue(const GlobalDeclID ) {
-return DenseMapInfo::getHashValue(Key.get());
+// Our default hash algorithm for 64 bits integer may not be very good.
+// In GlobalDeclID's case, it is pretty common that the lower 32 bits can
+// be same.
+return DenseMapInfo::getHashValue(Key.getModuleFileIndex()) ^
+   DenseMapInfo::getHashValue(Key.getLocalDeclIndex());
   }
 
   static bool isEqual(const GlobalDeclID , const GlobalDeclID ) {

``




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


[clang] [Serialization] Use specialized decl hash function for GlobalDeclID (PR #95730)

2024-06-16 Thread Chuanqi Xu via cfe-commits

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

See the comment:
https://github.com/llvm/llvm-project/pull/92083#issuecomment-2168121729

After the patch, https://github.com/llvm/llvm-project/pull/92083, the lower 32 
bits of DeclID can be the same commonly. This may produce many collisions. It 
will be best to change the default hash implementation for uint64_t. But sent 
this one as a quick workaround.

>From 50923aa33f09b2530cfe492a53f70296f9ce9107 Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Mon, 17 Jun 2024 11:32:35 +0800
Subject: [PATCH] [Serialization] Use specialized decl hash function for
 GlobalDeclID

See the comment:
https://github.com/llvm/llvm-project/pull/92083#issuecomment-2168121729

After the patch, https://github.com/llvm/llvm-project/pull/92083, the
lower 32 bits of DeclID can be the same commonly. This may produce many
collisions. It will be best to change the default hash implementation
for uint64_t. But sent this one as a quick workaround.
---
 clang/include/clang/AST/DeclID.h | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/AST/DeclID.h b/clang/include/clang/AST/DeclID.h
index 32d2ed41a374a..4ad7afb463b18 100644
--- a/clang/include/clang/AST/DeclID.h
+++ b/clang/include/clang/AST/DeclID.h
@@ -230,7 +230,11 @@ template <> struct DenseMapInfo {
   }
 
   static unsigned getHashValue(const GlobalDeclID ) {
-return DenseMapInfo::getHashValue(Key.get());
+// Our default hash algorithm for 64 bits integer may not be very good.
+// In GlobalDeclID's case, it is pretty common that the lower 32 bits can
+// be same.
+return DenseMapInfo::getHashValue(Key.getModuleFileIndex()) ^
+   DenseMapInfo::getHashValue(Key.getLocalDeclIndex());
   }
 
   static bool isEqual(const GlobalDeclID , const GlobalDeclID ) {

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


[clang] [Clang][AMDGPU] Add a new builtin type for buffer rsrc (PR #94830)

2024-06-16 Thread Shilei Tian via cfe-commits

https://github.com/shiltian updated 
https://github.com/llvm/llvm-project/pull/94830

>From 15ed0af5f5d23213fd4c10ff704ac26bb1b80030 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Sun, 16 Jun 2024 23:07:29 -0400
Subject: [PATCH] [Clang][AMDGPU] Add a new builtin type for buffer rsrc

---
 clang/include/clang/AST/ASTContext.h  |  2 +
 clang/include/clang/AST/Type.h|  3 +
 clang/include/clang/AST/TypeProperties.td |  4 +
 clang/include/clang/Basic/AMDGPUTypes.def | 21 +
 .../include/clang/Serialization/ASTBitCodes.h |  5 +-
 clang/lib/AST/ASTContext.cpp  | 16 
 clang/lib/AST/ASTImporter.cpp |  4 +
 clang/lib/AST/ExprConstant.cpp|  2 +
 clang/lib/AST/ItaniumMangle.cpp   |  6 ++
 clang/lib/AST/MicrosoftMangle.cpp |  2 +
 clang/lib/AST/NSAPI.cpp   |  2 +
 clang/lib/AST/PrintfFormatString.cpp  |  2 +
 clang/lib/AST/Type.cpp|  6 ++
 clang/lib/AST/TypeLoc.cpp |  2 +
 clang/lib/CodeGen/CGDebugInfo.cpp | 11 ++-
 clang/lib/CodeGen/CGDebugInfo.h   |  2 +
 clang/lib/CodeGen/CodeGenTypes.cpp|  5 ++
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |  2 +
 clang/lib/Index/USRGeneration.cpp |  4 +
 clang/lib/Sema/Sema.cpp   |  8 ++
 clang/lib/Sema/SemaExpr.cpp   |  4 +
 clang/lib/Serialization/ASTCommon.cpp |  5 ++
 clang/lib/Serialization/ASTReader.cpp |  5 ++
 clang/test/AST/ast-dump-amdgpu-types.c| 10 +++
 .../amdgpu-buffer-rsrc-type-debug-info.c  |  9 ++
 .../amdgpu-buffer-rsrc-typeinfo.cpp   |  9 ++
 .../CodeGenOpenCL/amdgcn-buffer-rsrc-type.cl  | 84 +++
 clang/test/SemaCXX/amdgpu-buffer-rsrc.cpp | 17 
 clang/tools/libclang/CIndex.cpp   |  2 +
 29 files changed, 252 insertions(+), 2 deletions(-)
 create mode 100644 clang/include/clang/Basic/AMDGPUTypes.def
 create mode 100644 clang/test/AST/ast-dump-amdgpu-types.c
 create mode 100644 clang/test/CodeGen/amdgpu-buffer-rsrc-type-debug-info.c
 create mode 100644 clang/test/CodeGenCXX/amdgpu-buffer-rsrc-typeinfo.cpp
 create mode 100644 clang/test/CodeGenOpenCL/amdgcn-buffer-rsrc-type.cl
 create mode 100644 clang/test/SemaCXX/amdgpu-buffer-rsrc.cpp

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 53ece996769a8..4d1f440506e09 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1147,6 +1147,8 @@ class ASTContext : public RefCountedBase {
 #include "clang/Basic/RISCVVTypes.def"
 #define WASM_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
 #include "clang/Basic/WebAssemblyReferenceTypes.def"
+#define AMDGPU_TYPE(Name, Id, SingletonId) CanQualType SingletonId;
+#include "clang/Basic/AMDGPUTypes.def"
 
   // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
   mutable QualType AutoDeductTy; // Deduction against 'auto'.
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index fab233b62d8d1..61246479188e9 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -3015,6 +3015,9 @@ class BuiltinType : public Type {
 // WebAssembly reference types
 #define WASM_TYPE(Name, Id, SingletonId) Id,
 #include "clang/Basic/WebAssemblyReferenceTypes.def"
+// AMDGPU types
+#define AMDGPU_TYPE(Name, Id, SingletonId) Id,
+#include "clang/Basic/AMDGPUTypes.def"
 // All other builtin types
 #define BUILTIN_TYPE(Id, SingletonId) Id,
 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
diff --git a/clang/include/clang/AST/TypeProperties.td 
b/clang/include/clang/AST/TypeProperties.td
index 40dd16f080e2e..aba14b222a03a 100644
--- a/clang/include/clang/AST/TypeProperties.td
+++ b/clang/include/clang/AST/TypeProperties.td
@@ -861,6 +861,10 @@ let Class = BuiltinType in {
   case BuiltinType::ID: return ctx.SINGLETON_ID;
 #include "clang/Basic/WebAssemblyReferenceTypes.def"
 
+#define AMDGPU_TYPE(NAME, ID, SINGLETON_ID) \
+  case BuiltinType::ID: return ctx.SINGLETON_ID;
+#include "clang/Basic/AMDGPUTypes.def"
+
 #define BUILTIN_TYPE(ID, SINGLETON_ID) \
   case BuiltinType::ID: return ctx.SINGLETON_ID;
 #include "clang/AST/BuiltinTypes.def"
diff --git a/clang/include/clang/Basic/AMDGPUTypes.def 
b/clang/include/clang/Basic/AMDGPUTypes.def
new file mode 100644
index 0..e0d7be470a325
--- /dev/null
+++ b/clang/include/clang/Basic/AMDGPUTypes.def
@@ -0,0 +1,21 @@
+//===-- AMDGPUTypes.def - Metadata about AMDGPU types ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines various AMDGPU 

[clang] [llvm] [Clang][Coroutines] Improve CoroElide with [[clang::coro_structured_concurrency]] attribute for C++ (PR #94693)

2024-06-16 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

Then we can find that the frontend part is much more complex and harder than 
the middle end part.  So maybe we can introduce the middle end part first and 
introduce a not so powerful attribute but introducing a function and statement 
level attribute `must_elide` in the beginning.

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


[clang] [llvm] [Clang][Coroutines] Improve CoroElide with [[clang::coro_structured_concurrency]] attribute for C++ (PR #94693)

2024-06-16 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

Thanks for the patch. I like it in the very high level. I did a quick scanning 
over the PR  and here is some comments:

- I feel the name containing `concurrency` is not proper. I don't feel it 
relates concurrency in any level.
- Every time we add or change IR related to coroutines, we need to update 
https://llvm.org/docs/Coroutines.html. So that we can understand the semantics 
of the proposed `llvm.coro.safe.elide` much easier.
- I'd like to add a new effect to the attribute to always inline (or an inline 
hint) every such callee function. Note that this won't be part of semantics but 
the implementation details.

For implementations,

- It looks like the argument of `llvm.coro.safe.elide` is the object. This is 
not good. The object is the concept in the higher level language but not the 
middle end language.
- What I prefer is to add a middle end function attribute (`must-coro-elide`) 
and apply this attribute and (always inline attribute) to the calls:
- In the inliner, when we inlined a call with attribute `must-coro-elide`, 
we can add the attribute again to inlined intrinsics `llvm.coro.id`.
- Then in the coro elider, we can decide whether or not to elide the 
specific corotuines by judging if the `llvm.coro.id` has the attribute very 
easily.

For FE implementation,
- To implement the semantics precisely, I think we have to touch the Parser and 
the Sema.  Otherwise, it may be pretty tricky to handle cases like `co_await 
foo(bar(...))` or `co_await (foo() + bar());`. It is hacky to implement this in 
CodeGen.

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


[clang] [clang][analyzer] use unqualified canonical type during merging equivalence class (PR #95729)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




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

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #95658
Unqualified canonical type should be used instead of normal QualType for type 
equality comparison


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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp (+2-1) 
- (modified) clang/test/Analysis/errno-stdlibraryfunctions.c (+24) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
index c6f87b45ab887..d8c257dbd731e 100644
--- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -2333,7 +2333,8 @@ inline ProgramStateRef 
EquivalenceClass::merge(RangeSet::Factory ,
   //
   //The moment we introduce symbolic casts, this restriction can be
   //lifted.
-  if (getType() != Other.getType())
+  if (getType()->getCanonicalTypeUnqualified() !=
+  Other.getType()->getCanonicalTypeUnqualified())
 return State;
 
   SymbolSet Members = getClassMembers(State);
diff --git a/clang/test/Analysis/errno-stdlibraryfunctions.c 
b/clang/test/Analysis/errno-stdlibraryfunctions.c
index a28efb764edfd..657aa37a42670 100644
--- a/clang/test/Analysis/errno-stdlibraryfunctions.c
+++ b/clang/test/Analysis/errno-stdlibraryfunctions.c
@@ -75,6 +75,30 @@ void errno_mkdtemp(char *template) {
   }
 }
 
+typedef char* CHAR_PTR;
+void errno_mkdtemp2(CHAR_PTR template) {
+  CHAR_PTR Dir = mkdtemp(template);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}
+if (errno) {} // no warning
+  } else {
+clang_analyzer_eval(Dir == template); // expected-warning{{TRUE}}
+if (errno) {} // expected-warning{{An undefined 
value may be read from 'errno'}}
+  }
+}
+
+typedef char const* CONST_CHAR_PTR;
+void errno_mkdtemp3(CHAR_PTR template) {
+  CONST_CHAR_PTR Dir = mkdtemp(template);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}
+if (errno) {} // no warning
+  } else {
+clang_analyzer_eval(Dir == template); // expected-warning{{TRUE}}
+if (errno) {} // expected-warning{{An undefined 
value may be read from 'errno'}}
+  }
+}
+
 void errno_getcwd(char *Buf, size_t Sz) {
   char *Path = getcwd(Buf, Sz);
   if (Sz == 0) {

``




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


[clang] [clang][analyzer] use unqualified canonical type during merging equivalence class (PR #95729)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #95658
Unqualified canonical type should be used instead of normal QualType for type 
equality comparison


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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp (+2-1) 
- (modified) clang/test/Analysis/errno-stdlibraryfunctions.c (+24) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
index c6f87b45ab887..d8c257dbd731e 100644
--- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -2333,7 +2333,8 @@ inline ProgramStateRef 
EquivalenceClass::merge(RangeSet::Factory ,
   //
   //The moment we introduce symbolic casts, this restriction can be
   //lifted.
-  if (getType() != Other.getType())
+  if (getType()->getCanonicalTypeUnqualified() !=
+  Other.getType()->getCanonicalTypeUnqualified())
 return State;
 
   SymbolSet Members = getClassMembers(State);
diff --git a/clang/test/Analysis/errno-stdlibraryfunctions.c 
b/clang/test/Analysis/errno-stdlibraryfunctions.c
index a28efb764edfd..657aa37a42670 100644
--- a/clang/test/Analysis/errno-stdlibraryfunctions.c
+++ b/clang/test/Analysis/errno-stdlibraryfunctions.c
@@ -75,6 +75,30 @@ void errno_mkdtemp(char *template) {
   }
 }
 
+typedef char* CHAR_PTR;
+void errno_mkdtemp2(CHAR_PTR template) {
+  CHAR_PTR Dir = mkdtemp(template);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}
+if (errno) {} // no warning
+  } else {
+clang_analyzer_eval(Dir == template); // expected-warning{{TRUE}}
+if (errno) {} // expected-warning{{An undefined 
value may be read from 'errno'}}
+  }
+}
+
+typedef char const* CONST_CHAR_PTR;
+void errno_mkdtemp3(CHAR_PTR template) {
+  CONST_CHAR_PTR Dir = mkdtemp(template);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}
+if (errno) {} // no warning
+  } else {
+clang_analyzer_eval(Dir == template); // expected-warning{{TRUE}}
+if (errno) {} // expected-warning{{An undefined 
value may be read from 'errno'}}
+  }
+}
+
 void errno_getcwd(char *Buf, size_t Sz) {
   char *Path = getcwd(Buf, Sz);
   if (Sz == 0) {

``




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


[clang] [clang][analyzer] use unqualified canonical type during merging equivalence class (PR #95729)

2024-06-16 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/95729

Fixes: #95658
Unqualified canonical type should be used instead of normal QualType for type 
equality comparison


>From 40f18f2be624ed2a5b4922e67e4ed6070d2d2400 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Mon, 17 Jun 2024 00:13:20 +
Subject: [PATCH] [clang][analyzer] use unqualified canonical type during
 merging equivalence class

Fixes: #95658
Unqualified canonical type should be used instead of normal QualType for type 
equality comparison
---
 .../Core/RangeConstraintManager.cpp   |  3 ++-
 .../test/Analysis/errno-stdlibraryfunctions.c | 24 +++
 2 files changed, 26 insertions(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
index c6f87b45ab887..d8c257dbd731e 100644
--- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -2333,7 +2333,8 @@ inline ProgramStateRef 
EquivalenceClass::merge(RangeSet::Factory ,
   //
   //The moment we introduce symbolic casts, this restriction can be
   //lifted.
-  if (getType() != Other.getType())
+  if (getType()->getCanonicalTypeUnqualified() !=
+  Other.getType()->getCanonicalTypeUnqualified())
 return State;
 
   SymbolSet Members = getClassMembers(State);
diff --git a/clang/test/Analysis/errno-stdlibraryfunctions.c 
b/clang/test/Analysis/errno-stdlibraryfunctions.c
index a28efb764edfd..657aa37a42670 100644
--- a/clang/test/Analysis/errno-stdlibraryfunctions.c
+++ b/clang/test/Analysis/errno-stdlibraryfunctions.c
@@ -75,6 +75,30 @@ void errno_mkdtemp(char *template) {
   }
 }
 
+typedef char* CHAR_PTR;
+void errno_mkdtemp2(CHAR_PTR template) {
+  CHAR_PTR Dir = mkdtemp(template);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}
+if (errno) {} // no warning
+  } else {
+clang_analyzer_eval(Dir == template); // expected-warning{{TRUE}}
+if (errno) {} // expected-warning{{An undefined 
value may be read from 'errno'}}
+  }
+}
+
+typedef char const* CONST_CHAR_PTR;
+void errno_mkdtemp3(CHAR_PTR template) {
+  CONST_CHAR_PTR Dir = mkdtemp(template);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0);  // expected-warning{{TRUE}}
+if (errno) {} // no warning
+  } else {
+clang_analyzer_eval(Dir == template); // expected-warning{{TRUE}}
+if (errno) {} // expected-warning{{An undefined 
value may be read from 'errno'}}
+  }
+}
+
 void errno_getcwd(char *Buf, size_t Sz) {
   char *Path = getcwd(Buf, Sz);
   if (Sz == 0) {

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


[clang] 15bb026 - [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (#75912)

2024-06-16 Thread via cfe-commits

Author: Chuanqi Xu
Date: 2024-06-17T10:25:35+08:00
New Revision: 15bb02650e26875c48889053d6a9697444583721

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

LOG: [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of 
dynamic classes (#75912)

Close https://github.com/llvm/llvm-project/issues/70585 and reflect
https://github.com/itanium-cxx-abi/cxx-abi/issues/170.

The significant change of the patch is: for dynamic classes attached to
module units, we generate the vtable to the attached module units
directly and the key functions for such classes is meaningless.

Added: 
clang/test/CodeGenCXX/pr70585.cppm

Modified: 
clang/include/clang/AST/DeclBase.h
clang/include/clang/Serialization/ASTBitCodes.h
clang/include/clang/Serialization/ASTReader.h
clang/include/clang/Serialization/ASTWriter.h
clang/lib/AST/DeclBase.cpp
clang/lib/CodeGen/CGVTables.cpp
clang/lib/CodeGen/ItaniumCXXABI.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Serialization/ASTWriterDecl.cpp
clang/test/CodeGenCXX/modules-vtable.cppm

Removed: 




diff  --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 5f19af1891b74..3310f57acc683 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -670,6 +670,9 @@ class alignas(8) Decl {
   /// Whether this declaration comes from another module unit.
   bool isInAnotherModuleUnit() const;
 
+  /// Whether this declaration comes from the same module unit being compiled.
+  bool isInCurrentModuleUnit() const;
+
   /// Whether the definition of the declaration should be emitted in external
   /// sources.
   bool shouldEmitInExternalSource() const;

diff  --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index 4ce6cd74dd834..a4728b1c06b3f 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -697,6 +697,9 @@ enum ASTRecordTypes {
 
   /// Record code for \#pragma clang unsafe_buffer_usage begin/end
   PP_UNSAFE_BUFFER_USAGE = 69,
+
+  /// Record code for vtables to emit.
+  VTABLES_TO_EMIT = 70,
 };
 
 /// Record types used within a source manager block.

diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 0a9006223dcbd..08f302c01f538 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -805,6 +805,11 @@ class ASTReader
   /// the consumer eagerly.
   SmallVector EagerlyDeserializedDecls;
 
+  /// The IDs of all vtables to emit. The referenced declarations are passed
+  /// to the consumers's HandleVTable eagerly after passing
+  /// EagerlyDeserializedDecls.
+  SmallVector VTablesToEmit;
+
   /// The IDs of all tentative definitions stored in the chain.
   ///
   /// Sema keeps track of all tentative definitions in a TU because it has to
@@ -1514,6 +1519,7 @@ class ASTReader
   bool isConsumerInterestedIn(Decl *D);
   void PassInterestingDeclsToConsumer();
   void PassInterestingDeclToConsumer(Decl *D);
+  void PassVTableToConsumer(CXXRecordDecl *RD);
 
   void finishPendingActions();
   void diagnoseOdrViolations();

diff  --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index fcc007d6f8637..e66b675510179 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -495,6 +495,10 @@ class ASTWriter : public ASTDeserializationListener,
   std::vector NonAffectingRanges;
   std::vector NonAffectingOffsetAdjustments;
 
+  /// A list of classes which need to emit the VTable in the corresponding
+  /// object file.
+  llvm::SmallVector PendingEmittingVTables;
+
   /// Computes input files that didn't affect compilation of the current 
module,
   /// and initializes data structures necessary for leaving those files out
   /// during \c SourceManager serialization.
@@ -849,6 +853,8 @@ class ASTWriter : public ASTDeserializationListener,
 
   bool getDoneWritingDeclsAndTypes() const { return DoneWritingDeclsAndTypes; }
 
+  void handleVTable(CXXRecordDecl *RD);
+
 private:
   // ASTDeserializationListener implementation
   void ReaderInitialized(ASTReader *Reader) override;
@@ -943,6 +949,7 @@ class PCHGenerator : public SemaConsumer {
 
   void InitializeSema(Sema ) override { SemaPtr =  }
   void HandleTranslationUnit(ASTContext ) override;
+  void HandleVTable(CXXRecordDecl *RD) override { Writer.handleVTable(RD); }
   ASTMutationListener 

[clang] [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (PR #75912)

2024-06-16 Thread Chuanqi Xu via cfe-commits

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


[clang] [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (PR #75912)

2024-06-16 Thread Chuanqi Xu via cfe-commits


@@ -6853,6 +6853,7 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
   DI->completeUnusedClass(*CRD);
 }
+

ChuanqiXu9 wrote:

Done

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


[clang] [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (PR #75912)

2024-06-16 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/75912

>From 4b595ee5b7a5fefb1e9ec0a152bce587ba463b4b Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Tue, 19 Dec 2023 17:00:59 +0800
Subject: [PATCH 1/8] [C++20] [Modules] [Itanium ABI] Generate the vtable in
 the module unit of dynamic classes

Close https://github.com/llvm/llvm-project/issues/70585 and reflect
https://github.com/itanium-cxx-abi/cxx-abi/issues/170.

The significant change of the patch is: for dynamic classes attached to
module units, we generate the vtable to the attached module units
directly and the key functions for such classes is meaningless.
---
 clang/include/clang/AST/DeclBase.h|  3 ++
 clang/lib/AST/DeclBase.cpp|  9 +
 clang/lib/CodeGen/CGVTables.cpp   | 28 ++
 clang/lib/CodeGen/CodeGenModule.cpp   |  7 
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |  3 ++
 clang/lib/Sema/SemaDecl.cpp   |  9 +
 clang/lib/Sema/SemaDeclCXX.cpp| 12 --
 clang/lib/Serialization/ASTReaderDecl.cpp |  6 +++
 clang/lib/Serialization/ASTWriterDecl.cpp |  6 +++
 clang/test/CodeGenCXX/modules-vtable.cppm | 31 +--
 clang/test/CodeGenCXX/pr70585.cppm| 47 +++
 11 files changed, 138 insertions(+), 23 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/pr70585.cppm

diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 5f19af1891b74..3310f57acc683 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -670,6 +670,9 @@ class alignas(8) Decl {
   /// Whether this declaration comes from another module unit.
   bool isInAnotherModuleUnit() const;
 
+  /// Whether this declaration comes from the same module unit being compiled.
+  bool isInCurrentModuleUnit() const;
+
   /// Whether the definition of the declaration should be emitted in external
   /// sources.
   bool shouldEmitInExternalSource() const;
diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index e64a8326e8d5d..78768792f1032 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -1128,6 +1128,15 @@ bool Decl::isInAnotherModuleUnit() const {
   return M != getASTContext().getCurrentNamedModule();
 }
 
+bool Decl::isInCurrentModuleUnit() const {
+  auto *M = getOwningModule();
+
+  if (!M || !M->isNamedModule())
+return false;
+
+  return M == getASTContext().getCurrentNamedModule();
+}
+
 bool Decl::shouldEmitInExternalSource() const {
   ExternalASTSource *Source = getASTContext().getExternalSource();
   if (!Source)
diff --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index 001633453f242..55c3032dc9332 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -1051,6 +1051,11 @@ CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) 
{
   if (!RD->isExternallyVisible())
 return llvm::GlobalVariable::InternalLinkage;
 
+  // V-tables for non-template classes with an owning module are always
+  // uniquely emitted in that module.
+  if (RD->isInNamedModule())
+return llvm::GlobalVariable::ExternalLinkage;
+
   // We're at the end of the translation unit, so the current key
   // function is fully correct.
   const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
@@ -1185,6 +1190,21 @@ bool CodeGenVTables::isVTableExternal(const 
CXXRecordDecl *RD) {
   TSK == TSK_ExplicitInstantiationDefinition)
 return false;
 
+  // Itanium C++ ABI [5.2.3]:
+  // Virtual tables for dynamic classes are emitted as follows:
+  //
+  // - If the class is templated, the tables are emitted in every object that
+  // references any of them.
+  // - Otherwise, if the class is attached to a module, the tables are uniquely
+  // emitted in the object for the module unit in which it is defined.
+  // - Otherwise, if the class has a key function (see below), the tables are
+  // emitted in the object for the translation unit containing the definition 
of
+  // the key function. This is unique if the key function is not inline.
+  // - Otherwise, the tables are emitted in every object that references any of
+  // them.
+  if (RD->isInNamedModule())
+return RD->shouldEmitInExternalSource();
+
   // Otherwise, if the class doesn't have a key function (possibly
   // anymore), the vtable must be defined here.
   const CXXMethodDecl *keyFunction = 
CGM.getContext().getCurrentKeyFunction(RD);
@@ -1194,13 +1214,7 @@ bool CodeGenVTables::isVTableExternal(const 
CXXRecordDecl *RD) {
   const FunctionDecl *Def;
   // Otherwise, if we don't have a definition of the key function, the
   // vtable must be defined somewhere else.
-  if (!keyFunction->hasBody(Def))
-return true;
-
-  assert(Def && "The body of the key function is not assigned to Def?");
-  // If the non-inline key function comes from another module unit, the vtable
-  // must be defined there.
-  return 

[clang] [C++20] [Modules] [Itanium ABI] Generate the vtable in the module unit of dynamic classes (PR #75912)

2024-06-16 Thread Chuanqi Xu via cfe-commits


@@ -318,6 +318,9 @@ namespace {
   if (Diags.hasUnrecoverableErrorOccurred())
 return;
 
+  if (RD->shouldEmitInExternalSource())

ChuanqiXu9 wrote:

Thanks. It makes sense.

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


[clang] [serialization] no transitive decl change (PR #92083)

2024-06-16 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> I got to the bottom of it. The problem is that our hash function for 64 bit 
> ints is [not very 
> good](https://github.com/llvm/llvm-project/blob/d5297b72aa32ad3a69563a1fcc61294282f0b379/llvm/include/llvm/ADT/DenseMapInfo.h#L140).
> 
> It will have a lot of collision when lower 32 bits are the same and the 
> higher 32 bits of a 64 bit value change. Coincidentally, this is quite common 
> in this case because collisions in low bits of `GlobalDeclID` are very much 
> expected.
> 
> I tried replacing it with a variant of MurmurHash I found randomly on the 
> internet and performance went back to normal. @ChuanqiXu9 I think changing 
> the default hash function for ints might have some far-reaching effects for 
> LLVM code using `DenseSet` and would warrant a bigger discussion on what that 
> function should be (I am not an expert in hash functions myself). I will be 
> happy to start that discussion on Monday, but feel free to jump into it 
> earlier, if you have time.
> 
> In the meantime, I would again propose to revert the change until we can fix 
> the hash function. (Alternatively, we can change the hash function for 
> `GlobalDeclID` specifically to workaround more locally, but we surely want a 
> better hash function for uint64 in general)

Thanks for the analysis. It's pretty helpful. For reverting, on the one hand, 
we've already targeted the root issue. I think then it is not so rationale to 
me to block the patch to problems in that level. On the other hand, (I think) 
the patch (series) is pretty important for named modules (and probably clang 
explicit modules). And I really want to make that in 19. Given 19 is going to 
be branched in the end of the next month. From my experience, it is not very 
hopeful to land such a fundamental change quickly. So I propose to change the 
hash function in Serialization locally as a workaround and propose a discussion 
about replacing the hash function in discussion parallelly.

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


[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread via cfe-commits

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


[clang] ef18986 - [clang-format] Handle Verilog delay control (#95703)

2024-06-16 Thread via cfe-commits

Author: sstwcw
Date: 2024-06-17T01:46:04Z
New Revision: ef18986b2033a44e69b7c3553a356e9037ac1413

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

LOG: [clang-format] Handle Verilog delay control (#95703)

I made a mistake when I tried to make the code handle the backtick
character like the hash character.  The code did not recognize the delay
control structure.  It caused net names in the declaration to be aligned
to the type name instead of the first net name.

new

```Verilog
wire logic #0 mynet, //
  mynet1;
```

old

```Verilog
wire logic #0 mynet, //
 mynet1;
```

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestVerilog.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1332445070314..e5fa997387d8b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3414,7 +3414,8 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
+  } else if (Tok->is(Keywords.kw_verilogHash)) {
+// Delay control.
 if (Next->is(tok::l_paren))
   Next = Next->MatchingParen;
 if (Next)

diff  --git a/clang/unittests/Format/FormatTestVerilog.cpp 
b/clang/unittests/Format/FormatTestVerilog.cpp
index b5241a4e0d6ae..fbaf289fbc4d6 100644
--- a/clang/unittests/Format/FormatTestVerilog.cpp
+++ b/clang/unittests/Format/FormatTestVerilog.cpp
@@ -391,6 +391,15 @@ TEST_F(FormatTestVerilog, Declaration) {
   verifyFormat("wire mynet, mynet1;");
   verifyFormat("wire mynet, //\n"
" mynet1;");
+  verifyFormat("wire #0 mynet, mynet1;");
+  verifyFormat("wire logic #0 mynet, mynet1;");
+  verifyFormat("wire #(1, 2, 3) mynet, mynet1;");
+  verifyFormat("wire #0 mynet, //\n"
+   "mynet1;");
+  verifyFormat("wire logic #0 mynet, //\n"
+   "  mynet1;");
+  verifyFormat("wire #(1, 2, 3) mynet, //\n"
+   "mynet1;");
   verifyFormat("wire mynet = enable;");
   verifyFormat("wire mynet = enable, mynet1;");
   verifyFormat("wire mynet = enable, //\n"



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


[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread via cfe-commits

https://github.com/sstwcw updated 
https://github.com/llvm/llvm-project/pull/95703

>From ef18986b2033a44e69b7c3553a356e9037ac1413 Mon Sep 17 00:00:00 2001
From: sstwcw 
Date: Sun, 16 Jun 2024 13:04:27 +
Subject: [PATCH] [clang-format] Handle Verilog delay control (#95703)

I made a mistake when I tried to make the code handle the backtick
character like the hash character.  The code did not recognize the delay
control structure.  It caused net names in the declaration to be aligned
to the type name instead of the first net name.

new

```Verilog
wire logic #0 mynet, //
  mynet1;
```

old

```Verilog
wire logic #0 mynet, //
 mynet1;
```
---
 clang/lib/Format/TokenAnnotator.cpp  | 3 ++-
 clang/unittests/Format/FormatTestVerilog.cpp | 9 +
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1332445070314..e5fa997387d8b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3414,7 +3414,8 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
+  } else if (Tok->is(Keywords.kw_verilogHash)) {
+// Delay control.
 if (Next->is(tok::l_paren))
   Next = Next->MatchingParen;
 if (Next)
diff --git a/clang/unittests/Format/FormatTestVerilog.cpp 
b/clang/unittests/Format/FormatTestVerilog.cpp
index b5241a4e0d6ae..fbaf289fbc4d6 100644
--- a/clang/unittests/Format/FormatTestVerilog.cpp
+++ b/clang/unittests/Format/FormatTestVerilog.cpp
@@ -391,6 +391,15 @@ TEST_F(FormatTestVerilog, Declaration) {
   verifyFormat("wire mynet, mynet1;");
   verifyFormat("wire mynet, //\n"
" mynet1;");
+  verifyFormat("wire #0 mynet, mynet1;");
+  verifyFormat("wire logic #0 mynet, mynet1;");
+  verifyFormat("wire #(1, 2, 3) mynet, mynet1;");
+  verifyFormat("wire #0 mynet, //\n"
+   "mynet1;");
+  verifyFormat("wire logic #0 mynet, //\n"
+   "  mynet1;");
+  verifyFormat("wire #(1, 2, 3) mynet, //\n"
+   "mynet1;");
   verifyFormat("wire mynet = enable;");
   verifyFormat("wire mynet = enable, mynet1;");
   verifyFormat("wire mynet = enable, //\n"

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


[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)

2024-06-16 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

> Hi @jcsxky , I fetched and rebased to origin/main just now (6/16/2024 at 
> 4:30pm Central US time), and rebuilt - and I see the crash. Did you try 
> rebasing to latest source and rebuilding?
> 
> `$ clang --analyze -Xclang -analyzer-config -Xclang 
> experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
> ctu-dir=ctudir -Xclang -analyzer-config -Xclang display-ctu-progress=true 
> test.cpp` `CTU loaded AST file: bstrwrap.cpp.ast` `clang: 
> clang/lib/AST/Decl.cpp:4045: void 
> clang::FunctionDecl::setDescribedFunctionTemplate(clang::FunctionTemplateDecl*):
>  Assertion "TemplateOrSpecialization.isNull() && "Member function is already 
> a specialization" failed.` `PLEASE submit a bug report to 
> https://github.com/llvm/llvm-project/issues/ and include the crash backtrace, 
> preprocessed source, and associated run script.`
> 
> ...

Yes, I have tried the latest source, but it still looks good. Also, I didn't 
see the output `CTU loaded AST file: bstrwrap.cpp.ast`. I tried this command 
`clang-extdef-mapping test.cpp` and output is `11:c:@F@test0#` which is 
different from yours(`f` and `F`, output of the other file is identical). This 
time I see `CTU loaded AST file: bstrwrap.cpp.ast` but still has no crash. 
@vabridgers Can you check your output with command `clang-extdef-mapping 
test.cpp`?

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


[clang] [clang][CodeGen] Add query for a target's flat address space (PR #95728)

2024-06-16 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx updated 
https://github.com/llvm/llvm-project/pull/95728

>From 2b500ad9ef2baf27da29146b5a4123dcb75e Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Mon, 17 Jun 2024 02:15:00 +0100
Subject: [PATCH] Add interface for exposing a target's flat address space, if
 it exists.

---
 clang/include/clang/Basic/TargetInfo.h | 7 +++
 clang/lib/Basic/Targets/AMDGPU.h   | 6 ++
 clang/lib/Basic/Targets/SPIR.h | 4 
 3 files changed, 17 insertions(+)

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 8a6511b9ced83..8841ec5f910d9 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1764,6 +1764,13 @@ class TargetInfo : public TransferrableTargetInfo,
 return 0;
   }
 
+  /// \returns Target specific flat ptr address space; a flat ptr is a ptr that
+  /// can be casted to / from all other target address spaces. If the target
+  /// exposes no such address space / does not care, we return 0.
+  virtual unsigned getFlatPtrAddressSpace() const {
+return 0;
+  }
+
   /// \returns If a target requires an address within a target specific address
   /// space \p AddressSpace to be converted in order to be used, then return 
the
   /// corresponding target specific DWARF address space.
diff --git a/clang/lib/Basic/Targets/AMDGPU.h b/clang/lib/Basic/Targets/AMDGPU.h
index 94d9ba93ed226..d06c7d58fe94c 100644
--- a/clang/lib/Basic/Targets/AMDGPU.h
+++ b/clang/lib/Basic/Targets/AMDGPU.h
@@ -379,6 +379,12 @@ class LLVM_LIBRARY_VISIBILITY AMDGPUTargetInfo final : 
public TargetInfo {
 return static_cast(llvm::AMDGPUAS::CONSTANT_ADDRESS);
   }
 
+  /// \returns Target specific flat ptr address space; a flat ptr is a ptr that
+  /// can be casted to / from all other target address spaces.
+  unsigned getFlatPtrAddressSpace() const override {
+return static_cast(llvm::AMDGPUAS::FLAT_ADDRESS);
+  }
+
   /// \returns If a target requires an address within a target specific address
   /// space \p AddressSpace to be converted in order to be used, then return 
the
   /// corresponding target specific DWARF address space.
diff --git a/clang/lib/Basic/Targets/SPIR.h b/clang/lib/Basic/Targets/SPIR.h
index 37cf9d7921bac..14d235bace960 100644
--- a/clang/lib/Basic/Targets/SPIR.h
+++ b/clang/lib/Basic/Targets/SPIR.h
@@ -182,6 +182,10 @@ class LLVM_LIBRARY_VISIBILITY BaseSPIRTargetInfo : public 
TargetInfo {
 return TargetInfo::VoidPtrBuiltinVaList;
   }
 
+  unsigned getFlatPtrAddressSpace() const override {
+return 4u; // 4 is generic i.e. flat for SPIR & SPIR-V.
+  }
+
   std::optional
   getDWARFAddressSpace(unsigned AddressSpace) const override {
 return AddressSpace;

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


[clang] [clang][CodeGen] Add query for a target's flat address space (PR #95728)

2024-06-16 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 527e7328607ea0a55855e53a59c5030a7d07a554 
2b500ad9ef2baf27da29146b5a4123dcb75e -- 
clang/include/clang/Basic/TargetInfo.h clang/lib/Basic/Targets/AMDGPU.h 
clang/lib/Basic/Targets/SPIR.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 8841ec5f91..a3b60db122 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1767,9 +1767,7 @@ public:
   /// \returns Target specific flat ptr address space; a flat ptr is a ptr that
   /// can be casted to / from all other target address spaces. If the target
   /// exposes no such address space / does not care, we return 0.
-  virtual unsigned getFlatPtrAddressSpace() const {
-return 0;
-  }
+  virtual unsigned getFlatPtrAddressSpace() const { return 0; }
 
   /// \returns If a target requires an address within a target specific address
   /// space \p AddressSpace to be converted in order to be used, then return 
the

``




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


[clang] [clang][CodeGen] Add query for a target's flat address space (PR #95728)

2024-06-16 Thread Alex Voicu via cfe-commits

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


[clang] [clang][CodeGen] Add query for a target's flat address space (PR #95728)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alex Voicu (AlexVlx)


Changes

Often, targets which are not address space agnostic expose a flat/generic 
address space, which acts as a shared, legal target for address space casts. 
Whilst today we accidentally (e.g. by using `PointerType::getUnqual`) treat 0 
as corresponding to this flat address space, there is no binding requirement 
placed on targets in this regard, which leads to issues such as those reflected 
in #93601 and #93914. This patch adds a 
`getFlatPtrAddressSpace()` interface in `TargetInfo`, allowing targets to 
inform the front-end. A possible alternative name would be 
`getGenericPtrAddressSpace()`, but that was not chosen since generic has a 
fairly specific meaning in C++ and it seemed somewhat confusing in this context.

The interface is not used anywhere at the moment, but the intention is to 
employ it, for example, to specify the pointer type for the `llvm.used` array's 
elements.

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


3 Files Affected:

- (modified) clang/include/clang/Basic/TargetInfo.h (+7) 
- (modified) clang/lib/Basic/Targets/AMDGPU.h (+6) 
- (modified) clang/lib/Basic/Targets/SPIR.h (+4) 


``diff
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 8a6511b9ced83..8841ec5f910d9 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1764,6 +1764,13 @@ class TargetInfo : public TransferrableTargetInfo,
 return 0;
   }
 
+  /// \returns Target specific flat ptr address space; a flat ptr is a ptr that
+  /// can be casted to / from all other target address spaces. If the target
+  /// exposes no such address space / does not care, we return 0.
+  virtual unsigned getFlatPtrAddressSpace() const {
+return 0;
+  }
+
   /// \returns If a target requires an address within a target specific address
   /// space \p AddressSpace to be converted in order to be used, then return 
the
   /// corresponding target specific DWARF address space.
diff --git a/clang/lib/Basic/Targets/AMDGPU.h b/clang/lib/Basic/Targets/AMDGPU.h
index 94d9ba93ed226..d06c7d58fe94c 100644
--- a/clang/lib/Basic/Targets/AMDGPU.h
+++ b/clang/lib/Basic/Targets/AMDGPU.h
@@ -379,6 +379,12 @@ class LLVM_LIBRARY_VISIBILITY AMDGPUTargetInfo final : 
public TargetInfo {
 return static_cast(llvm::AMDGPUAS::CONSTANT_ADDRESS);
   }
 
+  /// \returns Target specific flat ptr address space; a flat ptr is a ptr that
+  /// can be casted to / from all other target address spaces.
+  unsigned getFlatPtrAddressSpace() const override {
+return static_cast(llvm::AMDGPUAS::FLAT_ADDRESS);
+  }
+
   /// \returns If a target requires an address within a target specific address
   /// space \p AddressSpace to be converted in order to be used, then return 
the
   /// corresponding target specific DWARF address space.
diff --git a/clang/lib/Basic/Targets/SPIR.h b/clang/lib/Basic/Targets/SPIR.h
index 37cf9d7921bac..14d235bace960 100644
--- a/clang/lib/Basic/Targets/SPIR.h
+++ b/clang/lib/Basic/Targets/SPIR.h
@@ -182,6 +182,10 @@ class LLVM_LIBRARY_VISIBILITY BaseSPIRTargetInfo : public 
TargetInfo {
 return TargetInfo::VoidPtrBuiltinVaList;
   }
 
+  unsigned getFlatPtrAddressSpace() const override {
+return 4u; // 4 is generic i.e. flat for SPIR & SPIR-V.
+  }
+
   std::optional
   getDWARFAddressSpace(unsigned AddressSpace) const override {
 return AddressSpace;

``




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


[clang] [clang][CodeGen] Add query for a target's flat address space (PR #95728)

2024-06-16 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx created 
https://github.com/llvm/llvm-project/pull/95728

Often, targets which are not address space agnostic expose a flat/generic 
address space, which acts as a shared, legal target for address space casts. 
Whilst today we accidentally (e.g. by using `PointerType::getUnqual`) treat 0 
as corresponding to this flat address space, there is no binding requirement 
placed on targets in this regard, which leads to issues such as those reflected 
in #93601 and #93914. This patch adds a `getFlatPtrAddressSpace()` interface in 
`TargetInfo`, allowing targets to inform the front-end. A possible alternative 
name would be `getGenericPtrAddressSpace()`, but that was not chosen since 
generic has a fairly specific meaning in C++ and it seemed somewhat confusing 
in this context.

The interface is not used anywhere at the moment, but the intention is to 
employ it, for example, to specify the pointer type for the `llvm.used` array's 
elements.

>From 2b500ad9ef2baf27da29146b5a4123dcb75e Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Mon, 17 Jun 2024 02:15:00 +0100
Subject: [PATCH] Add interface for exposing a target's flat address space, if
 it exists.

---
 clang/include/clang/Basic/TargetInfo.h | 7 +++
 clang/lib/Basic/Targets/AMDGPU.h   | 6 ++
 clang/lib/Basic/Targets/SPIR.h | 4 
 3 files changed, 17 insertions(+)

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 8a6511b9ced83..8841ec5f910d9 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1764,6 +1764,13 @@ class TargetInfo : public TransferrableTargetInfo,
 return 0;
   }
 
+  /// \returns Target specific flat ptr address space; a flat ptr is a ptr that
+  /// can be casted to / from all other target address spaces. If the target
+  /// exposes no such address space / does not care, we return 0.
+  virtual unsigned getFlatPtrAddressSpace() const {
+return 0;
+  }
+
   /// \returns If a target requires an address within a target specific address
   /// space \p AddressSpace to be converted in order to be used, then return 
the
   /// corresponding target specific DWARF address space.
diff --git a/clang/lib/Basic/Targets/AMDGPU.h b/clang/lib/Basic/Targets/AMDGPU.h
index 94d9ba93ed226..d06c7d58fe94c 100644
--- a/clang/lib/Basic/Targets/AMDGPU.h
+++ b/clang/lib/Basic/Targets/AMDGPU.h
@@ -379,6 +379,12 @@ class LLVM_LIBRARY_VISIBILITY AMDGPUTargetInfo final : 
public TargetInfo {
 return static_cast(llvm::AMDGPUAS::CONSTANT_ADDRESS);
   }
 
+  /// \returns Target specific flat ptr address space; a flat ptr is a ptr that
+  /// can be casted to / from all other target address spaces.
+  unsigned getFlatPtrAddressSpace() const override {
+return static_cast(llvm::AMDGPUAS::FLAT_ADDRESS);
+  }
+
   /// \returns If a target requires an address within a target specific address
   /// space \p AddressSpace to be converted in order to be used, then return 
the
   /// corresponding target specific DWARF address space.
diff --git a/clang/lib/Basic/Targets/SPIR.h b/clang/lib/Basic/Targets/SPIR.h
index 37cf9d7921bac..14d235bace960 100644
--- a/clang/lib/Basic/Targets/SPIR.h
+++ b/clang/lib/Basic/Targets/SPIR.h
@@ -182,6 +182,10 @@ class LLVM_LIBRARY_VISIBILITY BaseSPIRTargetInfo : public 
TargetInfo {
 return TargetInfo::VoidPtrBuiltinVaList;
   }
 
+  unsigned getFlatPtrAddressSpace() const override {
+return 4u; // 4 is generic i.e. flat for SPIR & SPIR-V.
+  }
+
   std::optional
   getDWARFAddressSpace(unsigned AddressSpace) const override {
 return AddressSpace;

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


[clang] [clang-format][NFC] Add FormatToken::isAccessSpecifierKeyword() (PR #95727)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes



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


3 Files Affected:

- (modified) clang/lib/Format/FormatToken.h (+11-9) 
- (modified) clang/lib/Format/TokenAnnotator.cpp (+21-23) 
- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+11-12) 


``diff
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index e4a4f27e502b1..4ffd745bf9307 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -667,12 +667,16 @@ struct FormatToken {
 return Tok.isObjCAtKeyword(Kind);
   }
 
+  bool isAccessSpecifierKeyword() const {
+return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private);
+  }
+
   bool isAccessSpecifier(bool ColonRequired = true) const {
-if (!isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
+if (!isAccessSpecifierKeyword())
   return false;
 if (!ColonRequired)
   return true;
-const auto NextNonComment = getNextNonComment();
+const auto *NextNonComment = getNextNonComment();
 return NextNonComment && NextNonComment->is(tok::colon);
   }
 
@@ -1656,10 +1660,12 @@ struct AdditionalKeywords {
   /// If \c AcceptIdentifierName is true, returns true not only for keywords,
   // but also for IdentifierName tokens (aka pseudo-keywords), such as
   // ``yield``.
-  bool IsJavaScriptIdentifier(const FormatToken ,
+  bool isJavaScriptIdentifier(const FormatToken ,
   bool AcceptIdentifierName = true) const {
 // Based on the list of JavaScript & TypeScript keywords here:
 // 
https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
+if (Tok.isAccessSpecifierKeyword())
+  return false;
 switch (Tok.Tok.getKind()) {
 case tok::kw_break:
 case tok::kw_case:
@@ -1679,9 +1685,6 @@ struct AdditionalKeywords {
 case tok::kw_import:
 case tok::kw_module:
 case tok::kw_new:
-case tok::kw_private:
-case tok::kw_protected:
-case tok::kw_public:
 case tok::kw_return:
 case tok::kw_static:
 case tok::kw_switch:
@@ -1724,6 +1727,8 @@ struct AdditionalKeywords {
   /// Returns \c true if \p Tok is a C# keyword, returns
   /// \c false if it is a anything else.
   bool isCSharpKeyword(const FormatToken ) const {
+if (Tok.isAccessSpecifierKeyword())
+  return true;
 switch (Tok.Tok.getKind()) {
 case tok::kw_bool:
 case tok::kw_break:
@@ -1750,9 +1755,6 @@ struct AdditionalKeywords {
 case tok::kw_namespace:
 case tok::kw_new:
 case tok::kw_operator:
-case tok::kw_private:
-case tok::kw_protected:
-case tok::kw_public:
 case tok::kw_return:
 case tok::kw_short:
 case tok::kw_sizeof:
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1332445070314..5a256fc7ebd9f 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -647,8 +647,8 @@ class AnnotatingParser {
   return true;
 
 // Limit this to being an access modifier that follows.
-if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
- tok::comment, tok::kw_class, tok::kw_static,
+if (AttrTok->isAccessSpecifierKeyword() ||
+AttrTok->isOneOf(tok::comment, tok::kw_class, tok::kw_static,
  tok::l_square, Keywords.kw_internal)) {
   return true;
 }
@@ -1419,7 +1419,7 @@ class AnnotatingParser {
 Tok->setType(TT_CtorInitializerColon);
 } else {
   Tok->setType(TT_InheritanceColon);
-  if (Prev->isOneOf(tok::kw_public, tok::kw_private, 
tok::kw_protected))
+  if (Prev->isAccessSpecifierKeyword())
 Line.Type = LT_AccessModifier;
 }
   } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
@@ -2333,7 +2333,7 @@ class AnnotatingParser {
   if (Current.Previous) {
 bool IsIdentifier =
 Style.isJavaScript()
-? Keywords.IsJavaScriptIdentifier(
+? Keywords.isJavaScriptIdentifier(
   *Current.Previous, /* AcceptIdentifierName= */ true)
 : Current.Previous->is(tok::identifier);
 if (IsIdentifier ||
@@ -4948,11 +4948,11 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine ,
 
 // space between method modifier and opening parenthesis of a tuple return
 // type
-if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
- tok::kw_virtual, tok::kw_extern, tok::kw_static,
- Keywords.kw_internal, Keywords.kw_abstract,
- Keywords.kw_sealed, Keywords.kw_override,
- Keywords.kw_async, Keywords.kw_unsafe) &&
+if ((Left.isAccessSpecifierKeyword() ||
+ Left.isOneOf(tok::kw_virtual, tok::kw_extern, tok::kw_static,
+   

[clang] [clang-format][NFC] Add FormatToken::isAccessSpecifierKeyword() (PR #95727)

2024-06-16 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/95727

None

>From ec9b902518ef09d77e8b32777032a852d33476fd Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 16 Jun 2024 17:47:56 -0700
Subject: [PATCH] [clang-format][NFC] Add
 FormatToken::isAccessSpecifierKeyword()

---
 clang/lib/Format/FormatToken.h   | 20 ++-
 clang/lib/Format/TokenAnnotator.cpp  | 44 +++-
 clang/lib/Format/UnwrappedLineParser.cpp | 23 ++---
 3 files changed, 43 insertions(+), 44 deletions(-)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index e4a4f27e502b1..4ffd745bf9307 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -667,12 +667,16 @@ struct FormatToken {
 return Tok.isObjCAtKeyword(Kind);
   }
 
+  bool isAccessSpecifierKeyword() const {
+return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private);
+  }
+
   bool isAccessSpecifier(bool ColonRequired = true) const {
-if (!isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
+if (!isAccessSpecifierKeyword())
   return false;
 if (!ColonRequired)
   return true;
-const auto NextNonComment = getNextNonComment();
+const auto *NextNonComment = getNextNonComment();
 return NextNonComment && NextNonComment->is(tok::colon);
   }
 
@@ -1656,10 +1660,12 @@ struct AdditionalKeywords {
   /// If \c AcceptIdentifierName is true, returns true not only for keywords,
   // but also for IdentifierName tokens (aka pseudo-keywords), such as
   // ``yield``.
-  bool IsJavaScriptIdentifier(const FormatToken ,
+  bool isJavaScriptIdentifier(const FormatToken ,
   bool AcceptIdentifierName = true) const {
 // Based on the list of JavaScript & TypeScript keywords here:
 // 
https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
+if (Tok.isAccessSpecifierKeyword())
+  return false;
 switch (Tok.Tok.getKind()) {
 case tok::kw_break:
 case tok::kw_case:
@@ -1679,9 +1685,6 @@ struct AdditionalKeywords {
 case tok::kw_import:
 case tok::kw_module:
 case tok::kw_new:
-case tok::kw_private:
-case tok::kw_protected:
-case tok::kw_public:
 case tok::kw_return:
 case tok::kw_static:
 case tok::kw_switch:
@@ -1724,6 +1727,8 @@ struct AdditionalKeywords {
   /// Returns \c true if \p Tok is a C# keyword, returns
   /// \c false if it is a anything else.
   bool isCSharpKeyword(const FormatToken ) const {
+if (Tok.isAccessSpecifierKeyword())
+  return true;
 switch (Tok.Tok.getKind()) {
 case tok::kw_bool:
 case tok::kw_break:
@@ -1750,9 +1755,6 @@ struct AdditionalKeywords {
 case tok::kw_namespace:
 case tok::kw_new:
 case tok::kw_operator:
-case tok::kw_private:
-case tok::kw_protected:
-case tok::kw_public:
 case tok::kw_return:
 case tok::kw_short:
 case tok::kw_sizeof:
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1332445070314..5a256fc7ebd9f 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -647,8 +647,8 @@ class AnnotatingParser {
   return true;
 
 // Limit this to being an access modifier that follows.
-if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
- tok::comment, tok::kw_class, tok::kw_static,
+if (AttrTok->isAccessSpecifierKeyword() ||
+AttrTok->isOneOf(tok::comment, tok::kw_class, tok::kw_static,
  tok::l_square, Keywords.kw_internal)) {
   return true;
 }
@@ -1419,7 +1419,7 @@ class AnnotatingParser {
 Tok->setType(TT_CtorInitializerColon);
 } else {
   Tok->setType(TT_InheritanceColon);
-  if (Prev->isOneOf(tok::kw_public, tok::kw_private, 
tok::kw_protected))
+  if (Prev->isAccessSpecifierKeyword())
 Line.Type = LT_AccessModifier;
 }
   } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
@@ -2333,7 +2333,7 @@ class AnnotatingParser {
   if (Current.Previous) {
 bool IsIdentifier =
 Style.isJavaScript()
-? Keywords.IsJavaScriptIdentifier(
+? Keywords.isJavaScriptIdentifier(
   *Current.Previous, /* AcceptIdentifierName= */ true)
 : Current.Previous->is(tok::identifier);
 if (IsIdentifier ||
@@ -4948,11 +4948,11 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine ,
 
 // space between method modifier and opening parenthesis of a tuple return
 // type
-if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
- tok::kw_virtual, tok::kw_extern, tok::kw_static,
- Keywords.kw_internal, Keywords.kw_abstract,
- Keywords.kw_sealed, Keywords.kw_override,
-   

[clang] [clang][Parser] "Better" error messages for invalid template template (PR #95726)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (Veeloxfire)


Changes

For the somewhat easy mistake of `templatetemplate A ...` clang outputs 
a partially cryptic error

This patch changes this to assume the programmer intended `typename` in cases 
where `template` is illegal, and emit diagnostics (and forward parsing) 
accordingly

This mirrors the behaviour of `typedef` handling, so I feel its a reasonable 
qol change

Apologies if I missed any broken tests. Currently my local setup is messed up 
and fails on 100-200 tests eroniously, so I did my best to search through the 
errors and find the ones that needed updating

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


3 Files Affected:

- (modified) clang/lib/Parse/ParseTemplate.cpp (+17) 
- (modified) clang/test/CXX/drs/cwg1xx.cpp (+2) 
- (modified) clang/test/Parser/cxx-template-decl.cpp (+1-1) 


``diff
diff --git a/clang/lib/Parse/ParseTemplate.cpp 
b/clang/lib/Parse/ParseTemplate.cpp
index a5130f56600e5..e5308d9edac5f 100644
--- a/clang/lib/Parse/ParseTemplate.cpp
+++ b/clang/lib/Parse/ParseTemplate.cpp
@@ -787,6 +787,23 @@ NamedDecl *Parser::ParseTemplateTemplateParameter(unsigned 
Depth,
   unsigned Position) {
   assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
 
+  if (Token ahead = GetLookAheadToken(1);
+  ahead.isOneOf(tok::identifier, tok::ellipsis,
+tok::equal, tok::comma,
+tok::greater, tok::greatergreater, 
tok::greatergreatergreater)) {
+// Maybe they intended `typename` instead of `template` (given thats more 
common)
+// Error early, to add a fixit hint
+
+Diag(ahead.getLocation(), diag::err_expected_less_after) << "template";
+
+Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
+  << 
FixItHint::CreateReplacement(CharSourceRange::getTokenRange(Tok.getLocation()),
+  "typename");
+
+Tok.setKind(tok::kw_typename);
+return ParseTypeParameter(Depth, Position);
+  }
+
   // Handle the template <...> part.
   SourceLocation TemplateLoc = ConsumeToken();
   SmallVector TemplateParams;
diff --git a/clang/test/CXX/drs/cwg1xx.cpp b/clang/test/CXX/drs/cwg1xx.cpp
index e71ea9278..72b3ff40152d5 100644
--- a/clang/test/CXX/drs/cwg1xx.cpp
+++ b/clang/test/CXX/drs/cwg1xx.cpp
@@ -1145,8 +1145,10 @@ namespace cwg181 { // cwg181: yes
   namespace X {
 template  > struct A { };
 // expected-error@-1 +{{}}
+//  expected-note@-2 {{did you mean to use 'typename'?}}
 template  > void f(A) { }
 // expected-error@-1 +{{}}
+//  expected-note@-2 {{did you mean to use 'typename'?}}
   }
 
   namespace Y {
diff --git a/clang/test/Parser/cxx-template-decl.cpp 
b/clang/test/Parser/cxx-template-decl.cpp
index 734438069b9ae..69b9ab012b478 100644
--- a/clang/test/Parser/cxx-template-decl.cpp
+++ b/clang/test/Parser/cxx-template-decl.cpp
@@ -22,7 +22,7 @@ template> struct x3; // expected-error 
{{expected ',' or '>' in t
  cpp14-error {{template template 
parameter requires 'class' after the parameter list}} \
  cpp17-error {{template template 
parameter requires 'class' or 'typename' after the parameter list}}
 template  struct Err1; // expected-error {{expected '<' after 
'template'}} \
-// expected-error{{extraneous}}
+// expected-note{{did you mean to use 'typename'?}}
 template  > struct Err2;   // cpp14-error {{template 
template parameter requires 'class' after the parameter list}}
 // cpp17-error@-1{{template template parameter requires 'class' or 'typename' 
after the parameter list}}
 template  Foo> struct Err3;// cpp14-error {{template 
template parameter requires 'class' after the parameter list}}

``




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


[clang] [clang][Parser] "Better" error messages for invalid template template (PR #95726)

2024-06-16 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [clang][Parser] "Better" error messages for invalid template template (PR #95726)

2024-06-16 Thread via cfe-commits

https://github.com/Veeloxfire created 
https://github.com/llvm/llvm-project/pull/95726

For the somewhat easy mistake of `template ...` clang outputs a 
partially cryptic error

This patch changes this to assume the programmer intended `typename` in cases 
where `template` is illegal, and emit diagnostics (and forward parsing) 
accordingly

This mirrors the behaviour of `typedef` handling, so I feel its a reasonable 
qol change

Apologies if I missed any broken tests. Currently my local setup is messed up 
and fails on 100-200 tests eroniously, so I did my best to search through the 
errors and find the ones that needed updating

>From 44620330cd5238de549d3d77ddc447cd3bc51e60 Mon Sep 17 00:00:00 2001
From: Veeloxfire <58116051+veeloxf...@users.noreply.github.com>
Date: Mon, 17 Jun 2024 01:20:32 +0100
Subject: [PATCH] [clang][Parser] "Better" error messages for invalid template
 template

For the somewhat easy mistake of `template ...` clang outputs a 
partially cryptic error
Change this to assume the programmer intended `typename` in cases where 
`template` is illegal, and emit diagnostics (and forward parsing) accordingly
This mirrors the behaviour of `typedef` handling
---
 clang/lib/Parse/ParseTemplate.cpp   | 17 +
 clang/test/CXX/drs/cwg1xx.cpp   |  2 ++
 clang/test/Parser/cxx-template-decl.cpp |  2 +-
 3 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Parse/ParseTemplate.cpp 
b/clang/lib/Parse/ParseTemplate.cpp
index a5130f56600e5..e5308d9edac5f 100644
--- a/clang/lib/Parse/ParseTemplate.cpp
+++ b/clang/lib/Parse/ParseTemplate.cpp
@@ -787,6 +787,23 @@ NamedDecl *Parser::ParseTemplateTemplateParameter(unsigned 
Depth,
   unsigned Position) {
   assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
 
+  if (Token ahead = GetLookAheadToken(1);
+  ahead.isOneOf(tok::identifier, tok::ellipsis,
+tok::equal, tok::comma,
+tok::greater, tok::greatergreater, 
tok::greatergreatergreater)) {
+// Maybe they intended `typename` instead of `template` (given thats more 
common)
+// Error early, to add a fixit hint
+
+Diag(ahead.getLocation(), diag::err_expected_less_after) << "template";
+
+Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
+  << 
FixItHint::CreateReplacement(CharSourceRange::getTokenRange(Tok.getLocation()),
+  "typename");
+
+Tok.setKind(tok::kw_typename);
+return ParseTypeParameter(Depth, Position);
+  }
+
   // Handle the template <...> part.
   SourceLocation TemplateLoc = ConsumeToken();
   SmallVector TemplateParams;
diff --git a/clang/test/CXX/drs/cwg1xx.cpp b/clang/test/CXX/drs/cwg1xx.cpp
index e71ea9278..72b3ff40152d5 100644
--- a/clang/test/CXX/drs/cwg1xx.cpp
+++ b/clang/test/CXX/drs/cwg1xx.cpp
@@ -1145,8 +1145,10 @@ namespace cwg181 { // cwg181: yes
   namespace X {
 template  > struct A { };
 // expected-error@-1 +{{}}
+//  expected-note@-2 {{did you mean to use 'typename'?}}
 template  > void f(A) { }
 // expected-error@-1 +{{}}
+//  expected-note@-2 {{did you mean to use 'typename'?}}
   }
 
   namespace Y {
diff --git a/clang/test/Parser/cxx-template-decl.cpp 
b/clang/test/Parser/cxx-template-decl.cpp
index 734438069b9ae..69b9ab012b478 100644
--- a/clang/test/Parser/cxx-template-decl.cpp
+++ b/clang/test/Parser/cxx-template-decl.cpp
@@ -22,7 +22,7 @@ template> struct x3; // expected-error 
{{expected ',' or '>' in t
  cpp14-error {{template template 
parameter requires 'class' after the parameter list}} \
  cpp17-error {{template template 
parameter requires 'class' or 'typename' after the parameter list}}
 template  struct Err1; // expected-error {{expected '<' after 
'template'}} \
-// expected-error{{extraneous}}
+// expected-note{{did you mean to use 'typename'?}}
 template  > struct Err2;   // cpp14-error {{template 
template parameter requires 'class' after the parameter list}}
 // cpp17-error@-1{{template template parameter requires 'class' or 'typename' 
after the parameter list}}
 template  Foo> struct Err3;// cpp14-error {{template 
template parameter requires 'class' after the parameter list}}

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


[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)

2024-06-16 Thread via cfe-commits

vabridgers wrote:

Hi @jcsxky , I fetched and rebased to origin/main just now (6/16/2024 at 4:30pm 
Central US time), and rebuilt - and I see the crash. Did you try rebasing to 
latest source and rebuilding?

`$ clang --analyze -Xclang -analyzer-config -Xclang 
experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
ctu-dir=ctudir -Xclang -analyzer-config -Xclang display-ctu-progress=true 
test.cpp`
`CTU loaded AST file: bstrwrap.cpp.ast`
`clang: clang/lib/AST/Decl.cpp:4045: void 
clang::FunctionDecl::setDescribedFunctionTemplate(clang::FunctionTemplateDecl*):
 Assertion `TemplateOrSpecialization.isNull() && "Member function is already a 
specialization"' failed.`
`PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace, preprocessed source, and associated run script.`
`Stack dump:`
`0.  Program arguments: clang --analyze -Xclang -analyzer-config -Xclang 
experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
ctu-dir=ctudir -Xclang -analyzer-config -Xclang display-ctu-progress=true 
test.cpp`
`1.   parser at end of file`
`2.  While analyzing stack:`
`#0 Calling test0()`
`3.  test.cpp:3:21: Error evaluating statement`
`4.  test.cpp:3:21: Error evaluating statement`
`  #0 0x0683ef4a llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
llvm/lib/Support/Unix/Signals.inc:723:22`
`  #1 0x0683f384 PrintStackTraceSignalHandler(void*) 
llvm/lib/Support/Unix/Signals.inc:798:1`
`  #2 0x0683cc9d llvm::sys::RunSignalHandlers() 
llvm/lib/Support/Signals.cpp:105:20`
`  #3 0x0683e84b llvm::sys::CleanupOnSignal(unsgned long) 
llvm/lib/Support/Unix/Signals.inc:367:31`
`  #4 0x0677a190 (anonymous 
namespace)::CrashRecoveryContextImpl::HandleCrash(int, unsigned long) 
llvm/lib/Support/CrashRecoveryContext.cpp:73:5`
`  #5 0x0677a623 CrashRecoverySignalHandler(int) 
llvm/lib/Support/CrashRecoveryContext.cpp:391:1`
`  #6 0x7fbb10acd630 __restore_rt sigaction.c:0:0`
`  #7 0x7fbb0f80b387 raise (/lib64/libc.so.6+0x36387)`
`  #8 0x7fbb0f80ca78 abort (/lib64/libc.so.6+0x37a78)`
`  #9 0x7fbb0f8041a6 __assert_fail_base (/lib64/libc.so.6+0x2f1a6)`
` #10 0x7fbb0f804252 (/lib64/libc.so.6+0x2f252)`
` #11 0x0c2b9f73 
clang::FunctionDecl::setDescribedFunctionTemplate(clang::FunctionTemplateDecl*) 
clang/lib/AST/Decl.cpp:4045:3`



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


[clang] 527e732 - [clang-format][NFC] Suppress diagnostic noise in GetStyleOfFile test

2024-06-16 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2024-06-16T14:56:02-07:00
New Revision: 527e7328607ea0a55855e53a59c5030a7d07a554

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

LOG: [clang-format][NFC] Suppress diagnostic noise in GetStyleOfFile test

Added: 


Modified: 
clang/unittests/Format/ConfigParseTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index 2513ab3939595..aded3ed2a6596 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -15,6 +15,7 @@ namespace clang {
 namespace format {
 namespace {
 
+void dropDiagnosticHandler(const llvm::SMDiagnostic &, void *) {}
 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
 
 #define EXPECT_ALL_STYLES_EQUAL(Styles)
\
@@ -1240,7 +1241,8 @@ TEST(ConfigParseTest, GetStyleOfFile) {
   llvm::consumeError(Style4.takeError());
 
   // Test 5: error on invalid yaml on command line
-  auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
);
+  auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", ,
+ /*AllowUnknownOptions=*/false, dropDiagnosticHandler);
   ASSERT_FALSE((bool)Style5);
   llvm::consumeError(Style5.takeError());
 
@@ -1256,11 +1258,13 @@ TEST(ConfigParseTest, GetStyleOfFile) {
   "InvalidKey: 
InvalidValue")));
   ASSERT_TRUE(
   FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int 
i;")));
-  auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", );
+  auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", ,
+  /*AllowUnknownOptions=*/false, 
dropDiagnosticHandler);
   ASSERT_FALSE((bool)Style7a);
   llvm::consumeError(Style7a.takeError());
 
-  auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", , true);
+  auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", ,
+  /*AllowUnknownOptions=*/true, dropDiagnosticHandler);
   ASSERT_TRUE((bool)Style7b);
 
   // Test 8: inferred per-language defaults apply.
@@ -1466,8 +1470,7 @@ TEST(ConfigParseTest, GetStyleOutput) {
   // Suppress stderr.
   testing::internal::CaptureStderr();
   Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", ,
-   /*AllowUnknownOptions=*/true,
-   [](const llvm::SMDiagnostic &, void *) {});
+   /*AllowUnknownOptions=*/true, dropDiagnosticHandler);
   Output = testing::internal::GetCapturedStderr();
   ASSERT_TRUE((bool)Style);
   ASSERT_TRUE(Output.empty());



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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95718

>From c3912611dd63f81ea7067a4b26ef5450f6f01f75 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 22:35:38 +0100
Subject: [PATCH 1/2] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp | 10 +
 clang/www/cxx_dr_status.html |  2 +-
 12 files changed, 113 insertions(+), 75 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext ,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:
+  //   If the glvalue expression is obtained by applying the unary * operator 
to
+  //   a pointer and the pointer is a null pointer value, the typeid expression
+  //   throws the std::bad_typeid exception.
+  //
+  // However, this paragraph's intent is not clear.  We choose a very generous
+  // interpretation which implores us to consider comma operators, conditional
+  // operators, 

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95718

>From c3912611dd63f81ea7067a4b26ef5450f6f01f75 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 22:35:38 +0100
Subject: [PATCH] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp | 10 +
 clang/www/cxx_dr_status.html |  2 +-
 12 files changed, 113 insertions(+), 75 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext ,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:
+  //   If the glvalue expression is obtained by applying the unary * operator 
to
+  //   a pointer and the pointer is a null pointer value, the typeid expression
+  //   throws the std::bad_typeid exception.
+  //
+  // However, this paragraph's intent is not clear.  We choose a very generous
+  // interpretation which implores us to consider comma operators, conditional
+  // operators, 

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits


@@ -15598,7 +15598,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2632.html;>2632
-review
+drafting

Endilll wrote:

Update you branch with the latest `main` changes, and those unrelated changes 
will go away.

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

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

DR test looks good, but wait for more approvals.

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits


@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.

Endilll wrote:

```suggestion
- Clang now considers ``noexcept(typeid(expr))`` more carefully, instead of 
always assuming that ``std::bad_typeid`` can be thrown.
```

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95718

>From fc28e8f9b987ca35db457afaf19fa8c2af2f9574 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 20:27:15 +0100
Subject: [PATCH 1/4] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp |  8 
 11 files changed, 110 insertions(+), 74 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext ,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:
+  //   If the glvalue expression is obtained by applying the unary * operator 
to
+  //   a pointer and the pointer is a null pointer value, the typeid expression
+  //   throws the std::bad_typeid exception.
+  //
+  // However, this paragraph's intent is not clear.  We choose a very generous
+  // interpretation which implores us to consider comma operators, conditional
+  // operators, parentheses and other such constructs.
+  return 

[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits

huixie90 wrote:

@efriedma-quic 

I refactored the code which does the following
1. Breadth first search the AST type, fill in "occupied bits intervals"
2. sort and merge the occupied bits interval and work out the "padding" bits 
intervals
3. clear the padding intervals.  current converting to the byte level and write 
zeros byte. todo: need to deal with bits that don't occupy the full byte. need 
to generate instructions like `Byte &= ~PaddingBitMask` . How to generate such 
an IR instruction ?

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


[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-16 Thread via cfe-commits

pointhex wrote:

@owenca  Thanks a lot!

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

If you update the branch, you should be able to get rid of unrelated changes to 
`cxx_dr_status.html`.

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2538,6 +2539,205 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction , Value *Ptr, QualType Ty,
+ size_t CurrentStartOffset,
+ size_t , T &,
+ bool VisitVirtualBase);
+
+template 
+void ClearPaddingStruct(CodeGenFunction , Value *Ptr, QualType Ty,
+StructType *ST, size_t CurrentStartOffset,
+size_t , T &,
+bool VisitVirtualBase) {
+  llvm::dbgs() << "clear padding struct: " << ST->getName().data() << '\n';
+  const auto  = CGF.CGM.getModule().getDataLayout();
+  auto *SL = DL.getStructLayout(ST);
+  auto *R = dyn_cast(Ty->getAsRecordDecl());
+  if (!R) {
+llvm::dbgs() << "Not a CXXRecordDecl\n";
+return;
+  }
+  const ASTRecordLayout  = CGF.getContext().getASTRecordLayout(R);
+  if (ASTLayout.hasOwnVFPtr()) {
+llvm::dbgs() << "vtable ptr. Incrementing RunningOffset from "
+ << RunningOffset << " to "
+ << RunningOffset + DL.getPointerSizeInBits() / 8 << '\n';
+RunningOffset += DL.getPointerSizeInBits() / 8;
+  }
+  std::vector> Bases;
+  Bases.reserve(R->getNumBases());
+  // todo get vbases
+  for (auto Base : R->bases()) {
+auto *BaseRecord = cast(Base.getType()->getAsRecordDecl());
+if (!Base.isVirtual()) {
+  auto Offset = static_cast(

huixie90 wrote:

removed `size_t`

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


[clang] d340f62 - [clang][NFC] Update C++ DR issues list

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-06-17T00:22:47+03:00
New Revision: d340f6283a3d242bad190ed9b95baa03e5607639

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

LOG: [clang][NFC] Update C++ DR issues list

Added: 


Modified: 
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/www/cxx_dr_status.html b/clang/www/cxx_dr_status.html
index a7b1e652330e4..c00d022b86446 100755
--- a/clang/www/cxx_dr_status.html
+++ b/clang/www/cxx_dr_status.html
@@ -15598,7 +15598,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2632.html;>2632
-review
+drafting
 'user-declared' is not defined
 Not resolved
   
@@ -16691,7 +16691,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2814.html;>2814
-review
+tentatively ready
 Alignment requirement of incomplete class type
 Not resolved
   
@@ -17147,7 +17147,7 @@ C++ defect report implementation 
status
   
   
 https://cplusplus.github.io/CWG/issues/2890.html;>2890
-open
+review
 Defining members of local classes
 Not resolved
   
@@ -17163,27 +17163,27 @@ C++ defect report implementation 
status
 Unclear usual arithmetic conversions
 Not resolved
   
-  
+  
 https://cplusplus.github.io/CWG/issues/2893.html;>2893
-open
+NAD
 Instantiations in discarded if constexpr substatements
-Not resolved
+Unknown
   
   
 https://cplusplus.github.io/CWG/issues/2894.html;>2894
-open
+review
 Functional casts create prvalues of reference type
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2895.html;>2895
-open
+tentatively ready
 Initialization should ignore the destination type's 
cv-qualification
 Not resolved
   
   
 https://cplusplus.github.io/CWG/issues/2896.html;>2896
-open
+review
 Template argument deduction involving exception specifications
 Not resolved
   
@@ -17204,6 +17204,30 @@ C++ defect report implementation 
status
 open
 Bad value representations should cause undefined behavior
 Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2900.html;>2900
+open
+Deduction of non-type template arguments with placeholder types
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2901.html;>2901
+open
+Unclear semantics for near-match aliased access
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2902.html;>2902
+review
+Implicit this transformation outside of permitted 
contexts
+Not resolved
+  
+  
+https://cplusplus.github.io/CWG/issues/2903.html;>2903
+tentatively ready
+Can we omit the template disambiguator in 
nested-name-specifiers in type-only contexts?
+Not resolved
   
 
 



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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction , Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t , T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction , Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t , T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout  = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {
+std::cerr << "\n\n base!"  << std::endl;
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentBaseType = CGF.ConvertTypeForMem(Base.getType());
+Value *BaseElement = CGF.Builder.CreateGEP(CurrentBaseType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, BaseElement, Base.getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+
+  size_t NumFields = std::distance(R->field_begin(), R->field_end());
+  auto CurrentField = R->field_begin();
+  for (size_t I = 0; I < NumFields; ++I, ++CurrentField) {
+// Size needs to be in bytes so we can compare it later.
+auto Offset = ASTLayout.getFieldOffset(I) / 8;
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentFieldType = 
CGF.ConvertTypeForMem(CurrentField->getType());
+Value *Element = CGF.Builder.CreateGEP(CurrentFieldType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, Element, CurrentField->getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+}
+
+template 
+void ClearPaddingConstantArray(CodeGenFunction , Value *Ptr, llvm::Type 
*Type, ConstantArrayType const *AT, 
+   size_t CurrentStartOffset, size_t 
, T&& WriteZeroAtOffset) {
+  for (size_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
+   ++ArrIndex) {
+
+QualType ElementQualType = AT->getElementType();
+
+auto *ElementRecord = ElementQualType->getAsRecordDecl();
+if(!ElementRecord){
+  std::cerr<< "\n\n null!" << std::endl;
+}
+auto ElementAlign =ElementRecord?
+CGF.getContext().getASTRecordLayout(ElementRecord).getAlignment():
+CGF.getContext().getTypeAlignInChars(ElementQualType);
+
+  std::cerr<< "\n\n align: " << ElementAlign.getQuantity() << std::endl;
+
+// Value *Idx = CGF.Builder.getSize(0);
+// Value *ArrayElement = CGF.Builder.CreateGEP(ElementType, Ptr, Idx);
+
+Address FieldElementAddr{Ptr, Type, ElementAlign};
+
+auto Element =
+CGF.Builder.CreateConstArrayGEP(FieldElementAddr, ArrIndex);
+auto *ElementType = CGF.ConvertTypeForMem(ElementQualType);
+auto AllocSize = 
CGF.CGM.getModule().getDataLayout().getTypeAllocSize(ElementType);
+std::cerr << "\n\n clearing array index! " << ArrIndex << std::endl;
+RecursivelyClearPaddingImpl(CGF, Element.getPointer(), ElementQualType, 
CurrentStartOffset + ArrIndex * AllocSize.getKnownMinValue(), RunningOffset, 
WriteZeroAtOffset);
+  }
+}
+
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction , Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, 
+ size_t& RunningOffset, T&& WriteZeroAtOffset) 
{
+
+  std::cerr << "\n\n  zero padding before current  ["<< RunningOffset << ", " 
<< CurrentStartOffset<< ")"<< std::endl;
+  for (; RunningOffset < CurrentStartOffset; ++RunningOffset) {
+WriteZeroAtOffset(RunningOffset);
+  }
+  auto Type = CGF.ConvertTypeForMem(Ty);
+  auto Size = CGF.CGM.getModule()
+.getDataLayout()
+.getTypeSizeInBits(Type)
+.getKnownMinValue() / 8;
+
+  if (auto *AT = dyn_cast(Ty)) {
+ClearPaddingConstantArray(CGF, Ptr, Type, AT, CurrentStartOffset, 
RunningOffset, WriteZeroAtOffset);
+  }
+  else if (auto *ST = dyn_cast(Type); ST && Ty->isRecordType()) {
+ClearPaddingStruct(CGF, Ptr, Ty, ST, CurrentStartOffset, RunningOffset, 
WriteZeroAtOffset);
+  } else if (Ty->isAtomicType()) {
+RecursivelyClearPaddingImpl(CGF, Ptr, Ty.getAtomicUnqualifiedType(), 
CurrentStartOffset, RunningOffset, WriteZeroAtOffset);
+  } else {
+std::cerr << "\n\n increment running offset from: " << RunningOffset << " 
to " << RunningOffset + Size << std::endl;
+RunningOffset = 

[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction , Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t , T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction , Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t , T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout  = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {
+std::cerr << "\n\n base!"  << std::endl;
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentBaseType = CGF.ConvertTypeForMem(Base.getType());
+Value *BaseElement = CGF.Builder.CreateGEP(CurrentBaseType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, BaseElement, Base.getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+
+  size_t NumFields = std::distance(R->field_begin(), R->field_end());
+  auto CurrentField = R->field_begin();
+  for (size_t I = 0; I < NumFields; ++I, ++CurrentField) {
+// Size needs to be in bytes so we can compare it later.
+auto Offset = ASTLayout.getFieldOffset(I) / 8;
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentFieldType = 
CGF.ConvertTypeForMem(CurrentField->getType());
+Value *Element = CGF.Builder.CreateGEP(CurrentFieldType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, Element, CurrentField->getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+}
+
+template 
+void ClearPaddingConstantArray(CodeGenFunction , Value *Ptr, llvm::Type 
*Type, ConstantArrayType const *AT, 
+   size_t CurrentStartOffset, size_t 
, T&& WriteZeroAtOffset) {
+  for (size_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
+   ++ArrIndex) {
+
+QualType ElementQualType = AT->getElementType();
+
+auto *ElementRecord = ElementQualType->getAsRecordDecl();
+if(!ElementRecord){
+  std::cerr<< "\n\n null!" << std::endl;
+}
+auto ElementAlign =ElementRecord?
+CGF.getContext().getASTRecordLayout(ElementRecord).getAlignment():

huixie90 wrote:

removed

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction , Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t , T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction , Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t , T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout  = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {
+std::cerr << "\n\n base!"  << std::endl;
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);
+Value *Idx = CGF.Builder.getSize(Index);
+llvm::Type *CurrentBaseType = CGF.ConvertTypeForMem(Base.getType());
+Value *BaseElement = CGF.Builder.CreateGEP(CurrentBaseType, Ptr, Idx);
+RecursivelyClearPaddingImpl(CGF, BaseElement, Base.getType(), 
CurrentStartOffset + Offset, RunningOffset, WriteZeroAtOffset);
+  }
+
+  size_t NumFields = std::distance(R->field_begin(), R->field_end());
+  auto CurrentField = R->field_begin();
+  for (size_t I = 0; I < NumFields; ++I, ++CurrentField) {
+// Size needs to be in bytes so we can compare it later.
+auto Offset = ASTLayout.getFieldOffset(I) / 8;
+auto Index = SL->getElementContainingOffset(Offset);

huixie90 wrote:

It is almost working now. I managed to get all the Padding in bits now. the 
remaining thing is to zeroing them out, instead of current generating store 
instruction with zeros, i need to basically do this for the bits that don't 
occupy the entire byte
```
byte &= ~PaddingBitMask
```
How can I generate that IR ?

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction , Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t , T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction , Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t , T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout  = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {
+std::cerr << "\n\n base!"  << std::endl;
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);

huixie90 wrote:

I removed all the code using LLVM layouts

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits


@@ -2456,6 +2461,139 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction , Value *Ptr, QualType 
Ty, size_t CurrentStartOffset, size_t , T&& WriteZeroAtOffset);
+
+template 
+void ClearPaddingStruct(CodeGenFunction , Value *Ptr, QualType Ty, 
StructType *ST, 
+size_t CurrentStartOffset, size_t , T&& 
WriteZeroAtOffset) {
+  std::cerr << "\n struct! " << ST->getName().data() << std::endl;
+  auto SL = CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+
+  auto R = dyn_cast(Ty->getAsRecordDecl());
+  if(!R) {
+std::cerr << "\n not a CXXRecordDecl" << std::endl;
+
+  }
+  const ASTRecordLayout  = CGF.getContext().getASTRecordLayout(R);
+  for (auto Base : R->bases()) {

huixie90 wrote:

anyway. I changed the approach now.the new approach should work regardless of 
the orders

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


[clang] [libcxx] [clang] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2024-06-16 Thread via cfe-commits

https://github.com/huixie90 updated 
https://github.com/llvm/llvm-project/pull/75371

>From cb64639669286e5f48421ae8f569208e1e9717be Mon Sep 17 00:00:00 2001
From: zoecarver 
Date: Sat, 2 Dec 2023 20:00:30 +
Subject: [PATCH 1/2] [Builtin] Add __builtin_clear_padding

Adds `__builtin_clear_padding` to zero all padding bits of a struct. This 
builtin should match the behavior of those in NVCC and GCC (and MSVC?). There 
are some tests in this patch but hopefully we'll also get tests from other 
compilers (so all builtins can be as similar as possible).

I'm planning to add support for unions, bitfields (both as members and members 
of sub-objects), and booleans as follow up patches.

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

overlapping subobjects + opague pointer

union, rename, scalar types
---
 clang/include/clang/Basic/Builtins.td |   6 +
 clang/lib/CodeGen/CGBuiltin.cpp   | 207 +
 clang/lib/Sema/SemaChecking.cpp   |  31 +
 .../builtin-clear-padding-codegen.cpp | 112 +++
 clang/test/SemaCXX/builtin-clear-padding.cpp  |  15 +
 .../atomics/builtin_clear_padding.pass.cpp| 807 ++
 6 files changed, 1178 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/builtin-clear-padding-codegen.cpp
 create mode 100644 clang/test/SemaCXX/builtin-clear-padding.cpp
 create mode 100644 libcxx/test/libcxx/atomics/builtin_clear_padding.pass.cpp

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 11982af3fa609..44a239e50d5d8 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -932,6 +932,12 @@ def IsConstantEvaluated : LangBuiltin<"CXX_LANG"> {
   let Prototype = "bool()";
 }
 
+def ClearPadding : LangBuiltin<"CXX_LANG"> {
+  let Spellings = ["__builtin_clear_padding"];
+  let Attributes = [NoThrow];
+  let Prototype = "void(...)";
+}
+
 // GCC exception builtins
 def EHReturn : Builtin {
   let Spellings = ["__builtin_eh_return"];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index c16b69ba87567..e1d8135933bb3 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -63,6 +63,7 @@
 #include "llvm/Support/ScopedPrinter.h"
 #include "llvm/TargetParser/AArch64TargetParser.h"
 #include "llvm/TargetParser/X86TargetParser.h"
+#include 
 #include 
 #include 
 
@@ -2538,6 +2539,205 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+template 
+void RecursivelyClearPaddingImpl(CodeGenFunction , Value *Ptr, QualType Ty,
+ size_t CurrentStartOffset,
+ size_t , T &,
+ bool VisitVirtualBase);
+
+template 
+void ClearPaddingStruct(CodeGenFunction , Value *Ptr, QualType Ty,
+StructType *ST, size_t CurrentStartOffset,
+size_t , T &,
+bool VisitVirtualBase) {
+  llvm::dbgs() << "clear padding struct: " << ST->getName().data() << '\n';
+  const auto  = CGF.CGM.getModule().getDataLayout();
+  auto *SL = DL.getStructLayout(ST);
+  auto *R = dyn_cast(Ty->getAsRecordDecl());
+  if (!R) {
+llvm::dbgs() << "Not a CXXRecordDecl\n";
+return;
+  }
+  const ASTRecordLayout  = CGF.getContext().getASTRecordLayout(R);
+  if (ASTLayout.hasOwnVFPtr()) {
+llvm::dbgs() << "vtable ptr. Incrementing RunningOffset from "
+ << RunningOffset << " to "
+ << RunningOffset + DL.getPointerSizeInBits() / 8 << '\n';
+RunningOffset += DL.getPointerSizeInBits() / 8;
+  }
+  std::vector> Bases;
+  Bases.reserve(R->getNumBases());
+  // todo get vbases
+  for (auto Base : R->bases()) {
+auto *BaseRecord = cast(Base.getType()->getAsRecordDecl());
+if (!Base.isVirtual()) {
+  auto Offset = static_cast(
+  ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+  Bases.emplace_back(Offset, Base);
+}
+  }
+
+  auto VisitBases =
+  [&](std::vector> ) {
+std::sort(
+BasesToVisit.begin(), BasesToVisit.end(),
+[](const auto , const auto ) { return P1.first < P2.first; 
});
+for (const auto  : BasesToVisit) {
+  // is it OK to use structured binding in clang? what is the language
+  // version?
+  auto Offset = Pair.first;
+  auto Base = Pair.second;
+
+  llvm::dbgs() << "visiting base at offset " << Offset << '\n';
+  // Recursively zero out base classes.
+  auto Index = SL->getElementContainingOffset(Offset);
+  Value *Idx = CGF.Builder.getSize(Index);
+  llvm::Type *CurrentBaseType = CGF.ConvertTypeForMem(Base.getType());
+  Value *BaseElement = CGF.Builder.CreateGEP(CurrentBaseType, Ptr, 
Idx);
+  RecursivelyClearPaddingImpl(CGF, BaseElement, Base.getType(),
+ 

[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-16 Thread via cfe-commits

github-actions[bot] wrote:



@pointhex Congratulations on having your first Pull Request (PR) merged into 
the LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested
by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with 
a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as
the builds can include changes from many authors. It is not uncommon for your
change to be included in a build that fails due to someone else's changes, or
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself.
This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] fe9aef0 - [clang-format] Add DiagHandler parameter to format::getStyle() (#91317)

2024-06-16 Thread via cfe-commits

Author: pointhex
Date: 2024-06-16T13:58:26-07:00
New Revision: fe9aef05c2dcfbde6e29e2edb2d49e29a54bea4d

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

LOG: [clang-format] Add DiagHandler parameter to format::getStyle() (#91317)

It allows to control of error output for the function.

Closes #94205.

-

Co-authored-by: Owen Pan 

Added: 


Modified: 
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/unittests/Format/ConfigParseTest.cpp

Removed: 




diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index f9299ce89a624..7d257be10af42 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5387,10 +5387,11 @@ extern const char *DefaultFallbackStyle;
 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
 /// "file" and no file is found, returns ``FallbackStyle``. If no style could 
be
 /// determined, returns an Error.
-Expected getStyle(StringRef StyleName, StringRef FileName,
-   StringRef FallbackStyle, StringRef Code = "",
-   llvm::vfs::FileSystem *FS = nullptr,
-   bool AllowUnknownOptions = false);
+Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
+ StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr);
 
 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
 // Defaults to FormatStyle::LK_Cpp.

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index c015e03fa15e7..cd21fbb2221ac 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3946,20 +3946,24 @@ const char *DefaultFallbackStyle = "LLVM";
 
 llvm::ErrorOr>
 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
-   FormatStyle *Style, bool AllowUnknownOptions) {
+   FormatStyle *Style, bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   llvm::ErrorOr> Text =
   FS->getBufferForFile(ConfigFile.str());
   if (auto EC = Text.getError())
 return EC;
-  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions))
+  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
+   DiagHandler)) {
 return EC;
+  }
   return Text;
 }
 
 Expected getStyle(StringRef StyleName, StringRef FileName,
StringRef FallbackStyleName, StringRef Code,
llvm::vfs::FileSystem *FS,
-   bool AllowUnknownOptions) {
+   bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
   FormatStyle FallbackStyle = getNoStyle();
   if (!getPredefinedStyle(FallbackStyleName, Style.Language, ))
@@ -3972,7 +3976,7 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
 StringRef Source = "";
 if (std::error_code ec =
 parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), 
,
-   AllowUnknownOptions)) {
+   AllowUnknownOptions, DiagHandler)) {
   return make_string_error("Error parsing -style: " + ec.message());
 }
 
@@ -3992,7 +3996,8 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   StyleName.starts_with_insensitive("file:")) {
 auto ConfigFile = StyleName.substr(5);
 llvm::ErrorOr> Text =
-loadAndParseConfigFile(ConfigFile, FS, , AllowUnknownOptions);
+loadAndParseConfigFile(ConfigFile, FS, , AllowUnknownOptions,
+   DiagHandler);
 if (auto EC = Text.getError()) {
   return make_string_error("Error reading " + ConfigFile + ": " +
EC.message());
@@ -4031,8 +4036,9 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
 
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto  : llvm::reverse(ChildFormatTextToApply)) {
-  auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   dropDiagnosticHandler);
+  auto EC =
+  parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
+ DiagHandler ? DiagHandler : 
dropDiagnosticHandler);
   // It was already correctly parsed.
   assert(!EC);
   static_cast(EC);
@@ -4066,7 +4072,8 @@ Expected getStyle(StringRef StyleName, 
StringRef 

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95718

>From fc28e8f9b987ca35db457afaf19fa8c2af2f9574 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 20:27:15 +0100
Subject: [PATCH 1/3] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp |  8 
 11 files changed, 110 insertions(+), 74 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext ,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:
+  //   If the glvalue expression is obtained by applying the unary * operator 
to
+  //   a pointer and the pointer is a null pointer value, the typeid expression
+  //   throws the std::bad_typeid exception.
+  //
+  // However, this paragraph's intent is not clear.  We choose a very generous
+  // interpretation which implores us to consider comma operators, conditional
+  // operators, parentheses and other such constructs.
+  return 

[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] a106131 - [clang-format] Handle AttributeMacro before access modifiers (#95634)

2024-06-16 Thread via cfe-commits

Author: Owen Pan
Date: 2024-06-16T13:50:59-07:00
New Revision: a106131a34ed87f597c78183ada56f01fd17641d

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

LOG: [clang-format] Handle AttributeMacro before access modifiers (#95634)

Closes #95094.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/TokenAnnotator.h
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..1332445070314 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1419,6 +1419,8 @@ class AnnotatingParser {
 Tok->setType(TT_CtorInitializerColon);
 } else {
   Tok->setType(TT_InheritanceColon);
+  if (Prev->isOneOf(tok::kw_public, tok::kw_private, 
tok::kw_protected))
+Line.Type = LT_AccessModifier;
 }
   } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
  (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
@@ -1998,6 +2000,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (Line.Type == LT_AccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)

diff  --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..f4f2bba0eb217 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,8 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  // Contains public/private/protected followed by TT_InheritanceColon.
+  LT_AccessModifier,
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
@@ -45,7 +47,7 @@ enum ScopeType {
 class AnnotatedLine {
 public:
   AnnotatedLine(const UnwrappedLine )
-  : First(Line.Tokens.front().Tok), Level(Line.Level),
+  : First(Line.Tokens.front().Tok), Type(LT_Other), Level(Line.Level),
 PPLevel(Line.PPLevel),
 MatchingOpeningBlockLineIndex(Line.MatchingOpeningBlockLineIndex),
 MatchingClosingBlockLineIndex(Line.MatchingClosingBlockLineIndex),

diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken ) {
+  int getIndentOffset(const AnnotatedLine ) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, ]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken ) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed 

[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95503)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

You need to run `clang/www/make_cxx_dr_status` script.

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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/95634

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH 1/5] [clang-format] Handle AttributeMacro before access
 modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken ) {
+  int getIndentOffset(const AnnotatedLine ) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, ]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken ) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.IndentAccessModifiers ? 

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-clang

Author: Mital Ashok (MitalAshok)


Changes

Used to implement CWG2191 where `typeid` for a polymorphic glvalue only becomes 
potentially-throwing if the `typeid` operand was already potentially throwing 
or a `nullptr` check was inserted: 
https://cplusplus.github.io/CWG/issues/2191.html

Also change `Expr::hasSideEffects` for `CXXTypeidExpr` to check the operand for 
side-effects instead of always reporting that there are side-effects

Remove `IsDeref` parameter of `CGCXXABI::shouldTypeidBeNullChecked` because it 
should never return `true` if `!IsDeref` (we shouldn't add a null check that 
wasn't there in the first place)

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


11 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/AST/ExprCXX.h (+4) 
- (modified) clang/lib/AST/Expr.cpp (+12-4) 
- (modified) clang/lib/AST/ExprCXX.cpp (+49) 
- (modified) clang/lib/CodeGen/CGCXXABI.h (+1-2) 
- (modified) clang/lib/CodeGen/CGExprCXX.cpp (+9-44) 
- (modified) clang/lib/CodeGen/ItaniumCXXABI.cpp (+3-4) 
- (modified) clang/lib/CodeGen/MicrosoftCXXABI.cpp (+3-5) 
- (modified) clang/lib/Sema/SemaExceptionSpec.cpp (+5-15) 
- (modified) clang/test/CXX/drs/cwg21xx.cpp (+13) 
- (modified) clang/test/SemaCXX/warn-unused-value.cpp (+8) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext ,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} // namespace
+
+bool CXXTypeidExpr::hasNullCheck() const {
+  if (!isPotentiallyEvaluated())
+return false;
+
+  // C++ [expr.typeid]p2:

[clang] [Clang] Introduce `CXXTypeidExpr::hasNullCheck` (PR #95718)

2024-06-16 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok created 
https://github.com/llvm/llvm-project/pull/95718

Used to implement CWG2191 where `typeid` for a polymorphic glvalue only becomes 
potentially-throwing if the `typeid` operand was already potentially throwing 
or a `nullptr` check was inserted: 
https://cplusplus.github.io/CWG/issues/2191.html

Also change `Expr::hasSideEffects` for `CXXTypeidExpr` to check the operand for 
side-effects instead of always reporting that there are side-effects

Remove `IsDeref` parameter of `CGCXXABI::shouldTypeidBeNullChecked` because it 
should never return `true` if `!IsDeref` (we shouldn't add a null check that 
wasn't there in the first place)

>From fc28e8f9b987ca35db457afaf19fa8c2af2f9574 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sun, 16 Jun 2024 20:27:15 +0100
Subject: [PATCH] [Clang] Introduce CXXTypeidExpr::hasNullCheck

---
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/AST/ExprCXX.h|  4 ++
 clang/lib/AST/Expr.cpp   | 16 +--
 clang/lib/AST/ExprCXX.cpp| 49 ++
 clang/lib/CodeGen/CGCXXABI.h |  3 +-
 clang/lib/CodeGen/CGExprCXX.cpp  | 53 
 clang/lib/CodeGen/ItaniumCXXABI.cpp  |  7 ++--
 clang/lib/CodeGen/MicrosoftCXXABI.cpp|  8 ++--
 clang/lib/Sema/SemaExceptionSpec.cpp | 20 +++--
 clang/test/CXX/drs/cwg21xx.cpp   | 13 ++
 clang/test/SemaCXX/warn-unused-value.cpp |  8 
 11 files changed, 110 insertions(+), 74 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..6c92177d71298 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -268,6 +268,9 @@ Resolutions to C++ Defect Reports
 - Clang now requires a template argument list after a template keyword.
   (`CWG96: Syntactic disambiguation using the template keyword 
`_).
 
+- Clang no longer always reports ``!noexcept(typeid(expr))`` when the 
``typeid`` cannot throw a ``std::bad_typeid``.
+  (`CWG2191: Incorrect result for noexcept(typeid(v)) 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index d2e8d93656359..c2feac525c1ea 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -919,6 +919,10 @@ class CXXTypeidExpr : public Expr {
 reinterpret_cast(_cast(this)->Operand);
 return const_child_range(begin, begin + 1);
   }
+
+  /// Whether this is of a form like "typeid(*ptr)" that can throw a
+  /// std::bad_typeid if a pointer is a null pointer ([expr.typeid]p2)
+  bool hasNullCheck() const;
 };
 
 /// A member reference to an MSPropertyDecl.
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 7e555689b64c4..37ba5b69f446d 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3769,10 +3769,18 @@ bool Expr::HasSideEffects(const ASTContext ,
 break;
   }
 
-  case CXXTypeidExprClass:
-// typeid might throw if its subexpression is potentially-evaluated, so has
-// side-effects in that case whether or not its subexpression does.
-return cast(this)->isPotentiallyEvaluated();
+  case CXXTypeidExprClass: {
+const auto *TE = cast(this);
+if (!TE->isPotentiallyEvaluated())
+  return false;
+
+// If this type id expression can throw because of a null pointer, that is 
a
+// side-effect independent of if the operand has a side-effect
+if (IncludePossibleEffects && TE->hasNullCheck())
+  return true;
+
+break;
+  }
 
   case CXXConstructExprClass:
   case CXXTemporaryObjectExprClass: {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 2abc0acbfde3b..7ecdb908e7d9f 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -166,6 +166,55 @@ QualType CXXTypeidExpr::getTypeOperand(ASTContext 
) const {
   Operand.get()->getType().getNonReferenceType(), Quals);
 }
 
+namespace {
+static bool isGLValueFromPointerDeref(const Expr *E) {
+  E = E->IgnoreParens();
+
+  if (const auto *CE = dyn_cast(E)) {
+if (!CE->getSubExpr()->isGLValue())
+  return false;
+return isGLValueFromPointerDeref(CE->getSubExpr());
+  }
+
+  if (const auto *OVE = dyn_cast(E))
+return isGLValueFromPointerDeref(OVE->getSourceExpr());
+
+  if (const auto *BO = dyn_cast(E))
+if (BO->getOpcode() == BO_Comma)
+  return isGLValueFromPointerDeref(BO->getRHS());
+
+  if (const auto *ACO = dyn_cast(E))
+return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
+   isGLValueFromPointerDeref(ACO->getFalseExpr());
+
+  // C++11 [expr.sub]p1:
+  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
+  if (isa(E))
+return true;
+
+  if (const auto *UO = dyn_cast(E))
+if (UO->getOpcode() == UO_Deref)
+  return true;
+
+  return false;
+}
+} 

[clang] [Clang] Remove unreachable code in verilogGroupDecl (NFC) (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

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


[clang] [Clang] Remove unreachable code in verilogGroupDecl (NFC) (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

xgupta wrote:

> I think @sstwcw fixes this in #95703

Oh nice then, I will close this PR.

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


[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread Björn Schäpers via cfe-commits

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


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


[clang] [Clang] Remove unreachable code in verilogGroupDecl (NFC) (PR #95666)

2024-06-16 Thread Björn Schäpers via cfe-commits

HazardyKnusperkeks wrote:

I think @sstwcw fixes this in #95703

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


[clang] [clang-tools-extra] [llvm] [mlir] [clang][lldb][mlir] Fix some identical sub-expressions warnings (NFC) (PR #95715)

2024-06-16 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-mlir

@llvm/pr-subscribers-clang

Author: Shivam Gupta (xgupta)


Changes

This is reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N4-8

V501 There are identical sub-expressions 'FirstStmt-getStmtClass()' to the 
left and to the right of the '!=' operator. ASTUtils.cpp:99
V501 There are identical sub-expressions to the left and to the right of the 
'!=' operator: Fn1-isVariadic() != Fn1-isVariadic(). 
SemaOverload.cpp:10190
V501 There are identical sub-expressions to the left and to the right of the 
'' operator: G1-Rank  G1-Rank. SCCIterator.h:285
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:581
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:583
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:585
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:646
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:648
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:650
V501 There are identical sub-expressions 'EltRange.getEnd() = 
Range.getEnd()' to the left and to the right of the '||' operator. 
HTMLLogger.cpp:421
V501 There are identical sub-expressions 'SrcExpr.get()-containsErrors()' 
to the left and to the right of the '||' operator. SemaCast.cpp:2938
V501 There are identical sub-expressions 'ND-getDeclContext()' to the left 
and to the right of the '!=' operator. SemaDeclCXX.cpp:4391
V501 There are identical sub-expressions 'DepType != OMPC_DOACROSS_source' to 
the left and to the right of the '' operator. SemaOpenMP.cpp:24348
V501 There are identical sub-expressions '!OldMethod-isStatic()' to the 
left and to the right of the '' operator. SemaOverload.cpp:1425
V501 There are identical sub-expressions 'lldb::eTypeClassUnion' to the left 
and to the right of the '|' operator. JSONUtils.cpp:139
V501 There are identical sub-expressions to the left and to the right of the 
'' operator: !BFI !BFI. JumpThreading.cpp:2531
V501 There are identical sub-expressions 'BI-isConditional()' to the left 
and to the right of the '' operator. VPlanHCFGBuilder.cpp:401
V501 There are identical sub-expressions to the left and to the right of the 
'==' operator: getNumRows() == getNumRows(). Simplex.cpp:108

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


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/utils/ASTUtils.cpp (+1-1) 
- (modified) clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp (+3-4) 
- (modified) clang/lib/Sema/SemaCast.cpp (+1-2) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaOpenMP.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/JumpThreading.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp (+1-1) 
- (modified) mlir/lib/Analysis/Presburger/Simplex.cpp (+2-1) 
- (modified) mlir/lib/Interfaces/ValueBoundsOpInterface.cpp (+6-6) 


``diff
diff --git a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp 
b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
index fd5dadc9b01db..0cdc7d08abc99 100644
--- a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
@@ -96,7 +96,7 @@ bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt 
*SecondStmt,
   if (FirstStmt == SecondStmt)
 return true;
 
-  if (FirstStmt->getStmtClass() != FirstStmt->getStmtClass())
+  if (FirstStmt->getStmtClass() != SecondStmt->getStmtClass())
 return false;
 
   if (isa(FirstStmt) && isa(SecondStmt)) {
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index a36cb41a63dfb..323f9698dc2aa 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -430,11 +430,10 @@ class HTMLLogger : public Logger {
   AST.getSourceManager(), AST.getLangOpts());
   if (EltRange.isInvalid())
 continue;
-  if (EltRange.getBegin() < Range.getBegin() ||
-  EltRange.getEnd() >= Range.getEnd() ||
-  EltRange.getEnd() < Range.getBegin() ||
-  EltRange.getEnd() >= Range.getEnd())
+  if (EltRange.getEnd() <= Range.getBegin() ||
+  EltRange.getBegin() >= Range.getEnd())
 continue;
+
   unsigned Off = EltRange.getBegin().getRawEncoding() -
  Range.getBegin().getRawEncoding();

[clang] [clang-tools-extra] [llvm] [mlir] [clang][lldb][mlir] Fix some identical sub-expressions warnings (NFC) (PR #95715)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




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

Author: Shivam Gupta (xgupta)


Changes

This is reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N4-8

V501 There are identical sub-expressions 'FirstStmt-getStmtClass()' to the 
left and to the right of the '!=' operator. ASTUtils.cpp:99
V501 There are identical sub-expressions to the left and to the right of the 
'!=' operator: Fn1-isVariadic() != Fn1-isVariadic(). 
SemaOverload.cpp:10190
V501 There are identical sub-expressions to the left and to the right of the 
'' operator: G1-Rank  G1-Rank. SCCIterator.h:285
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:581
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:583
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:585
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:646
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:648
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:650
V501 There are identical sub-expressions 'EltRange.getEnd() = 
Range.getEnd()' to the left and to the right of the '||' operator. 
HTMLLogger.cpp:421
V501 There are identical sub-expressions 'SrcExpr.get()-containsErrors()' 
to the left and to the right of the '||' operator. SemaCast.cpp:2938
V501 There are identical sub-expressions 'ND-getDeclContext()' to the left 
and to the right of the '!=' operator. SemaDeclCXX.cpp:4391
V501 There are identical sub-expressions 'DepType != OMPC_DOACROSS_source' to 
the left and to the right of the '' operator. SemaOpenMP.cpp:24348
V501 There are identical sub-expressions '!OldMethod-isStatic()' to the 
left and to the right of the '' operator. SemaOverload.cpp:1425
V501 There are identical sub-expressions 'lldb::eTypeClassUnion' to the left 
and to the right of the '|' operator. JSONUtils.cpp:139
V501 There are identical sub-expressions to the left and to the right of the 
'' operator: !BFI !BFI. JumpThreading.cpp:2531
V501 There are identical sub-expressions 'BI-isConditional()' to the left 
and to the right of the '' operator. VPlanHCFGBuilder.cpp:401
V501 There are identical sub-expressions to the left and to the right of the 
'==' operator: getNumRows() == getNumRows(). Simplex.cpp:108

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


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/utils/ASTUtils.cpp (+1-1) 
- (modified) clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp (+3-4) 
- (modified) clang/lib/Sema/SemaCast.cpp (+1-2) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaOpenMP.cpp (+1-2) 
- (modified) llvm/lib/Transforms/Scalar/JumpThreading.cpp (+1-1) 
- (modified) llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp (+1-1) 
- (modified) mlir/lib/Analysis/Presburger/Simplex.cpp (+2-1) 
- (modified) mlir/lib/Interfaces/ValueBoundsOpInterface.cpp (+6-6) 


``diff
diff --git a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp 
b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
index fd5dadc9b01db..0cdc7d08abc99 100644
--- a/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ASTUtils.cpp
@@ -96,7 +96,7 @@ bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt 
*SecondStmt,
   if (FirstStmt == SecondStmt)
 return true;
 
-  if (FirstStmt->getStmtClass() != FirstStmt->getStmtClass())
+  if (FirstStmt->getStmtClass() != SecondStmt->getStmtClass())
 return false;
 
   if (isa(FirstStmt) && isa(SecondStmt)) {
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index a36cb41a63dfb..323f9698dc2aa 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -430,11 +430,10 @@ class HTMLLogger : public Logger {
   AST.getSourceManager(), AST.getLangOpts());
   if (EltRange.isInvalid())
 continue;
-  if (EltRange.getBegin() < Range.getBegin() ||
-  EltRange.getEnd() >= Range.getEnd() ||
-  EltRange.getEnd() < Range.getBegin() ||
-  EltRange.getEnd() >= Range.getEnd())
+  if (EltRange.getEnd() <= Range.getBegin() ||
+  EltRange.getBegin() >= Range.getEnd())
 continue;
+
   unsigned Off = EltRange.getBegin().getRawEncoding() -
  Range.getBegin().getRawEncoding();
   unsigned 

[clang] [clang-tools-extra] [llvm] [mlir] [clang][lldb][mlir] Fix some identical sub-expressions warnings (NFC) (PR #95715)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta created 
https://github.com/llvm/llvm-project/pull/95715

This is reported in https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment 
N4-8

V501 There are identical sub-expressions 'FirstStmt->getStmtClass()' to the 
left and to the right of the '!=' operator. ASTUtils.cpp:99
V501 There are identical sub-expressions to the left and to the right of the 
'!=' operator: Fn1->isVariadic() != Fn1->isVariadic(). SemaOverload.cpp:10190
V501 There are identical sub-expressions to the left and to the right of the 
'<' operator: G1->Rank < G1->Rank. SCCIterator.h:285
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:581
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:583
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:585
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:646
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to the 
left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:648
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:650
V501 There are identical sub-expressions 'EltRange.getEnd() >= Range.getEnd()' 
to the left and to the right of the '||' operator. HTMLLogger.cpp:421
V501 There are identical sub-expressions 'SrcExpr.get()->containsErrors()' to 
the left and to the right of the '||' operator. SemaCast.cpp:2938
V501 There are identical sub-expressions 'ND->getDeclContext()' to the left and 
to the right of the '!=' operator. SemaDeclCXX.cpp:4391
V501 There are identical sub-expressions 'DepType != OMPC_DOACROSS_source' to 
the left and to the right of the '&&' operator. SemaOpenMP.cpp:24348
V501 There are identical sub-expressions '!OldMethod->isStatic()' to the left 
and to the right of the '&&' operator. SemaOverload.cpp:1425
V501 There are identical sub-expressions 'lldb::eTypeClassUnion' to the left 
and to the right of the '|' operator. JSONUtils.cpp:139
V501 There are identical sub-expressions to the left and to the right of the 
'&&' operator: !BFI &&!BFI. JumpThreading.cpp:2531
V501 There are identical sub-expressions 'BI->isConditional()' to the left and 
to the right of the '&&' operator. VPlanHCFGBuilder.cpp:401
V501 There are identical sub-expressions to the left and to the right of the 
'==' operator: getNumRows() == getNumRows(). Simplex.cpp:108

>From f80cc3b6ee218e954d68e867637c38211f344d83 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 23:39:47 +0530
Subject: [PATCH] [clang][lldb][mlir] Fix some identical sub-expressions
 warnings (NFC)

This is actually reported in 
https://pvs-studio.com/en/blog/posts/cpp/1126/, fragment N4-8

V501 There are identical sub-expressions 'FirstStmt->getStmtClass()' to the 
left and to the right of the '!=' operator. ASTUtils.cpp:99
V501 There are identical sub-expressions to the left and to the right of 
the '!=' operator: Fn1->isVariadic() != Fn1->isVariadic(). 
SemaOverload.cpp:10190
V501 There are identical sub-expressions to the left and to the right of 
the '<' operator: G1->Rank < G1->Rank. SCCIterator.h:285
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' 
to the left and to the right of the '==' operator. 
ValueBoundsOpInterface.cpp:581
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:583
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' 
to the left and to the right of the '==' operator. 
ValueBoundsOpInterface.cpp:585
V501 There are identical sub-expressions 'slice1.getMixedOffsets().size()' 
to the left and to the right of the '==' operator. 
ValueBoundsOpInterface.cpp:646
V501 There are identical sub-expressions 'slice1.getMixedSizes().size()' to 
the left and to the right of the '==' operator. ValueBoundsOpInterface.cpp:648
V501 There are identical sub-expressions 'slice1.getMixedStrides().size()' 
to the left and to the right of the '==' operator. 
ValueBoundsOpInterface.cpp:650
V501 There are identical sub-expressions 'EltRange.getEnd() >= 
Range.getEnd()' to the left and to the right of the '||' operator. 
HTMLLogger.cpp:421
V501 There are identical sub-expressions 'SrcExpr.get()->containsErrors()' 
to the left and to the right of the '||' operator. SemaCast.cpp:2938
V501 There are identical sub-expressions 'ND->getDeclContext()' to the left 
and to the right of the '!=' operator. SemaDeclCXX.cpp:4391
V501 There are identical 

[clang-tools-extra] [llvm] [llvm] Remove the Legacy PM Hello example (PR #95708)

2024-06-16 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> > You also need to remove the use of this pass (for testing purposes) from 
> > clang-tools-extra.
> 
> Done, thanks!
> 
> I don't understand why CI still fails:
> 
> ```shell
> Total Discovered Tests: 60135
> --
>   | Skipped  :15 (0.02%)
>   | Unsupported  :  1005 (1.67%)
>   | Passed   : 58946 (98.02%)
>   | Expectedly Failed:   169 (0.28%)
>   | ninja: build stopped: cannot make progress due to previous errors.
>   | + show-stats
>   | + mkdir -p artifacts
>   | + ccache --print-stats
>   |  Error: The command exited with status 1
> ```
> 
> Can you see the actual failure? Looks like all tests passed, right?

It is caused by libc/lldb test failures. Don't worry :)


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


[clang-tools-extra] [llvm] [llvm] Remove the Legacy PM Hello example (PR #95708)

2024-06-16 Thread Andrzej Warzyński via cfe-commits

banach-space wrote:

> You also need to remove the use of this pass (for testing purposes) from 
> clang-tools-extra.

Done, thanks!

I don't understand why CI still fails:
```bash
Total Discovered Tests: 60135
--
  | Skipped  :15 (0.02%)
  | Unsupported  :  1005 (1.67%)
  | Passed   : 58946 (98.02%)
  | Expectedly Failed:   169 (0.28%)
  | ninja: build stopped: cannot make progress due to previous errors.
  | + show-stats
  | + mkdir -p artifacts
  | + ccache --print-stats
  |  Error: The command exited with status 1
```

Can you see the actual failure? Looks like all tests passed, right?

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread via cfe-commits

llvmbot wrote:




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

Author: Tor Shepherd (torshepherd)


Changes

Title. This PR adds support for showing implicit lambda captures:

![image](https://github.com/llvm/llvm-project/assets/49597791/d0150817-f71e-4971-8d8b-e25d2b1e8bf8)

and defaulted function arguments:

![image](https://github.com/llvm/llvm-project/assets/49597791/2a6b83a9-b918-4363-be67-d79ce244b067)

as inlay hints.

If the list of captures (or default args) is too long (based on TypeNameLimit), 
shows "..." instead:

![image](https://github.com/llvm/llvm-project/assets/49597791/9bd5ee8c-ed73-44f9-821f-f2b29e612432)

![image](https://github.com/llvm/llvm-project/assets/49597791/c48acd28-091a-4d7d-9344-01e12c622024)

Note: I wrote this before https://github.com/llvm/llvm-project/pull/85497 
landed. With this we should probably also follow up with go-to-definition on 
the lambda captures at least; I could see that being helpful

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


8 Files Affected:

- (modified) clang-tools-extra/clangd/Config.h (+2) 
- (modified) clang-tools-extra/clangd/ConfigCompile.cpp (+14-5) 
- (modified) clang-tools-extra/clangd/ConfigFragment.h (+5) 
- (modified) clang-tools-extra/clangd/ConfigYAML.cpp (+8-1) 
- (modified) clang-tools-extra/clangd/InlayHints.cpp (+84-3) 
- (modified) clang-tools-extra/clangd/Protocol.cpp (+7-1) 
- (modified) clang-tools-extra/clangd/Protocol.h (+24-9) 
- (modified) clang-tools-extra/clangd/unittests/InlayHintTests.cpp (+62-4) 


``diff
diff --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 41143b9ebc8d2..5100214244454 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -148,6 +148,8 @@ struct Config {
 bool DeducedTypes = true;
 bool Designators = true;
 bool BlockEnd = false;
+bool LambdaCaptures = false;
+bool DefaultArguments = false;
 // Limit the length of type names in inlay hints. (0 means no limit)
 uint32_t TypeNameLimit = 32;
   } InlayHints;
diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index f32f674443ffe..dcdb71ea01bb2 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -43,7 +43,6 @@
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/SMLoc.h"
 #include "llvm/Support/SourceMgr.h"
-#include 
 #include 
 #include 
 #include 
@@ -504,10 +503,10 @@ struct FragmentCompiler {
   auto Fast = isFastTidyCheck(Str);
   if (!Fast.has_value()) {
 diag(Warning,
- llvm::formatv(
- "Latency of clang-tidy check '{0}' is not known. "
- "It will only run if ClangTidy.FastCheckFilter is Loose or 
None",
- Str)
+ llvm::formatv("Latency of clang-tidy check '{0}' is not known. "
+   "It will only run if ClangTidy.FastCheckFilter is "
+   "Loose or None",
+   Str)
  .str(),
  Arg.Range);
   } else if (!*Fast) {
@@ -654,6 +653,16 @@ struct FragmentCompiler {
   Out.Apply.push_back([Value(**F.BlockEnd)](const Params &, Config ) {
 C.InlayHints.BlockEnd = Value;
   });
+if (F.LambdaCaptures)
+  Out.Apply.push_back(
+  [Value(**F.LambdaCaptures)](const Params &, Config ) {
+C.InlayHints.LambdaCaptures = Value;
+  });
+if (F.DefaultArguments)
+  Out.Apply.push_back(
+  [Value(**F.DefaultArguments)](const Params &, Config ) {
+C.InlayHints.DefaultArguments = Value;
+  });
 if (F.TypeNameLimit)
   Out.Apply.push_back(
   [Value(**F.TypeNameLimit)](const Params &, Config ) {
diff --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index f3e51a9b6dbc4..ad30b43f34874 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -331,6 +331,11 @@ struct Fragment {
 std::optional> Designators;
 /// Show defined symbol names at the end of a definition block.
 std::optional> BlockEnd;
+/// Show names of captured variables by default capture groups in lambdas.
+std::optional> LambdaCaptures;
+/// Show parameter names and default values of default arguments after all
+/// of the explicit arguments.
+std::optional> DefaultArguments;
 /// Limit the length of type name hints. (0 means no limit)
 std::optional> TypeNameLimit;
   };
diff --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 3e9b6a07d3b32..58e5f8bead101 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -14,7 +14,6 @@
 #include "llvm/Support/YAMLParser.h"
 #include 
 #include 
-#include 
 
 namespace clang {
 namespace clangd {
@@ -264,6 +263,14 @@ class Parser 

[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang-tools-extra] [clangd] Add inlay hints for default function arguments and implicit lambda captures (PR #95712)

2024-06-16 Thread Tor Shepherd via cfe-commits

https://github.com/torshepherd created 
https://github.com/llvm/llvm-project/pull/95712

Title. This PR adds support for showing implicit lambda captures:

![image](https://github.com/llvm/llvm-project/assets/49597791/d0150817-f71e-4971-8d8b-e25d2b1e8bf8)

and defaulted function arguments:

![image](https://github.com/llvm/llvm-project/assets/49597791/2a6b83a9-b918-4363-be67-d79ce244b067)

as inlay hints.

If the list of captures (or default args) is too long (based on TypeNameLimit), 
shows "..." instead:

![image](https://github.com/llvm/llvm-project/assets/49597791/9bd5ee8c-ed73-44f9-821f-f2b29e612432)

![image](https://github.com/llvm/llvm-project/assets/49597791/c48acd28-091a-4d7d-9344-01e12c622024)

Note: I wrote this before https://github.com/llvm/llvm-project/pull/85497 
landed. With this we should probably also follow up with go-to-definition on 
the lambda captures at least; I could see that being helpful

>From 741921857955983e1bce2ba828ec369568948688 Mon Sep 17 00:00:00 2001
From: Tor Shepherd 
Date: Sun, 16 Jun 2024 10:54:43 -0400
Subject: [PATCH] Add default arguments and lambda captures only

---
 clang-tools-extra/clangd/Config.h |  2 +
 clang-tools-extra/clangd/ConfigCompile.cpp| 19 ++--
 clang-tools-extra/clangd/ConfigFragment.h |  5 ++
 clang-tools-extra/clangd/ConfigYAML.cpp   |  9 +-
 clang-tools-extra/clangd/InlayHints.cpp   | 87 ++-
 clang-tools-extra/clangd/Protocol.cpp |  8 +-
 clang-tools-extra/clangd/Protocol.h   | 33 +--
 .../clangd/unittests/InlayHintTests.cpp   | 66 +-
 8 files changed, 206 insertions(+), 23 deletions(-)

diff --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 41143b9ebc8d2..5100214244454 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -148,6 +148,8 @@ struct Config {
 bool DeducedTypes = true;
 bool Designators = true;
 bool BlockEnd = false;
+bool LambdaCaptures = false;
+bool DefaultArguments = false;
 // Limit the length of type names in inlay hints. (0 means no limit)
 uint32_t TypeNameLimit = 32;
   } InlayHints;
diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index f32f674443ffe..dcdb71ea01bb2 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -43,7 +43,6 @@
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/SMLoc.h"
 #include "llvm/Support/SourceMgr.h"
-#include 
 #include 
 #include 
 #include 
@@ -504,10 +503,10 @@ struct FragmentCompiler {
   auto Fast = isFastTidyCheck(Str);
   if (!Fast.has_value()) {
 diag(Warning,
- llvm::formatv(
- "Latency of clang-tidy check '{0}' is not known. "
- "It will only run if ClangTidy.FastCheckFilter is Loose or 
None",
- Str)
+ llvm::formatv("Latency of clang-tidy check '{0}' is not known. "
+   "It will only run if ClangTidy.FastCheckFilter is "
+   "Loose or None",
+   Str)
  .str(),
  Arg.Range);
   } else if (!*Fast) {
@@ -654,6 +653,16 @@ struct FragmentCompiler {
   Out.Apply.push_back([Value(**F.BlockEnd)](const Params &, Config ) {
 C.InlayHints.BlockEnd = Value;
   });
+if (F.LambdaCaptures)
+  Out.Apply.push_back(
+  [Value(**F.LambdaCaptures)](const Params &, Config ) {
+C.InlayHints.LambdaCaptures = Value;
+  });
+if (F.DefaultArguments)
+  Out.Apply.push_back(
+  [Value(**F.DefaultArguments)](const Params &, Config ) {
+C.InlayHints.DefaultArguments = Value;
+  });
 if (F.TypeNameLimit)
   Out.Apply.push_back(
   [Value(**F.TypeNameLimit)](const Params &, Config ) {
diff --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index f3e51a9b6dbc4..ad30b43f34874 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -331,6 +331,11 @@ struct Fragment {
 std::optional> Designators;
 /// Show defined symbol names at the end of a definition block.
 std::optional> BlockEnd;
+/// Show names of captured variables by default capture groups in lambdas.
+std::optional> LambdaCaptures;
+/// Show parameter names and default values of default arguments after all
+/// of the explicit arguments.
+std::optional> DefaultArguments;
 /// Limit the length of type name hints. (0 means no limit)
 std::optional> TypeNameLimit;
   };
diff --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 3e9b6a07d3b32..58e5f8bead101 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -14,7 +14,6 @@
 #include 

[clang] [Clang][AArch64] Generalise streaming mode checks for builtins. (PR #93802)

2024-06-16 Thread Sander de Smalen via cfe-commits

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


[clang-tools-extra] [llvm] [llvm] Remove the Legacy PM Hello example (PR #95708)

2024-06-16 Thread Andrzej Warzyński via cfe-commits

https://github.com/banach-space updated 
https://github.com/llvm/llvm-project/pull/95708

From d75a05030447e8bcb1dd0b575ff5e7aa5c89f0bb Mon Sep 17 00:00:00 2001
From: Andrzej Warzynski 
Date: Sun, 16 Jun 2024 13:58:41 +0100
Subject: [PATCH 1/3] [llvm] Remove the Legacy PM Hello example

The Legacy PM was deprecated for the optimization pipeline in LLVM 14
[1] (the support was removed altogether in the following release). This
patch removes the original Hello example that was introduced to
illustrate the Legacy PM. The Hello example no longer works and hence is
deleted. The corresponding documentation is also removed.

Note, Hello example for new PM is located in
  * llvm/lib/Transforms/Utils/HelloWorld.cpp
and documented in
  * WritingAnLLVMNewPMPass.rst.

[1] 
https://releases.llvm.org/14.0.0/docs/ReleaseNotes.html#changes-to-the-llvm-ir
---
 llvm/lib/Transforms/CMakeLists.txt   |  1 -
 llvm/lib/Transforms/Hello/CMakeLists.txt | 20 
 llvm/lib/Transforms/Hello/Hello.cpp  | 64 
 llvm/lib/Transforms/Hello/Hello.exports  |  0
 4 files changed, 85 deletions(-)
 delete mode 100644 llvm/lib/Transforms/Hello/CMakeLists.txt
 delete mode 100644 llvm/lib/Transforms/Hello/Hello.cpp
 delete mode 100644 llvm/lib/Transforms/Hello/Hello.exports

diff --git a/llvm/lib/Transforms/CMakeLists.txt 
b/llvm/lib/Transforms/CMakeLists.txt
index 84a7e34147d08..7046f2f4b1d2c 100644
--- a/llvm/lib/Transforms/CMakeLists.txt
+++ b/llvm/lib/Transforms/CMakeLists.txt
@@ -5,7 +5,6 @@ add_subdirectory(InstCombine)
 add_subdirectory(Scalar)
 add_subdirectory(IPO)
 add_subdirectory(Vectorize)
-add_subdirectory(Hello)
 add_subdirectory(ObjCARC)
 add_subdirectory(Coroutines)
 add_subdirectory(CFGuard)
diff --git a/llvm/lib/Transforms/Hello/CMakeLists.txt 
b/llvm/lib/Transforms/Hello/CMakeLists.txt
deleted file mode 100644
index 9510c31f633fe..0
--- a/llvm/lib/Transforms/Hello/CMakeLists.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-# If we don't need RTTI or EH, there's no reason to export anything
-# from the hello plugin.
-if( NOT LLVM_REQUIRES_RTTI )
-  if( NOT LLVM_REQUIRES_EH )
-set(LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/Hello.exports)
-  endif()
-endif()
-
-if(WIN32 OR CYGWIN OR ZOS)
-  set(LLVM_LINK_COMPONENTS Core Support)
-endif()
-
-add_llvm_library( LLVMHello MODULE BUILDTREE_ONLY
-  Hello.cpp
-
-  DEPENDS
-  intrinsics_gen
-  PLUGIN_TOOL
-  opt
-  )
diff --git a/llvm/lib/Transforms/Hello/Hello.cpp 
b/llvm/lib/Transforms/Hello/Hello.cpp
deleted file mode 100644
index b0adb5401f891..0
--- a/llvm/lib/Transforms/Hello/Hello.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-//===- Hello.cpp - Example code from "Writing an LLVM Pass" 
---===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-// This file implements two versions of the LLVM "Hello World" pass described
-// in docs/WritingAnLLVMPass.html
-//
-//===--===//
-
-#include "llvm/ADT/Statistic.h"
-#include "llvm/IR/Function.h"
-#include "llvm/Pass.h"
-#include "llvm/Support/raw_ostream.h"
-using namespace llvm;
-
-#define DEBUG_TYPE "hello"
-
-STATISTIC(HelloCounter, "Counts number of functions greeted");
-
-namespace {
-  // Hello - The first implementation, without getAnalysisUsage.
-  struct Hello : public FunctionPass {
-static char ID; // Pass identification, replacement for typeid
-Hello() : FunctionPass(ID) {}
-
-bool runOnFunction(Function ) override {
-  ++HelloCounter;
-  errs() << "Hello: ";
-  errs().write_escaped(F.getName()) << '\n';
-  return false;
-}
-  };
-}
-
-char Hello::ID = 0;
-static RegisterPass X("hello", "Hello World Pass");
-
-namespace {
-  // Hello2 - The second implementation with getAnalysisUsage implemented.
-  struct Hello2 : public FunctionPass {
-static char ID; // Pass identification, replacement for typeid
-Hello2() : FunctionPass(ID) {}
-
-bool runOnFunction(Function ) override {
-  ++HelloCounter;
-  errs() << "Hello: ";
-  errs().write_escaped(F.getName()) << '\n';
-  return false;
-}
-
-// We don't modify the program, so we preserve all analyses.
-void getAnalysisUsage(AnalysisUsage ) const override {
-  AU.setPreservesAll();
-}
-  };
-}
-
-char Hello2::ID = 0;
-static RegisterPass
-Y("hello2", "Hello World Pass (with getAnalysisUsage implemented)");
diff --git a/llvm/lib/Transforms/Hello/Hello.exports 
b/llvm/lib/Transforms/Hello/Hello.exports
deleted file mode 100644
index e69de29bb2d1d..0

From bed0a86befc6f6b88a28a0eec53499e02b8bddad Mon Sep 17 00:00:00 2001
From: Andrzej Warzynski 
Date: Sun, 16 Jun 2024 17:10:37 +0100
Subject: [PATCH 2/3] fixup! [llvm] 

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-16 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/86629

>From b8a69cbd9e0ee0aa35b38b7e3a78048cbe61447e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 23:30:10 +0800
Subject: [PATCH 01/16] [clangd] Support go-to-definition on type hints. The
 core part

---
 clang-tools-extra/clangd/AST.cpp  |   9 +
 clang-tools-extra/clangd/AST.h|   2 +
 clang-tools-extra/clangd/InlayHints.cpp   | 251 +-
 .../clangd/index/IndexAction.cpp  |   9 +-
 .../clangd/unittests/InlayHintTests.cpp   |  22 ++
 5 files changed, 279 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 1b86ea19cf28d..ef87f1bcb8443 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -1019,5 +1019,14 @@ bool isExpandedFromParameterPack(const ParmVarDecl *D) {
   return getUnderlyingPackType(D) != nullptr;
 }
 
+std::optional toURI(OptionalFileEntryRef File) {
+  if (!File)
+return std::nullopt;
+  auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
+  if (AbsolutePath.empty())
+return std::nullopt;
+  return URI::create(AbsolutePath);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fb0722d697cd0..3ae624b1ab741 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -250,6 +250,8 @@ resolveForwardingParameters(const FunctionDecl *D, unsigned 
MaxDepth = 10);
 /// reference to one (e.g. `Args&...` or `Args&&...`).
 bool isExpandedFromParameterPack(const ParmVarDecl *D);
 
+std::optional toURI(OptionalFileEntryRef File);
+
 } // namespace clangd
 } // namespace clang
 
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index cd4f1931b3ce1..f9e0a51ddcc9f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/SourceManager.h"
@@ -372,6 +373,197 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+std::optional toLocation(SourceManager , SourceRange Range) {
+  if (Range.isInvalid())
+return std::nullopt;
+  if (auto URI =
+  toURI(SM.getFileEntryRefForID(SM.getFileID(Range.getBegin() {
+Location L;
+L.range.start = sourceLocToPosition(SM, Range.getBegin());
+L.range.end = sourceLocToPosition(SM, Range.getEnd());
+if (auto File = URIForFile::fromURI(*URI, ""))
+  L.uri = File.get();
+return L;
+  }
+  return std::nullopt;
+}
+
+class TypeInlayHintLabelPartBuilder
+: public TypeVisitor {
+  QualType Current;
+  ASTContext 
+  const PrintingPolicy 
+  std::vector 
+
+  bool ShouldAddLinksToTagTypes = false;
+
+  struct CurrentTypeRAII {
+TypeInlayHintLabelPartBuilder 
+QualType PreviousType;
+bool PreviousShouldAddLinksToTagTypes;
+CurrentTypeRAII(TypeInlayHintLabelPartBuilder , QualType New,
+bool ShouldAddLinksToTagTypes)
+: Builder(Builder), PreviousType(Builder.Current) {
+  Builder.Current = New;
+  Builder.ShouldAddLinksToTagTypes = ShouldAddLinksToTagTypes;
+}
+~CurrentTypeRAII() {
+  Builder.Current = PreviousType;
+  Builder.ShouldAddLinksToTagTypes = PreviousShouldAddLinksToTagTypes;
+}
+  };
+
+  void addLabel(llvm::function_ref NamePrinter,
+llvm::function_ref SourceRangeGetter) {
+auto  = LabelChunks.emplace_back();
+llvm::raw_string_ostream OS(Name.value);
+NamePrinter(OS);
+Name.location = toLocation(Context.getSourceManager(), 
SourceRangeGetter());
+  }
+
+  void printTemplateArgumentList(llvm::ArrayRef Args) {
+unsigned Size = Args.size();
+for (unsigned I = 0; I < Size; ++I) {
+  auto  = Args[I];
+  if (PP.SuppressDefaultTemplateArgs && TA.getIsDefaulted())
+continue;
+  if (I)
+LabelChunks.emplace_back(", ");
+  printTemplateArgument(TA);
+}
+  }
+
+  void printTemplateArgument(const TemplateArgument ) {
+if (TA.getKind() == TemplateArgument::Pack)
+  return printTemplateArgumentList(TA.pack_elements());
+if (TA.getKind() == TemplateArgument::Type) {
+  CurrentTypeRAII Guard(*this, TA.getAsType(),
+/*ShouldAddLinksToTagTypes=*/true);
+  return Visit(TA.getAsType().getTypePtr());
+}
+llvm::raw_string_ostream OS(LabelChunks.emplace_back().value);
+TA.print(PP, OS, /*IncludeType=*/true);
+  }
+
+  void
+  processTemplateSpecialization(TemplateName TN,
+llvm::ArrayRef Args,
+SourceRange TemplateNameRange = SourceRange()) 
{
+

[clang] [Clang] Remove unreachable code in verilogGroupDecl (NFC) (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/95666

>From 0e88700adf7add65f3eb8a2d4d2c2de72703a0f0 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sat, 15 Jun 2024 21:56:09 +0530
Subject: [PATCH 1/4] [Clang] Fix logical error in 'if else' condition that
 lead to an unreachable code

This is describe in https://pvs-studio.com/en/blog/posts/cpp/1126/ so caught by 
PVS
Studio analyzer.

Warning message  -
The use of 'if (A) {...} else if (A) {...}' pattern was detected

There were two same 'if' condition (Tok->is(tok::hash) but different execution 
blocks that was leading to
unnreachable code for second 'if else' condition.
---
 clang/lib/Format/TokenAnnotator.cpp | 23 +--
 1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..5a7029bda65f3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,11 +3369,19 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-// Start of a macro expansion.
-First = Tok;
-Tok = Next;
-if (Tok)
-  Tok = Tok->getNextNonComment();
+
+if (Next && Next->is(tok::l_paren)) {
+  // Handle parameterized macro.
+  Next = Next->MatchingParen;
+  if (Next)
+Tok = Next->getNextNonComment();
+} else {
+  // Start of a macro expansion.
+  First = Tok;
+  Tok = Next;
+  if (Tok)
+Tok = Tok->getNextNonComment();
+}
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;
@@ -3410,11 +3418,6 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
-if (Next->is(tok::l_paren))
-  Next = Next->MatchingParen;
-if (Next)
-  Tok = Next->getNextNonComment();
   } else {
 break;
   }

>From 17e1c3561830866592fd3a55e7a296194b221a90 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:00:48 +0530
Subject: [PATCH 2/4] remove dead code

---
 clang/lib/Format/TokenAnnotator.cpp | 7 ---
 1 file changed, 7 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5a7029bda65f3..3bc7caaa95529 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,13 +3369,6 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-
-if (Next && Next->is(tok::l_paren)) {
-  // Handle parameterized macro.
-  Next = Next->MatchingParen;
-  if (Next)
-Tok = Next->getNextNonComment();
-} else {
   // Start of a macro expansion.
   First = Tok;
   Tok = Next;

>From 3928b8936f05562312e177443821f452829034db Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:18:49 +0530
Subject: [PATCH 3/4] clang-format

---
 clang/lib/Format/TokenAnnotator.cpp | 12 ++--
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3bc7caaa95529..4150c59ac5081 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,12 +3369,12 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-  // Start of a macro expansion.
-  First = Tok;
-  Tok = Next;
-  if (Tok)
-Tok = Tok->getNextNonComment();
-}
+// Start of a macro expansion.
+First = Tok;
+Tok = Next;
+if (Tok)
+  Tok = Tok->getNextNonComment();
+  }
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;

>From 6f000eb0403847996b3da588f07b4506d4ec7c41 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:20:22 +0530
Subject: [PATCH 4/4] minor change

---
 clang/lib/Format/TokenAnnotator.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 4150c59ac5081..07599b6e1e3e1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3374,7 +3374,6 @@ class ExpressionParser {
 Tok = Next;
 if (Tok)
   Tok = Tok->getNextNonComment();
-  }
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;

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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/95666

>From 0e88700adf7add65f3eb8a2d4d2c2de72703a0f0 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sat, 15 Jun 2024 21:56:09 +0530
Subject: [PATCH 1/3] [Clang] Fix logical error in 'if else' condition that
 lead to an unreachable code

This is describe in https://pvs-studio.com/en/blog/posts/cpp/1126/ so caught by 
PVS
Studio analyzer.

Warning message  -
The use of 'if (A) {...} else if (A) {...}' pattern was detected

There were two same 'if' condition (Tok->is(tok::hash) but different execution 
blocks that was leading to
unnreachable code for second 'if else' condition.
---
 clang/lib/Format/TokenAnnotator.cpp | 23 +--
 1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..5a7029bda65f3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,11 +3369,19 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-// Start of a macro expansion.
-First = Tok;
-Tok = Next;
-if (Tok)
-  Tok = Tok->getNextNonComment();
+
+if (Next && Next->is(tok::l_paren)) {
+  // Handle parameterized macro.
+  Next = Next->MatchingParen;
+  if (Next)
+Tok = Next->getNextNonComment();
+} else {
+  // Start of a macro expansion.
+  First = Tok;
+  Tok = Next;
+  if (Tok)
+Tok = Tok->getNextNonComment();
+}
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;
@@ -3410,11 +3418,6 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
-if (Next->is(tok::l_paren))
-  Next = Next->MatchingParen;
-if (Next)
-  Tok = Next->getNextNonComment();
   } else {
 break;
   }

>From 17e1c3561830866592fd3a55e7a296194b221a90 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:00:48 +0530
Subject: [PATCH 2/3] remove dead code

---
 clang/lib/Format/TokenAnnotator.cpp | 7 ---
 1 file changed, 7 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5a7029bda65f3..3bc7caaa95529 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,13 +3369,6 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-
-if (Next && Next->is(tok::l_paren)) {
-  // Handle parameterized macro.
-  Next = Next->MatchingParen;
-  if (Next)
-Tok = Next->getNextNonComment();
-} else {
   // Start of a macro expansion.
   First = Tok;
   Tok = Next;

>From 3928b8936f05562312e177443821f452829034db Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:18:49 +0530
Subject: [PATCH 3/3] clang-format

---
 clang/lib/Format/TokenAnnotator.cpp | 12 ++--
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3bc7caaa95529..4150c59ac5081 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,12 +3369,12 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-  // Start of a macro expansion.
-  First = Tok;
-  Tok = Next;
-  if (Tok)
-Tok = Tok->getNextNonComment();
-}
+// Start of a macro expansion.
+First = Tok;
+Tok = Next;
+if (Tok)
+  Tok = Tok->getNextNonComment();
+  }
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;

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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 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 fa9745e8d39498a7090b108dd2717ca0466189e3 
17e1c3561830866592fd3a55e7a296194b221a90 -- clang/lib/Format/TokenAnnotator.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3bc7caaa95..4150c59ac5 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,12 +3369,12 @@ private:
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-  // Start of a macro expansion.
-  First = Tok;
-  Tok = Next;
-  if (Tok)
-Tok = Tok->getNextNonComment();
-}
+// Start of a macro expansion.
+First = Tok;
+Tok = Next;
+if (Tok)
+  Tok = Tok->getNextNonComment();
+  }
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;

``




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


[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)

2024-06-16 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

```cpp
ls
bstrwrap.cpp  bstrwrap.h  ctudir  test.cpp  test.plist  test.sh

cat bstrwrap.cpp
#include "bstrwrap.h"
#include 
Bstrlib::CBString::CBString () {
}

cat bstrwrap.h
#include 
namespace Bstrlib {
struct CBString {
 CBString ();
};
extern std::istream& getline (void);
}

cat test.cpp
#include "bstrwrap.h"
int test0 (void) {
 Bstrlib::CBString c0;
 return 0;
}

cat ctudir/externalDefMap.txt 
11:c:@f@test0# test.cpp.ast
35:c:@n@Bstrlib@S@CBString@F@CBString# bstrwrap.cpp.ast

~/llvm-project/build/bin/clang test.cpp -emit-ast -D__clang_analyzer__ -w -o 
ctudir/test.cpp.ast
~/llvm-project/build/bin/clang bstrwrap.cpp -emit-ast -D__clang_analyzer__ -w 
-o ctudir/bstrwrap.cpp.ast
~/llvm-project/build/bin/clang --analyze -Xclang -analyzer-config -Xclang 
experimental-enable-naive-ctu-analysis=true -Xclang -analyzer-config -Xclang 
ctu-dir=ctudir -Xclang -analyzer-config -Xclang display-ctu-progress=true 
test.cpp
```
I have tested locally using main branch with clang and it has no crash. Maybe I 
missed something? Could you please take a second look? @vabridgers 

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


[clang] [Clang] Fix logical error in 'if else' condition that lead to an unreachable code (PR #95666)

2024-06-16 Thread Shivam Gupta via cfe-commits

https://github.com/xgupta updated 
https://github.com/llvm/llvm-project/pull/95666

>From 0e88700adf7add65f3eb8a2d4d2c2de72703a0f0 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sat, 15 Jun 2024 21:56:09 +0530
Subject: [PATCH 1/2] [Clang] Fix logical error in 'if else' condition that
 lead to an unreachable code

This is describe in https://pvs-studio.com/en/blog/posts/cpp/1126/ so caught by 
PVS
Studio analyzer.

Warning message  -
The use of 'if (A) {...} else if (A) {...}' pattern was detected

There were two same 'if' condition (Tok->is(tok::hash) but different execution 
blocks that was leading to
unnreachable code for second 'if else' condition.
---
 clang/lib/Format/TokenAnnotator.cpp | 23 +--
 1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..5a7029bda65f3 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,11 +3369,19 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-// Start of a macro expansion.
-First = Tok;
-Tok = Next;
-if (Tok)
-  Tok = Tok->getNextNonComment();
+
+if (Next && Next->is(tok::l_paren)) {
+  // Handle parameterized macro.
+  Next = Next->MatchingParen;
+  if (Next)
+Tok = Next->getNextNonComment();
+} else {
+  // Start of a macro expansion.
+  First = Tok;
+  Tok = Next;
+  if (Tok)
+Tok = Tok->getNextNonComment();
+}
   } else if (Tok->is(tok::hashhash)) {
 // Concatenation. Skip.
 Tok = Next;
@@ -3410,11 +3418,6 @@ class ExpressionParser {
 } else {
   break;
 }
-  } else if (Tok->is(tok::hash)) {
-if (Next->is(tok::l_paren))
-  Next = Next->MatchingParen;
-if (Next)
-  Tok = Next->getNextNonComment();
   } else {
 break;
   }

>From 17e1c3561830866592fd3a55e7a296194b221a90 Mon Sep 17 00:00:00 2001
From: Shivam Gupta 
Date: Sun, 16 Jun 2024 20:00:48 +0530
Subject: [PATCH 2/2] remove dead code

---
 clang/lib/Format/TokenAnnotator.cpp | 7 ---
 1 file changed, 7 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5a7029bda65f3..3bc7caaa95529 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3369,13 +3369,6 @@ class ExpressionParser {
   FormatToken *Next = Tok->getNextNonComment();
 
   if (Tok->is(tok::hash)) {
-
-if (Next && Next->is(tok::l_paren)) {
-  // Handle parameterized macro.
-  Next = Next->MatchingParen;
-  if (Next)
-Tok = Next->getNextNonComment();
-} else {
   // Start of a macro expansion.
   First = Tok;
   Tok = Next;

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


  1   2   >