[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)

2024-04-21 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/89497

>From 91915f68902ade86c0bf8eba643428017ae8bb3c Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sat, 20 Apr 2024 17:58:19 +0800
Subject: [PATCH 1/4] [tidy] add new check
 bugprone-return-const-ref-from-parameter

Detects the function which returns the const reference from parameter which
causes potential use after free if the caller uses xvalue as argument.
In c++, const reference parameter can accept xvalue which will be destructed
after the call. When the function returns this parameter also as const 
reference,
then the returned reference can be used after the object it refers to has been
destroyed.
Fixes: #85253
---
 .../bugprone/BugproneTidyModule.cpp   |  3 ++
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../ReturnConstRefFromParameterCheck.cpp  | 41 +++
 .../ReturnConstRefFromParameterCheck.h| 35 
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 +++
 .../return-const-ref-from-parameter.rst   | 30 ++
 .../docs/clang-tidy/checks/list.rst   |  9 ++--
 .../return-const-ref-from-parameter.cpp   | 31 ++
 8 files changed, 152 insertions(+), 4 deletions(-)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/return-const-ref-from-parameter.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 2931325d8b5798..1b92d2e60cc173 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -54,6 +54,7 @@
 #include "PosixReturnCheck.h"
 #include "RedundantBranchConditionCheck.h"
 #include "ReservedIdentifierCheck.h"
+#include "ReturnConstRefFromParameterCheck.h"
 #include "SharedPtrArrayMismatchCheck.h"
 #include "SignalHandlerCheck.h"
 #include "SignedCharMisuseCheck.h"
@@ -137,6 +138,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-inaccurate-erase");
 CheckFactories.registerCheck(
 "bugprone-incorrect-enable-if");
+CheckFactories.registerCheck(
+"bugprone-return-const-ref-from-parameter");
 CheckFactories.registerCheck(
 "bugprone-switch-missing-default-case");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 081ba67efe1538..2d303191f88650 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -26,6 +26,7 @@ add_clang_library(clangTidyBugproneModule
   ImplicitWideningOfMultiplicationResultCheck.cpp
   InaccurateEraseCheck.cpp
   IncorrectEnableIfCheck.cpp
+  ReturnConstRefFromParameterCheck.cpp
   SuspiciousStringviewDataUsageCheck.cpp
   SwitchMissingDefaultCaseCheck.cpp
   IncDecInConditionsCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp
new file mode 100644
index 00..87fc663231496e
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp
@@ -0,0 +1,41 @@
+//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ReturnConstRefFromParameterCheck.h"
+#include "../utils/Matchers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+std::optional
+ReturnConstRefFromParameterCheck::getCheckTraversalKind() const {
+  // Use 'AsIs' to make sure the return type is exactly the same as the
+  // parameter type.
+  return TK_AsIs;
+}
+
+void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  returnStmt(hasReturnValue(declRefExpr(to(parmVarDecl(hasType(
+ hasCanonicalType(matchers::isReferenceToConst(
+  .bind("ret"),
+  this);
+}
+
+void ReturnConstRefFromParameterCheck::check(
+const MatchFinder::MatchResult ) {
+  const auto *R = Result.Nodes.getNodeAs("ret");
+  diag(R->getRetValue()->getBeginLoc(),
+   "return const reference parameter cause potential use-after-free "
+   

[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)

2024-04-21 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/89497

>From 91915f68902ade86c0bf8eba643428017ae8bb3c Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sat, 20 Apr 2024 17:58:19 +0800
Subject: [PATCH 1/4] [tidy] add new check
 bugprone-return-const-ref-from-parameter

Detects the function which returns the const reference from parameter which
causes potential use after free if the caller uses xvalue as argument.
In c++, const reference parameter can accept xvalue which will be destructed
after the call. When the function returns this parameter also as const 
reference,
then the returned reference can be used after the object it refers to has been
destroyed.
Fixes: #85253
---
 .../bugprone/BugproneTidyModule.cpp   |  3 ++
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../ReturnConstRefFromParameterCheck.cpp  | 41 +++
 .../ReturnConstRefFromParameterCheck.h| 35 
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 +++
 .../return-const-ref-from-parameter.rst   | 30 ++
 .../docs/clang-tidy/checks/list.rst   |  9 ++--
 .../return-const-ref-from-parameter.cpp   | 31 ++
 8 files changed, 152 insertions(+), 4 deletions(-)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/return-const-ref-from-parameter.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 2931325d8b5798..1b92d2e60cc173 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -54,6 +54,7 @@
 #include "PosixReturnCheck.h"
 #include "RedundantBranchConditionCheck.h"
 #include "ReservedIdentifierCheck.h"
+#include "ReturnConstRefFromParameterCheck.h"
 #include "SharedPtrArrayMismatchCheck.h"
 #include "SignalHandlerCheck.h"
 #include "SignedCharMisuseCheck.h"
@@ -137,6 +138,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-inaccurate-erase");
 CheckFactories.registerCheck(
 "bugprone-incorrect-enable-if");
+CheckFactories.registerCheck(
+"bugprone-return-const-ref-from-parameter");
 CheckFactories.registerCheck(
 "bugprone-switch-missing-default-case");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 081ba67efe1538..2d303191f88650 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -26,6 +26,7 @@ add_clang_library(clangTidyBugproneModule
   ImplicitWideningOfMultiplicationResultCheck.cpp
   InaccurateEraseCheck.cpp
   IncorrectEnableIfCheck.cpp
+  ReturnConstRefFromParameterCheck.cpp
   SuspiciousStringviewDataUsageCheck.cpp
   SwitchMissingDefaultCaseCheck.cpp
   IncDecInConditionsCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp
new file mode 100644
index 00..87fc663231496e
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp
@@ -0,0 +1,41 @@
+//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ReturnConstRefFromParameterCheck.h"
+#include "../utils/Matchers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+std::optional
+ReturnConstRefFromParameterCheck::getCheckTraversalKind() const {
+  // Use 'AsIs' to make sure the return type is exactly the same as the
+  // parameter type.
+  return TK_AsIs;
+}
+
+void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  returnStmt(hasReturnValue(declRefExpr(to(parmVarDecl(hasType(
+ hasCanonicalType(matchers::isReferenceToConst(
+  .bind("ret"),
+  this);
+}
+
+void ReturnConstRefFromParameterCheck::check(
+const MatchFinder::MatchResult ) {
+  const auto *R = Result.Nodes.getNodeAs("ret");
+  diag(R->getRetValue()->getBeginLoc(),
+   "return const reference parameter cause potential use-after-free "
+   

[clang] [clang-tools-extra] [clangd] Show struct fields and enum members in hovers (PR #89557)

2024-04-21 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 commented:

Thank you! I have a few questions:
1) Do we want an RFC in discourse for the changes in `DeclPrinter`?
2) Do you think we should also add some test cases to `DeclPrinterTest.cpp`?

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


[clang] [clang-tools-extra] [clangd] Show struct fields and enum members in hovers (PR #89557)

2024-04-21 Thread Younan Zhang via cfe-commits


@@ -474,6 +477,17 @@ void DeclPrinter::VisitDeclContext(DeclContext *DC, bool 
Indent) {
   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = 
DC->decls_end();
D != DEnd; ++D) {
 
+// Print enum members and public struct fields when
+// PrintTagTypeContents=true. Only applicable when TerseOutput=true since
+// otherwise all members are printed.
+if (Policy.TerseOutput) {
+  assert(Policy.PrintTagTypeContents);

zyn0217 wrote:

This assertion is doing nothing because we have exited early at the function 
beginning...?

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


[clang] [clang-tools-extra] [clangd] Show struct fields and enum members in hovers (PR #89557)

2024-04-21 Thread Younan Zhang via cfe-commits


@@ -474,6 +477,17 @@ void DeclPrinter::VisitDeclContext(DeclContext *DC, bool 
Indent) {
   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = 
DC->decls_end();
D != DEnd; ++D) {
 
+// Print enum members and public struct fields when
+// PrintTagTypeContents=true. Only applicable when TerseOutput=true since
+// otherwise all members are printed.
+if (Policy.TerseOutput) {
+  assert(Policy.PrintTagTypeContents);
+  if (!(isa(*D) ||
+(isa(*D) &&
+ dyn_cast(*D)->getAccess() == AS_public)))

zyn0217 wrote:

Do you have any tests on C codes? Looking around the codebase, I think 
`AS_none` *might* be used in some cases wrt non-C++ codes?

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


[clang] [clang-tools-extra] [clangd] Show struct fields and enum members in hovers (PR #89557)

2024-04-21 Thread Younan Zhang via cfe-commits

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


[clang] [AIX][TLS][clang] Add -maix-small-local-dynamic-tls clang option (PR #88829)

2024-04-21 Thread Chen Zheng via cfe-commits

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

LGTM with one nit. Thanks for adding this support.

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


[clang] [AIX][TLS][clang] Add -maix-small-local-dynamic-tls clang option (PR #88829)

2024-04-21 Thread Chen Zheng via cfe-commits


@@ -6,6 +6,9 @@
 // RUN: %clang -target powerpc64-unknown-aix -maix-small-local-exec-tls -S 
-emit-llvm \
 // RUN:%s -o - | FileCheck %s --check-prefix=CHECK-AIX_SMALL_LOCALEXEC_TLS
 
+// RUN: %clang -target powerpc64-unknown-aix -maix-small-local-dynamic-tls -S 
-emit-llvm \

chenzheng1030 wrote:

nit: maybe we can rename this file?

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


[clang] [AIX][TLS][clang] Add -maix-small-local-dynamic-tls clang option (PR #88829)

2024-04-21 Thread Chen Zheng via cfe-commits

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


[clang] [clang-tools-extra] [clangd] Show struct fields and enum members in hovers (PR #89557)

2024-04-21 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

A few things I would appreciate feedback on:

 1. I know a [previous comment on the 
bug](https://github.com/clangd/clangd/issues/959#issuecomment-998927030) stated 
"We don't show bodies of classes/enums/functions etc by policy", but can we 
consider changing this policy in the more limited case of public struct fields 
and enum members? Like I mentioned in [this 
comment](https://github.com/clangd/clangd/issues/959#issuecomment-2068307365), 
the usefulness/verbosity tradeoff might be different in this subset of cases. 
Also cc @colin-grant-work in case you'd like to weigh in on this further.
 2. If we're willing to make this change, do we want it unconditionally, or 
behind a new config option in the `Hover` section? My personal opinion is that 
even in the case of a struct/enum with many members this is not particularly 
bothersome and would lean towards making it unconditional, but I am of course 
happy to put it behind a config option if that helps build a consensus for this.
 3. Regarding the implementation approach, is it fine to add a flag to 
`PrintingPolicy` (which is a clang utility class used in a variety of places) 
for a clangd-specific use case like this? I did it this way because the 
alternative seemed to involve duplicating a bunch of code related to 
decl-printing, but I'm happy to explore alternatives if this is an issue.

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


[clang] [Clang] Fix a crash introduced in PR#88666 (PR #89567)

2024-04-21 Thread via cfe-commits

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


[clang] [clang-tools-extra] [clangd] Show struct fields and enum members in hovers (PR #89557)

2024-04-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Nathan Ridge (HighCommander4)


Changes

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

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


4 Files Affected:

- (modified) clang-tools-extra/clangd/Hover.cpp (+2) 
- (modified) clang-tools-extra/clangd/unittests/HoverTests.cpp (+13-4) 
- (modified) clang/include/clang/AST/PrettyPrinter.h (+9-1) 
- (modified) clang/lib/AST/DeclPrinter.cpp (+17-3) 


``diff
diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 06b949bc4a2b55..d7c433876b08bc 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -69,6 +69,8 @@ namespace {
 PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
   Base.AnonymousTagLocations = false;
   Base.TerseOutput = true;
+  // Show struct fields and enum members.
+  Base.PrintTagTypeContents = true;
   Base.PolishForDeclaration = true;
   Base.ConstantsAsWritten = true;
   Base.SuppressTemplateArgsInCXXConstructors = true;
diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 35db757b9c15b5..8c19f5fb3b0ad0 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1645,7 +1645,16 @@ TEST(Hover, All) {
   {
   R"cpp(// Struct
 namespace ns1 {
-  struct MyClass {};
+  struct MyClass {
+// Public fields shown in hover
+int field1;
+int field2;
+
+// Methods and private fields not shown
+void method();
+  private:
+bool private_field;
+  };
 } // namespace ns1
 int main() {
   ns1::[[My^Class]]* Params;
@@ -1655,7 +1664,7 @@ TEST(Hover, All) {
 HI.Name = "MyClass";
 HI.Kind = index::SymbolKind::Struct;
 HI.NamespaceScope = "ns1::";
-HI.Definition = "struct MyClass {}";
+HI.Definition = "struct MyClass {\n  int field1;\n  int 
field2;\n}";
   }},
   {
   R"cpp(// Class
@@ -1685,7 +1694,7 @@ TEST(Hover, All) {
 HI.Name = "MyUnion";
 HI.Kind = index::SymbolKind::Union;
 HI.NamespaceScope = "ns1::";
-HI.Definition = "union MyUnion {}";
+HI.Definition = "union MyUnion {\n  int x;\n  int y;\n}";
   }},
   {
   R"cpp(// Function definition via pointer
@@ -2030,7 +2039,7 @@ TEST(Hover, All) {
 HI.Name = "Hello";
 HI.Kind = index::SymbolKind::Enum;
 HI.NamespaceScope = "";
-HI.Definition = "enum Hello {}";
+HI.Definition = "enum Hello { ONE, TWO, THREE }";
 HI.Documentation = "Enum declaration";
   }},
   {
diff --git a/clang/include/clang/AST/PrettyPrinter.h 
b/clang/include/clang/AST/PrettyPrinter.h
index da276e26049b00..6b8f1ae9143df3 100644
--- a/clang/include/clang/AST/PrettyPrinter.h
+++ b/clang/include/clang/AST/PrettyPrinter.h
@@ -70,7 +70,7 @@ struct PrintingPolicy {
 Restrict(LO.C99), Alignof(LO.CPlusPlus11), UnderscoreAlignof(LO.C11),
 UseVoidForZeroParams(!LO.CPlusPlus),
 SplitTemplateClosers(!LO.CPlusPlus11), TerseOutput(false),
-PolishForDeclaration(false), Half(LO.Half),
+PrintTagTypeContents(false), PolishForDeclaration(false), 
Half(LO.Half),
 MSWChar(LO.MicrosoftExt && !LO.WChar), IncludeNewlines(true),
 MSVCFormatting(false), ConstantsAsWritten(false),
 SuppressImplicitBase(false), FullyQualifiedName(false),
@@ -252,6 +252,14 @@ struct PrintingPolicy {
   LLVM_PREFERRED_TYPE(bool)
   unsigned TerseOutput : 1;
 
+  /// Print the contents of tag (i.e. record and enum) types, even with
+  /// TerseOutput=true.
+  ///
+  /// For record types (structs/classes/unions), this only prints public
+  /// data members. For enum types, this prints enumerators.
+  /// Has no effect if TerseOutput=false (which prints all members).
+  unsigned PrintTagTypeContents : 1;
+
   /// When true, do certain refinement needed for producing proper declaration
   /// tag; such as, do not print attributes attached to the declaration.
   ///
diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp
index 43d221968ea3fb..3fe02fff687fe1 100644
--- a/clang/lib/AST/DeclPrinter.cpp
+++ b/clang/lib/AST/DeclPrinter.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/Basic/Module.h"
+#include "clang/Basic/Specifiers.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace clang;
 
@@ -464,8 +465,10 @@ void 
DeclPrinter::PrintConstructorInitializers(CXXConstructorDecl *CDecl,
 //
 
 void DeclPrinter::VisitDeclContext(DeclContext 

[clang] [clang-tools-extra] [clangd] Show struct fields and enum members in hovers (PR #89557)

2024-04-21 Thread Nathan Ridge via cfe-commits

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


[clang] [Clang] Fix a crash introduced in PR#88666 (PR #89567)

2024-04-21 Thread Shilei Tian via cfe-commits

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

>From 041574d22c2debb5299926b58aed529919905902 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Mon, 22 Apr 2024 01:09:47 -0400
Subject: [PATCH] [Clang] Fix a crash introduced in PR#88666

The unroll value can be a template variable such that we need to check it before
we verify if it is constant value.
---
 clang/lib/Sema/SemaStmtAttr.cpp |  2 +-
 clang/test/Sema/unroll-template-value-crash.cpp | 10 ++
 2 files changed, 11 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Sema/unroll-template-value-crash.cpp

diff --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp
index 7cd494b42250d4..9d44c22c8ddcc3 100644
--- a/clang/lib/Sema/SemaStmtAttr.cpp
+++ b/clang/lib/Sema/SemaStmtAttr.cpp
@@ -109,7 +109,7 @@ static Attr *handleLoopHintAttr(Sema , Stmt *St, const 
ParsedAttr ,
 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
   } else if (PragmaName == "unroll") {
 // #pragma unroll N
-if (ValueExpr) {
+if (ValueExpr && !ValueExpr->isValueDependent()) {
   llvm::APSInt ValueAPS;
   ExprResult R = S.VerifyIntegerConstantExpression(ValueExpr, );
   assert(!R.isInvalid() && "unroll count value must be a valid value, it's 
"
diff --git a/clang/test/Sema/unroll-template-value-crash.cpp 
b/clang/test/Sema/unroll-template-value-crash.cpp
new file mode 100644
index 00..d8953c4845c265
--- /dev/null
+++ b/clang/test/Sema/unroll-template-value-crash.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -x c++ -verify %s
+// expected-no-diagnostics
+
+template  void foo() {
+  #pragma unroll Unroll
+  for (int i = 0; i < Unroll; ++i);
+
+  #pragma GCC unroll Unroll
+  for (int i = 0; i < Unroll; ++i);
+}

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


[clang] [Clang] Fix a crash introduced in PR#88666 (PR #89567)

2024-04-21 Thread via cfe-commits


@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -x c++ -verify %s
+// expected-no-diagnostics
+
+template  void foo() {
+  #pragma unroll Unroll
+  for (int i = 0; i < Unroll; ++i);
+}

yronglin wrote:

I'd like to add a test for '#pragma GCC unroll N', WDYT?

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


[clang] [Clang] Fix a crash introduced in PR#88666 (PR #89567)

2024-04-21 Thread via cfe-commits

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

Thakns for your fix, LGTM!

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


[clang] [Clang] Allow the value of unroll count to be zero in `#pragma GCC unroll` and `#pragma unroll` (PR #88666)

2024-04-21 Thread via cfe-commits

yronglin wrote:

Thank you report this issue! @ronlieb Could you please provide a simple 
reproducer, we can use it to strengthen clang's test.

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


[clang] [Clang] Fix a crash introduced in PR#88666 (PR #89567)

2024-04-21 Thread Shilei Tian via cfe-commits

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

>From 3503f2bfd28af5be8e87835c47207d770659db3c Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Mon, 22 Apr 2024 00:06:31 -0400
Subject: [PATCH] [Clang] Fix a crash introduced in PR#88666

The unroll value can be a template variable such that we need to check it before
we verify if it is constant value.
---
 clang/lib/Sema/SemaStmtAttr.cpp | 2 +-
 clang/test/Sema/unroll-template-value-crash.cpp | 7 +++
 2 files changed, 8 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Sema/unroll-template-value-crash.cpp

diff --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp
index 7cd494b42250d4..9d44c22c8ddcc3 100644
--- a/clang/lib/Sema/SemaStmtAttr.cpp
+++ b/clang/lib/Sema/SemaStmtAttr.cpp
@@ -109,7 +109,7 @@ static Attr *handleLoopHintAttr(Sema , Stmt *St, const 
ParsedAttr ,
 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
   } else if (PragmaName == "unroll") {
 // #pragma unroll N
-if (ValueExpr) {
+if (ValueExpr && !ValueExpr->isValueDependent()) {
   llvm::APSInt ValueAPS;
   ExprResult R = S.VerifyIntegerConstantExpression(ValueExpr, );
   assert(!R.isInvalid() && "unroll count value must be a valid value, it's 
"
diff --git a/clang/test/Sema/unroll-template-value-crash.cpp 
b/clang/test/Sema/unroll-template-value-crash.cpp
new file mode 100644
index 00..4aea46ca727a8d
--- /dev/null
+++ b/clang/test/Sema/unroll-template-value-crash.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -x c++ -verify %s
+// expected-no-diagnostics
+
+template  void foo() {
+  #pragma unroll Unroll
+  for (int i = 0; i < Unroll; ++i);
+}

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


[clang] [Clang] Allow the value of unroll count to be zero in `#pragma GCC unroll` and `#pragma unroll` (PR #88666)

2024-04-21 Thread Shilei Tian via cfe-commits

shiltian wrote:

@alexfh @ronlieb @Endilll fix in 
https://github.com/llvm/llvm-project/pull/89567.

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


[clang] [Clang] Fix a crash introduced in PR#88666 (PR #89567)

2024-04-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Shilei Tian (shiltian)


Changes

The unroll value can be a template variable such that we need to check it before
we verify if it is constant value.


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


2 Files Affected:

- (modified) clang/lib/Sema/SemaStmtAttr.cpp (+1-1) 
- (added) clang/test/Sema/unroll-template-value-crash.cpp (+7) 


``diff
diff --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp
index 7cd494b42250d4..9d44c22c8ddcc3 100644
--- a/clang/lib/Sema/SemaStmtAttr.cpp
+++ b/clang/lib/Sema/SemaStmtAttr.cpp
@@ -109,7 +109,7 @@ static Attr *handleLoopHintAttr(Sema , Stmt *St, const 
ParsedAttr ,
 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
   } else if (PragmaName == "unroll") {
 // #pragma unroll N
-if (ValueExpr) {
+if (ValueExpr && !ValueExpr->isValueDependent()) {
   llvm::APSInt ValueAPS;
   ExprResult R = S.VerifyIntegerConstantExpression(ValueExpr, );
   assert(!R.isInvalid() && "unroll count value must be a valid value, it's 
"
diff --git a/clang/test/Sema/unroll-template-value-crash.cpp 
b/clang/test/Sema/unroll-template-value-crash.cpp
new file mode 100644
index 00..bb200fc3667c8f
--- /dev/null
+++ b/clang/test/Sema/unroll-template-value-crash.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -x c++ -emit-llvm -S -verify %s
+// expected-no-diagnostics
+
+template  void foo() {
+  #pragma unroll Unroll
+  for (int i = 0; i < Unroll; ++i);
+}

``




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


[clang] [llvm] [clang][MBD] set up module build daemon infrastructure (PR #67562)

2024-04-21 Thread Connor Sughrue via cfe-commits


@@ -0,0 +1,25 @@
+// Check that a clang invocation can spawn and handshake with a module build 
daemon
+
+// RUN: %kill-process "-cc1modbuildd mbd-handshake"
+// RUN: rm -rf mbd-handshake %t
+// RUN: split-file %s %t
+
+//--- main.c
+int main() {return 0;}
+
+// RUN: %clang -fmodule-build-daemon=mbd-handshake -Rmodule-build-daemon 
%t/main.c &> %t/output-new || true

cpsughrue wrote:

That's understandable. To ensure I understand, do you want to see an example 
where the client dies after receiving the handshake response and fails to 
deliver a payload or do you want to see a payload and response sent back and 
forth after the handshake? I think it would be sufficient to carry out a second 
handshake if it's the latter. The only difference between a second handshake 
and a new payload message is the contents of the buffer, which I don't think is 
super important since we mainly care about the mechanisms behind preventing 
zombie processes.

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


[clang] [Clang] Fix a crash introduced in PR#88666 (PR #89567)

2024-04-21 Thread Shilei Tian via cfe-commits

https://github.com/shiltian created 
https://github.com/llvm/llvm-project/pull/89567

The unroll value can be a template variable such that we need to check it before
we verify if it is constant value.


>From 8f14bcc2ea3d4badb63b953dc23b27b49b0a6521 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Sun, 21 Apr 2024 23:41:35 -0400
Subject: [PATCH] [Clang] Fix a crash introduced in PR#88666

The unroll value can be a template variable such that we need to check it before
we verify if it is constant value.
---
 clang/lib/Sema/SemaStmtAttr.cpp | 2 +-
 clang/test/Sema/unroll-template-value-crash.cpp | 7 +++
 2 files changed, 8 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Sema/unroll-template-value-crash.cpp

diff --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp
index 7cd494b42250d4..9d44c22c8ddcc3 100644
--- a/clang/lib/Sema/SemaStmtAttr.cpp
+++ b/clang/lib/Sema/SemaStmtAttr.cpp
@@ -109,7 +109,7 @@ static Attr *handleLoopHintAttr(Sema , Stmt *St, const 
ParsedAttr ,
 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable);
   } else if (PragmaName == "unroll") {
 // #pragma unroll N
-if (ValueExpr) {
+if (ValueExpr && !ValueExpr->isValueDependent()) {
   llvm::APSInt ValueAPS;
   ExprResult R = S.VerifyIntegerConstantExpression(ValueExpr, );
   assert(!R.isInvalid() && "unroll count value must be a valid value, it's 
"
diff --git a/clang/test/Sema/unroll-template-value-crash.cpp 
b/clang/test/Sema/unroll-template-value-crash.cpp
new file mode 100644
index 00..bb200fc3667c8f
--- /dev/null
+++ b/clang/test/Sema/unroll-template-value-crash.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -x c++ -emit-llvm -S -verify %s
+// expected-no-diagnostics
+
+template  void foo() {
+  #pragma unroll Unroll
+  for (int i = 0; i < Unroll; ++i);
+}

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


[clang] [llvm] [clang][MBD] set up module build daemon infrastructure (PR #67562)

2024-04-21 Thread Connor Sughrue via cfe-commits


@@ -264,6 +264,26 @@ def err_test_module_file_extension_version : Error<
   "test module file extension '%0' has different version (%1.%2) than expected 
"
   "(%3.%4)">;
 
+// Module Build Daemon

cpsughrue wrote:

I don't think that's a bad idea. There are currently only 6 options in the 
`ModuleBuildDaemon` group so for now I'd vote to keep them a part of 
`DiagnositcFrontendKinds.td` but in subsequent PRs if the number increases, I 
can pull them out to there own `.td` file

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


[clang] [clang][CoverageMapping] do not emit gap when either end is an `ImplicitValueInitExpr` (PR #89564)

2024-04-21 Thread Wentao Zhang via cfe-commits

https://github.com/whentojump updated 
https://github.com/llvm/llvm-project/pull/89564

>From abbdb318d62bb2e5ab6f07e7d0fe11f4a06b5a11 Mon Sep 17 00:00:00 2001
From: Wentao Zhang 
Date: Sun, 21 Apr 2024 21:27:01 -0500
Subject: [PATCH] [clang][CoverageMapping] do not emit gap when either end is
 an ImplicitValueInitExpr

---
 clang/lib/CodeGen/CoverageMappingGen.cpp | 9 ++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 64c39c5de351c7..dd8c0577d758ca 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1368,9 +1368,12 @@ struct CounterCoverageMappingBuilder
 for (const Stmt *Child : S->children())
   if (Child) {
 // If last statement contains terminate statements, add a gap area
-// between the two statements. Skipping attributed statements, because
-// they don't have valid start location.
-if (LastStmt && HasTerminateStmt && !isa(Child)) {
+// between the two statements. Skipping attributed statements and
+// implicit initializations, because they don't have valid source
+// location.
+if (LastStmt && HasTerminateStmt && !isa(Child) &&
+!isa(Child) &&
+!isa(LastStmt)) {
   auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
   if (Gap)
 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),

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


[clang] Don't wrap immediate invocations in ConstantExprs within constexpr initializers (PR #89565)

2024-04-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Daniel M. Katz (katzdm)


Changes

The following program produces a diagnostic in Clang and EDG, but compiles 
correctly in GCC and MSVC:
```cpp
#include vector

consteval std::vectorint fn() { return {1,2,3}; }
constexpr int a = fn()[1];
```

Clang's diagnostic is as follows:
```cpp
source:6:19: error: call to consteval function 'fn' is not a constant 
expression
6 | constexpr int a = fn()[1];
  |   ^
source:6:19: note: pointer to subobject of heap-allocated object is not 
a constant expression
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/14.0.1/../../../../include/c++/14.0.1/bits/allocator.h:193:31:
 note: heap allocation performed here
  193 | return static_cast_Tp*(::operator new(__n));
  |  ^
1 error generated.
Compiler returned: 1
```

Based on my understanding of 
[`[dcl.constexpr]/6`](https://eel.is/c++draft/dcl.constexpr#6):
 In any constexpr variable declaration, the full-expression of the 
initialization shall be a constant expression

It seems to me that GCC and MSVC are correct: the initializer `fn()[1]` does 
not evaluate to an lvalue referencing a heap-allocated value within the 
`vector` returned by `fn()`; it evaluates to an lvalue-to-rvalue conversion 
_from_ that heap-allocated value.

A dump of the AST for the variable declaration elucidates what I believe to be 
a problem:
```
`-VarDecl line:6:1, col:25 col:15 a 'const int' constexpr cinit
  |-value: Int 2
  `-ExprWithCleanups col:19, col:25 'value_type':'int'
`-ImplicitCastExpr col:19, col:25 'value_type':'int' 
LValueToRValue
  `-CXXOperatorCallExpr col:19, col:25 'value_type':'int' lvalue 
'[]'
|-ImplicitCastExpr col:23, col:25 'reference (*)(size_type) 
noexcept' FunctionToPointerDecay
| `-DeclRefExpr col:23, col:25 'reference (size_type) noexcept' 
lvalue CXXMethod 0xd1497a0 'operator[]' 'reference (size_type) noexcept'
|-MaterializeTemporaryExpr col:19, col:22 
'std::vectorint' lvalue
| `-ConstantExpr col:19, col:22 'std::vectorint'
|   `-ExprWithCleanups col:19, col:22 'std::vectorint'
| `-CXXBindTemporaryExpr col:19, col:22 
'std::vectorint' (CXXTemporary 0xd180de8)
|   `-CallExpr col:19, col:22 'std::vectorint'
| `-ImplicitCastExpr col:19 'std::vectorint 
(*)()' FunctionToPointerDecay
|   `-DeclRefExpr col:19 'std::vectorint ()' 
lvalue Function 0xd12e7b8 'fn' 'std::vectorint ()'
`-ImplicitCastExpr col:24 'size_type':'unsigned long' 
IntegralCast
  `-IntegerLiteral col:24 'int' 1
```

There is a `ConstantExpr` wrapping the `CallExpr` to `fn`, causing it to be 
evaluated independently as a constant expression rather than evaluated as a 
component of the larger LValueToRValue-ImplicitCastExpr. Because the 
initializer of any constexpr variable declaration is itself a constant 
expression (as cited above), I believe this is incorrect.

The `ConstantExpr` wrapper is created because `fn()` is an immediate function 
call within an evaluation context that Clang [classifies as 
`PotentiallyEvaluated`](https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaDeclCXX.cpp#L18579-L18581)
 rather than `ConstantEvaluated`. Setting the 
`Sema::isConstantEvaluatedOverride` flag during evaluation of an initializer 
seems to address the problem.

I added a test to `clang/test/SemaCXX/cxx2a-consteval.cpp` to cover this case, 
and "fixed" the few tests that fail in response to it. [One such 
test](https://github.com/llvm/llvm-project/compare/main...katzdm:constexpr-init-fix?expand=1#diff-f10defc3f20fb095bf22b3a79bead200d494bde9d503e283067a57aff483936cL729)
 was documented by a `FIXME` that this change appears to fix.

Most of the other changes to tests consist of removing annotations expecting 
diagnostics for the issue being fixed here - from a quick spot check, nothing 
jumped out as "hey, that looks like it really should be an error", but another 
set of eyes would be helpful here.

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


5 Files Affected:

- (modified) clang/lib/Parse/ParseDecl.cpp (+11-1) 
- (modified) clang/test/CXX/expr/expr.const/p6-2a.cpp (+3-4) 
- (modified) clang/test/SemaCXX/builtin_vectorelements.cpp (+2-2) 
- (modified) clang/test/SemaCXX/cxx2a-consteval.cpp (+20-12) 
- (modified) clang/unittests/Support/TimeProfilerTest.cpp (-1) 


``diff
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 583232f2d610d0..0ea6fccaa7eb34 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -2554,6 +2554,13 @@ Decl *Parser::ParseDeclarationAfterDeclarator(
   return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
 }
 
+static bool isConstexprVariable(const Decl *D) {
+  if (const VarDecl *Var = dyn_cast_or_null(D))
+return Var->isConstexpr();
+
+  return false;
+}

[clang] Don't wrap immediate invocations in ConstantExprs within constexpr initializers (PR #89565)

2024-04-21 Thread Daniel M. Katz via cfe-commits

https://github.com/katzdm created 
https://github.com/llvm/llvm-project/pull/89565

The following program produces a diagnostic in Clang and EDG, but compiles 
correctly in GCC and MSVC:
```cpp
#include 

consteval std::vector fn() { return {1,2,3}; }
constexpr int a = fn()[1];
```

Clang's diagnostic is as follows:
```cpp
:6:19: error: call to consteval function 'fn' is not a constant 
expression
6 | constexpr int a = fn()[1];
  |   ^
:6:19: note: pointer to subobject of heap-allocated object is not a 
constant expression
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/14.0.1/../../../../include/c++/14.0.1/bits/allocator.h:193:31:
 note: heap allocation performed here
  193 | return static_cast<_Tp*>(::operator new(__n));
  |  ^
1 error generated.
Compiler returned: 1
```

Based on my understanding of 
[`[dcl.constexpr]/6`](https://eel.is/c++draft/dcl.constexpr#6):
> In any constexpr variable declaration, the full-expression of the 
> initialization shall be a constant expression

It seems to me that GCC and MSVC are correct: the initializer `fn()[1]` does 
not evaluate to an lvalue referencing a heap-allocated value within the 
`vector` returned by `fn()`; it evaluates to an lvalue-to-rvalue conversion 
_from_ that heap-allocated value.

A dump of the AST for the variable declaration elucidates what I believe to be 
a problem:
```
`-VarDecl  col:15 a 'const int' constexpr cinit
  |-value: Int 2
  `-ExprWithCleanups  'value_type':'int'
`-ImplicitCastExpr  'value_type':'int' 
  `-CXXOperatorCallExpr  'value_type':'int' lvalue '[]'
|-ImplicitCastExpr  'reference (*)(size_type) noexcept' 

| `-DeclRefExpr  'reference (size_type) noexcept' 
lvalue CXXMethod 0xd1497a0 'operator[]' 'reference (size_type) noexcept'
|-MaterializeTemporaryExpr  'std::vector' lvalue
| `-ConstantExpr  'std::vector'
|   `-ExprWithCleanups  'std::vector'
| `-CXXBindTemporaryExpr  'std::vector' 
(CXXTemporary 0xd180de8)
|   `-CallExpr  'std::vector'
| `-ImplicitCastExpr  'std::vector (*)()' 

|   `-DeclRefExpr  'std::vector ()' lvalue 
Function 0xd12e7b8 'fn' 'std::vector ()'
`-ImplicitCastExpr  'size_type':'unsigned long' 
  `-IntegerLiteral  'int' 1
```

There is a `ConstantExpr` wrapping the `CallExpr` to `fn`, causing it to be 
evaluated independently as a constant expression rather than evaluated as a 
component of the larger LValueToRValue-ImplicitCastExpr. Because the 
initializer of any constexpr variable declaration is itself a constant 
expression (as cited above), I believe this is incorrect.

The `ConstantExpr` wrapper is created because `fn()` is an immediate function 
call within an evaluation context that Clang [classifies as 
`PotentiallyEvaluated`](https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaDeclCXX.cpp#L18579-L18581)
 rather than `ConstantEvaluated`. Setting the 
`Sema::isConstantEvaluatedOverride` flag during evaluation of an initializer 
seems to address the problem.

I added a test to `clang/test/SemaCXX/cxx2a-consteval.cpp` to cover this case, 
and "fixed" the few tests that fail in response to it. [One such 
test](https://github.com/llvm/llvm-project/compare/main...katzdm:constexpr-init-fix?expand=1#diff-f10defc3f20fb095bf22b3a79bead200d494bde9d503e283067a57aff483936cL729)
 was documented by a `FIXME` that this change appears to fix.

Most of the other changes to tests consist of removing annotations expecting 
diagnostics for the issue being fixed here - from a quick spot check, nothing 
jumped out as "hey, that looks like it really should be an error", but another 
set of eyes would be helpful here.

>From a3f8a8648e2002273d47d7886b29fb02c728b5b7 Mon Sep 17 00:00:00 2001
From: Dan Katz 
Date: Tue, 16 Apr 2024 17:14:50 -0400
Subject: [PATCH] Fix bug with constexpr initialization.

---
 clang/lib/Parse/ParseDecl.cpp | 12 ++-
 clang/test/CXX/expr/expr.const/p6-2a.cpp  |  7 ++--
 clang/test/SemaCXX/builtin_vectorelements.cpp |  4 +--
 clang/test/SemaCXX/cxx2a-consteval.cpp| 32 ---
 clang/unittests/Support/TimeProfilerTest.cpp  |  1 -
 5 files changed, 36 insertions(+), 20 deletions(-)

diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 583232f2d610d0..0ea6fccaa7eb34 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -2554,6 +2554,13 @@ Decl *Parser::ParseDeclarationAfterDeclarator(
   return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
 }
 
+static bool isConstexprVariable(const Decl *D) {
+  if (const VarDecl *Var = dyn_cast_or_null(D))
+return Var->isConstexpr();
+
+  return false;
+}
+
 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
 Declarator , const ParsedTemplateInfo , ForRangeInit *FRI) {
   // RAII type used to track whether we're 

[clang] [clang][CoverageMapping] do not emit gap when either end is an `ImplicitValueInitExpr` (PR #89564)

2024-04-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Wentao Zhang (whentojump)


Changes

Fixes #86998 

Two compiler explorer examples: 
[1](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:___c,selection:(endColumn:21,endLineNumber:8,positionColumn:21,positionLineNumber:8,selectionStartColumn:21,selectionStartLineNumber:8,startColumn:21,startLineNumber:8),source:'struct+Foo+%7B%0Aint+field1%3B%0Aint+field2%3B%0A%7D%3B%0A%0Aint+main(void)+%7B%0Astruct+Foo+foo+%3D+%7B%0A.field1+%3D+(%7B%0Aswitch+(0)+%7B%0Acase+0:%0Abreak%3B%0A+//+%5E%5E%5E%5E%5E+HasTerminateStmt+set%0A%7D%0A0%3B%0A%7D),%0A//+%3C--+ImplicitValueInitExpr+introduced+for+.field2%0A%7D%3B%0A%7D'),l:'5',n:'0',o:'C+source+%231',t:'0')),k:61.44745998608211,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:cclang_assertions_trunk,filters:(b:'0',binary:'1',binaryObject:'1',commentOnly:'0',debugCalls:'1',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1',verboseDemangling:'0'),flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:2,lang:___c,libs:!(),options:'-fprofile-instr-generate+-fcoverage-mapping',overrides:!(),selection:(endColumn:45,endLineNumber:3,positionColumn:45,positionLineNumber:3,selectionStartColumn:45,selectionStartLineNumber:3,startColumn:45,startLineNumber:3),source:1),l:'5',n:'0',o:'+x86-64+clang+(assertions+trunk)+(Editor+%231)',t:'0')),k:34.5741843594503,l:'4',m:28.903654485049834,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compilerName:'x86-64+clang+(trunk)',editorid:1,fontScale:14,fontUsePx:'0',j:2,wrap:'1'),l:'5',n:'0',o:'Output+of+x86-64+clang+(assertions+trunk)+(Compiler+%232)',t:'0')),header:(),l:'4',m:71.09634551495017,n:'0',o:'',s:0,t:'0')),k:38.55254001391788,l:'3',n:'0',o:'',t:'0')),l:'2',m:100,n:'0',o:'',t:'0')),version:4),
 
[2](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:___c,selection:(endColumn:2,endLineNumber:12,positionColumn:2,positionLineNumber:12,selectionStartColumn:2,selectionStartLineNumber:12,startColumn:2,startLineNumber:12),source:'int+main(void)+%7B%0Aint+arr%5B3%5D+%3D+%7B%0A%5B0%5D+%3D+(%7B%0Agoto+L0%3B%0A+//+%5E%5E%5E%5E+HasTerminateStmt+set%0AL0:%0A0%3B%0A%7D),%0A//+%3C--+ImplicitValueInitExpr+introduced+for+subscript+%5B1%5D%0A%5B2%5D+%3D+0,%0A%7D%3B%0A%7D'),l:'5',n:'0',o:'C+source+%231',t:'0')),k:61.44745998608211,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:cclang_assertions_trunk,filters:(b:'0',binary:'1',binaryObject:'1',commentOnly:'0',debugCalls:'1',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1',verboseDemangling:'0'),flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:2,lang:___c,libs:!(),options:'-fprofile-instr-generate+-fcoverage-mapping',overrides:!(),selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'+x86-64+clang+(assertions+trunk)+(Editor+%231)',t:'0')),k:34.5741843594503,l:'4',m:28.903654485049834,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compilerName:'x86-64+clang+(trunk)',editorid:1,fontScale:14,fontUsePx:'0',j:2,wrap:'1'),l:'5',n:'0',o:'Output+of+x86-64+clang+(assertions+trunk)+(Compiler+%232)',t:'0')),header:(),l:'4',m:71.09634551495017,n:'0',o:'',s:0,t:'0')),k:38.55254001391788,l:'3',n:'0',o:'',t:'0')),l:'2',m:100,n:'0',o:'',t:'0')),version:4)

Cause:

1. When visiting AST and generating mapping regions, a [region 
terminator](https://github.com/llvm/llvm-project/blob/llvmorg-18.1.4/clang/lib/CodeGen/CoverageMappingGen.cpp#L1197)
 (like `break` and `goto`) is likely followed by a stmt with `invalid 
sloc` (like `ImplicitValueInitExpr`).
2. Because a terminator is seen, the below branch will be executed when 
visiting the 2nd stmt:


https://github.com/llvm/llvm-project/blob/e6c3289804a67ea0bb6a86fadbe454dd93b8d855/clang/lib/CodeGen/CoverageMappingGen.cpp#L1375-L1376

3. However, the 2nd stmt doesn't have a valid source location and will fail 
some assertions in `findGapAreaBetween()`.







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


1 Files Affected:

- (modified) clang/lib/CodeGen/CoverageMappingGen.cpp (+3-1) 


``diff
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 64c39c5de351c7..45296ff9cfb5e3 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1370,7 +1370,9 @@ struct CounterCoverageMappingBuilder
 // If last statement contains terminate statements, add a gap area
 // between the two statements. Skipping attributed statements, because
 // they don't have valid start location.
-if 

[clang] [clang][CoverageMapping] do not emit gap when either end is an `ImplicitValueInitExpr` (PR #89564)

2024-04-21 Thread Wentao Zhang via cfe-commits

https://github.com/whentojump created 
https://github.com/llvm/llvm-project/pull/89564

Fixes #86998 

Two compiler explorer examples: 
[1](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:___c,selection:(endColumn:21,endLineNumber:8,positionColumn:21,positionLineNumber:8,selectionStartColumn:21,selectionStartLineNumber:8,startColumn:21,startLineNumber:8),source:'struct+Foo+%7B%0Aint+field1%3B%0Aint+field2%3B%0A%7D%3B%0A%0Aint+main(void)+%7B%0Astruct+Foo+foo+%3D+%7B%0A.field1+%3D+(%7B%0Aswitch+(0)+%7B%0Acase+0:%0Abreak%3B%0A+//+%5E%5E%5E%5E%5E+HasTerminateStmt+set%0A%7D%0A0%3B%0A%7D),%0A//+%3C--+ImplicitValueInitExpr+introduced+for+.field2%0A%7D%3B%0A%7D'),l:'5',n:'0',o:'C+source+%231',t:'0')),k:61.44745998608211,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:cclang_assertions_trunk,filters:(b:'0',binary:'1',binaryObject:'1',commentOnly:'0',debugCalls:'1',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1',verboseDemangling:'0'),flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:2,lang:___c,libs:!(),options:'-fprofile-instr-generate+-fcoverage-mapping',overrides:!(),selection:(endColumn:45,endLineNumber:3,positionColumn:45,positionLineNumber:3,selectionStartColumn:45,selectionStartLineNumber:3,startColumn:45,startLineNumber:3),source:1),l:'5',n:'0',o:'+x86-64+clang+(assertions+trunk)+(Editor+%231)',t:'0')),k:34.5741843594503,l:'4',m:28.903654485049834,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compilerName:'x86-64+clang+(trunk)',editorid:1,fontScale:14,fontUsePx:'0',j:2,wrap:'1'),l:'5',n:'0',o:'Output+of+x86-64+clang+(assertions+trunk)+(Compiler+%232)',t:'0')),header:(),l:'4',m:71.09634551495017,n:'0',o:'',s:0,t:'0')),k:38.55254001391788,l:'3',n:'0',o:'',t:'0')),l:'2',m:100,n:'0',o:'',t:'0')),version:4),
 
[2](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:___c,selection:(endColumn:2,endLineNumber:12,positionColumn:2,positionLineNumber:12,selectionStartColumn:2,selectionStartLineNumber:12,startColumn:2,startLineNumber:12),source:'int+main(void)+%7B%0Aint+arr%5B3%5D+%3D+%7B%0A%5B0%5D+%3D+(%7B%0Agoto+L0%3B%0A+//+%5E%5E%5E%5E+HasTerminateStmt+set%0AL0:%0A0%3B%0A%7D),%0A//+%3C--+ImplicitValueInitExpr+introduced+for+subscript+%5B1%5D%0A%5B2%5D+%3D+0,%0A%7D%3B%0A%7D'),l:'5',n:'0',o:'C+source+%231',t:'0')),k:61.44745998608211,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:cclang_assertions_trunk,filters:(b:'0',binary:'1',binaryObject:'1',commentOnly:'0',debugCalls:'1',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1',verboseDemangling:'0'),flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:2,lang:___c,libs:!(),options:'-fprofile-instr-generate+-fcoverage-mapping',overrides:!(),selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'+x86-64+clang+(assertions+trunk)+(Editor+%231)',t:'0')),k:34.5741843594503,l:'4',m:28.903654485049834,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compilerName:'x86-64+clang+(trunk)',editorid:1,fontScale:14,fontUsePx:'0',j:2,wrap:'1'),l:'5',n:'0',o:'Output+of+x86-64+clang+(assertions+trunk)+(Compiler+%232)',t:'0')),header:(),l:'4',m:71.09634551495017,n:'0',o:'',s:0,t:'0')),k:38.55254001391788,l:'3',n:'0',o:'',t:'0')),l:'2',m:100,n:'0',o:'',t:'0')),version:4)

Cause:

1. When visiting AST and generating mapping regions, a [region 
terminator](https://github.com/llvm/llvm-project/blob/llvmorg-18.1.4/clang/lib/CodeGen/CoverageMappingGen.cpp#L1197)
 (like `break` and `goto`) is likely followed by a stmt with `` 
(like `ImplicitValueInitExpr`).
2. Because a terminator is seen, the below branch will be executed when 
visiting the 2nd stmt:


https://github.com/llvm/llvm-project/blob/e6c3289804a67ea0bb6a86fadbe454dd93b8d855/clang/lib/CodeGen/CoverageMappingGen.cpp#L1375-L1376

3. However, the 2nd stmt doesn't have a valid source location and will fail 
some assertions in `findGapAreaBetween()`.







>From 73e29e5dc47bfdab0708476eb5961c70de59a6cd Mon Sep 17 00:00:00 2001
From: Wentao Zhang 
Date: Sun, 21 Apr 2024 21:27:01 -0500
Subject: [PATCH] [clang][CoverageMapping] do not emit gap when either end is
 an ImplicitValueInitExpr

---
 clang/lib/CodeGen/CoverageMappingGen.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 64c39c5de351c7..45296ff9cfb5e3 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1370,7 +1370,9 @@ struct CounterCoverageMappingBuilder
 // If last statement contains terminate statements, add a gap area
   

[clang] [clang-tools-extra] [clangd] Show struct fields and enum members in hovers (PR #89557)

2024-04-21 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/89557

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

>From d98c95bf213f0c6e81a46a9e37d376b855bb4867 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 21 Apr 2024 20:30:16 -0400
Subject: [PATCH] [clangd] Show struct fields and enum members in hovers

Fixes https://github.com/clangd/clangd/issues/959
---
 clang-tools-extra/clangd/Hover.cpp|  2 ++
 .../clangd/unittests/HoverTests.cpp   | 17 
 clang/include/clang/AST/PrettyPrinter.h   | 10 +-
 clang/lib/AST/DeclPrinter.cpp | 20 ---
 4 files changed, 41 insertions(+), 8 deletions(-)

diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 06b949bc4a2b55..d7c433876b08bc 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -69,6 +69,8 @@ namespace {
 PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
   Base.AnonymousTagLocations = false;
   Base.TerseOutput = true;
+  // Show struct fields and enum members.
+  Base.PrintTagTypeContents = true;
   Base.PolishForDeclaration = true;
   Base.ConstantsAsWritten = true;
   Base.SuppressTemplateArgsInCXXConstructors = true;
diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 35db757b9c15b5..8c19f5fb3b0ad0 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1645,7 +1645,16 @@ TEST(Hover, All) {
   {
   R"cpp(// Struct
 namespace ns1 {
-  struct MyClass {};
+  struct MyClass {
+// Public fields shown in hover
+int field1;
+int field2;
+
+// Methods and private fields not shown
+void method();
+  private:
+bool private_field;
+  };
 } // namespace ns1
 int main() {
   ns1::[[My^Class]]* Params;
@@ -1655,7 +1664,7 @@ TEST(Hover, All) {
 HI.Name = "MyClass";
 HI.Kind = index::SymbolKind::Struct;
 HI.NamespaceScope = "ns1::";
-HI.Definition = "struct MyClass {}";
+HI.Definition = "struct MyClass {\n  int field1;\n  int 
field2;\n}";
   }},
   {
   R"cpp(// Class
@@ -1685,7 +1694,7 @@ TEST(Hover, All) {
 HI.Name = "MyUnion";
 HI.Kind = index::SymbolKind::Union;
 HI.NamespaceScope = "ns1::";
-HI.Definition = "union MyUnion {}";
+HI.Definition = "union MyUnion {\n  int x;\n  int y;\n}";
   }},
   {
   R"cpp(// Function definition via pointer
@@ -2030,7 +2039,7 @@ TEST(Hover, All) {
 HI.Name = "Hello";
 HI.Kind = index::SymbolKind::Enum;
 HI.NamespaceScope = "";
-HI.Definition = "enum Hello {}";
+HI.Definition = "enum Hello { ONE, TWO, THREE }";
 HI.Documentation = "Enum declaration";
   }},
   {
diff --git a/clang/include/clang/AST/PrettyPrinter.h 
b/clang/include/clang/AST/PrettyPrinter.h
index da276e26049b00..6b8f1ae9143df3 100644
--- a/clang/include/clang/AST/PrettyPrinter.h
+++ b/clang/include/clang/AST/PrettyPrinter.h
@@ -70,7 +70,7 @@ struct PrintingPolicy {
 Restrict(LO.C99), Alignof(LO.CPlusPlus11), UnderscoreAlignof(LO.C11),
 UseVoidForZeroParams(!LO.CPlusPlus),
 SplitTemplateClosers(!LO.CPlusPlus11), TerseOutput(false),
-PolishForDeclaration(false), Half(LO.Half),
+PrintTagTypeContents(false), PolishForDeclaration(false), 
Half(LO.Half),
 MSWChar(LO.MicrosoftExt && !LO.WChar), IncludeNewlines(true),
 MSVCFormatting(false), ConstantsAsWritten(false),
 SuppressImplicitBase(false), FullyQualifiedName(false),
@@ -252,6 +252,14 @@ struct PrintingPolicy {
   LLVM_PREFERRED_TYPE(bool)
   unsigned TerseOutput : 1;
 
+  /// Print the contents of tag (i.e. record and enum) types, even with
+  /// TerseOutput=true.
+  ///
+  /// For record types (structs/classes/unions), this only prints public
+  /// data members. For enum types, this prints enumerators.
+  /// Has no effect if TerseOutput=false (which prints all members).
+  unsigned PrintTagTypeContents : 1;
+
   /// When true, do certain refinement needed for producing proper declaration
   /// tag; such as, do not print attributes attached to the declaration.
   ///
diff --git a/clang/lib/AST/DeclPrinter.cpp b/clang/lib/AST/DeclPrinter.cpp
index 43d221968ea3fb..3fe02fff687fe1 100644
--- a/clang/lib/AST/DeclPrinter.cpp
+++ b/clang/lib/AST/DeclPrinter.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/Basic/Module.h"
+#include "clang/Basic/Specifiers.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace clang;
 
@@ 

[clang] [llvm] [ARM] Armv8-R does not require fp64 or neon. (PR #88287)

2024-04-21 Thread Chris Copeland via cfe-commits

https://github.com/chrisnc updated 
https://github.com/llvm/llvm-project/pull/88287

>From 46803a6da62b8348f3eb8759c74ec6abf8693c92 Mon Sep 17 00:00:00 2001
From: Chris Copeland 
Date: Fri, 5 Apr 2024 22:40:46 -0700
Subject: [PATCH] [ARM] Armv8-R does not require fp64 or neon.

Specifying cortex-r52 still enables neon and fp64.
Change the default Armv8-R cpu from cortex-r52 to generic so it will not
enable these features by default.

Remove the GENERIC case from llvm/test/CodeGen/ARM/useaa.ll because it
is the same as the USEAA case now that AA is enabled for all targets.
---
 clang/test/Driver/arm-cortex-cpus-1.c  | 8 
 clang/test/Driver/arm-features.c   | 2 +-
 clang/test/Preprocessor/arm-target-features.c  | 4 ++--
 llvm/docs/ReleaseNotes.rst | 2 ++
 llvm/include/llvm/TargetParser/ARMTargetParser.def | 4 ++--
 llvm/lib/Target/ARM/ARM.td | 7 ---
 llvm/test/Analysis/CostModel/ARM/arith.ll  | 2 +-
 llvm/test/Analysis/CostModel/ARM/cast.ll   | 4 ++--
 llvm/test/Analysis/CostModel/ARM/cast_ldst.ll  | 4 ++--
 llvm/test/Analysis/CostModel/ARM/cmps.ll   | 4 ++--
 llvm/test/Analysis/CostModel/ARM/divrem.ll | 2 +-
 llvm/test/CodeGen/ARM/cortex-a57-misched-basic.ll  | 2 +-
 llvm/test/CodeGen/ARM/fpconv.ll| 4 ++--
 llvm/test/CodeGen/ARM/half.ll  | 4 ++--
 llvm/test/CodeGen/ARM/useaa.ll | 6 +-
 llvm/unittests/TargetParser/TargetParserTest.cpp   | 4 ++--
 16 files changed, 31 insertions(+), 32 deletions(-)

diff --git a/clang/test/Driver/arm-cortex-cpus-1.c 
b/clang/test/Driver/arm-cortex-cpus-1.c
index 25abbe1e3a8ad7..6f0b64910f9b07 100644
--- a/clang/test/Driver/arm-cortex-cpus-1.c
+++ b/clang/test/Driver/arm-cortex-cpus-1.c
@@ -153,23 +153,23 @@
 // RUN: %clang -target armv8r-linux-gnueabi -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8R %s
 // RUN: %clang -target arm -march=armv8r -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8R %s
 // RUN: %clang -target arm -march=armv8-r -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8R %s
-// CHECK-V8R: "-cc1"{{.*}} "-triple" "armv8r-{{.*}} "-target-cpu" "cortex-r52"
+// CHECK-V8R: "-cc1"{{.*}} "-triple" "armv8r-{{.*}} "-target-cpu" "generic"
 
 // RUN: %clang -target armv8r-linux-gnueabi -mbig-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8R-BIG %s
 // RUN: %clang -target arm -march=armv8r -mbig-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8R-BIG %s
 // RUN: %clang -target arm -march=armv8-r -mbig-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8R-BIG %s
-// CHECK-V8R-BIG: "-cc1"{{.*}} "-triple" "armebv8r-{{.*}} "-target-cpu" 
"cortex-r52"
+// CHECK-V8R-BIG: "-cc1"{{.*}} "-triple" "armebv8r-{{.*}} "-target-cpu" 
"generic"
 
 // RUN: %clang -target armv8r-linux-gnueabi -mthumb -### -c %s 2>&1 | \
 // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB %s
 // RUN: %clang -target arm -march=armv8r -mthumb -### -c %s 2>&1 | \
 // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB %s
-// CHECK-V8R-THUMB: "-cc1"{{.*}} "-triple" "thumbv8r-{{.*}} "-target-cpu" 
"cortex-r52"
+// CHECK-V8R-THUMB: "-cc1"{{.*}} "-triple" "thumbv8r-{{.*}} "-target-cpu" 
"generic"
 // RUN: %clang -target armv8r-linux-gnueabi -mthumb -mbig-endian -### -c %s 
2>&1 | \
 // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB-BIG %s
 // RUN: %clang -target arm -march=armv8r -mthumb -mbig-endian -### -c %s 2>&1 
| \
 // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB-BIG %s
-// CHECK-V8R-THUMB-BIG: "-cc1"{{.*}} "-triple" "thumbebv8r-{{.*}} 
"-target-cpu" "cortex-r52"
+// CHECK-V8R-THUMB-BIG: "-cc1"{{.*}} "-triple" "thumbebv8r-{{.*}} 
"-target-cpu" "generic"
 
 // RUN: %clang -mcpu=generic -target armv8 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8A-GENERIC %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8 -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8A-GENERIC %s
diff --git a/clang/test/Driver/arm-features.c b/clang/test/Driver/arm-features.c
index e043244f18a61f..eb424f5f61116b 100644
--- a/clang/test/Driver/arm-features.c
+++ b/clang/test/Driver/arm-features.c
@@ -74,7 +74,7 @@
 // Check +crypto for M and R profiles:
 //
 // RUN: %clang -target arm-arm-none-eabi -march=armv8-r+crypto   -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-CRYPTO-R %s
-// CHECK-CRYPTO-R: "-cc1"{{.*}} "-target-cpu" "cortex-r52"{{.*}} 
"-target-feature" "+sha2" "-target-feature" "+aes"
+// CHECK-CRYPTO-R: "-cc1"{{.*}} "-target-cpu" "generic"{{.*}} 
"-target-feature" "+sha2" "-target-feature" "+aes"
 // RUN: %clang -target arm-arm-none-eabi -march=armv8-m.base+crypto -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s
 // RUN: %clang -target arm-arm-none-eabi -march=armv8-m.main+crypto -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s
 // RUN: %clang -target arm-arm-none-eabi -mcpu=cortex-m23+crypto -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s
diff 

[clang] [llvm] [ARM] Armv8-R does not require fp64 or neon. (PR #88287)

2024-04-21 Thread Chris Copeland via cfe-commits

chrisnc wrote:

Added an item to the release notes and fixed another place where fp64+neon was 
being added (the target parser); now I see the expected results when using just 
armv8r-none-eabi (sans -mcpu=cortex-r52).

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


[clang] [llvm] [ARM] Armv8-R does not require fp64 or neon. (PR #88287)

2024-04-21 Thread Chris Copeland via cfe-commits

https://github.com/chrisnc updated 
https://github.com/llvm/llvm-project/pull/88287

>From 575128cc6b494fed2065cae07754477426cb1c24 Mon Sep 17 00:00:00 2001
From: Chris Copeland 
Date: Fri, 5 Apr 2024 22:40:46 -0700
Subject: [PATCH] [ARM] Armv8-R does not require fp64 or neon.

Specifying cortex-r52 still enables neon and fp64.
Change the default Armv8-R cpu from cortex-r52 to generic so it will not
enable these features by default.
---
 clang/test/Driver/arm-cortex-cpus-1.c  | 8 
 clang/test/Driver/arm-features.c   | 2 +-
 clang/test/Preprocessor/arm-target-features.c  | 4 ++--
 llvm/docs/ReleaseNotes.rst | 2 ++
 llvm/include/llvm/TargetParser/ARMTargetParser.def | 4 ++--
 llvm/lib/Target/ARM/ARM.td | 7 ---
 llvm/test/Analysis/CostModel/ARM/arith.ll  | 2 +-
 llvm/test/Analysis/CostModel/ARM/cast.ll   | 4 ++--
 llvm/test/Analysis/CostModel/ARM/cast_ldst.ll  | 4 ++--
 llvm/test/Analysis/CostModel/ARM/cmps.ll   | 4 ++--
 llvm/test/Analysis/CostModel/ARM/divrem.ll | 2 +-
 llvm/test/CodeGen/ARM/cortex-a57-misched-basic.ll  | 2 +-
 llvm/test/CodeGen/ARM/fpconv.ll| 4 ++--
 llvm/test/CodeGen/ARM/half.ll  | 4 ++--
 llvm/test/CodeGen/ARM/useaa.ll | 2 +-
 llvm/unittests/TargetParser/TargetParserTest.cpp   | 4 ++--
 16 files changed, 31 insertions(+), 28 deletions(-)

diff --git a/clang/test/Driver/arm-cortex-cpus-1.c 
b/clang/test/Driver/arm-cortex-cpus-1.c
index 25abbe1e3a8ad7..6f0b64910f9b07 100644
--- a/clang/test/Driver/arm-cortex-cpus-1.c
+++ b/clang/test/Driver/arm-cortex-cpus-1.c
@@ -153,23 +153,23 @@
 // RUN: %clang -target armv8r-linux-gnueabi -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8R %s
 // RUN: %clang -target arm -march=armv8r -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8R %s
 // RUN: %clang -target arm -march=armv8-r -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8R %s
-// CHECK-V8R: "-cc1"{{.*}} "-triple" "armv8r-{{.*}} "-target-cpu" "cortex-r52"
+// CHECK-V8R: "-cc1"{{.*}} "-triple" "armv8r-{{.*}} "-target-cpu" "generic"
 
 // RUN: %clang -target armv8r-linux-gnueabi -mbig-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8R-BIG %s
 // RUN: %clang -target arm -march=armv8r -mbig-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8R-BIG %s
 // RUN: %clang -target arm -march=armv8-r -mbig-endian -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8R-BIG %s
-// CHECK-V8R-BIG: "-cc1"{{.*}} "-triple" "armebv8r-{{.*}} "-target-cpu" 
"cortex-r52"
+// CHECK-V8R-BIG: "-cc1"{{.*}} "-triple" "armebv8r-{{.*}} "-target-cpu" 
"generic"
 
 // RUN: %clang -target armv8r-linux-gnueabi -mthumb -### -c %s 2>&1 | \
 // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB %s
 // RUN: %clang -target arm -march=armv8r -mthumb -### -c %s 2>&1 | \
 // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB %s
-// CHECK-V8R-THUMB: "-cc1"{{.*}} "-triple" "thumbv8r-{{.*}} "-target-cpu" 
"cortex-r52"
+// CHECK-V8R-THUMB: "-cc1"{{.*}} "-triple" "thumbv8r-{{.*}} "-target-cpu" 
"generic"
 // RUN: %clang -target armv8r-linux-gnueabi -mthumb -mbig-endian -### -c %s 
2>&1 | \
 // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB-BIG %s
 // RUN: %clang -target arm -march=armv8r -mthumb -mbig-endian -### -c %s 2>&1 
| \
 // RUN: FileCheck -check-prefix=CHECK-V8R-THUMB-BIG %s
-// CHECK-V8R-THUMB-BIG: "-cc1"{{.*}} "-triple" "thumbebv8r-{{.*}} 
"-target-cpu" "cortex-r52"
+// CHECK-V8R-THUMB-BIG: "-cc1"{{.*}} "-triple" "thumbebv8r-{{.*}} 
"-target-cpu" "generic"
 
 // RUN: %clang -mcpu=generic -target armv8 -### -c %s 2>&1 | FileCheck 
-check-prefix=CHECK-V8A-GENERIC %s
 // RUN: %clang -mcpu=generic -target arm -march=armv8 -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8A-GENERIC %s
diff --git a/clang/test/Driver/arm-features.c b/clang/test/Driver/arm-features.c
index e043244f18a61f..eb424f5f61116b 100644
--- a/clang/test/Driver/arm-features.c
+++ b/clang/test/Driver/arm-features.c
@@ -74,7 +74,7 @@
 // Check +crypto for M and R profiles:
 //
 // RUN: %clang -target arm-arm-none-eabi -march=armv8-r+crypto   -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-CRYPTO-R %s
-// CHECK-CRYPTO-R: "-cc1"{{.*}} "-target-cpu" "cortex-r52"{{.*}} 
"-target-feature" "+sha2" "-target-feature" "+aes"
+// CHECK-CRYPTO-R: "-cc1"{{.*}} "-target-cpu" "generic"{{.*}} 
"-target-feature" "+sha2" "-target-feature" "+aes"
 // RUN: %clang -target arm-arm-none-eabi -march=armv8-m.base+crypto -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s
 // RUN: %clang -target arm-arm-none-eabi -march=armv8-m.main+crypto -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s
 // RUN: %clang -target arm-arm-none-eabi -mcpu=cortex-m23+crypto -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO5 %s
diff --git a/clang/test/Preprocessor/arm-target-features.c 
b/clang/test/Preprocessor/arm-target-features.c
index 236c9f2479b705..2d65bfd4f43995 100644

[clang] Add ``ignoringParenImpCasts`` in arguments of hasArgument (PR #89553)

2024-04-21 Thread via cfe-commits

https://github.com/komalverma04 updated 
https://github.com/llvm/llvm-project/pull/89553

>From 4a56db71e8bf2b6414cd305515d9d4434be8efc0 Mon Sep 17 00:00:00 2001
From: komalverma04 
Date: Mon, 22 Apr 2024 02:37:25 +0530
Subject: [PATCH 1/2] remove IgnoreParenImpCasts() from hasArgument matcher

---
 clang/include/clang/ASTMatchers/ASTMatchers.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 8a2bbfff9e9e6b..f900ad42e3efb7 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -4560,7 +4560,7 @@ AST_POLYMORPHIC_MATCHER_P2(hasArgument,
   const Expr *Arg = Node.getArg(N);
   if (Finder->isTraversalIgnoringImplicitNodes() && 
isa(Arg))
 return false;
-  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
+  return InnerMatcher.matches(*Arg->ignoringParenImpCasts(), Finder, Builder);
 }
 
 /// Matches the operand that does not contain the parameter pack.

>From 78b028f3c780a964df90807e5eecf47fdaed7a36 Mon Sep 17 00:00:00 2001
From: komalverma04 
Date: Mon, 22 Apr 2024 03:39:35 +0530
Subject: [PATCH 2/2] remove IgnoreParenImpCasts

---
 clang/include/clang/ASTMatchers/ASTMatchers.h | 427 +++---
 1 file changed, 169 insertions(+), 258 deletions(-)

diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index f900ad42e3efb7..b315f894f9b236 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -112,8 +112,7 @@ class BoundNodes {
   ///
   /// Returns NULL if there was no node bound to \c ID or if there is a node 
but
   /// it cannot be converted to the specified type.
-  template 
-  const T *getNodeAs(StringRef ID) const {
+  template  const T *getNodeAs(StringRef ID) const {
 return MyBoundNodes.getNodeAs(ID);
   }
 
@@ -123,9 +122,7 @@ class BoundNodes {
   using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
 
   /// Retrieve mapping from binding identifiers to bound nodes.
-  const IDToNodeMap () const {
-return MyBoundNodes.getMap();
-  }
+  const IDToNodeMap () const { return MyBoundNodes.getMap(); }
 
 private:
   friend class internal::BoundNodesTreeBuilder;
@@ -318,13 +315,15 @@ AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
   std::string, MacroName) {
   // Verifies that the statement' beginning and ending are both expanded from
   // the same instance of the given macro.
-  auto& Context = Finder->getASTContext();
+  auto  = Finder->getASTContext();
   std::optional B =
   internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
-  if (!B) return false;
+  if (!B)
+return false;
   std::optional E =
   internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
-  if (!E) return false;
+  if (!E)
+return false;
   return *B == *E;
 }
 
@@ -690,9 +689,7 @@ AST_POLYMORPHIC_MATCHER(isPrivate,
 /// \endcode
 /// fieldDecl(isBitField())
 ///   matches 'int a;' but not 'int b;'.
-AST_MATCHER(FieldDecl, isBitField) {
-  return Node.isBitField();
-}
+AST_MATCHER(FieldDecl, isBitField) { return Node.isBitField(); }
 
 /// Matches non-static data members that are bit-fields of the specified
 /// bit width.
@@ -735,9 +732,7 @@ AST_MATCHER_P(FieldDecl, hasInClassInitializer, 
internal::Matcher,
 
 /// Determines whether the function is "main", which is the entry point
 /// into an executable program.
-AST_MATCHER(FunctionDecl, isMain) {
-  return Node.isMain();
-}
+AST_MATCHER(FunctionDecl, isMain) { return Node.isMain(); }
 
 /// Matches the specialized template of a specialization declaration.
 ///
@@ -751,9 +746,8 @@ AST_MATCHER(FunctionDecl, isMain) {
 ///   declaration of 'A' at #1.
 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
   internal::Matcher, InnerMatcher) {
-  const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
-  return (Decl != nullptr &&
-  InnerMatcher.matches(*Decl, Finder, Builder));
+  const ClassTemplateDecl *Decl = Node.getSpecializedTemplate();
+  return (Decl != nullptr && InnerMatcher.matches(*Decl, Finder, Builder));
 }
 
 /// Matches an entity that has been implicitly added by the compiler (e.g.
@@ -788,8 +782,7 @@ AST_POLYMORPHIC_MATCHER(isImplicit,
 AST_POLYMORPHIC_MATCHER_P(
 hasAnyTemplateArgument,
 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
-TemplateSpecializationType,
-FunctionDecl),
+TemplateSpecializationType, FunctionDecl),
 internal::Matcher, InnerMatcher) {
   ArrayRef List =
   internal::getTemplateSpecializationArgs(Node);
@@ -890,8 +883,7 @@ traverse(TraversalKind TK, const 
internal::MapAnyOfHelper ) {
 ///varDecl(hasInitializer(cxxConstructExpr()))
 /// 

[clang] Add ``ignoringParenImpCasts`` in arguments of hasArgument (PR #89553)

2024-04-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (komalverma04)


Changes

# Maintaining Consistency in `hasAnyArgument()` and `hasArgument()` Matchers in 
Clang AST Matchers

The correct behavior is to not ignore implicit AST nodes in hasArgument. We 
have the TK_IgnoreUnlessSpelledInSource traversal kind for when the user wants 
to silently skip implicit nodes.
The code changes made are as follows:

```diff
- return InnerMatcher.matches(*Arg-IgnoreParenImpCasts(), Finder, Builder); 
+ return InnerMatcher.matches(*Arg, Finder, Builder);
```


Fixes #75754

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


1 Files Affected:

- (modified) clang/include/clang/ASTMatchers/ASTMatchers.h (+1-1) 


``diff
diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 8a2bbfff9e9e6b..f900ad42e3efb7 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -4560,7 +4560,7 @@ AST_POLYMORPHIC_MATCHER_P2(hasArgument,
   const Expr *Arg = Node.getArg(N);
   if (Finder->isTraversalIgnoringImplicitNodes() && 
isa(Arg))
 return false;
-  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
+  return InnerMatcher.matches(*Arg->ignoringParenImpCasts(), Finder, Builder);
 }
 
 /// Matches the operand that does not contain the parameter pack.

``




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


[clang] Add ``ignoringParenImpCasts`` in arguments of hasArgument (PR #89553)

2024-04-21 Thread via cfe-commits

https://github.com/komalverma04 created 
https://github.com/llvm/llvm-project/pull/89553

# Maintaining Consistency in `hasAnyArgument()` and `hasArgument()` Matchers in 
Clang AST Matchers

The correct behavior is to not ignore implicit AST nodes in hasArgument. We 
have the TK_IgnoreUnlessSpelledInSource traversal kind for when the user wants 
to silently skip implicit nodes.
The code changes made are as follows:

```diff
- return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder); 
+ return InnerMatcher.matches(*Arg, Finder, Builder);
```


Fixes #75754

>From 4a56db71e8bf2b6414cd305515d9d4434be8efc0 Mon Sep 17 00:00:00 2001
From: komalverma04 
Date: Mon, 22 Apr 2024 02:37:25 +0530
Subject: [PATCH] remove IgnoreParenImpCasts() from hasArgument matcher

---
 clang/include/clang/ASTMatchers/ASTMatchers.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 8a2bbfff9e9e6b..f900ad42e3efb7 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -4560,7 +4560,7 @@ AST_POLYMORPHIC_MATCHER_P2(hasArgument,
   const Expr *Arg = Node.getArg(N);
   if (Finder->isTraversalIgnoringImplicitNodes() && 
isa(Arg))
 return false;
-  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
+  return InnerMatcher.matches(*Arg->ignoringParenImpCasts(), Finder, Builder);
 }
 
 /// Matches the operand that does not contain the parameter pack.

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


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-21 Thread Utkarsh Saxena via cfe-commits

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


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-21 Thread Utkarsh Saxena via cfe-commits

usx95 wrote:

(addressed one more problem with conditional lifetime extension.)

> What, if anything, about the scenario you're describing is specific to 
> "normal" cleanups?

We do not see this with `EHCleanup`s because `EmitBranchThroughCleanup` does 
not consider `EHCleanup`. It branches through all the "Normal" cleanups in the 
`EHStack`.

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


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-21 Thread Utkarsh Saxena via cfe-commits

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Piotr Zegar via cfe-commits


@@ -16,6 +16,75 @@
 using namespace clang::ast_matchers;
 
 namespace clang::tidy::modernize {
+namespace {
+// Given two argument indices X and Y, matches when a call expression has a
+// string at index X with an expression representing that string's length at
+// index Y. The string can be a string literal or a variable. The length can be
+// matched via an integer literal or a call to strlen() in the case of a string
+// literal, and by a call to size() or length() in the string variable case.
+AST_POLYMORPHIC_MATCHER_P2(hasStringAndLengthArguments,
+   AST_POLYMORPHIC_SUPPORTED_TYPES(
+   CallExpr, CXXConstructExpr,
+   CXXUnresolvedConstructExpr, ObjCMessageExpr),
+   unsigned, StringArgIndex, unsigned, LengthArgIndex) 
{
+  if (StringArgIndex >= Node.getNumArgs() ||
+  LengthArgIndex >= Node.getNumArgs()) {
+return false;
+  }
+
+  const Expr *StringArgExpr =
+  Node.getArg(StringArgIndex)->IgnoreParenImpCasts();
+  const Expr *LengthArgExpr =
+  Node.getArg(LengthArgIndex)->IgnoreParenImpCasts();
+
+  if (const auto *StringArg = dyn_cast(StringArgExpr)) {
+// Match an integer literal equal to the string length or a call to strlen.
+
+static const auto Matcher = expr(anyOf(
+integerLiteral().bind("integer_literal_size"),
+callExpr(callee(functionDecl(hasName("strlen"))), argumentCountIs(1),
+ hasArgument(0, stringLiteral().bind("strlen_arg");
+
+if (!Matcher.matches(*LengthArgExpr, Finder, Builder)) {
+  return false;
+}
+
+return Builder->removeBindings(
+[&](const ast_matchers::internal::BoundNodesMap ) {
+  const auto *IntegerLiteralSize =
+  Nodes.getNodeAs("integer_literal_size");
+  const auto *StrlenArg = Nodes.getNodeAs("strlen_arg");
+  if (IntegerLiteralSize) {
+return IntegerLiteralSize->getValue().getZExtValue() !=
+   StringArg->getLength();
+  }
+  return StrlenArg->getLength() != StringArg->getLength();
+});
+  }
+
+  if (const auto *StringArg = dyn_cast(StringArgExpr)) {
+// Match a call to size() or length() on the same variable.
+
+static const auto Matcher = cxxMemberCallExpr(
+on(declRefExpr(to(varDecl().bind("string_var_decl",
+callee(cxxMethodDecl(hasAnyName("size", "length"), isConst(),
+ parameterCountIs(0;

PiotrZSL wrote:

instead of making them static, pass them to this matcher as two "InnerMatcher", 
check how other checks/matchers do that. Static matchers could make problems 
with object lifetime, and code like this is not allowed per codding standard.

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Nicolas van Kempen via cfe-commits

nicovank wrote:

Update following feedback. I rewrote `hasStringAndLengthArguments` to only 
build the matchers once (`static`), with necessary information being saved in 
variable bindings. @PiotrZSL This should be better, right? 

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Nicolas van Kempen via cfe-commits

https://github.com/nicovank updated 
https://github.com/llvm/llvm-project/pull/89530

>From ff7ebb3086d5467685e54435f3eabe86c76c24b0 Mon Sep 17 00:00:00 2001
From: Nicolas van Kempen 
Date: Sun, 21 Apr 2024 05:17:19 +
Subject: [PATCH] [clang-tidy][modernize-use-starts-ends-with] Add support for
 compare()

---
 .../modernize/UseStartsEndsWithCheck.cpp  | 118 +++---
 .../modernize/UseStartsEndsWithCheck.h|   4 +-
 clang-tools-extra/docs/ReleaseNotes.rst   |   4 +
 .../checks/modernize/use-starts-ends-with.rst |   6 +-
 .../clang-tidy/checkers/Inputs/Headers/string |   4 +
 .../checkers/Inputs/Headers/string.h  |   1 +
 .../abseil/redundant-strcat-calls.cpp |   2 -
 .../modernize/use-starts-ends-with.cpp|  45 +++
 8 files changed, 163 insertions(+), 21 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
index 062f6e9911dbed..2374213911beb4 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
@@ -16,6 +16,75 @@
 using namespace clang::ast_matchers;
 
 namespace clang::tidy::modernize {
+namespace {
+// Given two argument indices X and Y, matches when a call expression has a
+// string at index X with an expression representing that string's length at
+// index Y. The string can be a string literal or a variable. The length can be
+// matched via an integer literal or a call to strlen() in the case of a string
+// literal, and by a call to size() or length() in the string variable case.
+AST_POLYMORPHIC_MATCHER_P2(hasStringAndLengthArguments,
+   AST_POLYMORPHIC_SUPPORTED_TYPES(
+   CallExpr, CXXConstructExpr,
+   CXXUnresolvedConstructExpr, ObjCMessageExpr),
+   unsigned, StringArgIndex, unsigned, LengthArgIndex) 
{
+  if (StringArgIndex >= Node.getNumArgs() ||
+  LengthArgIndex >= Node.getNumArgs()) {
+return false;
+  }
+
+  const Expr *StringArgExpr =
+  Node.getArg(StringArgIndex)->IgnoreParenImpCasts();
+  const Expr *LengthArgExpr =
+  Node.getArg(LengthArgIndex)->IgnoreParenImpCasts();
+
+  if (const auto *StringArg = dyn_cast(StringArgExpr)) {
+// Match an integer literal equal to the string length or a call to strlen.
+
+static const auto Matcher = expr(anyOf(
+integerLiteral().bind("integer_literal_size"),
+callExpr(callee(functionDecl(hasName("strlen"))), argumentCountIs(1),
+ hasArgument(0, stringLiteral().bind("strlen_arg");
+
+if (!Matcher.matches(*LengthArgExpr, Finder, Builder)) {
+  return false;
+}
+
+return Builder->removeBindings(
+[&](const ast_matchers::internal::BoundNodesMap ) {
+  const auto *IntegerLiteralSize =
+  Nodes.getNodeAs("integer_literal_size");
+  const auto *StrlenArg = Nodes.getNodeAs("strlen_arg");
+  if (IntegerLiteralSize) {
+return IntegerLiteralSize->getValue().getZExtValue() !=
+   StringArg->getLength();
+  }
+  return StrlenArg->getLength() != StringArg->getLength();
+});
+  }
+
+  if (const auto *StringArg = dyn_cast(StringArgExpr)) {
+// Match a call to size() or length() on the same variable.
+
+static const auto Matcher = cxxMemberCallExpr(
+on(declRefExpr(to(varDecl().bind("string_var_decl",
+callee(cxxMethodDecl(hasAnyName("size", "length"), isConst(),
+ parameterCountIs(0;
+
+if (!Matcher.matches(*LengthArgExpr, Finder, Builder)) {
+  return false;
+}
+
+return Builder->removeBindings(
+[&](const ast_matchers::internal::BoundNodesMap ) {
+  const auto *StringVarDecl =
+  Nodes.getNodeAs("string_var_decl");
+  return StringVarDecl != StringArg->getDecl();
+});
+  }
+
+  return false;
+}
+} // namespace
 
 UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name,
ClangTidyContext *Context)
@@ -43,7 +112,9 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder 
*Finder) {
   callee(cxxMethodDecl(hasName("find")).bind("find_fun")),
   // ... on a class with a starts_with function.
   on(hasType(
-  hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction);
+  hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction,
+  // Bind search expression.
+  hasArgument(0, expr().bind("search_expr")));
 
   const auto RFindExpr = cxxMemberCallExpr(
   // A method call with a second argument of zero...
@@ -52,15 +123,30 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder 
*Finder) {
   callee(cxxMethodDecl(hasName("rfind")).bind("find_fun")),
   // ... on a class with a starts_with 

[clang] [C++17] Support __GCC_[CON|DE]STRUCTIVE_SIZE (PR #89446)

2024-04-21 Thread Ulrich Weigand via cfe-commits

uweigand wrote:

For SystemZ the correct value is 256.   In general I agree it makes sense to 
look at the GCC implementation as a source of reasonable values.   Also, I 
think there probably should be no generic default value at all - it there is no 
platform-specific value known, it seems better to not define those values 
rather than define them to some incorrect value ...

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


[clang] [llvm] [ARM] Armv8-R does not require fp64 or neon. (PR #88287)

2024-04-21 Thread David Green via cfe-commits

davemgreen wrote:

As far as I understand this will remove the tuning we do for cortex-r52 when 
using armv8r, which will mean a little less performance but the tuning features 
in the Arm backend are not handled as well as they could be.

Can you add release note explaining what will change? Thanks.

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-04-21 Thread via cfe-commits

sopyb wrote:

Ping

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


[clang] [llvm] [ARM] Armv8-R does not require fp64 or neon. (PR #88287)

2024-04-21 Thread Chris Copeland via cfe-commits

chrisnc wrote:

Another option is to include `FeatureFPARMv8_D16_SP` in `ARMv8r`. The R-profile 
supplement of the Arm manual does say that this is a minimum feature 
requirement (as opposed to just being a variant of the R52).

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-04-21 Thread via cfe-commits

sopyb wrote:

Sorry for taking so long to come back with the changes. I have changed my 
environment last week and didn't have time to properly setup everything to make 
the required changes until now.

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


[clang] [llvm] [RISCV] Add processor definition for XiangShan-KunMingHu (PR #89359)

2024-04-21 Thread Camel Coder via cfe-commits

camel-cdr wrote:

Has the target architecture been finalized? (As in what it should be, not 
necessarily the rtl)

Just yesterday, there was a significant change in vector execution units:

[before](https://github.com/OpenXiangShan/XiangShan/blob/e25e4d90505c592524b410b127fe611ac49a3adf/src/main/scala/xiangshan/Parameters.scala#L355):
```
VFEX0: VfaluCfg, VfmaCfg, VialuCfg, VimacCfg
VFEX1: VipuCfg, VppuCfg, VfcvtCfg, F2vCfg, F2fCfg, F2iCfg, VSetRvfWvfCfg
VFEX2: VfaluCfg, VfmaCfg, VialuCfg
VFEX3: VfdivCfg, VidivCfg
```
[after](https://github.com/OpenXiangShan/XiangShan/blob/2e61107/src/main/scala/xiangshan/Parameters.scala#L357):
```
VFEX0: VfmaCfg, VialuCfg, VimacCfg, VppuCfg
VFEX1: VfaluCfg, VfcvtCfg, VipuCfg, VSetRvfWvfCfg
VFEX2: VfmaCfg, VialuCfg, F2vCfg
VFEX3: VfaluCfg, VfcvtCfg
VFEX4: VfdivCfg, VidivCfg
VFEX5: VfdivCfg, VidivCfg
```


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


[clang] [clang]MveEmitter: Pass Args as a const reference (PR #89551)

2024-04-21 Thread via cfe-commits

https://github.com/aniplcc created 
https://github.com/llvm/llvm-project/pull/89551

Closes #89192.
Also updated with review patches.
In continuation of: `https://github.com/llvm/llvm-project/pull/89202` [Closed 
due to a bad rebase]



>From 21ef2c83063a16866edec3eaa1847db7b34592c4 Mon Sep 17 00:00:00 2001
From: aniplcc 
Date: Sun, 21 Apr 2024 23:01:20 +0530
Subject: [PATCH 1/2] [clang]MveEmitter: Pass Args as a const reference

---
 clang/utils/TableGen/MveEmitter.cpp | 10 +-
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/clang/utils/TableGen/MveEmitter.cpp 
b/clang/utils/TableGen/MveEmitter.cpp
index 88e7b6e8546595..5f6546a6498c3c 100644
--- a/clang/utils/TableGen/MveEmitter.cpp
+++ b/clang/utils/TableGen/MveEmitter.cpp
@@ -658,9 +658,9 @@ class IRBuilderResult : public Result {
   std::vector Args;
   std::set AddressArgs;
   std::map IntegerArgs;
-  IRBuilderResult(StringRef CallPrefix, std::vector Args,
-  std::set AddressArgs,
-  std::map IntegerArgs)
+  IRBuilderResult(StringRef CallPrefix, const std::vector ,
+  const std::set ,
+  const std::map )
   : CallPrefix(CallPrefix), Args(Args), AddressArgs(AddressArgs),
 IntegerArgs(IntegerArgs) {}
   void genCode(raw_ostream ,
@@ -727,8 +727,8 @@ class IRIntrinsicResult : public Result {
   std::string IntrinsicID;
   std::vector ParamTypes;
   std::vector Args;
-  IRIntrinsicResult(StringRef IntrinsicID, std::vector 
ParamTypes,
-std::vector Args)
+  IRIntrinsicResult(StringRef IntrinsicID, const std::vector 
,
+const std::vector )
   : IntrinsicID(std::string(IntrinsicID)), ParamTypes(ParamTypes),
 Args(Args) {}
   void genCode(raw_ostream ,

>From d0bfc710b9fa90d71f544451432577620b4cf610 Mon Sep 17 00:00:00 2001
From: aniplcc 
Date: Sun, 21 Apr 2024 23:13:50 +0530
Subject: [PATCH 2/2] format fixes

---
 clang/utils/TableGen/MveEmitter.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/utils/TableGen/MveEmitter.cpp 
b/clang/utils/TableGen/MveEmitter.cpp
index 5f6546a6498c3c..c455071ed9da7c 100644
--- a/clang/utils/TableGen/MveEmitter.cpp
+++ b/clang/utils/TableGen/MveEmitter.cpp
@@ -727,7 +727,8 @@ class IRIntrinsicResult : public Result {
   std::string IntrinsicID;
   std::vector ParamTypes;
   std::vector Args;
-  IRIntrinsicResult(StringRef IntrinsicID, const std::vector 
,
+  IRIntrinsicResult(StringRef IntrinsicID,
+const std::vector ,
 const std::vector )
   : IntrinsicID(std::string(IntrinsicID)), ParamTypes(ParamTypes),
 Args(Args) {}

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


[clang] Reapply "[Clang][Sema] placement new initializes typedef array with correct size (#83124)" (PR #89036)

2024-04-21 Thread via cfe-commits

mahtohappy wrote:

Hi @cor3ntin Please merge this. 

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


[clang] [llvm] [AMDGPU][WIP] Add support for i64/f64 readlane, writelane and readfirstlane operations. (PR #89217)

2024-04-21 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm commented:

In a separate patch should have AMDGPUInstCombineIntrinsic try to fold bitcasts 
into the intrinsic 

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] [llvm] [AMDGPU][WIP] Add support for i64/f64 readlane, writelane and readfirstlane operations. (PR #89217)

2024-04-21 Thread Matt Arsenault via cfe-commits


@@ -18410,6 +18410,24 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 CGM.getIntrinsic(Intrinsic::amdgcn_update_dpp, Args[0]->getType());
 return Builder.CreateCall(F, Args);
   }
+  case AMDGPU::BI__builtin_amdgcn_readlane:
+  case AMDGPU::BI__builtin_amdgcn_readfirstlane: {

arsenm wrote:

readfirstlane case can just call emitUnaryBuiltin. readlane can probably get 
away with emitBinaryBuiltin, although it doesn't quite fit the binary intrinsic 
signature 

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] [llvm] [AMDGPU][WIP] Add support for i64/f64 readlane, writelane and readfirstlane operations. (PR #89217)

2024-04-21 Thread Matt Arsenault via cfe-commits


@@ -18410,6 +18410,24 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 CGM.getIntrinsic(Intrinsic::amdgcn_update_dpp, Args[0]->getType());
 return Builder.CreateCall(F, Args);
   }
+  case AMDGPU::BI__builtin_amdgcn_readlane:
+  case AMDGPU::BI__builtin_amdgcn_readfirstlane: {
+llvm::SmallVector Args;
+unsigned ICEArguments = 0;
+ASTContext::GetBuiltinTypeError Error;
+Intrinsic::ID IID = (BuiltinID == AMDGPU::BI__builtin_amdgcn_readlane)
+? Intrinsic::amdgcn_readlane
+: Intrinsic::amdgcn_readfirstlane;
+
+getContext().GetBuiltinType(BuiltinID, Error, );
+assert(Error == ASTContext::GE_None && "Should not codegen an error");
+for (unsigned I = 0; I != E->getNumArgs(); ++I) {
+  Args.push_back(EmitScalarOrConstFoldImmArg(ICEArguments, I, E));

arsenm wrote:

This doesn't require the constant folding. This can use a plain EmitScalarExpr 

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] [llvm] [AMDGPU][WIP] Add support for i64/f64 readlane, writelane and readfirstlane operations. (PR #89217)

2024-04-21 Thread Matt Arsenault via cfe-commits


@@ -4822,6 +4822,111 @@ static MachineBasicBlock *lowerWaveReduce(MachineInstr 
,
   return RetBB;
 }
 
+static MachineBasicBlock *lowerPseudoLaneOp(MachineInstr ,

arsenm wrote:

You should try to do this before selection. Doing it after just adds a lot of 
complexity and interferes with combine opportunities 

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] [llvm] [AMDGPU][WIP] Add support for i64/f64 readlane, writelane and readfirstlane operations. (PR #89217)

2024-04-21 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm edited 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] Add ignoring paren imp casts in has any argument (PR #89509)

2024-04-21 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)

2024-04-21 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,34 @@
+//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ReturnConstRefFromParameterCheck.h"
+#include "../utils/Matchers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  returnStmt(hasReturnValue(declRefExpr(to(parmVarDecl(hasType(
+ hasCanonicalType(matchers::isReferenceToConst(
+  .bind("ret"),
+  this);
+}
+
+void ReturnConstRefFromParameterCheck::check(
+const MatchFinder::MatchResult ) {
+  const auto *R = Result.Nodes.getNodeAs("ret");
+  diag(R->getRetValue()->getBeginLoc(),
+   "return const reference parameter cause potential use-after-free "
+   "when function accepts immediately constructed value.");

5chmidti wrote:

What do you think about `returning a const reference parameter may cause a 
use-after-free when the parameter is constructed from a temporary` (`const` vs 
`constant` argument in the other thread aside)

I'm not sure if it should be `may` or `will`, because it is only a 
use-after-free if the returned value is actually used (FWICT).

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


[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)

2024-04-21 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,35 @@
+//===--- ReturnConstRefFromParameterCheck.h - clang-tidy *- 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
+//
+//===--===//
+
+#ifndef 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_RETURNCONSTREFFROMPARAMETERCHECK_H
+#define 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_RETURNCONSTREFFROMPARAMETERCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::bugprone {
+
+/// Detects the function which returns the const reference from parameter which
+/// causes potential use after free if the caller uses xvalue as argument.

5chmidti wrote:

I think `Detects statements that return constant` should actually be `Detects 
return statements that return constant`.

As for consistency: in docs/clang-tidy, there are ~116 const's (minus `const` 
in code snippets and check names) where ~50% of them are in ``, and there are 
91 constants (although 60 are in `identifier-naming.rst`.

`might cause potential` sounds not right to me, the `might` and `potential` 
mean the same thing IMO. 
I would suggest: `This might cause use-after-free errors ...` (or with `may` 
instead of `might`)

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


[clang] [clang] reject to capture variable in `RequiresExprBodyDecl` (PR #78598)

2024-04-21 Thread Yu Zeng via cfe-commits

l1nxy wrote:

@cor3ntin @shafikHi, I want to take charge of this issue and submit a PR for 
the fix. 

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


[clang] [Clang][Parser] Don't always destroy template annotations at the end of a declaration (PR #89494)

2024-04-21 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

> Are there actually any benefit from being that eager to delete template 
> annotations?

Well, I don't have much context of that patch, but I think that makes sense in 
part e.g. When we have a function that involves many generic lambdas, where we 
would destroy template annotations at the end of each lambda, comparing to 
destroying these at the end of the function.

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


[clang-tools-extra] Add ignoring paren imp casts in has any argument (PR #89509)

2024-04-21 Thread Julian Schmidt via cfe-commits


@@ -90,8 +91,9 @@ RewriteRuleWith StringviewNullptrCheckImpl() {
   auto HandleTemporaryCXXTemporaryObjectExprAndCompoundLiteralExpr = makeRule(
   cxxTemporaryObjectExpr(cxxConstructExpr(
   HasBasicStringViewType, argumentCountIs(1),
-  hasAnyArgument(/* `hasArgument` would skip over parens */ anyOf(
-  NullLiteral, NullInitList, EmptyInitList)),
+  hasAnyArgument(
+  /* `hasArgument` would skip over parens */ ignoringParenImpCasts(
+  anyOf(NullLiteral, NullInitList, EmptyInitList))),

5chmidti wrote:

Same as above

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


[clang-tools-extra] Add ignoring paren imp casts in has any argument (PR #89509)

2024-04-21 Thread Julian Schmidt via cfe-commits


@@ -74,8 +74,9 @@ RewriteRuleWith StringviewNullptrCheckImpl() {
   auto BasicStringViewConstructingFromNullExpr =
   cxxConstructExpr(
   HasBasicStringViewType, argumentCountIs(1),
-  hasAnyArgument(/* `hasArgument` would skip over parens */ anyOf(
-  NullLiteral, NullInitList, EmptyInitList)),
+  hasAnyArgument(
+  /* `hasArgument` would skip over parens */ ignoringParenImpCasts(
+  anyOf(NullLiteral, NullInitList, EmptyInitList))),

5chmidti wrote:

Checkout this file later for this and the other section I highlighted, here it 
looks like the only reason that  `hasAnyArgument` was chosen is because of this 
differing behavior, instead, this can be replaced with `hasArgument(0, ...)` 
after the `IgnoreParenImpCasts` is removed from the `hasArgument` matcher.

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


[clang-tools-extra] Add ignoring paren imp casts in has any argument (PR #89509)

2024-04-21 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] Add ignoring paren imp casts in has any argument (PR #89509)

2024-04-21 Thread Julian Schmidt via cfe-commits

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

I started taking a look at this and realized you switched up which argument 
matcher needs the extra `ignoringParenImpCasts`, so that it can be removed from 
the matcher definition.

See 
https://github.com/llvm/llvm-project/blob/d674f45d51bffbba474b12e07f7d57a2390d2f31/clang/include/clang/ASTMatchers/ASTMatchers.h#L4891-L4907
vs 
https://github.com/llvm/llvm-project/blob/d674f45d51bffbba474b12e07f7d57a2390d2f31/clang/include/clang/ASTMatchers/ASTMatchers.h#L4553-L4564.
 We don't want the `IgnoreParenImpCasts()` inside the `hasArgument` matcher, 
because that is not it's job. So we want to a) add `ignoringParenImpCasts` to 
arguments of the `hasArgument` matcher, and b) remove the call to 
`IgnoreParenImpCasts` from the `hasArgument` matcher.
See this comment from the original issue: 
https://github.com/llvm/llvm-project/issues/75754#issuecomment-1887818096

This is also the reason why the tests are failing, you are actually changing 
the behavior of these checks.

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


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-21 Thread Utkarsh Saxena via cfe-commits

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


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-21 Thread Utkarsh Saxena via cfe-commits

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


[clang] [flang] [flang] Default -g to full debug info. (PR #89418)

2024-04-21 Thread Tom Eccles via cfe-commits

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


[clang] [flang] [flang] Default -g to full debug info. (PR #89418)

2024-04-21 Thread Tom Eccles via cfe-commits

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

LGTM

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


[clang] Re-apply "Emit missing cleanups for stmt-expr" and other commits (PR #89154)

2024-04-21 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/89154

>From f1ab4c2677394bbfc985d9680d5eecd7b2e6a882 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Wed, 17 Apr 2024 22:47:36 +
Subject: [PATCH 1/3] Reapply "[codegen] Emit missing cleanups for stmt-expr
 and coro suspensions" and related commits (#4)

This reverts commit 9d8be2408768912dc113a342050049231e4fc8d1.
---
 clang/lib/CodeGen/CGCall.cpp  |  13 +-
 clang/lib/CodeGen/CGCleanup.cpp   |  49 ++-
 clang/lib/CodeGen/CGCleanup.h |  57 ++-
 clang/lib/CodeGen/CGDecl.cpp  |  61 ++-
 clang/lib/CodeGen/CGExpr.cpp  |  12 +-
 clang/lib/CodeGen/CGExprAgg.cpp   |  87 ++--
 clang/lib/CodeGen/CGExprCXX.cpp   |  38 +-
 clang/lib/CodeGen/CodeGenFunction.cpp |   6 +
 clang/lib/CodeGen/CodeGenFunction.h   |  99 -
 .../CodeGenCXX/control-flow-in-stmt-expr.cpp  | 409 ++
 .../coro-suspend-cleanups.cpp |  93 
 11 files changed, 796 insertions(+), 128 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/control-flow-in-stmt-expr.cpp
 create mode 100644 clang/test/CodeGenCoroutines/coro-suspend-cleanups.cpp

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 3f5463a9a70e9d..9004e96bc1a0cf 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4693,11 +4693,11 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 AggValueSlot Slot = args.isUsingInAlloca()
 ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
 
-bool DestroyedInCallee = true, NeedsEHCleanup = true;
+bool DestroyedInCallee = true, NeedsCleanup = true;
 if (const auto *RD = type->getAsCXXRecordDecl())
   DestroyedInCallee = RD->hasNonTrivialDestructor();
 else
-  NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
+  NeedsCleanup = type.isDestructedType();
 
 if (DestroyedInCallee)
   Slot.setExternallyDestructed();
@@ -4706,14 +4706,15 @@ void CodeGenFunction::EmitCallArg(CallArgList , 
const Expr *E,
 RValue RV = Slot.asRValue();
 args.add(RV, type);
 
-if (DestroyedInCallee && NeedsEHCleanup) {
+if (DestroyedInCallee && NeedsCleanup) {
   // Create a no-op GEP between the placeholder and the cleanup so we can
   // RAUW it successfully.  It also serves as a marker of the first
   // instruction where the cleanup is active.
-  pushFullExprCleanup(EHCleanup, Slot.getAddress(),
-  type);
+  pushFullExprCleanup(NormalAndEHCleanup,
+  Slot.getAddress(), type);
   // This unreachable is a temporary marker which will be removed later.
-  llvm::Instruction *IsActive = Builder.CreateUnreachable();
+  llvm::Instruction *IsActive =
+  Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
   args.addArgCleanupDeactivation(EHStack.stable_begin(), IsActive);
 }
 return;
diff --git a/clang/lib/CodeGen/CGCleanup.cpp b/clang/lib/CodeGen/CGCleanup.cpp
index e6f8e6873004f2..8683f19d9da28e 100644
--- a/clang/lib/CodeGen/CGCleanup.cpp
+++ b/clang/lib/CodeGen/CGCleanup.cpp
@@ -634,12 +634,19 @@ static void destroyOptimisticNormalEntry(CodeGenFunction 
,
 /// Pops a cleanup block.  If the block includes a normal cleanup, the
 /// current insertion point is threaded through the cleanup, as are
 /// any branch fixups on the cleanup.
-void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
+void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,
+  bool ForDeactivation) {
   assert(!EHStack.empty() && "cleanup stack is empty!");
   assert(isa(*EHStack.begin()) && "top not a cleanup!");
   EHCleanupScope  = cast(*EHStack.begin());
   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
 
+  // If we are deactivating a normal cleanup, we need to pretend that the
+  // fallthrough is unreachable. We restore this IP before returning.
+  CGBuilderTy::InsertPoint NormalDeactivateOrigIP;
+  if (ForDeactivation && (Scope.isNormalCleanup() || !getLangOpts().EHAsynch)) 
{
+NormalDeactivateOrigIP = Builder.saveAndClearIP();
+  }
   // Remember activation information.
   bool IsActive = Scope.isActive();
   Address NormalActiveFlag =
@@ -667,7 +674,8 @@ void CodeGenFunction::PopCleanupBlock(bool 
FallthroughIsBranchThrough) {
 
   // - whether there's a fallthrough
   llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
-  bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
+  bool HasFallthrough =
+  FallthroughSource != nullptr && (IsActive || HasExistingBranches);
 
   // Branch-through fall-throughs leave the insertion point set to the
   // end of the last cleanup, which points to the current scope.  The
@@ -692,7 +700,11 @@ void 

[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Piotr Zegar via cfe-commits


@@ -16,6 +16,49 @@
 using namespace clang::ast_matchers;
 
 namespace clang::tidy::modernize {
+namespace {
+// Given two argument indices X and Y, matches when a call expression has a
+// string at index X with an expression representing that string's length at
+// index Y. The string can be a string literal or a variable. The length can be
+// matched via an integer literal or a call to strlen() in the case of a string
+// literal, and by a call to size() or length() in the string variable case.
+AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments,
+   AST_POLYMORPHIC_SUPPORTED_TYPES(
+   CallExpr, CXXConstructExpr,
+   CXXUnresolvedConstructExpr, ObjCMessageExpr),
+   unsigned, StringArgIndex, unsigned, LengthArgIndex) 
{
+  if (StringArgIndex >= Node.getNumArgs() ||
+  LengthArgIndex >= Node.getNumArgs()) {
+return false;
+  }
+
+  const Expr *StringArgExpr =
+  Node.getArg(StringArgIndex)->IgnoreParenImpCasts();
+  const Expr *LengthArgExpr =
+  Node.getArg(LengthArgIndex)->IgnoreParenImpCasts();
+
+  if (const auto *StringArg = dyn_cast(StringArgExpr)) {
+// Match an integer literal equal to the string length or a call to strlen.
+const auto Matcher = expr(anyOf(
+integerLiteral(equals(StringArg->getLength())),
+callExpr(
+callee(functionDecl(hasName("strlen"))), argumentCountIs(1),
+hasArgument(0, stringLiteral(hasSize(StringArg->getLength()));
+return Matcher.matches(*LengthArgExpr, Finder, Builder);

PiotrZSL wrote:

i do not recommend constructing matcher in matcher, mainly due to performance 
reasons (constant construction of matcher).
What you could do is to pass matcher to this matcher as "inner matcher", and 
then just call it here, or convert it to simple function.

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Piotr Zegar via cfe-commits


@@ -16,6 +16,49 @@
 using namespace clang::ast_matchers;
 
 namespace clang::tidy::modernize {
+namespace {
+// Given two argument indices X and Y, matches when a call expression has a
+// string at index X with an expression representing that string's length at
+// index Y. The string can be a string literal or a variable. The length can be
+// matched via an integer literal or a call to strlen() in the case of a string
+// literal, and by a call to size() or length() in the string variable case.
+AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments,
+   AST_POLYMORPHIC_SUPPORTED_TYPES(
+   CallExpr, CXXConstructExpr,
+   CXXUnresolvedConstructExpr, ObjCMessageExpr),
+   unsigned, StringArgIndex, unsigned, LengthArgIndex) 
{
+  if (StringArgIndex >= Node.getNumArgs() ||
+  LengthArgIndex >= Node.getNumArgs()) {
+return false;
+  }
+
+  const Expr *StringArgExpr =
+  Node.getArg(StringArgIndex)->IgnoreParenImpCasts();
+  const Expr *LengthArgExpr =
+  Node.getArg(LengthArgIndex)->IgnoreParenImpCasts();
+
+  if (const auto *StringArg = dyn_cast(StringArgExpr)) {
+// Match an integer literal equal to the string length or a call to strlen.
+const auto Matcher = expr(anyOf(
+integerLiteral(equals(StringArg->getLength())),
+callExpr(
+callee(functionDecl(hasName("strlen"))), argumentCountIs(1),
+hasArgument(0, stringLiteral(hasSize(StringArg->getLength()));
+return Matcher.matches(*LengthArgExpr, Finder, Builder);

PiotrZSL wrote:

same in line 52

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Piotr Zegar via cfe-commits


@@ -298,6 +298,10 @@ Changes in existing checks
   check by resolving fix-it overlaps in template code by disregarding implicit
   instances.
 
+- Improved :doc:`modernize-use-starts-ends-with
+  ` check to also handle
+  cases using `compare()`.

PiotrZSL wrote:

'to also handle calls to ``compare`` method`, or something like that

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Piotr Zegar via cfe-commits

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

Looks +- fine, I just worry a little bit about performance.
But as "HasStringAndLengthArguments" will be executed only for an compare 
methods, then probably it could be fine.

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Piotr Zegar via cfe-commits


@@ -16,6 +16,49 @@
 using namespace clang::ast_matchers;
 
 namespace clang::tidy::modernize {
+namespace {
+// Given two argument indices X and Y, matches when a call expression has a
+// string at index X with an expression representing that string's length at
+// index Y. The string can be a string literal or a variable. The length can be
+// matched via an integer literal or a call to strlen() in the case of a string
+// literal, and by a call to size() or length() in the string variable case.
+AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments,

PiotrZSL wrote:

HasStringAndLengthArguments -> hasStringAndLengthArguments

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread Piotr Zegar via cfe-commits


@@ -94,11 +155,12 @@ void UseStartsEndsWithCheck::check(const 
MatchFinder::MatchResult ) {
   Diagnostic << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
   ComparisonExpr->getBeginLoc(), FindExpr->getBeginLoc()));
 
-  // Replace '(r?)find' with 'starts_with'.
+  // Replace method name by 'starts_with'.
+  // Remove possible arguments before search expression.
   Diagnostic << FixItHint::CreateReplacement(
-  CharSourceRange::getTokenRange(FindExpr->getExprLoc(),
- FindExpr->getExprLoc()),
-  StartsWithFunction->getName());
+  CharSourceRange::getCharRange(FindExpr->getExprLoc(),
+SearchExpr->getBeginLoc()),
+  StartsWithFunction->getNameAsString() + "(");

PiotrZSL wrote:

consider llvm::Twine for string merging.

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread via cfe-commits


@@ -298,6 +298,10 @@ Changes in existing checks
   check by resolving fix-it overlaps in template code by disregarding implicit
   instances.
 
+- Improved :doc:`modernize-use-starts-ends-with

EugeneZelenko wrote:

Please keep alphabetical order in this section (by check name).

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


[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

2024-04-21 Thread via cfe-commits


@@ -298,6 +298,10 @@ Changes in existing checks
   check by resolving fix-it overlaps in template code by disregarding implicit
   instances.
 
+- Improved :doc:`modernize-use-starts-ends-with
+  ` check to also handle
+  cases using `compare()`.

EugeneZelenko wrote:

Please use double back-ticks for language constructs.

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


[clang] [clang-repl] Implement value printing of custom types (PR #84769)

2024-04-21 Thread Vassil Vassilev via cfe-commits

https://github.com/vgvassilev updated 
https://github.com/llvm/llvm-project/pull/84769

>From a1639ef21a6085f12383e815ce2ed31976f78cfa Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Sun, 16 Jul 2023 21:18:26 +
Subject: [PATCH 1/2] [clang-repl] Implement value printing of custom types.

Differential revision: https://reviews.llvm.org/D146809
---
 clang/include/clang/Interpreter/Interpreter.h |   6 +
 .../Interpreter/PartialTranslationUnit.h  |   2 +
 clang/include/clang/Interpreter/Value.h   |   7 +-
 clang/lib/Headers/CMakeLists.txt  |   1 +
 .../__clang_interpreter_runtime_printvalue.h  | 261 
 clang/lib/Interpreter/CMakeLists.txt  |   1 +
 clang/lib/Interpreter/DeviceOffload.cpp   |   4 +-
 clang/lib/Interpreter/DeviceOffload.h |   4 +-
 clang/lib/Interpreter/IncrementalExecutor.cpp |   8 +-
 clang/lib/Interpreter/IncrementalExecutor.h   |   7 +-
 clang/lib/Interpreter/IncrementalParser.cpp   |   5 +-
 clang/lib/Interpreter/IncrementalParser.h |   5 +-
 clang/lib/Interpreter/Interpreter.cpp |  28 +-
 clang/lib/Interpreter/InterpreterUtils.cpp| 399 -
 clang/lib/Interpreter/InterpreterUtils.h  |  22 +-
 clang/lib/Interpreter/Value.cpp   |  33 +-
 clang/lib/Interpreter/ValuePrinter.cpp| 564 ++
 clang/test/Interpreter/pretty-print.cpp   | 206 +++
 clang/tools/clang-repl/CMakeLists.txt |  59 ++
 clang/tools/clang-repl/ClangRepl.cpp  |  21 +-
 .../Interpreter/CodeCompletionTest.cpp|  10 +-
 .../InterpreterExceptionTest.cpp  |   5 +-
 .../IncrementalCompilerBuilderTest.cpp|   4 +-
 .../Interpreter/IncrementalProcessingTest.cpp |   5 +-
 .../Interpreter/InterpreterExtensionsTest.cpp |   9 +-
 .../unittests/Interpreter/InterpreterTest.cpp |   5 +-
 26 files changed, 1627 insertions(+), 54 deletions(-)
 create mode 100644 clang/lib/Headers/__clang_interpreter_runtime_printvalue.h
 create mode 100644 clang/lib/Interpreter/ValuePrinter.cpp
 create mode 100644 clang/test/Interpreter/pretty-print.cpp

diff --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index 970e0245417b51..43331b0fe92c96 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -38,6 +38,8 @@ class ThreadSafeContext;
 namespace clang {
 
 class CompilerInstance;
+
+namespace caas {
 class IncrementalExecutor;
 class IncrementalParser;
 
@@ -150,6 +152,7 @@ class Interpreter {
   llvm::Expected getExecutionEngine();
 
   llvm::Expected Parse(llvm::StringRef Code);
+  llvm::Error ExecuteModule(std::unique_ptr );
   llvm::Error Execute(PartialTranslationUnit );
   llvm::Error ParseAndExecute(llvm::StringRef Code, Value *V = nullptr);
   llvm::Expected CompileDtorCall(CXXRecordDecl 
*CXXRD);
@@ -182,6 +185,8 @@ class Interpreter {
 
   Expr *SynthesizeExpr(Expr *E);
 
+  std::unique_ptr GenModule();
+
 private:
   size_t getEffectivePTUSize() const;
   void markUserCodeStart();
@@ -190,6 +195,7 @@ class Interpreter {
 
   llvm::SmallVector ValuePrintingInfo;
 };
+} // namespace caas
 } // namespace clang
 
 #endif // LLVM_CLANG_INTERPRETER_INTERPRETER_H
diff --git a/clang/include/clang/Interpreter/PartialTranslationUnit.h 
b/clang/include/clang/Interpreter/PartialTranslationUnit.h
index bf91d559452b8a..d28cd30010cb92 100644
--- a/clang/include/clang/Interpreter/PartialTranslationUnit.h
+++ b/clang/include/clang/Interpreter/PartialTranslationUnit.h
@@ -24,6 +24,7 @@ namespace clang {
 
 class TranslationUnitDecl;
 
+namespace caas {
 /// The class keeps track of various objects created as part of processing
 /// incremental inputs.
 struct PartialTranslationUnit {
@@ -32,6 +33,7 @@ struct PartialTranslationUnit {
   /// The llvm IR produced for the input.
   std::unique_ptr TheModule;
 };
+} // namespace caas
 } // namespace clang
 
 #endif // LLVM_CLANG_INTERPRETER_PARTIALTRANSLATIONUNIT_H
diff --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
index d70e8f8719026b..6b737c05846fff 100644
--- a/clang/include/clang/Interpreter/Value.h
+++ b/clang/include/clang/Interpreter/Value.h
@@ -49,9 +49,11 @@ class raw_ostream;
 namespace clang {
 
 class ASTContext;
-class Interpreter;
 class QualType;
 
+namespace caas {
+class Interpreter;
+
 #if defined(_WIN32)
 // REPL_EXTERNAL_VISIBILITY are symbols that we need to be able to locate
 // at runtime. On Windows, this requires them to be exported from any of the
@@ -138,6 +140,7 @@ class REPL_EXTERNAL_VISIBILITY Value {
   void setOpaqueType(void *Ty) { OpaqueType = Ty; }
 
   void *getPtr() const;
+  void **getPtrAddress() const;
   void setPtr(void *Ptr) { Data.m_Ptr = Ptr; }
 
 #define X(type, name)  
\
@@ -204,6 +207,6 @@ template <> inline void *Value::as() const {
 return Data.m_Ptr;
   return (void *)as();
 }
-
+} // 

[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)

2024-04-21 Thread via cfe-commits


@@ -112,6 +112,12 @@ New checks
   Detects error-prone Curiously Recurring Template Pattern usage, when the CRTP
   can be constructed outside itself and the derived class.
 
+- New :doc:`bugprone-return-const-ref-from-parameter
+  ` check.
+
+  Detects the function which returns the const reference from parameter which

EugeneZelenko wrote:

Please synchronize with first statement in documentation.

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


[clang-tools-extra] Add ignoring paren imp casts in has any argument (PR #89509)

2024-04-21 Thread via cfe-commits

komalverma04 wrote:

@PiotrZSL Please guide me tackling the failing tests

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


[clang] [clang] reject to capture variable in `RequiresExprBodyDecl` (PR #78598)

2024-04-21 Thread via cfe-commits

cor3ntin wrote:

If @HerrCai0907 doesn't reply, we should take over
@shafik @erichkeane @Endilll 

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


[clang] [clang][frontend] Make DumpModuleInfoAction emit the full macro (PR #85745)

2024-04-21 Thread Zhang Yi via cfe-commits

zhanyi22333 wrote:

This commit use tokens from MacroInfo to emit the macro body.
It emits macro body below the part of macro name.

For import test case, it can not get MacroInfo. So it will just print macro 
name as below.

```
   Macro Definitions:
 CONSTANT
 FUNC_Macro
 FOO
   Macro Definition Bodies:
 CONSTANT
 FUNC_Macro
 FOO
```

 I wonder whether it is better to not print body part for import case.


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


[clang] [clang] Mark ill-formed partial specialization as invalid (PR #89536)

2024-04-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

Fixes #89374
Solution suggested by @cor3ntin

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


3 Files Affected:

- (modified) clang/lib/Sema/SemaTemplate.cpp (+2) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+3) 
- (modified) clang/test/SemaCXX/template-specialization.cpp (+28) 


``diff
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index d4976f9d0d11d8..2bcbc081750b31 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -9459,6 +9459,7 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
 << ClassTemplate->getDeclName();
   isPartialSpecialization = false;
+  Invalid = true;
 }
   }
 
@@ -9674,6 +9675,7 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   if (SkipBody && SkipBody->ShouldSkip)
 return SkipBody->Previous;
 
+  Specialization->setInvalidDecl(Invalid);
   return Specialization;
 }
 
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 0b6375001f5326..c3815bca038554 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1914,6 +1914,9 @@ static TemplateDeductionResult 
DeduceTemplateArgumentsByTypeMatch(
   if (!S.isCompleteType(Info.getLocation(), A))
 return Result;
 
+  if (getCanonicalRD(A)->isInvalidDecl())
+return Result;
+
   // Reset the incorrectly deduced argument from above.
   Deduced = DeducedOrig;
 
diff --git a/clang/test/SemaCXX/template-specialization.cpp 
b/clang/test/SemaCXX/template-specialization.cpp
index 7b26ff9f5c5ba4..eabb84f2e13d3e 100644
--- a/clang/test/SemaCXX/template-specialization.cpp
+++ b/clang/test/SemaCXX/template-specialization.cpp
@@ -52,3 +52,31 @@ void instantiate() {
 }
 
 }
+
+namespace GH89374 {
+
+struct A {};
+
+template 
+struct MatrixBase { // #GH89374-MatrixBase
+  template 
+  Derived =(const MatrixBase &); // 
#GH89374-copy-assignment
+};
+
+template 
+struct solve_retval;
+
+template 
+struct solve_retval : MatrixBase > {};
+// expected-error@-1 {{partial specialization of 'solve_retval' does not use 
any of its template parameters}}
+
+void ApproximateChebyshev() {
+  MatrixBase c;
+  c = solve_retval();
+  // expected-error@-1 {{no viable overloaded '='}}
+  //   expected-note@#GH89374-copy-assignment {{candidate template ignored: 
could not match 'MatrixBase' against 'solve_retval'}}
+  //   expected-note@#GH89374-MatrixBase {{candidate function (the implicit 
copy assignment operator) not viable: no known conversion from 
'solve_retval' to 'const MatrixBase' for 1st argument}}
+  //   expected-note@#GH89374-MatrixBase {{candidate function (the implicit 
move assignment operator) not viable: no known conversion from 
'solve_retval' to 'MatrixBase' for 1st argument}}
+}
+
+} // namespace GH89374

``




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


[clang] [clang] Mark ill-formed partial specialization as invalid (PR #89536)

2024-04-21 Thread Vlad Serebrennikov via cfe-commits

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

Fixes #89374
Solution suggested by @cor3ntin

>From 58058a88305c7d4c1b1a30d8572ca481889ea3f9 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sun, 21 Apr 2024 13:29:39 +0300
Subject: [PATCH] [clang] Mark ill-formed partial specialization as invalid

Fixes #89374
Solution suggested by @cor3ntin
---
 clang/lib/Sema/SemaTemplate.cpp   |  2 ++
 clang/lib/Sema/SemaTemplateDeduction.cpp  |  3 ++
 .../test/SemaCXX/template-specialization.cpp  | 28 +++
 3 files changed, 33 insertions(+)

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index d4976f9d0d11d8..2bcbc081750b31 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -9459,6 +9459,7 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
 << ClassTemplate->getDeclName();
   isPartialSpecialization = false;
+  Invalid = true;
 }
   }
 
@@ -9674,6 +9675,7 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   if (SkipBody && SkipBody->ShouldSkip)
 return SkipBody->Previous;
 
+  Specialization->setInvalidDecl(Invalid);
   return Specialization;
 }
 
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 0b6375001f5326..c3815bca038554 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1914,6 +1914,9 @@ static TemplateDeductionResult 
DeduceTemplateArgumentsByTypeMatch(
   if (!S.isCompleteType(Info.getLocation(), A))
 return Result;
 
+  if (getCanonicalRD(A)->isInvalidDecl())
+return Result;
+
   // Reset the incorrectly deduced argument from above.
   Deduced = DeducedOrig;
 
diff --git a/clang/test/SemaCXX/template-specialization.cpp 
b/clang/test/SemaCXX/template-specialization.cpp
index 7b26ff9f5c5ba4..eabb84f2e13d3e 100644
--- a/clang/test/SemaCXX/template-specialization.cpp
+++ b/clang/test/SemaCXX/template-specialization.cpp
@@ -52,3 +52,31 @@ void instantiate() {
 }
 
 }
+
+namespace GH89374 {
+
+struct A {};
+
+template 
+struct MatrixBase { // #GH89374-MatrixBase
+  template 
+  Derived =(const MatrixBase &); // 
#GH89374-copy-assignment
+};
+
+template 
+struct solve_retval;
+
+template 
+struct solve_retval : MatrixBase > {};
+// expected-error@-1 {{partial specialization of 'solve_retval' does not use 
any of its template parameters}}
+
+void ApproximateChebyshev() {
+  MatrixBase c;
+  c = solve_retval();
+  // expected-error@-1 {{no viable overloaded '='}}
+  //   expected-note@#GH89374-copy-assignment {{candidate template ignored: 
could not match 'MatrixBase' against 'solve_retval'}}
+  //   expected-note@#GH89374-MatrixBase {{candidate function (the implicit 
copy assignment operator) not viable: no known conversion from 
'solve_retval' to 'const MatrixBase' for 1st argument}}
+  //   expected-note@#GH89374-MatrixBase {{candidate function (the implicit 
move assignment operator) not viable: no known conversion from 
'solve_retval' to 'MatrixBase' for 1st argument}}
+}
+
+} // namespace GH89374

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


[clang] [clang]MveEmitter:Pass Args as const references (PR #89202)

2024-04-21 Thread Simon Pilgrim via cfe-commits


@@ -660,7 +660,7 @@ class IRBuilderResult : public Result {
   std::map IntegerArgs;
   IRBuilderResult(StringRef CallPrefix, std::vector Args,

RKSimon wrote:

std::vector Args?

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


[clang] [clang]MveEmitter:Pass Args as const references (PR #89202)

2024-04-21 Thread Simon Pilgrim via cfe-commits


@@ -660,7 +660,7 @@ class IRBuilderResult : public Result {
   std::map IntegerArgs;
   IRBuilderResult(StringRef CallPrefix, std::vector Args,
   std::set AddressArgs,

RKSimon wrote:

std::set AddressArgs?

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


[clang] [clang]MveEmitter:Pass Args as const references (PR #89202)

2024-04-21 Thread Simon Pilgrim via cfe-commits


@@ -728,7 +728,7 @@ class IRIntrinsicResult : public Result {
   std::vector ParamTypes;
   std::vector Args;
   IRIntrinsicResult(StringRef IntrinsicID, std::vector 
ParamTypes,

RKSimon wrote:

std::vector ParamTypes?

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


[clang] [Clang][Parser] Don't always destroy template annotations at the end of a declaration (PR #89494)

2024-04-21 Thread via cfe-commits

cor3ntin wrote:

Are there actually any benefit from being _that_ eager to delete template 
annotations?
Getting back to a place where who only delete at the end of Top level decls 
would avoid the new complexity, right?

That design question notwithstanding, the patch looks reasonable to me

@AaronBallman @shafik 

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


[clang] [Clang] Allow the value of unroll count to be zero in `#pragma GCC unroll` and `#pragma unroll` (PR #88666)

2024-04-21 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

@ronlieb nice and small reproducer would definitely help resolving this.

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


[clang] aa22d44 - [Clang] Do not try to diagnose parameter packs in invalid pack expressions (#89257)

2024-04-21 Thread via cfe-commits

Author: cor3ntin
Date: 2024-04-21T11:43:51+02:00
New Revision: aa22d4422ee031d3867290e6ec12985f87d9ea2f

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

LOG: [Clang] Do not try to diagnose parameter packs in invalid pack expressions 
(#89257)

In a pack expression, if the id-expression is not valid, do no try to
detect whether it is a pack as that would lead to a crash trying to
print a recovery expression.

Fixes #88929

Added: 


Modified: 
clang/lib/Sema/SemaTemplateVariadic.cpp
clang/test/SemaCXX/cxx2c-pack-indexing.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateVariadic.cpp 
b/clang/lib/Sema/SemaTemplateVariadic.cpp
index 4909414c0c78d4..a4b681ae4f008e 100644
--- a/clang/lib/Sema/SemaTemplateVariadic.cpp
+++ b/clang/lib/Sema/SemaTemplateVariadic.cpp
@@ -1085,9 +1085,11 @@ ExprResult Sema::ActOnPackIndexingExpr(Scope *S, Expr 
*PackExpression,
SourceLocation RSquareLoc) {
   bool isParameterPack = ::isParameterPack(PackExpression);
   if (!isParameterPack) {
-CorrectDelayedTyposInExpr(IndexExpr);
-Diag(PackExpression->getBeginLoc(), diag::err_expected_name_of_pack)
-<< PackExpression;
+if (!PackExpression->containsErrors()) {
+  CorrectDelayedTyposInExpr(IndexExpr);
+  Diag(PackExpression->getBeginLoc(), diag::err_expected_name_of_pack)
+  << PackExpression;
+}
 return ExprError();
   }
   ExprResult Res =

diff  --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp 
b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
index e13635383b6ca6..606715e6aacffd 100644
--- a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
+++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
@@ -154,3 +154,9 @@ void f() {
 }
 
 }
+
+namespace GH88929 {
+bool b = a...[0];  // expected-error {{use of undeclared identifier 'a'}}
+using E = P...[0]; // expected-error {{unknown type name 'P'}} \
+   // expected-error {{expected ';' after alias 
declaration}}
+}



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


[clang] [Clang] Do not try to diagnose parameter packs in invalid pack expressions (PR #89257)

2024-04-21 Thread via cfe-commits

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


[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)

2024-04-21 Thread Danny Mösch via cfe-commits


@@ -0,0 +1,35 @@
+//===--- ReturnConstRefFromParameterCheck.h - clang-tidy *- 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
+//
+//===--===//
+
+#ifndef 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_RETURNCONSTREFFROMPARAMETERCHECK_H
+#define 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_RETURNCONSTREFFROMPARAMETERCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::bugprone {
+
+/// Detects the function which returns the const reference from parameter which
+/// causes potential use after free if the caller uses xvalue as argument.

SimplyDanny wrote:

My thought was that this is text and "const" is not an English word but 
"constant" and `const` is a keyword. On the other hand, "const reference" is a 
well known term to C++ people. So in the end, it should be consistent with 
existing text in the project. Alternatively, putting the term monospaced as 
`const &` would also work I guess.

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


[clang] [clang][frontend] Make DumpModuleInfoAction emit the full macro (PR #85745)

2024-04-21 Thread Zhang Yi via cfe-commits

https://github.com/zhanyi22333 updated 
https://github.com/llvm/llvm-project/pull/85745

>From 61b24269867dcec12c8fcab0c26b444f33a57454 Mon Sep 17 00:00:00 2001
From: root 
Date: Sun, 21 Apr 2024 16:43:17 +0800
Subject: [PATCH 1/2] [clang][frontend] change DumpModuleInfoAction test cases.

---
 .../test/Modules/cxx20-module-file-info-macros.cpp | 14 ++
 1 file changed, 14 insertions(+)

diff --git a/clang/test/Modules/cxx20-module-file-info-macros.cpp 
b/clang/test/Modules/cxx20-module-file-info-macros.cpp
index 3b67e9b9acd410..567d21cf1fa43d 100644
--- a/clang/test/Modules/cxx20-module-file-info-macros.cpp
+++ b/clang/test/Modules/cxx20-module-file-info-macros.cpp
@@ -40,6 +40,11 @@
 // CHECK-DAG: FUNC_Macro
 // CHECK-DAG: CONSTANT
 // CHECK-DAG: FOO
+// CHECK: Macro Definition Bodies:
+// CHECK-DAG: REDEFINE
+// CHECK-DAG: FUNC_Macro(X) (X+1)
+// CHECK-DAG: CONSTANT 43
+// CHECK-DAG: FOO
 // CHECK-NEXT: ===
 
 //--- include_foo.h
@@ -49,6 +54,10 @@
 // CHECK-DAG: CONSTANT
 // CHECK-DAG: FUNC_Macro
 // CHECK-DAG: FOO
+// CHECK: Macro Definition Bodies:
+// CHECK-DAG: FUNC_Macro(X) (X+1)
+// CHECK-DAG: CONSTANT 43
+// CHECK-DAG: FOO
 // CHECK-NEXT: ===
 
 //--- import_foo.h
@@ -58,6 +67,10 @@ import "foo.h";
 // CHECK-DAG: CONSTANT
 // CHECK-DAG: FUNC_Macro
 // CHECK-DAG: FOO
+// CHECK: Macro Definition Bodies:
+// CHECK-DAG: FUNC_Macro
+// CHECK-DAG: CONSTANT
+// CHECK-DAG: FOO
 // CHECK-NEXT: ===
 
 //--- named_module.cppm
@@ -66,3 +79,4 @@ module;
 export module M;
 #define M_Module 43
 // CHECK-NOT: Macro Definitions:
+// CHECK-NOT: Macro Definition Bodies:

>From ce3e5abfe2d994974d3a41b98f7e152e358afdb7 Mon Sep 17 00:00:00 2001
From: root 
Date: Sun, 21 Apr 2024 16:45:04 +0800
Subject: [PATCH 2/2] [clang][frontend] Make DumpModuleInfoAction emit the full
 macro.

---
 clang/lib/Frontend/FrontendActions.cpp | 61 ++
 1 file changed, 53 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Frontend/FrontendActions.cpp 
b/clang/lib/Frontend/FrontendActions.cpp
index 04eb1041326713..3800958e34cca5 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -943,17 +943,62 @@ void DumpModuleInfoAction::ExecuteAction() {
   for (/* pair*/ const auto  :
FilteredMacros)
 Out << " " << Macro.first->getName() << "\n";
-}
 
-// Now let's print out any modules we did not see as part of the Primary.
-for (const auto  : SubModMap) {
-  if (!SM.second.Seen && SM.second.Mod) {
-Out << "  " << ModuleKindName(SM.second.Kind) << " '" << SM.first
-<< "' at index #" << SM.second.Idx
-<< " has no direct reference in the Primary\n";
+  // Emit the macro definition bodies completely.
+  Out << "   Macro Definition Bodies:\n";
+  for (const auto  : FilteredMacros) {
+Out << " " << Macro.first->getName();
+clang::MacroInfo *MI = PP.getMacroInfo(Macro.first);
+if (MI == nullptr) {
+  Out << '\n';
+  continue;
+}
+if (MI->isFunctionLike()) {
+  Out << '(';
+  if (!MI->param_empty()) {
+MacroInfo::param_iterator AI = MI->param_begin(),
+  E = MI->param_end();
+for (; AI + 1 != E; ++AI) {
+  Out << (*AI)->getName();
+  Out << ',';
+}
+
+// Last argument.
+if ((*AI)->getName() == "__VA_ARGS__")
+  Out << "...";
+else
+  Out << (*AI)->getName();
+  }
+
+  if (MI->isGNUVarargs())
+// #define foo(x...)
+Out << "...";
+
+  Out << ')';
+}
+
+SmallString<128> SpellingBuffer;
+bool First = true;
+for (const auto  : MI->tokens()) {
+  if (First || T.hasLeadingSpace())
+Out << " ";
+  First = false;
+
+  Out << PP.getSpelling(T, SpellingBuffer);
+}
+Out << '\n';
+  }
+
+  // Now let's print out any modules we did not see as part of the Primary.
+  for (const auto  : SubModMap) {
+if (!SM.second.Seen && SM.second.Mod) {
+  Out << "  " << ModuleKindName(SM.second.Kind) << " '" << SM.first
+  << "' at index #" << SM.second.Idx
+  << " has no direct reference in the Primary\n";
+}
   }
+  Out << "  == ==\n";
 }
-Out << "  == ==\n";
   }
 
   // The reminder of the output is produced from the listener as the AST

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


[clang] [Clang] Allow the value of unroll count to be zero in `#pragma GCC unroll` and `#pragma unroll` (PR #88666)

2024-04-21 Thread via cfe-commits

ronlieb wrote:

our downstream CI for amdgpu build of rccl, rocblas and rocSolver are seeing 
this assertions due to this patch
[2024-04-21T03:28:05.859Z] clang-19: 
/jenkins/workspace/compiler-psdb-amd-staging/repos/external/llvm-project/clang/lib/AST/ExprConstant.cpp:15721:
 bool clang::Expr::EvaluateAsRValue(clang::Expr::EvalResult&, const 
clang::ASTContext&, bool) const: Assertion `!isValueDependent() && "Expression 
evaluator can't be called on a dependent expression."' failed.

if a reproducer is needed, we can try and get one , bit of effort. let me know.

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


[clang] [llvm] [cmake] Remove custom linker flag check function (PR #86602)

2024-04-21 Thread Petr Hosek via cfe-commits

petrhosek wrote:

I'd actually prefer this not be merged as is. I have already made a similar 
change locally but during testing I discovered a major issue with 
`check_linker_flag`: unlike other CMake `check_*` functions, and even 
`llvm_check_linker_flag`, `check_linker_flag` doesn't apply 
`CMAKE_REQUIRED_LINK_OPTIONS` because [the implementation overrides 
it](https://gitlab.kitware.com/cmake/cmake/-/blob/14de6802e40edcdeebc73d81210fe8e1ec0f469e/Modules/Internal/CheckLinkerFlag.cmake#L25)
 and this can result in failed checks when `CMAKE_REQUIRED_LINK_OPTIONS` 
contains necessary flags (it actually breaks the runtimes build which this 
change doesn't touch). I'd rather prefer to continue using 
`llvm_check_linker_flag` with our own implementation [similar to the CMake 
one](https://gitlab.kitware.com/cmake/cmake/-/blob/14de6802e40edcdeebc73d81210fe8e1ec0f469e/Modules/Internal/CheckLinkerFlag.cmake)
 that appends `CMAKE_REQUIRED_LINK_OPTIONS` rather than overwriting it. If you 
want to implement such a change, that would be great, otherwise I can take a 
stab at it when I have some time.

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


[clang] Fix objc_sel_{name,types} missing an underscore (PR #88713)

2024-04-21 Thread Jonathan Schleifer via cfe-commits

Midar wrote:

Maybe @rjmccall would be a good reviewer?

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


[clang] Reapply "[Clang][Sema] placement new initializes typedef array with correct size (#83124)" (PR #89036)

2024-04-21 Thread via cfe-commits

https://github.com/mahtohappy updated 
https://github.com/llvm/llvm-project/pull/89036

>From 56c2b4f70735a6ef3b80cb8461a88ea51f2d02d7 Mon Sep 17 00:00:00 2001
From: mahtohappy 
Date: Tue, 16 Apr 2024 17:48:45 +0530
Subject: [PATCH 1/6] [Clang][Sema] placement new initializes typedef array
 with correct size (#83124)

When in-place new-ing a local variable of an array of trivial type, the
generated code calls 'memset' with the correct size of the array,
earlier it was generating size (squared of the typedef array + size).

The cause: `typedef TYPE TArray[8]; TArray x;` The type of declarator is
Tarray[8] and in `SemaExprCXX.cpp::BuildCXXNew` we check if it's of
typedef and of constant size then we get the original type and it works
fine for non-dependent cases.
But in case of template we do `TreeTransform.h:TransformCXXNEWExpr` and
there we again check the allocated type which is TArray[8] and it stays
that way, so ArraySize=(Tarray[8] type, alloc Tarray[8*type]) so the
squared size allocation.

ArraySize gets calculated earlier in `TreeTransform.h` so that
`if(!ArraySize)` condition was failing.
fix: I changed that condition to `if(ArraySize)`.


Fixes #41441
---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/Sema/TreeTransform.h| 14 -
 .../instantiate-new-placement-size.cpp| 20 +++
 3 files changed, 35 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/SemaCXX/instantiate-new-placement-size.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 96ad92b540b47f..636d76f1836759 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -534,6 +534,8 @@ Bug Fixes to C++ Support
   Fixes (#GH70604), (#GH79754), (#GH84163), (#GH84425), (#GH86054), 
(#GH86398), and (#GH86399).
 - Fix a crash when deducing ``auto`` from an invalid dereference (#GH88329).
 - Fix a crash in requires expression with templated base class member 
function. Fixes (#GH84020).
+- placement new initializes typedef array with correct size
+  (`#GH41441 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index eb05783a6219dc..0c7fdb357235e1 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -12864,6 +12864,19 @@ TreeTransform::TransformCXXNewExpr(CXXNewExpr 
*E) {
 ArraySize = NewArraySize.get();
   }
 
+  // Per C++0x [expr.new]p5, the type being constructed may be a
+  // typedef of an array type.
+  QualType AllocType = AllocTypeInfo->getType();
+  if (ArraySize) {
+if (const ConstantArrayType *Array =
+SemaRef.Context.getAsConstantArrayType(AllocType)) {
+  ArraySize = IntegerLiteral::Create(SemaRef.Context, Array->getSize(),
+ SemaRef.Context.getSizeType(),
+ E->getBeginLoc());
+  AllocType = Array->getElementType();
+}
+  }
+
   // Transform the placement arguments (if any).
   bool ArgumentChanged = false;
   SmallVector PlacementArgs;
@@ -12925,7 +12938,6 @@ TreeTransform::TransformCXXNewExpr(CXXNewExpr 
*E) {
 return E;
   }
 
-  QualType AllocType = AllocTypeInfo->getType();
   if (!ArraySize) {
 // If no array size was specified, but the new expression was
 // instantiated with an array type (e.g., "new T" where T is
diff --git a/clang/test/SemaCXX/instantiate-new-placement-size.cpp 
b/clang/test/SemaCXX/instantiate-new-placement-size.cpp
new file mode 100644
index 00..7a29d3dee8491e
--- /dev/null
+++ b/clang/test/SemaCXX/instantiate-new-placement-size.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang -S -fno-discard-value-names -emit-llvm -o - %s | FileCheck %s
+// Issue no: 41441
+#include 
+
+// CHECK: call void @llvm.memset.p0.i64(ptr align 1 %x, i8 0, i64 8, i1 false)
+// CHECK: call void @llvm.memset.p0.i64(ptr align 16 %x, i8 0, i64 32, i1 
false)
+template 
+void f()
+{
+typedef TYPE TArray[8];
+
+TArray x;
+new() TArray();
+}
+
+int main()
+{
+f();
+f();
+}

>From bdd7f66e560f60d1f0027b04ad12989b2f786df3 Mon Sep 17 00:00:00 2001
From: mahtohappy 
Date: Wed, 17 Apr 2024 00:12:14 +0530
Subject: [PATCH 2/6] [Clang][Sema] placement new initializes typedef array
 with correct size (#88902)

Build Failure Fix
Fixes build failures due to #83124
---
 .../{instantiate-new-placement-size.cpp => PR41441.cpp}   | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
 rename clang/test/SemaCXX/{instantiate-new-placement-size.cpp => PR41441.cpp} 
(75%)

diff --git a/clang/test/SemaCXX/instantiate-new-placement-size.cpp 
b/clang/test/SemaCXX/PR41441.cpp
similarity index 75%
rename from clang/test/SemaCXX/instantiate-new-placement-size.cpp
rename to clang/test/SemaCXX/PR41441.cpp
index 7a29d3dee8491e..0b012b33fce343 100644
--- a/clang/test/SemaCXX/instantiate-new-placement-size.cpp
+++ 

[clang] fa01d04 - [clang][Interp][NFC] Change pointer offset to uint64

2024-04-21 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-04-21T08:30:58+02:00
New Revision: fa01d04c9b9a3c8454194a36a0e64daf43cddaf2

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

LOG: [clang][Interp][NFC] Change pointer offset to uint64

To accomodate for recent changes in array index calculations.

Added: 


Modified: 
clang/lib/AST/Interp/Pointer.cpp
clang/lib/AST/Interp/Pointer.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Pointer.cpp 
b/clang/lib/AST/Interp/Pointer.cpp
index e163e658d462b2..5ef31671ae7be5 100644
--- a/clang/lib/AST/Interp/Pointer.cpp
+++ b/clang/lib/AST/Interp/Pointer.cpp
@@ -23,7 +23,7 @@ Pointer::Pointer(Block *Pointee)
 : Pointer(Pointee, Pointee->getDescriptor()->getMetadataSize(),
   Pointee->getDescriptor()->getMetadataSize()) {}
 
-Pointer::Pointer(Block *Pointee, unsigned BaseAndOffset)
+Pointer::Pointer(Block *Pointee, uint64_t BaseAndOffset)
 : Pointer(Pointee, BaseAndOffset, BaseAndOffset) {}
 
 Pointer::Pointer(const Pointer )
@@ -34,7 +34,7 @@ Pointer::Pointer(const Pointer )
 PointeeStorage.BS.Pointee->addPointer(this);
 }
 
-Pointer::Pointer(Block *Pointee, unsigned Base, unsigned Offset)
+Pointer::Pointer(Block *Pointee, unsigned Base, uint64_t Offset)
 : Offset(Offset), StorageKind(Storage::Block) {
   assert((Base == RootPtrMark || Base % alignof(void *) == 0) && "wrong base");
 

diff  --git a/clang/lib/AST/Interp/Pointer.h b/clang/lib/AST/Interp/Pointer.h
index b4475577b74625..c4d701bc71b7bf 100644
--- a/clang/lib/AST/Interp/Pointer.h
+++ b/clang/lib/AST/Interp/Pointer.h
@@ -89,10 +89,10 @@ class Pointer {
 PointeeStorage.Int.Desc = nullptr;
   }
   Pointer(Block *B);
-  Pointer(Block *B, unsigned BaseAndOffset);
+  Pointer(Block *B, uint64_t BaseAndOffset);
   Pointer(const Pointer );
   Pointer(Pointer &);
-  Pointer(uint64_t Address, const Descriptor *Desc, unsigned Offset = 0)
+  Pointer(uint64_t Address, const Descriptor *Desc, uint64_t Offset = 0)
   : Offset(Offset), StorageKind(Storage::Int) {
 PointeeStorage.Int.Value = Address;
 PointeeStorage.Int.Desc = Desc;
@@ -134,14 +134,14 @@ class Pointer {
   std::optional toRValue(const Context ) const;
 
   /// Offsets a pointer inside an array.
-  [[nodiscard]] Pointer atIndex(unsigned Idx) const {
+  [[nodiscard]] Pointer atIndex(uint64_t Idx) const {
 if (isIntegralPointer())
   return Pointer(asIntPointer().Value, asIntPointer().Desc, Idx);
 
 if (asBlockPointer().Base == RootPtrMark)
   return Pointer(asBlockPointer().Pointee, RootPtrMark,
  getDeclDesc()->getSize());
-unsigned Off = Idx * elemSize();
+uint64_t Off = Idx * elemSize();
 if (getFieldDesc()->ElemDesc)
   Off += sizeof(InlineDescriptor);
 else
@@ -630,7 +630,7 @@ class Pointer {
   friend class DeadBlock;
   friend struct InitMap;
 
-  Pointer(Block *Pointee, unsigned Base, unsigned Offset);
+  Pointer(Block *Pointee, unsigned Base, uint64_t Offset);
 
   /// Returns the embedded descriptor preceding a field.
   InlineDescriptor *getInlineDesc() const {
@@ -656,7 +656,7 @@ class Pointer {
   }
 
   /// Offset into the storage.
-  unsigned Offset = 0;
+  uint64_t Offset = 0;
 
   /// Previous link in the pointer chain.
   Pointer *Prev = nullptr;



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