[clang] [clang][analyzer] Check for label location bindings in `DereferenceChecker` (PR #91119)

2024-05-13 Thread Balazs Benics via cfe-commits

https://github.com/steakhal updated 
https://github.com/llvm/llvm-project/pull/91119

>From 78a2afab67eef9a8a05ced89df0aadb56a2ec2b8 Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Sun, 5 May 2024 18:05:00 +0530
Subject: [PATCH 1/2] [clang][analyzer] Check for label location bindings in
 `DereferenceChecker`

Resolves #89264
---
 .../Checkers/DereferenceChecker.cpp   | 15 ++-
 clang/test/Analysis/gh-issue-89185.c  |  7 +++
 2 files changed, 17 insertions(+), 5 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
index 1cebfbbee77da..0355eede75eae 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
@@ -31,11 +31,13 @@ class DereferenceChecker
 : public Checker< check::Location,
   check::Bind,
   EventDispatcher > {
-  enum DerefKind { NullPointer, UndefinedPointerValue };
+  enum DerefKind { NullPointer, UndefinedPointerValue, AddressOfLabel };
 
   BugType BT_Null{this, "Dereference of null pointer", categories::LogicError};
   BugType BT_Undef{this, "Dereference of undefined pointer value",
categories::LogicError};
+  BugType BT_Label{this, "Dereference of the address of a label",
+   categories::LogicError};
 
   void reportBug(DerefKind K, ProgramStateRef State, const Stmt *S,
  CheckerContext &C) const;
@@ -167,6 +169,11 @@ void DereferenceChecker::reportBug(DerefKind K, 
ProgramStateRef State,
 DerefStr1 = " results in an undefined pointer dereference";
 DerefStr2 = " results in a dereference of an undefined pointer value";
 break;
+  case DerefKind::AddressOfLabel:
+BT = &BT_Label;
+DerefStr1 = " results in an undefined pointer dereference";
+DerefStr2 = " results in a dereference of an address of a label";
+break;
   };
 
   // Generate an error node.
@@ -287,6 +294,12 @@ void DereferenceChecker::checkBind(SVal L, SVal V, const 
Stmt *S,
   if (V.isUndef())
 return;
 
+  // One should never write to label addresses.
+  if (auto Label = L.getAs()) {
+reportBug(DerefKind::AddressOfLabel, C.getState(), S, C);
+return;
+  }
+
   const MemRegion *MR = L.getAsRegion();
   const TypedValueRegion *TVR = dyn_cast_or_null(MR);
   if (!TVR)
diff --git a/clang/test/Analysis/gh-issue-89185.c 
b/clang/test/Analysis/gh-issue-89185.c
index 8a907f198a5fd..27456e7efe885 100644
--- a/clang/test/Analysis/gh-issue-89185.c
+++ b/clang/test/Analysis/gh-issue-89185.c
@@ -7,8 +7,7 @@ void clang_analyzer_dump_ptr(char*);
 void binding_to_label_loc() {
   char *b = &&MyLabel;
 MyLabel:
-  *b = 0; // no-crash
-  clang_analyzer_dump_ptr(b); // expected-warning {{&&MyLabel}}
-  clang_analyzer_dump(*b); // expected-warning {{Unknown}}
-  // FIXME: We should never reach here, as storing to a label is invalid.
+  *b = 0; // expected-warning {{Dereference of the address of a label}}
+  clang_analyzer_dump_ptr(b);
+  clang_analyzer_dump(*b);
 }

>From 68b541906c5238b9165702c5623a00c877b53cbf Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Mon, 13 May 2024 09:17:13 +0200
Subject: [PATCH 2/2] Track the LHS of assignments for deref bugs

This adds notes for the "definition" lines for the dereferenced
variables that are raised for assignment expressions.
---
 .../StaticAnalyzer/Core/BugReporterVisitors.cpp|  3 +++
 clang/test/Analysis/gh-issue-89185.c   | 14 +++---
 2 files changed, 10 insertions(+), 7 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 984755fa7e502..487a3bd16b674 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -113,6 +113,9 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
   if (const Expr *Inner = peelOffPointerArithmetic(B)) {
 E = Inner;
+  } else if (B->isAssignmentOp()) {
+// Follow LHS of assignments: '*p = 404' -> 'p'.
+E = B->getLHS();
   } else {
 // Probably more arithmetic can be pattern-matched here,
 // but for now give up.
diff --git a/clang/test/Analysis/gh-issue-89185.c 
b/clang/test/Analysis/gh-issue-89185.c
index 27456e7efe885..49526d2daa866 100644
--- a/clang/test/Analysis/gh-issue-89185.c
+++ b/clang/test/Analysis/gh-issue-89185.c
@@ -1,13 +1,13 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -verify 
%s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-analyzer-output text -verify %s 
 
-void clang_analyzer_dump(char);
-void clang_analyzer_dump_ptr(char*);
+void clang_analyzer_warnIfReached(void);
 
 // https://github.com/llvm/llvm-project/issues/89185
 void binding_to_label_loc() {
-  char *b = 

[clang] [clang][analyzer] Check for label location bindings in `DereferenceChecker` (PR #91119)

2024-05-13 Thread Balazs Benics via cfe-commits

steakhal wrote:

This one looks good to me. I wanna hear your opinion @NagyDonat 

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


[clang] [clang-format][NFC] Move LeftRightQualifierAlignmentFixer::is...() (PR #91930)

2024-05-13 Thread Owen Pan via cfe-commits

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

Move static member functions LeftRightQualifierAlignmentFixer::is...() out the 
class so that #91712 can reland.

>From 6d346a4ec253110288a806fabde093678228184b Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Mon, 13 May 2024 00:07:50 -0700
Subject: [PATCH] [clang-format][NFC] Move
 LeftRightQualifierAlignmentFixer::is...()

Move static member functions LeftRightQualifierAlignmentFixer::is...() out
the class so that #91712 can reland.
---
 clang/lib/Format/QualifierAlignmentFixer.cpp  | 11 +--
 clang/lib/Format/QualifierAlignmentFixer.h| 19 ++--
 clang/unittests/Format/QualifierFixerTest.cpp | 98 +++
 3 files changed, 52 insertions(+), 76 deletions(-)

diff --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index c263530456727..36d0639041c6c 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -614,22 +614,21 @@ void prepareLeftRightOrderingForQualifierAlignmentFixer(
   }
 }
 
-bool LeftRightQualifierAlignmentFixer::isQualifierOrType(const FormatToken 
*Tok,
- bool IsCpp) {
+bool isQualifierOrType(const FormatToken *Tok, bool IsCpp) {
   return Tok &&
  (Tok->isTypeName(IsCpp) || Tok->is(tok::kw_auto) || isQualifier(Tok));
 }
 
-bool LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-const FormatToken *Tok, const std::vector &Qualifiers,
-bool IsCpp) {
+bool isConfiguredQualifierOrType(const FormatToken *Tok,
+ const std::vector &Qualifiers,
+ bool IsCpp) {
   return Tok && (Tok->isTypeName(IsCpp) || Tok->is(tok::kw_auto) ||
  isConfiguredQualifier(Tok, Qualifiers));
 }
 
 // If a token is an identifier and it's upper case, it could
 // be a macro and hence we need to be able to ignore it.
-bool LeftRightQualifierAlignmentFixer::isPossibleMacro(const FormatToken *Tok) 
{
+bool isPossibleMacro(const FormatToken *Tok) {
   if (!Tok)
 return false;
   if (Tok->isNot(tok::identifier))
diff --git a/clang/lib/Format/QualifierAlignmentFixer.h 
b/clang/lib/Format/QualifierAlignmentFixer.h
index e1cc27e62b13a..e31d525da1640 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.h
+++ b/clang/lib/Format/QualifierAlignmentFixer.h
@@ -32,6 +32,15 @@ void prepareLeftRightOrderingForQualifierAlignmentFixer(
 std::vector &RightOrder,
 std::vector &Qualifiers);
 
+// Is the Token a simple or qualifier type
+bool isQualifierOrType(const FormatToken *Tok, bool IsCpp = true);
+bool isConfiguredQualifierOrType(const FormatToken *Tok,
+ const std::vector &Qualifiers,
+ bool IsCpp = true);
+
+// Is the Token likely a Macro
+bool isPossibleMacro(const FormatToken *Tok);
+
 class LeftRightQualifierAlignmentFixer : public TokenAnalyzer {
   std::string Qualifier;
   bool RightAlign;
@@ -69,16 +78,6 @@ class LeftRightQualifierAlignmentFixer : public 
TokenAnalyzer {
  const FormatToken *Tok,
  const std::string &Qualifier,
  tok::TokenKind QualifierType);
-
-  // Is the Token a simple or qualifier type
-  static bool isQualifierOrType(const FormatToken *Tok, bool IsCpp = true);
-  static bool
-  isConfiguredQualifierOrType(const FormatToken *Tok,
-  const std::vector &Qualifiers,
-  bool IsCpp = true);
-
-  // Is the Token likely a Macro
-  static bool isPossibleMacro(const FormatToken *Tok);
 };
 
 } // end namespace format
diff --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index 792d8f3c3a982..1e997bb06b867 100644
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -1059,66 +1059,44 @@ TEST_F(QualifierFixerTest, IsQualifierType) {
   "const static inline auto restrict int double long constexpr friend");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
 
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[0], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[1], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[2], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[3], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[4], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[5], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[

[clang] [clang-format][NFC] Move LeftRightQualifierAlignmentFixer::is...() (PR #91930)

2024-05-13 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Move static member functions LeftRightQualifierAlignmentFixer::is...() out the 
class so that #91712 can reland.

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


3 Files Affected:

- (modified) clang/lib/Format/QualifierAlignmentFixer.cpp (+5-6) 
- (modified) clang/lib/Format/QualifierAlignmentFixer.h (+9-10) 
- (modified) clang/unittests/Format/QualifierFixerTest.cpp (+38-60) 


``diff
diff --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index c263530456727..36d0639041c6c 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -614,22 +614,21 @@ void prepareLeftRightOrderingForQualifierAlignmentFixer(
   }
 }
 
-bool LeftRightQualifierAlignmentFixer::isQualifierOrType(const FormatToken 
*Tok,
- bool IsCpp) {
+bool isQualifierOrType(const FormatToken *Tok, bool IsCpp) {
   return Tok &&
  (Tok->isTypeName(IsCpp) || Tok->is(tok::kw_auto) || isQualifier(Tok));
 }
 
-bool LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-const FormatToken *Tok, const std::vector &Qualifiers,
-bool IsCpp) {
+bool isConfiguredQualifierOrType(const FormatToken *Tok,
+ const std::vector &Qualifiers,
+ bool IsCpp) {
   return Tok && (Tok->isTypeName(IsCpp) || Tok->is(tok::kw_auto) ||
  isConfiguredQualifier(Tok, Qualifiers));
 }
 
 // If a token is an identifier and it's upper case, it could
 // be a macro and hence we need to be able to ignore it.
-bool LeftRightQualifierAlignmentFixer::isPossibleMacro(const FormatToken *Tok) 
{
+bool isPossibleMacro(const FormatToken *Tok) {
   if (!Tok)
 return false;
   if (Tok->isNot(tok::identifier))
diff --git a/clang/lib/Format/QualifierAlignmentFixer.h 
b/clang/lib/Format/QualifierAlignmentFixer.h
index e1cc27e62b13a..e31d525da1640 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.h
+++ b/clang/lib/Format/QualifierAlignmentFixer.h
@@ -32,6 +32,15 @@ void prepareLeftRightOrderingForQualifierAlignmentFixer(
 std::vector &RightOrder,
 std::vector &Qualifiers);
 
+// Is the Token a simple or qualifier type
+bool isQualifierOrType(const FormatToken *Tok, bool IsCpp = true);
+bool isConfiguredQualifierOrType(const FormatToken *Tok,
+ const std::vector &Qualifiers,
+ bool IsCpp = true);
+
+// Is the Token likely a Macro
+bool isPossibleMacro(const FormatToken *Tok);
+
 class LeftRightQualifierAlignmentFixer : public TokenAnalyzer {
   std::string Qualifier;
   bool RightAlign;
@@ -69,16 +78,6 @@ class LeftRightQualifierAlignmentFixer : public 
TokenAnalyzer {
  const FormatToken *Tok,
  const std::string &Qualifier,
  tok::TokenKind QualifierType);
-
-  // Is the Token a simple or qualifier type
-  static bool isQualifierOrType(const FormatToken *Tok, bool IsCpp = true);
-  static bool
-  isConfiguredQualifierOrType(const FormatToken *Tok,
-  const std::vector &Qualifiers,
-  bool IsCpp = true);
-
-  // Is the Token likely a Macro
-  static bool isPossibleMacro(const FormatToken *Tok);
 };
 
 } // end namespace format
diff --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index 792d8f3c3a982..1e997bb06b867 100644
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -1059,66 +1059,44 @@ TEST_F(QualifierFixerTest, IsQualifierType) {
   "const static inline auto restrict int double long constexpr friend");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
 
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[0], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[1], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[2], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[3], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[4], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[5], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[6], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[7], ConfiguredTokens));
-  EXPECT_TRUE(LeftRightQualifierAlignmentFixer::isConfiguredQualifierOrType(
-  Tokens[8], ConfiguredTokens)

[clang] [clang][analyzer] Check for label location bindings in `DereferenceChecker` (PR #91119)

2024-05-13 Thread Balazs Benics via cfe-commits

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


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


[clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-13 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/90961

>From 0bdb18c0ffc37b38e81487b45e0e00e4480473aa Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 3 May 2024 11:04:21 +0200
Subject: [PATCH 1/2] [clang] CTAD alias: refine the transformation for the
 require-clause expr.

In the clang AST, constraint nodes are deliberately not instantiated unless they
are actively being evaluated. Consequently, occurrences of template parameters
in the require-clause expression have a subtle "depth" difference compared to
normal occurrences in place contexts, such as function parameters. When
transforming the require-clause, we must take this distinction into account.

The existing implementation overlooks this consideration. This patch is
to rewrite the implementation of the require-clause transformation to
address this issue.
---
 clang/lib/Sema/SemaTemplate.cpp  | 147 +--
 clang/test/AST/ast-dump-ctad-alias.cpp   |  40 +
 clang/test/SemaCXX/cxx20-ctad-type-alias.cpp |  68 +
 3 files changed, 242 insertions(+), 13 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-ctad-alias.cpp

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 0e7bd8dd89573..88becbdba6449 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2758,31 +2758,151 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateParameterDepth(NamedDecl *TemplateParam) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return NTTP->getDepth();
+  llvm_unreachable("Unhandled template parameter types");
+}
+
 NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
   NamedDecl *TemplateParam,
   MultiLevelTemplateArgumentList &Args,
-  unsigned NewIndex) {
+  unsigned NewIndex, unsigned NewDepth) {
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
   NewIndex);
   if (auto *TTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
-  TTP->getDepth());
+  NewDepth);
   if (auto *NTTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
-  NTTP->getDepth());
+  NewDepth);
   llvm_unreachable("Unhandled template parameter types");
 }
 
-Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
- llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
+// Transform the require-clause of F if any.
+// The return result is expected to be the require-clause for the synthesized
+// alias deduction guide.
+Expr *transformRequireClause(
+Sema &SemaRef, FunctionTemplateDecl *F,
+TypeAliasTemplateDecl *AliasTemplate,
+ArrayRef DeduceResults) {
+  Expr *RC = F->getTemplateParameters()->getRequiresClause();
   if (!RC)
 return nullptr;
+
+  auto &Context = SemaRef.Context;
+  LocalInstantiationScope Scope(SemaRef);
+
+  // In the clang AST, constraint nodes are deliberately not instantiated 
unless
+  // they are actively being evaluated. Consequently, occurrences of template
+  // parameters in the require-clause expression have a subtle "depth"
+  // difference compared to normal occurrences in places, such as function
+  // parameters. When transforming the require-clause, we must take this
+  // distinction into account:
+  //
+  //   1) In the transformed require-clause, occurrences of template parameters
+  //   must use the "uninstantiated" depth;
+  //   2) When substituting on the require-clause expr of the underlying
+  //   deduction guide, we must use the entire set of template argument lists;
+  //
+  // It's important to note that we're performing this transformation on an
+  // *instantiated* AliasTemplate.
+
+  // For 1), if the alias template is nested within a class template, we
+  // calcualte the 'uninstantiated' depth by adding the substitution level 
back.
+  unsigned AdjustDepth = 0;
+  if (auto *PrimaryTemplate = 
AliasTemplate->getInstantiatedFromMemberTemplate())
+AdjustDepth = PrimaryTemplate->getTemplateDepth();
+
+  // We rebuild all template parameters with the uninstantiated depth, and
+  // build template arguments refer to them.
+  SmallVector AdjustedAliasTemplateArgs;
+
+  for (auto *TP : *AliasTemplate->getTemplateParameters()) {
+// Reb

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

2024-05-13 Thread Chuanqi Xu via cfe-commits

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

>From 8ec79e4a7fdf0d75030e81d713ac9fe629ee97eb Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Fri, 10 May 2024 15:36:31 +0800
Subject: [PATCH] [serialization] no transitive decl change

---
 clang/include/clang/AST/DeclBase.h|  17 +-
 clang/include/clang/AST/DeclID.h  |  23 ++-
 .../include/clang/Serialization/ASTBitCodes.h |   6 +
 clang/include/clang/Serialization/ASTReader.h |  36 ++--
 .../include/clang/Serialization/ModuleFile.h  |  18 +-
 .../clang/Serialization/ModuleManager.h   |   2 +-
 clang/lib/AST/DeclBase.cpp|  34 +++-
 clang/lib/Serialization/ASTReader.cpp | 159 ++
 clang/lib/Serialization/ASTReaderDecl.cpp |  12 +-
 clang/lib/Serialization/ASTWriter.cpp |   7 +-
 clang/lib/Serialization/ModuleFile.cpp|   3 +-
 .../Modules/no-transitive-decls-change.cppm   | 112 
 12 files changed, 282 insertions(+), 147 deletions(-)
 create mode 100644 clang/test/Modules/no-transitive-decls-change.cppm

diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index e43e812cd9455..4bdf27aa99405 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -701,10 +701,7 @@ class alignas(8) Decl {
 
   /// Set the owning module ID.  This may only be called for
   /// deserialized Decls.
-  void setOwningModuleID(unsigned ID) {
-assert(isFromASTFile() && "Only works on a deserialized declaration");
-*((unsigned*)this - 2) = ID;
-  }
+  void setOwningModuleID(unsigned ID);
 
 public:
   /// Determine the availability of the given declaration.
@@ -777,19 +774,11 @@ class alignas(8) Decl {
 
   /// Retrieve the global declaration ID associated with this
   /// declaration, which specifies where this Decl was loaded from.
-  GlobalDeclID getGlobalID() const {
-if (isFromASTFile())
-  return (*((const GlobalDeclID *)this - 1));
-return GlobalDeclID();
-  }
+  GlobalDeclID getGlobalID() const;
 
   /// Retrieve the global ID of the module that owns this particular
   /// declaration.
-  unsigned getOwningModuleID() const {
-if (isFromASTFile())
-  return *((const unsigned*)this - 2);
-return 0;
-  }
+  unsigned getOwningModuleID() const;
 
 private:
   Module *getOwningModuleSlow() const;
diff --git a/clang/include/clang/AST/DeclID.h b/clang/include/clang/AST/DeclID.h
index 614ba06b63860..a6e4b31f3a6fb 100644
--- a/clang/include/clang/AST/DeclID.h
+++ b/clang/include/clang/AST/DeclID.h
@@ -19,6 +19,8 @@
 #include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/ADT/iterator.h"
 
+#include 
+
 namespace clang {
 
 /// Predefined declaration IDs.
@@ -107,12 +109,16 @@ class DeclIDBase {
   ///
   /// DeclID should only be used directly in serialization. All other users
   /// should use LocalDeclID or GlobalDeclID.
-  using DeclID = uint32_t;
+  using DeclID = uint64_t;
 
 protected:
   DeclIDBase() : ID(PREDEF_DECL_NULL_ID) {}
   explicit DeclIDBase(DeclID ID) : ID(ID) {}
 
+  explicit DeclIDBase(unsigned LocalID, unsigned ModuleFileIndex) {
+ID = (DeclID)LocalID | ((DeclID)ModuleFileIndex << 32);
+  }
+
 public:
   DeclID get() const { return ID; }
 
@@ -124,6 +130,15 @@ class DeclIDBase {
 
   bool isInvalid() const { return ID == PREDEF_DECL_NULL_ID; }
 
+  unsigned getModuleFileIndex() const { return ID >> 32; }
+
+  unsigned getLocalDeclIndex() const {
+// Implement it directly instead of calling `llvm::maskTrailingOnes` since
+// we don't want `MathExtras.h` to be inclued here.
+const unsigned Bits = CHAR_BIT * sizeof(DeclID);
+return ID & (DeclID(-1) >> (Bits - 32));
+  }
+
   friend bool operator==(const DeclIDBase &LHS, const DeclIDBase &RHS) {
 return LHS.ID == RHS.ID;
   }
@@ -156,6 +171,9 @@ class LocalDeclID : public DeclIDBase {
   LocalDeclID(PredefinedDeclIDs ID) : Base(ID) {}
   explicit LocalDeclID(DeclID ID) : Base(ID) {}
 
+  explicit LocalDeclID(unsigned LocalID, unsigned ModuleFileIndex)
+  : Base(LocalID, ModuleFileIndex) {}
+
   LocalDeclID &operator++() {
 ++ID;
 return *this;
@@ -175,6 +193,9 @@ class GlobalDeclID : public DeclIDBase {
   GlobalDeclID() : Base() {}
   explicit GlobalDeclID(DeclID ID) : Base(ID) {}
 
+  explicit GlobalDeclID(unsigned LocalID, unsigned ModuleFileIndex)
+  : Base(LocalID, ModuleFileIndex) {}
+
   // For DeclIDIterator to be able to convert a GlobalDeclID
   // to a LocalDeclID.
   explicit operator LocalDeclID() const { return LocalDeclID(this->ID); }
diff --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index d3538e43d3d78..772452e3afc55 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -255,6 +255,12 @@ class DeclOffset {
   }
 };
 
+// The unaligned decl ID used in the Blobs of bistreams.
+using unalighed_decl_id_t =
+

[clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-13 Thread Haojian Wu via cfe-commits

hokein wrote:

I'm merging it now (happy to address any post-comments).

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


[clang] d182877 - [clang] CTAD alias: fix the transformation for the require-clause expr (#90961)

2024-05-13 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-05-13T09:33:35+02:00
New Revision: d182877ba3f5ad93e061f68a9ecce38cb8cec418

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

LOG: [clang] CTAD alias: fix the transformation for the require-clause expr 
(#90961)

In the clang AST, constraint nodes are deliberately not instantiated
unless they are actively being evaluated. Consequently, occurrences of
template parameters in the require-clause expression have a subtle
"depth" difference compared to normal occurrences in places, such as
function parameters. When transforming the require-clause, we must take
this distinction into account.

The existing implementation overlooks this consideration. This patch is
to rewrite the implementation of the require-clause transformation to
address this issue.

Fixes #90177

Added: 
clang/test/AST/ast-dump-ctad-alias.cpp

Modified: 
clang/lib/Sema/SemaTemplate.cpp
clang/test/SemaCXX/cxx20-ctad-type-alias.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 0e7bd8dd89573..bae00c6292703 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2758,31 +2758,149 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateParameterDepth(NamedDecl *TemplateParam) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return NTTP->getDepth();
+  llvm_unreachable("Unhandled template parameter types");
+}
+
 NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
   NamedDecl *TemplateParam,
   MultiLevelTemplateArgumentList &Args,
-  unsigned NewIndex) {
+  unsigned NewIndex, unsigned NewDepth) {
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
   NewIndex);
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
-  TTP->getDepth());
+return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex, NewDepth);
   if (auto *NTTP = dyn_cast(TemplateParam))
-return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
-  NTTP->getDepth());
+return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex, NewDepth);
   llvm_unreachable("Unhandled template parameter types");
 }
 
-Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
- llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
+// Transform the require-clause of F if any.
+// The return result is expected to be the require-clause for the synthesized
+// alias deduction guide.
+Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *F,
+ TypeAliasTemplateDecl *AliasTemplate,
+ ArrayRef DeduceResults) {
+  Expr *RC = F->getTemplateParameters()->getRequiresClause();
   if (!RC)
 return nullptr;
+
+  auto &Context = SemaRef.Context;
+  LocalInstantiationScope Scope(SemaRef);
+
+  // In the clang AST, constraint nodes are deliberately not instantiated 
unless
+  // they are actively being evaluated. Consequently, occurrences of template
+  // parameters in the require-clause expression have a subtle "depth"
+  // 
diff erence compared to normal occurrences in places, such as function
+  // parameters. When transforming the require-clause, we must take this
+  // distinction into account:
+  //
+  //   1) In the transformed require-clause, occurrences of template parameters
+  //   must use the "uninstantiated" depth;
+  //   2) When substituting on the require-clause expr of the underlying
+  //   deduction guide, we must use the entire set of template argument lists;
+  //
+  // It's important to note that we're performing this transformation on an
+  // *instantiated* AliasTemplate.
+
+  // For 1), if the alias template is nested within a class template, we
+  // calcualte the 'uninstantiated' depth by adding the substitution level 
back.
+  unsigned AdjustDepth = 0;
+  if (auto *PrimaryTemplate =
+  AliasTemplate->getInstantiatedFromMemberTemplate())
+AdjustDepth = PrimaryTemplate->getTemplateDepth();
+
+  // We rebuild all template parameters with the uninstantiated depth, and
+  // build templa

[clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-13 Thread Haojian Wu via cfe-commits

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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-13 Thread Pierre van Houtryve via cfe-commits


@@ -18365,6 +18366,28 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
   return nullptr;
 }
 
+void CodeGenFunction::AddAMDGCNFenceAddressSpaceMMRA(llvm::Instruction *Inst,
+ const CallExpr *E) {
+  constexpr const char *Tag = "amdgpu-as";

Pierre-vh wrote:

I think it's just more readable this way, but I have no strong preference 
either.
I'd say let's keep it this way, it can very easily be renamed later if we want 
to.

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


[clang] [Clang] Added check for unexpanded pack in attribute [[assume]] (PR #91893)

2024-05-13 Thread via cfe-commits

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

LGTM!
Thanks for working on this

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


[clang] [analyzer] Move `CTUPhase1InliningMode` option to String analyzer options category (PR #91932)

2024-05-13 Thread via cfe-commits

https://github.com/shenjunjiekoda created 
https://github.com/llvm/llvm-project/pull/91932

The `CTUPhase1InliningMode`option was originally placed under Unsigned analyzer 
options, but its value is a string. 

This move aligns the option with its actual type.

>From 4d7485bf955d04eb83960b7b590750a8738a2e54 Mon Sep 17 00:00:00 2001
From: Shenjunjie 
Date: Mon, 13 May 2024 03:54:21 -0400
Subject: [PATCH] [analyzer] Move `CTUPhase1InliningMode` option to String
 analyzer options

---
 .../StaticAnalyzer/Core/AnalyzerOptions.def   | 32 +--
 1 file changed, 16 insertions(+), 16 deletions(-)

diff --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index 2fc825c2af9c3..f008c9c581d95 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -413,22 +413,6 @@ ANALYZER_OPTION(
 "analysis is too low, it is meaningful to provide a minimum value that "
 "serves as an upper bound instead.", 1)
 
-ANALYZER_OPTION(
-StringRef, CTUPhase1InliningMode, "ctu-phase1-inlining",
-"Controls which functions will be inlined during the first phase of the 
ctu "
-"analysis. "
-"If the value is set to 'all' then all foreign functions are inlinied "
-"immediately during the first phase, thus rendering the second phase a 
noop. "
-"The 'ctu-max-nodes-*' budge has no effect in this case. "
-"If the value is 'small' then only functions with a linear CFG and with a "
-"limited number of statements would be inlined during the first phase. The 
"
-"long and/or nontrivial functions are handled in the second phase and are "
-"controlled by the 'ctu-max-nodes-*' budge. "
-"The value 'none' means that all foreign functions are inlined only in the 
"
-"second phase, 'ctu-max-nodes-*' budge limits the second phase. "
-"Value: \"none\", \"small\", \"all\".",
-"small")
-
 ANALYZER_OPTION(
 unsigned, RegionStoreSmallStructLimit, "region-store-small-struct-limit",
 "The largest number of fields a struct can have and still be considered "
@@ -478,6 +462,22 @@ ANALYZER_OPTION(
 "where to look for those alternative implementations (called models).",
 "")
 
+ANALYZER_OPTION(
+StringRef, CTUPhase1InliningMode, "ctu-phase1-inlining",
+"Controls which functions will be inlined during the first phase of the 
ctu "
+"analysis. "
+"If the value is set to 'all' then all foreign functions are inlinied "
+"immediately during the first phase, thus rendering the second phase a 
noop. "
+"The 'ctu-max-nodes-*' budge has no effect in this case. "
+"If the value is 'small' then only functions with a linear CFG and with a "
+"limited number of statements would be inlined during the first phase. The 
"
+"long and/or nontrivial functions are handled in the second phase and are "
+"controlled by the 'ctu-max-nodes-*' budge. "
+"The value 'none' means that all foreign functions are inlined only in the 
"
+"second phase, 'ctu-max-nodes-*' budge limits the second phase. "
+"Value: \"none\", \"small\", \"all\".",
+"small")
+
 ANALYZER_OPTION(
 StringRef, CXXMemberInliningMode, "c++-inlining",
 "Controls which C++ member functions will be considered for inlining. "

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


[clang] [analyzer] Move `CTUPhase1InliningMode` option to String analyzer options category (PR #91932)

2024-05-13 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: JOSTAR (shenjunjiekoda)


Changes

The `CTUPhase1InliningMode`option was originally placed under Unsigned analyzer 
options, but its value is a string. 

This move aligns the option with its actual type.

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


1 Files Affected:

- (modified) clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
(+16-16) 


``diff
diff --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index 2fc825c2af9c3..f008c9c581d95 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -413,22 +413,6 @@ ANALYZER_OPTION(
 "analysis is too low, it is meaningful to provide a minimum value that "
 "serves as an upper bound instead.", 1)
 
-ANALYZER_OPTION(
-StringRef, CTUPhase1InliningMode, "ctu-phase1-inlining",
-"Controls which functions will be inlined during the first phase of the 
ctu "
-"analysis. "
-"If the value is set to 'all' then all foreign functions are inlinied "
-"immediately during the first phase, thus rendering the second phase a 
noop. "
-"The 'ctu-max-nodes-*' budge has no effect in this case. "
-"If the value is 'small' then only functions with a linear CFG and with a "
-"limited number of statements would be inlined during the first phase. The 
"
-"long and/or nontrivial functions are handled in the second phase and are "
-"controlled by the 'ctu-max-nodes-*' budge. "
-"The value 'none' means that all foreign functions are inlined only in the 
"
-"second phase, 'ctu-max-nodes-*' budge limits the second phase. "
-"Value: \"none\", \"small\", \"all\".",
-"small")
-
 ANALYZER_OPTION(
 unsigned, RegionStoreSmallStructLimit, "region-store-small-struct-limit",
 "The largest number of fields a struct can have and still be considered "
@@ -478,6 +462,22 @@ ANALYZER_OPTION(
 "where to look for those alternative implementations (called models).",
 "")
 
+ANALYZER_OPTION(
+StringRef, CTUPhase1InliningMode, "ctu-phase1-inlining",
+"Controls which functions will be inlined during the first phase of the 
ctu "
+"analysis. "
+"If the value is set to 'all' then all foreign functions are inlinied "
+"immediately during the first phase, thus rendering the second phase a 
noop. "
+"The 'ctu-max-nodes-*' budge has no effect in this case. "
+"If the value is 'small' then only functions with a linear CFG and with a "
+"limited number of statements would be inlined during the first phase. The 
"
+"long and/or nontrivial functions are handled in the second phase and are "
+"controlled by the 'ctu-max-nodes-*' budge. "
+"The value 'none' means that all foreign functions are inlined only in the 
"
+"second phase, 'ctu-max-nodes-*' budge limits the second phase. "
+"Value: \"none\", \"small\", \"all\".",
+"small")
+
 ANALYZER_OPTION(
 StringRef, CXXMemberInliningMode, "c++-inlining",
 "Controls which C++ member functions will be considered for inlining. "

``




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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-13 Thread Pierre van Houtryve via cfe-commits


@@ -4408,6 +4409,42 @@ Target-Specific Extensions
 
 Clang supports some language features conditionally on some targets.
 
+AMDGPU Language Extensions
+--
+
+__builtin_amdgcn_fence
+^^
+
+``__builtin_amdgcn_fence`` emits a fence.
+
+* ``unsigned`` atomic ordering, e.g. ``__ATOMIC_ACQUIRE``
+* ``const char *`` synchronization scope, e.g. ``workgroup``
+* Zero or more ``const char *`` address spaces names.
+
+The address spaces arguments must be string literals with known values, such 
as:
+
+* ``"local"``
+* ``"global"``
+* ``"image"``
+
+If one or more address space name are provided, the code generator will attempt
+to emit potentially faster instructions that only fence those address spaces.
+Emitting such instructions may not always be possible and the compiler is free
+to fence more aggressively.
+
+If no address spaces names are provided, all address spaces are fenced.
+
+.. code-block:: c++
+
+  // Fence all address spaces.
+  __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");
+  __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
+
+  // Fence only requested address spaces.
+  __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local")

Pierre-vh wrote:

I wasusing the OpenCL terminology: 
https://registry.khronos.org/OpenCL/sdk/3.0/docs/man/html/atomic_work_item_fence.html

> flags must be set to CLK_GLOBAL_MEM_FENCE, CLK_LOCAL_MEM_FENCE, 
> CLK_IMAGE_MEM_FENCE 

Thinking about it, maybe it's better to use names consistent with our AMDGPUAS 
definitions, so image would just be "private" but local/global stay. What do 
you think?

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


[clang] [clang-tools-extra] [flang] [lld] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread via cfe-commits


@@ -45,10 +45,10 @@
 # RUN: ld.lld -Ttext 0x201000 %t.o -o %t4
 # RUN: llvm-readelf -S -l %t4 | FileCheck %s --check-prefix=USER3
 # USER3: .text   PROGBITS 00201000 001000 01
-# USER3-NEX: .rodata PROGBITS 00202000 002000 08
-# USER3-NEX: .aw PROGBITS 00203000 003000 08
-# USER3-NEX: .data   PROGBITS 00203008 003008 08
-# USER3-NEX: .bssNOBITS   00203010 003010 08
+# USER3-NEXT: .rodata PROGBITS 00202000 002000 08

klensy wrote:

Oh, found your commit 
https://github.com/llvm/llvm-project/commit/b1f04d57f5818914d7db506985e2932f217844bd.

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


[clang] [clang-format][NFC] Move LeftRightQualifierAlignmentFixer::is...() (PR #91930)

2024-05-13 Thread Owen Pan via cfe-commits

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


[clang] [Clang] Fix dependency computation for pack indexing expression (PR #91933)

2024-05-13 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/91933

Given `foo...[idx]` if idx is value dependent, the expression is type dependent.

Fixes #91885
Fixes #91884

>From 066e23de6ef0b3bb44513c1d239981e7d0f4453e Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 13 May 2024 10:00:19 +0200
Subject: [PATCH] [Clang] Fix dependency computation for pack indexing
 expression

Given `foo...[idx]` if idx is value dependent, the expression
is type dependent.

Fixes #91885
Fixes #91884
---
 clang/lib/AST/ComputeDependence.cpp|  3 +++
 clang/test/SemaCXX/cxx2c-pack-indexing.cpp | 14 ++
 2 files changed, 17 insertions(+)

diff --git a/clang/lib/AST/ComputeDependence.cpp 
b/clang/lib/AST/ComputeDependence.cpp
index bad8e75b2f878..ee56c50d76512 100644
--- a/clang/lib/AST/ComputeDependence.cpp
+++ b/clang/lib/AST/ComputeDependence.cpp
@@ -376,6 +376,9 @@ ExprDependence clang::computeDependence(PackExpansionExpr 
*E) {
 
 ExprDependence clang::computeDependence(PackIndexingExpr *E) {
   ExprDependence D = E->getIndexExpr()->getDependence();
+  if (D & ExprDependence::Value)
+D |= ExprDependence::TypeInstantiation;
+
   ArrayRef Exprs = E->getExpressions();
   if (Exprs.empty())
 D |= (E->getPackIdExpression()->getDependence() |
diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp 
b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
index a3e5a0931491b..764f6163710bd 100644
--- a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
+++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
@@ -194,3 +194,17 @@ void h() {
   // expected-note-re@-2 {{function template specialization '{{.*}}' requested 
here}}
 }
 }
+
+namespace GH91885 {
+
+void test(auto...args){
+[&](){
+using R = decltype( args...[idx] ) ;
+}.template operator()<0>();
+}
+
+void f( ) {
+test(1);
+}
+
+}

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


[clang] [Clang] Fix dependency computation for pack indexing expression (PR #91933)

2024-05-13 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

Given `foo...[idx]` if idx is value dependent, the expression is type dependent.

Fixes #91885
Fixes #91884

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


2 Files Affected:

- (modified) clang/lib/AST/ComputeDependence.cpp (+3) 
- (modified) clang/test/SemaCXX/cxx2c-pack-indexing.cpp (+14) 


``diff
diff --git a/clang/lib/AST/ComputeDependence.cpp 
b/clang/lib/AST/ComputeDependence.cpp
index bad8e75b2f878..ee56c50d76512 100644
--- a/clang/lib/AST/ComputeDependence.cpp
+++ b/clang/lib/AST/ComputeDependence.cpp
@@ -376,6 +376,9 @@ ExprDependence clang::computeDependence(PackExpansionExpr 
*E) {
 
 ExprDependence clang::computeDependence(PackIndexingExpr *E) {
   ExprDependence D = E->getIndexExpr()->getDependence();
+  if (D & ExprDependence::Value)
+D |= ExprDependence::TypeInstantiation;
+
   ArrayRef Exprs = E->getExpressions();
   if (Exprs.empty())
 D |= (E->getPackIdExpression()->getDependence() |
diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp 
b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
index a3e5a0931491b..764f6163710bd 100644
--- a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
+++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
@@ -194,3 +194,17 @@ void h() {
   // expected-note-re@-2 {{function template specialization '{{.*}}' requested 
here}}
 }
 }
+
+namespace GH91885 {
+
+void test(auto...args){
+[&](){
+using R = decltype( args...[idx] ) ;
+}.template operator()<0>();
+}
+
+void f( ) {
+test(1);
+}
+
+}

``




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


[clang] [clang-tools-extra] [compiler-rt] [lldb] [llvm] [mlir] [openmp] [polly] fix(python): fix comparison to None (PR #91857)

2024-05-13 Thread David Spickett via cfe-commits

DavidSpickett wrote:

LLVM uses a GitHub setting where the PR is squashed, and the commit message is 
taken from the PR description rather than the commits themselves. So all you 
have to do here is copy the commit message you updated into the PR's 
description.

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


[clang] [clang-tools-extra] [compiler-rt] [lldb] [llvm] [mlir] [openmp] [polly] fix(python): fix comparison to None (PR #91857)

2024-05-13 Thread David Spickett via cfe-commits

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

LLDB changes look good to me.

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


[clang] [clang] Allow pack expansions when partial ordering against template template parameters (PR #91833)

2024-05-13 Thread via cfe-commits

cor3ntin wrote:

I have confirmed that with this change, `stdexec` compiles successfully, 
addressing both #89807 and #91787

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


[clang] d4f5cf2 - [Clang] Added check for unexpanded pack in attribute [[assume]] (#91893)

2024-05-13 Thread via cfe-commits

Author: Azmat Yusuf
Date: 2024-05-13T10:31:10+02:00
New Revision: d4f5cf267936a082196b0c22fe45c730b24b9fe0

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

LOG: [Clang] Added check for unexpanded pack in attribute [[assume]] (#91893)

Added a check for unexpanded parameter pack in attribute [[assume]].
Tested it with expected-error statements from clang fronted. 

This fixes #91232.

Added: 


Modified: 
clang/lib/Sema/SemaStmtAttr.cpp
clang/test/SemaCXX/cxx23-assume.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp
index 1c84830b6ddd2..36f8ecadcfab7 100644
--- a/clang/lib/Sema/SemaStmtAttr.cpp
+++ b/clang/lib/Sema/SemaStmtAttr.cpp
@@ -670,6 +670,11 @@ ExprResult Sema::ActOnCXXAssumeAttr(Stmt *St, const 
ParsedAttr &A,
   }
 
   auto *Assumption = A.getArgAsExpr(0);
+
+  if (DiagnoseUnexpandedParameterPack(Assumption)) {
+return ExprError();
+  }
+
   if (Assumption->getDependence() == ExprDependence::None) {
 ExprResult Res = BuildCXXAssumeExpr(Assumption, A.getAttrName(), Range);
 if (Res.isInvalid())

diff  --git a/clang/test/SemaCXX/cxx23-assume.cpp 
b/clang/test/SemaCXX/cxx23-assume.cpp
index 8676970de14f6..e67d72ae0a995 100644
--- a/clang/test/SemaCXX/cxx23-assume.cpp
+++ b/clang/test/SemaCXX/cxx23-assume.cpp
@@ -138,3 +138,8 @@ constexpr int foo() {
 }
 
 static_assert(foo() == 0);
+
+template 
+void f() {
+[[assume(val)]]; // expected-error {{expression contains unexpanded 
parameter pack}}
+}



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


[clang] [Clang] Added check for unexpanded pack in attribute [[assume]] (PR #91893)

2024-05-13 Thread via cfe-commits

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


[clang] [Clang] Added check for unexpanded pack in attribute [[assume]] (PR #91893)

2024-05-13 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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


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


[clang] [Clang] Fix dependency computation for pack indexing expression (PR #91933)

2024-05-13 Thread via cfe-commits

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

>From 4cadff527e02ae03aa5850ee713fe57aee663a52 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 13 May 2024 10:00:19 +0200
Subject: [PATCH] [Clang] Fix dependency computation for pack indexing
 expression

Given `foo...[idx]` if idx is value dependent, the expression
is type dependent.

Fixes #91885
Fixes #91884
---
 clang/lib/AST/ComputeDependence.cpp|  3 +++
 clang/test/SemaCXX/cxx2c-pack-indexing.cpp | 14 ++
 2 files changed, 17 insertions(+)

diff --git a/clang/lib/AST/ComputeDependence.cpp 
b/clang/lib/AST/ComputeDependence.cpp
index bad8e75b2f878..ee56c50d76512 100644
--- a/clang/lib/AST/ComputeDependence.cpp
+++ b/clang/lib/AST/ComputeDependence.cpp
@@ -376,6 +376,9 @@ ExprDependence clang::computeDependence(PackExpansionExpr 
*E) {
 
 ExprDependence clang::computeDependence(PackIndexingExpr *E) {
   ExprDependence D = E->getIndexExpr()->getDependence();
+  if (D & ExprDependence::Value)
+D |= ExprDependence::TypeInstantiation;
+
   ArrayRef Exprs = E->getExpressions();
   if (Exprs.empty())
 D |= (E->getPackIdExpression()->getDependence() |
diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp 
b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
index a3e5a0931491b..764f6163710bd 100644
--- a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
+++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
@@ -194,3 +194,17 @@ void h() {
   // expected-note-re@-2 {{function template specialization '{{.*}}' requested 
here}}
 }
 }
+
+namespace GH91885 {
+
+void test(auto...args){
+[&](){
+using R = decltype( args...[idx] ) ;
+}.template operator()<0>();
+}
+
+void f( ) {
+test(1);
+}
+
+}

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


[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)

2024-05-13 Thread kadir çetinkaya via cfe-commits


@@ -572,32 +572,43 @@ struct FragmentCompiler {
 #else
 static llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags;
 #endif
-auto Filters = std::make_shared>();
-for (auto &HeaderPattern : F.IgnoreHeader) {
-  // Anchor on the right.
-  std::string AnchoredPattern = "(" + *HeaderPattern + ")$";
-  llvm::Regex CompiledRegex(AnchoredPattern, Flags);
-  std::string RegexError;
-  if (!CompiledRegex.isValid(RegexError)) {
-diag(Warning,
- llvm::formatv("Invalid regular expression '{0}': {1}",
-   *HeaderPattern, RegexError)
- .str(),
- HeaderPattern.Range);
-continue;
+std::shared_ptr> Filters;
+if (!F.IgnoreHeader.empty()) {

kadircet wrote:

config compilation isn't really a hot code path, hence i'd lean towards 
simplicity. up to you though.

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


[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)

2024-05-13 Thread kadir çetinkaya via cfe-commits


@@ -572,32 +572,43 @@ struct FragmentCompiler {
 #else
 static llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags;
 #endif
-auto Filters = std::make_shared>();
-for (auto &HeaderPattern : F.IgnoreHeader) {
-  // Anchor on the right.
-  std::string AnchoredPattern = "(" + *HeaderPattern + ")$";
-  llvm::Regex CompiledRegex(AnchoredPattern, Flags);
-  std::string RegexError;
-  if (!CompiledRegex.isValid(RegexError)) {
-diag(Warning,
- llvm::formatv("Invalid regular expression '{0}': {1}",
-   *HeaderPattern, RegexError)
- .str(),
- HeaderPattern.Range);
-continue;
+std::shared_ptr> Filters;
+if (!F.IgnoreHeader.empty()) {
+  Filters = std::make_shared>();
+  for (auto &HeaderPattern : F.IgnoreHeader) {
+// Anchor on the right.
+std::string AnchoredPattern = "(" + *HeaderPattern + ")$";
+llvm::Regex CompiledRegex(AnchoredPattern, Flags);
+std::string RegexError;
+if (!CompiledRegex.isValid(RegexError)) {
+  diag(Warning,
+   llvm::formatv("Invalid regular expression '{0}': {1}",
+ *HeaderPattern, RegexError)
+   .str(),
+   HeaderPattern.Range);
+  continue;
+}
+Filters->push_back(std::move(CompiledRegex));
   }
-  Filters->push_back(std::move(CompiledRegex));
 }
-if (Filters->empty())
+std::optional AnalyzeSystemHeaders;
+if (F.AnalyzeSystemHeaders.has_value())
+  AnalyzeSystemHeaders = **F.AnalyzeSystemHeaders;

kadircet wrote:

> F.AnalyzeSystemHeaders is a std::optional>

Hence RHS is just a `bool`, so I don't understand why we prefer a bool.

But now that I read the logic again it actually makes sense, not for C++23 
idioms, but because we want to override the config field only if it was 
explicitly set, and inherit from parent config fragment otherwise. Can you add 
a comment about that?

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


[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)

2024-05-13 Thread kadir çetinkaya via cfe-commits


@@ -135,6 +135,21 @@ TEST(IncludeCleaner, GetUnusedHeaders) {
Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
+TEST(IncludeCleaner, SystemUnusedHeaders) {
+  auto TU = TestTU::withCode(R"cpp(
+#include 
+#include 
+SystemClass x;
+  )cpp");
+  TU.AdditionalFiles["system/system_header.h"] = guard("class SystemClass 
{};");
+  TU.AdditionalFiles["system/system_unused.h"] = guard("");
+  TU.ExtraArgs = {"-isystem", testPath("system")};
+  auto AST = TU.build();
+  IncludeCleanerFindings Findings = computeIncludeCleanerFindings(AST, true);

kadircet wrote:

> Isn;t this already covered by the GetUnusedHeaders test?

Yes but that one is a more bulky test that checks for multiple pieces playing 
nicely together. Whereas this one is more "specific" to the code-path you're 
adding.

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


[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)

2024-05-13 Thread kadir çetinkaya via cfe-commits


@@ -135,6 +135,21 @@ TEST(IncludeCleaner, GetUnusedHeaders) {
Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
+TEST(IncludeCleaner, SystemUnusedHeaders) {
+  auto TU = TestTU::withCode(R"cpp(
+#include 
+#include 
+SystemClass x;
+  )cpp");
+  TU.AdditionalFiles["system/system_header.h"] = guard("class SystemClass 
{};");
+  TU.AdditionalFiles["system/system_unused.h"] = guard("");
+  TU.ExtraArgs = {"-isystem", testPath("system")};

kadircet wrote:

thanks, sgtm

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


[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)

2024-05-13 Thread kadir çetinkaya via cfe-commits


@@ -68,24 +68,32 @@ bool isIgnored(llvm::StringRef HeaderPath, HeaderFilter 
IgnoreHeaders) {
 }
 
 bool mayConsiderUnused(const Inclusion &Inc, ParsedAST &AST,
-   const include_cleaner::PragmaIncludes *PI) {
+   const include_cleaner::PragmaIncludes *PI,
+   bool AnalyzeAngledIncludes) {
   assert(Inc.HeaderID);
   auto HID = static_cast(*Inc.HeaderID);
   auto FE = AST.getSourceManager().getFileManager().getFileRef(
   AST.getIncludeStructure().getRealPath(HID));
   assert(FE);
   if (FE->getDir() == AST.getPreprocessor()
-  .getHeaderSearchInfo()
-  .getModuleMap()
-  .getBuiltinDir()) 
+  .getHeaderSearchInfo()
+  .getModuleMap()
+  .getBuiltinDir())
 return false;
   if (PI && PI->shouldKeep(*FE))
 return false;
   // FIXME(kirillbobyrev): We currently do not support the umbrella headers.
   // System headers are likely to be standard library headers.
-  // Until we have good support for umbrella headers, don't warn about them.
-  if (Inc.Written.front() == '<')
-return tooling::stdlib::Header::named(Inc.Written).has_value();
+  // Until we have good support for umbrella headers, don't warn about them
+  // (unless analysis is explicitly enabled).
+  if (Inc.Written.front() == '<') {
+if (tooling::stdlib::Header::named(Inc.Written)) {
+  return true;
+}
+if (!AnalyzeAngledIncludes) {
+  return false;
+}

kadircet wrote:

LLVM style prefers no braces for single line && statement blocks.

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


[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)

2024-05-13 Thread kadir çetinkaya via cfe-commits

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

thanks a lot, LGTM!

it'd be great if you can also follow up with a change to 
https://github.com/llvm/clangd-www/blob/main/config.md

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


[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder'. (PR #91445)

2024-05-13 Thread Endre Fülöp via cfe-commits

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

Emitting a note to the location where the first part of the detected pattern 
(the `setuid(getuid())` call) seems like useful information, but this patch is 
great as it is.
You could also add it in another patch if it is not trivial.

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


[clang] [clang][analyzer] Check for label location bindings in `DereferenceChecker` (PR #91119)

2024-05-13 Thread Donát Nagy via cfe-commits

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

LGTM.

My only significant observation is that `BugReporterVisitors.cpp` must be 
cleaned up eventually, as it is currently a heap of ad-hoc special cases. 
However, it would be unreasonable to wait for that difficult cleanup with this 
simple improvement, so it's reasonable that you add yet another special case 
that ensures that your example works as intended. 

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread David Green via cfe-commits

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread David Green via cfe-commits

https://github.com/davemgreen commented:

The Arm/AArch64 tests looks OK for the most part. I might be able to help with 
some of them if that is easier than trying to sort them all here.

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread David Green via cfe-commits


@@ -22,7 +22,7 @@ define signext i8 @test1(i32 %A) {
 ; CHECK-V7:   @ %bb.0:
 ; CHECK-V7-NEXT:sbfx r0, r0, #8, #8
 ; CHECK-V7-NEXT:bx lr
-; CHECk-V7: sbfx r0, r0, #8, #8
+; CHECK-V7: sbfx r0, r0, #8, #8

davemgreen wrote:

I believe we can delete this line, it was left in from the old checks.

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread David Green via cfe-commits


@@ -217,42 +217,42 @@ define <4 x i32> @load_v3i8_to_4xi32_const_offset_3(ptr 
%src) {
 }
 
 define <4 x i32> @volatile_load_v3i8_to_4xi32(ptr %src) {
-; check-label: volatile_load_v3i8_to_4xi32:
+; check-LABEL: volatile_load_v3i8_to_4xi32:

davemgreen wrote:

I think we can delete these. The real check lines are below.

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread David Green via cfe-commits


@@ -189,15 +189,15 @@ define i32 @shr(i32 %a, i32 %b) {
 
 
 define i1 @outer_and1(i1 %a) {
-; check-label: @outer_and1(
-; check-not: call i1 @and1
+; check-LABEL: @outer_and1(

davemgreen wrote:

Should all these be "CHECK"?

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread David Green via cfe-commits


@@ -121,7 +121,7 @@ define i32 @test_orr_extract_from_mul_1(i32 %x, i32 %y) {
 ; CHECK-THUMB-NEXT:orrs r0, r1
 ; CHECK-THUMB-NEXT:bx lr
 entry:
-; CHECk-THUMB: orrs r0, r1

davemgreen wrote:

I believe we can delete this line, it was left in from the old checks.

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


[clang] [clang][SPIR-V] Always add convergence intrinsics (PR #88918)

2024-05-13 Thread Nathan Gauër via cfe-commits


@@ -1586,6 +1586,12 @@ class CodeGenModule : public CodeGenTypeCache {
   void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
  bool IsDtorAttrFunc = false);
 
+  // Return whether structured convergence intrinsics should be generated for
+  // this target.
+  bool shouldEmitConvergenceTokens() const {
+return getTriple().isSPIRVLogical();

Keenuts wrote:

Not necessarily. The SPIR-V compute (as OpenCL not Vulkan compute) doesn't 
require a structured CFG, so this could remain forever if they don't see any 
benefit in generating a SCFG.

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


[clang] [clang] Allow pack expansions when partial ordering against template template parameters (PR #91833)

2024-05-13 Thread via cfe-commits

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


[clang] [clang][SPIR-V] Always add convergence intrinsics (PR #88918)

2024-05-13 Thread Nathan Gauër via cfe-commits

Keenuts wrote:

Thanks for the reviews. Waiting for 1 approval from MS and I'll merge

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread David Green via cfe-commits


@@ -189,15 +189,15 @@ define i32 @shr(i32 %a, i32 %b) {
 
 
 define i1 @outer_and1(i1 %a) {
-; check-label: @outer_and1(
-; check-not: call i1 @and1
+; check-LABEL: @outer_and1(

davemgreen wrote:

I've regenerated the check lines in 220756f1f92b335cbafdff67c570d096a6925d87.

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


[clang] [flang] [flang] New -fdebug-unparse-with-modules option (PR #91660)

2024-05-13 Thread via cfe-commits

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

Looks great and useful!

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


[clang] [Clang] Add support for [[msvc::noinline]] attribute. (PR #91720)

2024-05-13 Thread Xu Zhang via cfe-commits

simonzgx wrote:

 Hi @cor3ntin, could you please help review this patch?

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


[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder'. (PR #91445)

2024-05-13 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};

NagyDonat wrote:

`BT` is fairly traditional in the codebase: there are 40+ checker source files 
that use it as a variable name for _the_ bug type. However, this longer name is 
also fine if you prefer it.  

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


[clang] [Clang] Fix dependency computation for pack indexing expression (PR #91933)

2024-05-13 Thread Younan Zhang via cfe-commits


@@ -376,6 +376,9 @@ ExprDependence clang::computeDependence(PackExpansionExpr 
*E) {
 
 ExprDependence clang::computeDependence(PackIndexingExpr *E) {
   ExprDependence D = E->getIndexExpr()->getDependence();
+  if (D & ExprDependence::Value)
+D |= ExprDependence::TypeInstantiation;

zyn0217 wrote:

Does it mean "if the index expression is value-dependent, then the whole 
`PackIndexingExpr` is type-dependent despite its expressions"? For example,
```cpp
template 
auto foo() {
  return E...[N];
}
```
Should `E...[N]` be treated as type-dependent regardless of the result being 
always an int?

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


[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder'. (PR #91445)

2024-05-13 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,170 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,security.SetgidSetuidOrder 
-verify %s
+
+#include "Inputs/system-header-simulator-setgid-setuid.h"
+
+void correct_order() {
+  if (setgid(getgid()) == -1)
+return;
+  if (setuid(getuid()) == -1)
+return;
+  if (setgid(getgid()) == -1)
+return;

NagyDonat wrote:

But why do the SEI-CERT best practices mandate that "this should not be 
recognized as an error"? Could you briefly explain this in a comment? (E.g. 
"Special case: calling `setgid(getgid())` after an earlier `setgid(getgid()); 
setuid(getuid())` combination is legitimate, because it... ")

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


[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder'. (PR #91445)

2024-05-13 Thread Donát Nagy via cfe-commits

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


[clang] [clang] Report erroneous floating point results in _Complex math (PR #90588)

2024-05-13 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Ping

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


[clang] [Clang] Fix dependency computation for pack indexing expression (PR #91933)

2024-05-13 Thread Younan Zhang via cfe-commits


@@ -376,6 +376,9 @@ ExprDependence clang::computeDependence(PackExpansionExpr 
*E) {
 
 ExprDependence clang::computeDependence(PackIndexingExpr *E) {
   ExprDependence D = E->getIndexExpr()->getDependence();
+  if (D & ExprDependence::Value)
+D |= ExprDependence::TypeInstantiation;

zyn0217 wrote:

Probably `E->getPackIdExpression()->getDependence() & 
ExprDependence::TypeInstantiation`?

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


[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder'. (PR #91445)

2024-05-13 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,196 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+enum SetPrivilegeFunctionKind { Irrelevant, Setuid, Setgid };
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{CDM::CLibrary, {"setuid"}, 1};
+  const CallDescription SetgidDesc{CDM::CLibrary, {"setgid"}, 1};
+
+  const CallDescription GetuidDesc{CDM::CLibrary, {"getuid"}, 0};
+  const CallDescription GetgidDesc{CDM::CLibrary, {"getgid"}, 0};
+
+  CallDescriptionSet OtherSetPrivilegeDesc{
+  {CDM::CLibrary, {"seteuid"}, 1},   {CDM::CLibrary, {"setegid"}, 1},
+  {CDM::CLibrary, {"setreuid"}, 2},  {CDM::CLibrary, {"setregid"}, 2},
+  {CDM::CLibrary, {"setresuid"}, 3}, {CDM::CLibrary, {"setresgid"}, 3}};
+
+public:
+  SetgidSetuidOrderChecker() {}
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
+  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
+ bool Assumption) const;
+
+private:
+  ProgramStateRef processSetuid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processSetgid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processOther(ProgramStateRef State, const CallEvent &Call,
+   CheckerContext &C) const;
+  /// Check if a function like \c getuid or \c getgid is called directly from
+  /// the first argument of function called from \a Call.
+  bool isFunctionCalledInArg(const CallDescription &Desc,
+ const CallEvent &Call) const;
+  void emitReport(ProgramStateRef State, CheckerContext &C) const;
+};
+
+} // end anonymous namespace
+
+/// Store if there was a call to 'setuid(getuid())' or 'setgid(getgid())' not
+/// followed by other different privilege-change functions.
+/// If the value \c Setuid is stored and a 'setgid(getgid())' call is found we
+/// have found the bug to be reported. Value \c Setgid is used too to prevent
+/// warnings at a setgid-setuid-setgid sequence.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetPrivilegeCall, 
SetPrivilegeFunctionKind)
+/// Store the symbol value of the last 'setuid(getuid())' call. This is used to
+/// detect if the result is compared to -1 and avoid warnings on that branch
+/// (which is the failure branch of the call).
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetuidCallSVal, SymbolRef)
+
+void SetgidSetuidOrderChecker::checkPostCall(const CallEvent &Call,
+ CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  if (SetuidDesc.matches(Call)) {
+State = processSetuid(State, Call, C);
+  } else if (SetgidDesc.matches(Call)) {
+State = processSetgid(State, Call, C);
+  } else if (OtherSetPrivilegeDesc.contains(Call)) {
+State = processOther(State, Call, C);
+  }
+  if (State)
+C.addTransition(State);
+}
+
+void SetgidSetuidOrderChecker::checkDeadSymbols(SymbolReaper &SymReaper,
+CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  SymbolRef LastSetuidSym = State->get();
+  if (!LastSetuidSym)
+return;
+
+  if (!SymReaper.isDead(LastSetuidSym))
+return;
+
+  State = State->set(SymbolRef{});
+  C.addTransition(State, C.getPredecessor());
+}
+
+ProgramStateRef SetgidSetuidOrderChecker::evalAssume(ProgramStateRef State,
+ SVal Cond,
+ bool Assumption) const {
+  S

[clang] [Clang] Add attribute for consteval builtins; Declare constexpr builtins as constexpr in C++ (PR #91894)

2024-05-13 Thread via cfe-commits


@@ -14,13 +14,18 @@ void __builtin_va_copy(double d);
 // expected-error@+2 {{cannot redeclare builtin function '__builtin_va_end'}}
 // expected-note@+1 {{'__builtin_va_end' is a builtin with type}}
 void __builtin_va_end(__builtin_va_list);
-// RUN: %clang_cc1 %s -fsyntax-only -verify 
-// RUN: %clang_cc1 %s -fsyntax-only -verify -x c
 
 void __va_start(__builtin_va_list*, ...);
 
+  void *__builtin_assume_aligned(const void *, size_t, ...);
 #ifdef __cplusplus
-void *__builtin_assume_aligned(const void *, size_t, ...) noexcept;
-#else
-void *__builtin_assume_aligned(const void *, size_t, ...);
+constexpr void *__builtin_assume_aligned(const void *, size_t, ...);
+  void *__builtin_assume_aligned(const void *, size_t, ...) noexcept;
+constexpr void *__builtin_assume_aligned(const void *, size_t, ...) noexcept;
+  void *__builtin_assume_aligned(const void *, size_t, ...) throw();
+constexpr void *__builtin_assume_aligned(const void *, size_t, ...) throw();
+

cor3ntin wrote:

What is the motivation to allow that?

I kind of understand letting users defining builtin (actually, I am not sure I 
do). but once the builtin is redefined once, I think should be some sort of 
consistency with the language rules.
Here if you were to replace `__builtin_assume_aligned` with `f`, it would be 
ill-formed, for god reason.

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread via cfe-commits

klensy wrote:

> The Arm/AArch64 tests looks OK for the most part. I might be able to help 
> with some of them if that is easier than trying to sort them all here.

It will be nice if you can list tests exactly so i can copy them into separate 
pr; or if you prefer, you can copy them yourself.

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread Daniel Grumberg via cfe-commits

https://github.com/daniel-grumberg approved this pull request.

LGTM to me for the ExtractAPI one.

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


[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder'. (PR #91445)

2024-05-13 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat commented:

Thanks for updating your commit! Now there are only two remaining issues and 
they are both very minor (marked by inline comments: renaming `CallExpr *CE` 
and explaining the reason why "trying to set the gid again" appears as a 
special case in the SEI-CERT standard).

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


[clang] [llvm] [AMDGPU] Add amdgpu-as MMRA for fences (PR #78572)

2024-05-13 Thread Matt Arsenault via cfe-commits


@@ -4408,6 +4409,42 @@ Target-Specific Extensions
 
 Clang supports some language features conditionally on some targets.
 
+AMDGPU Language Extensions
+--
+
+__builtin_amdgcn_fence
+^^
+
+``__builtin_amdgcn_fence`` emits a fence.
+
+* ``unsigned`` atomic ordering, e.g. ``__ATOMIC_ACQUIRE``
+* ``const char *`` synchronization scope, e.g. ``workgroup``
+* Zero or more ``const char *`` address spaces names.
+
+The address spaces arguments must be string literals with known values, such 
as:
+
+* ``"local"``
+* ``"global"``
+* ``"image"``
+
+If one or more address space name are provided, the code generator will attempt
+to emit potentially faster instructions that only fence those address spaces.
+Emitting such instructions may not always be possible and the compiler is free
+to fence more aggressively.
+
+If no address spaces names are provided, all address spaces are fenced.
+
+.. code-block:: c++
+
+  // Fence all address spaces.
+  __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");
+  __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
+
+  // Fence only requested address spaces.
+  __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local")

arsenm wrote:

Not sure we can get away without image

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


[clang] [Clang] Ensure ``if consteval`` consititute an immediate function context (PR #91939)

2024-05-13 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/91939

We did not set the correct evaluation context for the compound statement of an 
``if consteval`` statement
in a templated entity in TreeTransform.

Fixes #91509

>From e84c8c5e0f1bc9e094dfef961763db825234f7aa Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 13 May 2024 11:26:40 +0200
Subject: [PATCH] [Clang] Ensure ``if consteval`` consititute an immediate
 function context.

We did not set the correct evaluation context for the compound
statement of an ``if consteval`` statement
in a templated entity in TreeTransform.

Fixes 91509
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/lib/Sema/TreeTransform.h| 18 +
 .../SemaCXX/cxx2b-consteval-propagate.cpp | 26 +++
 3 files changed, 45 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7c5dcc59c7016..4702b8c10cdbb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -707,6 +707,7 @@ Bug Fixes to C++ Support
   initialized, rather than evaluating them as a part of the larger manifestly 
constant evaluated
   expression.
 - Fix a bug in access control checking due to dealyed checking of friend 
declaration. Fixes (#GH12361).
+- Correctly treat the compound statement of an ``if consteval`` as an 
immediate context. Fixes (#GH91509).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 0b3cf566e3a7b..391cfb0fa4032 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -7964,6 +7964,15 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "then" branch.
   StmtResult Then;
   if (!ConstexprConditionValue || *ConstexprConditionValue) {
+Sema::ExpressionEvaluationContext Context =
+S->isNonNegatedConsteval()
+? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
+: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
+
+EnterExpressionEvaluationContext Ctx(
+getSema(), Context, nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other);
+
 Then = getDerived().TransformStmt(S->getThen());
 if (Then.isInvalid())
   return StmtError();
@@ -7978,6 +7987,15 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "else" branch.
   StmtResult Else;
   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
+Sema::ExpressionEvaluationContext Context =
+S->isNegatedConsteval()
+? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
+: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
+
+EnterExpressionEvaluationContext Ctx(
+getSema(), Context, nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other);
+
 Else = getDerived().TransformStmt(S->getElse());
 if (Else.isInvalid())
   return StmtError();
diff --git a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp 
b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
index 37fa1f1bdf59d..07937deb66738 100644
--- a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
+++ b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
@@ -420,3 +420,29 @@ int f = *fn().value + fn2();  // expected-error {{call to 
consteval function 'lv
   // expected-note {{pointer to heap-allocated 
object}}
 }
 #endif
+
+
+#if __cplusplus >= 202302L
+
+namespace GH91509 {
+
+consteval int f(int) { return 0; }
+
+template
+constexpr int g(int x) {
+if consteval {
+return f(x);
+}
+if !consteval {}
+else {
+return f(x);
+}
+return 1;
+}
+
+int h(int x) {
+return g(x);
+}
+}
+
+#endif

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


[clang] [Clang] Ensure ``if consteval`` consititute an immediate function context (PR #91939)

2024-05-13 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

We did not set the correct evaluation context for the compound statement of an 
``if consteval`` statement
in a templated entity in TreeTransform.

Fixes #91509

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1) 
- (modified) clang/lib/Sema/TreeTransform.h (+18) 
- (modified) clang/test/SemaCXX/cxx2b-consteval-propagate.cpp (+26) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7c5dcc59c7016..4702b8c10cdbb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -707,6 +707,7 @@ Bug Fixes to C++ Support
   initialized, rather than evaluating them as a part of the larger manifestly 
constant evaluated
   expression.
 - Fix a bug in access control checking due to dealyed checking of friend 
declaration. Fixes (#GH12361).
+- Correctly treat the compound statement of an ``if consteval`` as an 
immediate context. Fixes (#GH91509).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 0b3cf566e3a7b..391cfb0fa4032 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -7964,6 +7964,15 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "then" branch.
   StmtResult Then;
   if (!ConstexprConditionValue || *ConstexprConditionValue) {
+Sema::ExpressionEvaluationContext Context =
+S->isNonNegatedConsteval()
+? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
+: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
+
+EnterExpressionEvaluationContext Ctx(
+getSema(), Context, nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other);
+
 Then = getDerived().TransformStmt(S->getThen());
 if (Then.isInvalid())
   return StmtError();
@@ -7978,6 +7987,15 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "else" branch.
   StmtResult Else;
   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
+Sema::ExpressionEvaluationContext Context =
+S->isNegatedConsteval()
+? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
+: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
+
+EnterExpressionEvaluationContext Ctx(
+getSema(), Context, nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other);
+
 Else = getDerived().TransformStmt(S->getElse());
 if (Else.isInvalid())
   return StmtError();
diff --git a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp 
b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
index 37fa1f1bdf59d..07937deb66738 100644
--- a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
+++ b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
@@ -420,3 +420,29 @@ int f = *fn().value + fn2();  // expected-error {{call to 
consteval function 'lv
   // expected-note {{pointer to heap-allocated 
object}}
 }
 #endif
+
+
+#if __cplusplus >= 202302L
+
+namespace GH91509 {
+
+consteval int f(int) { return 0; }
+
+template
+constexpr int g(int x) {
+if consteval {
+return f(x);
+}
+if !consteval {}
+else {
+return f(x);
+}
+return 1;
+}
+
+int h(int x) {
+return g(x);
+}
+}
+
+#endif

``




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


[clang] 61d4ca8 - [clang][ExtractAPI] Distinguish between record kind for display and for RTTI (#91466)

2024-05-13 Thread via cfe-commits

Author: Daniel Grumberg
Date: 2024-05-13T10:37:09+01:00
New Revision: 61d4ca872215d3dfff0b3c92151dcbdc546a0aab

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

LOG: [clang][ExtractAPI] Distinguish between record kind for display and for 
RTTI (#91466)

rdar://127732562

Added: 


Modified: 
clang/include/clang/ExtractAPI/API.h
clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp

Removed: 




diff  --git a/clang/include/clang/ExtractAPI/API.h 
b/clang/include/clang/ExtractAPI/API.h
index d323e1668a72b..bf291074fd061 100644
--- a/clang/include/clang/ExtractAPI/API.h
+++ b/clang/include/clang/ExtractAPI/API.h
@@ -266,6 +266,8 @@ struct APIRecord {
 
   AccessControl Access;
 
+  RecordKind KindForDisplay;
+
 private:
   const RecordKind Kind;
   friend class RecordContext;
@@ -277,6 +279,7 @@ struct APIRecord {
   APIRecord *getNextInContext() const { return NextInContext; }
 
   RecordKind getKind() const { return Kind; }
+  RecordKind getKindForDisplay() const { return KindForDisplay; }
 
   static APIRecord *castFromRecordContext(const RecordContext *Ctx);
   static RecordContext *castToRecordContext(const APIRecord *Record);
@@ -293,10 +296,10 @@ struct APIRecord {
 Availability(std::move(Availability)), Linkage(Linkage),
 Comment(Comment), Declaration(Declaration), SubHeading(SubHeading),
 IsFromSystemHeader(IsFromSystemHeader), Access(std::move(Access)),
-Kind(Kind) {}
+KindForDisplay(Kind), Kind(Kind) {}
 
   APIRecord(RecordKind Kind, StringRef USR, StringRef Name)
-  : USR(USR), Name(Name), Kind(Kind) {}
+  : USR(USR), Name(Name), KindForDisplay(Kind), Kind(Kind) {}
 
   // Pure virtual destructor to make APIRecord abstract
   virtual ~APIRecord() = 0;

diff  --git a/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h 
b/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
index 97cc457ea2a92..8ccebe457ed53 100644
--- a/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
+++ b/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
@@ -194,6 +194,15 @@ class ExtractAPIVisitorBase : public 
RecursiveASTVisitor {
 return Bases;
   }
 
+  APIRecord::RecordKind getKindForDisplay(const CXXRecordDecl *Decl) {
+if (Decl->isUnion())
+  return APIRecord::RK_Union;
+if (Decl->isStruct())
+  return APIRecord::RK_Struct;
+
+return APIRecord::RK_CXXClass;
+  }
+
   StringRef getOwningModuleName(const Decl &D) {
 if (auto *OwningModule = D.getImportedOwningModule())
   return OwningModule->Name;
@@ -599,13 +608,6 @@ bool ExtractAPIVisitorBase::VisitCXXRecordDecl(
   DeclarationFragments SubHeading =
   DeclarationFragmentsBuilder::getSubHeading(Decl);
 
-  APIRecord::RecordKind Kind;
-  if (Decl->isUnion())
-Kind = APIRecord::RecordKind::RK_Union;
-  else if (Decl->isStruct())
-Kind = APIRecord::RecordKind::RK_Struct;
-  else
-Kind = APIRecord::RecordKind::RK_CXXClass;
   auto Access = DeclarationFragmentsBuilder::getAccessControl(Decl);
 
   CXXClassRecord *Record;
@@ -619,13 +621,15 @@ bool ExtractAPIVisitorBase::VisitCXXRecordDecl(
 AvailabilityInfo::createFromDecl(Decl), Comment, Declaration,
 SubHeading, Template(Decl->getDescribedClassTemplate()), Access,
 isInSystemHeader(Decl));
-  } else
+  } else {
 Record = API.createRecord(
 USR, Name, createHierarchyInformationForDecl(*Decl), Loc,
 AvailabilityInfo::createFromDecl(Decl), Comment, Declaration,
-SubHeading, Kind, Access, isInSystemHeader(Decl),
-isEmbeddedInVarDeclarator(*Decl));
+SubHeading, APIRecord::RecordKind::RK_CXXClass, Access,
+isInSystemHeader(Decl), isEmbeddedInVarDeclarator(*Decl));
+  }
 
+  Record->KindForDisplay = getKindForDisplay(Decl);
   Record->Bases = getBases(Decl);
 
   return true;
@@ -849,6 +853,7 @@ bool ExtractAPIVisitorBase::
   Template(Decl), DeclarationFragmentsBuilder::getAccessControl(Decl),
   isInSystemHeader(Decl));
 
+  CTPSR->KindForDisplay = getKindForDisplay(Decl);
   CTPSR->Bases = getBases(Decl);
 
   return true;

diff  --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index 34278b5d40c42..c16d4623f115d 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -514,7 +514,7 @@ Object serializeSymbolKind(APIRecord::RecordKind RK, 
Language Lang) {
 /// which is prefixed by the source language name, useful for tooling to parse
 /// the kind, and a \c displayName for rendering human-readable names.
 Object serializeSymbolKind(const APIRecord &Record, Language Lang) {
-  return serial

[clang] [clang][ExtractAPI] Distinguish between record kind for display and for RTTI (PR #91466)

2024-05-13 Thread Daniel Grumberg via cfe-commits

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


[clang-tools-extra] [clang-tidy] Ignore `if consteval` in else-after-return (PR #91588)

2024-05-13 Thread Congcong Cai via cfe-commits

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


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


[clang] [clang] Processing real directories added as virtual ones (PR #91645)

2024-05-13 Thread Ivan Murashko via cfe-commits

ivanmurashko wrote:

Hi @sam-mccall, 

The patch touches some fairly old code that hasn't been modified for a long 
time. You are one of the few people who worked on it recently, around two years 
ago. I would appreciate any comments and a review of the suggested patch.

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


[clang] [Clang] Ensure ``if consteval`` consititute an immediate function context (PR #91939)

2024-05-13 Thread Mital Ashok via cfe-commits


@@ -7964,6 +7964,15 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "then" branch.
   StmtResult Then;
   if (!ConstexprConditionValue || *ConstexprConditionValue) {
+Sema::ExpressionEvaluationContext Context =
+S->isNonNegatedConsteval()
+? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
+: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
+
+EnterExpressionEvaluationContext Ctx(
+getSema(), Context, nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other);

MitalAshok wrote:

```suggestion
EnterExpressionEvaluationContext Ctx(
getSema(), Sema::ExpressionEvaluationContext::ImmediateFunctionContext, 
nullptr,
Sema::ExpressionEvaluationContextRecord::EK_Other,
S->isNonNegatedConsteval());
```

(and ditto for the else branch) to only push a context if needed

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


[clang-tools-extra] [clangd] Add config option to allow detection of unused system headers (PR #87208)

2024-05-13 Thread Vadim D. via cfe-commits

https://github.com/vvd170501 updated 
https://github.com/llvm/llvm-project/pull/87208

>From 35db92dfd0c2b43fc7afde5b093598763c4b8c89 Mon Sep 17 00:00:00 2001
From: Vadim Dudkin 
Date: Mon, 1 Apr 2024 02:26:14 +0300
Subject: [PATCH 1/6] Add config option to analyze unused system headers

---
 clang-tools-extra/clangd/Config.h |  1 +
 clang-tools-extra/clangd/ConfigCompile.cpp| 57 +++
 clang-tools-extra/clangd/ConfigFragment.h |  4 ++
 clang-tools-extra/clangd/ConfigYAML.cpp   |  4 ++
 clang-tools-extra/clangd/IncludeCleaner.cpp   | 34 +++
 clang-tools-extra/clangd/IncludeCleaner.h | 13 +
 clang-tools-extra/clangd/ParsedAST.cpp|  3 +-
 .../clangd/unittests/ConfigCompileTests.cpp   |  6 ++
 .../clangd/unittests/ConfigYAMLTests.cpp  | 15 +
 .../clangd/unittests/IncludeCleanerTests.cpp  | 15 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 ++
 11 files changed, 112 insertions(+), 45 deletions(-)

diff --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 4371c80a6c587..9629854abff31 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -114,6 +114,7 @@ struct Config {
 /// these regexes.
 struct {
   std::vector> IgnoreHeader;
+  bool AnalyzeSystemHeaders = false;
 } Includes;
   } Diagnostics;
 
diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index 5bb2eb4a9f803..f74c870adfb73 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -572,32 +572,43 @@ struct FragmentCompiler {
 #else
 static llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags;
 #endif
-auto Filters = std::make_shared>();
-for (auto &HeaderPattern : F.IgnoreHeader) {
-  // Anchor on the right.
-  std::string AnchoredPattern = "(" + *HeaderPattern + ")$";
-  llvm::Regex CompiledRegex(AnchoredPattern, Flags);
-  std::string RegexError;
-  if (!CompiledRegex.isValid(RegexError)) {
-diag(Warning,
- llvm::formatv("Invalid regular expression '{0}': {1}",
-   *HeaderPattern, RegexError)
- .str(),
- HeaderPattern.Range);
-continue;
+std::shared_ptr> Filters;
+if (!F.IgnoreHeader.empty()) {
+  Filters = std::make_shared>();
+  for (auto &HeaderPattern : F.IgnoreHeader) {
+// Anchor on the right.
+std::string AnchoredPattern = "(" + *HeaderPattern + ")$";
+llvm::Regex CompiledRegex(AnchoredPattern, Flags);
+std::string RegexError;
+if (!CompiledRegex.isValid(RegexError)) {
+  diag(Warning,
+   llvm::formatv("Invalid regular expression '{0}': {1}",
+ *HeaderPattern, RegexError)
+   .str(),
+   HeaderPattern.Range);
+  continue;
+}
+Filters->push_back(std::move(CompiledRegex));
   }
-  Filters->push_back(std::move(CompiledRegex));
 }
-if (Filters->empty())
+std::optional AnalyzeSystemHeaders;
+if (F.AnalyzeSystemHeaders.has_value())
+  AnalyzeSystemHeaders = **F.AnalyzeSystemHeaders;
+if (!Filters && !AnalyzeSystemHeaders.has_value())
   return;
-auto Filter = [Filters](llvm::StringRef Path) {
-  for (auto &Regex : *Filters)
-if (Regex.match(Path))
-  return true;
-  return false;
-};
-Out.Apply.push_back([Filter](const Params &, Config &C) {
-  C.Diagnostics.Includes.IgnoreHeader.emplace_back(Filter);
+Out.Apply.push_back([Filters = std::move(Filters),
+ AnalyzeSystemHeaders](const Params &, Config &C) {
+  if (Filters) {
+auto Filter = [Filters](llvm::StringRef Path) {
+  for (auto &Regex : *Filters)
+if (Regex.match(Path))
+  return true;
+  return false;
+};
+C.Diagnostics.Includes.IgnoreHeader.emplace_back(std::move(Filter));
+  }
+  if (AnalyzeSystemHeaders.has_value())
+C.Diagnostics.Includes.AnalyzeSystemHeaders = *AnalyzeSystemHeaders;
 });
   }
 
diff --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index 7fa61108c78a0..ac8b88c245412 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -254,6 +254,10 @@ struct Fragment {
   /// unused or missing. These can match any suffix of the header file in
   /// question.
   std::vector> IgnoreHeader;
+
+  /// If false (default), unused system headers will be ignored.
+  /// Standard library headers are analyzed regardless of this option.
+  std::optional> AnalyzeSystemHeaders;
 };
 IncludesBlock Includes;
 
diff --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index ce09af819247a..7608af4200538 100644
--- a/clang-t

[clang] [Clang] Ensure ``if consteval`` consititute an immediate function context (PR #91939)

2024-05-13 Thread via cfe-commits

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

>From e84c8c5e0f1bc9e094dfef961763db825234f7aa Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 13 May 2024 11:26:40 +0200
Subject: [PATCH 1/2] [Clang] Ensure ``if consteval`` consititute an immediate
 function context.

We did not set the correct evaluation context for the compound
statement of an ``if consteval`` statement
in a templated entity in TreeTransform.

Fixes 91509
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/lib/Sema/TreeTransform.h| 18 +
 .../SemaCXX/cxx2b-consteval-propagate.cpp | 26 +++
 3 files changed, 45 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7c5dcc59c7016..4702b8c10cdbb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -707,6 +707,7 @@ Bug Fixes to C++ Support
   initialized, rather than evaluating them as a part of the larger manifestly 
constant evaluated
   expression.
 - Fix a bug in access control checking due to dealyed checking of friend 
declaration. Fixes (#GH12361).
+- Correctly treat the compound statement of an ``if consteval`` as an 
immediate context. Fixes (#GH91509).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 0b3cf566e3a7b..391cfb0fa4032 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -7964,6 +7964,15 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "then" branch.
   StmtResult Then;
   if (!ConstexprConditionValue || *ConstexprConditionValue) {
+Sema::ExpressionEvaluationContext Context =
+S->isNonNegatedConsteval()
+? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
+: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
+
+EnterExpressionEvaluationContext Ctx(
+getSema(), Context, nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other);
+
 Then = getDerived().TransformStmt(S->getThen());
 if (Then.isInvalid())
   return StmtError();
@@ -7978,6 +7987,15 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "else" branch.
   StmtResult Else;
   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
+Sema::ExpressionEvaluationContext Context =
+S->isNegatedConsteval()
+? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
+: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
+
+EnterExpressionEvaluationContext Ctx(
+getSema(), Context, nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other);
+
 Else = getDerived().TransformStmt(S->getElse());
 if (Else.isInvalid())
   return StmtError();
diff --git a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp 
b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
index 37fa1f1bdf59d..07937deb66738 100644
--- a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
+++ b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
@@ -420,3 +420,29 @@ int f = *fn().value + fn2();  // expected-error {{call to 
consteval function 'lv
   // expected-note {{pointer to heap-allocated 
object}}
 }
 #endif
+
+
+#if __cplusplus >= 202302L
+
+namespace GH91509 {
+
+consteval int f(int) { return 0; }
+
+template
+constexpr int g(int x) {
+if consteval {
+return f(x);
+}
+if !consteval {}
+else {
+return f(x);
+}
+return 1;
+}
+
+int h(int x) {
+return g(x);
+}
+}
+
+#endif

>From 9d7a4c78529310cdcf4e92d85ca4f9c5bb8682e6 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 13 May 2024 12:39:51 +0200
Subject: [PATCH 2/2] address review feedback

---
 clang/lib/Sema/TreeTransform.h | 20 ++--
 1 file changed, 6 insertions(+), 14 deletions(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 391cfb0fa4032..126965088831d 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -7964,14 +7964,10 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "then" branch.
   StmtResult Then;
   if (!ConstexprConditionValue || *ConstexprConditionValue) {
-Sema::ExpressionEvaluationContext Context =
-S->isNonNegatedConsteval()
-? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
-: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
-
 EnterExpressionEvaluationContext Ctx(
-getSema(), Context, nullptr,
-Sema::ExpressionEvaluationContextRecord::EK_Other);
+getSema(), Sema::ExpressionEvaluationContext::ImmediateFunctionContext,
+nullptr, Sema::ExpressionEvaluationContextRecord::EK_Other,
+S->isNonNegatedConsteval());
 
 Then = getDerived().TransformStmt(S->getThen());
 if (Then.isInvalid())
@@ -7987,14 +7983,10 @@ TreeTransform::TransformIf

[clang] [Clang] Ensure ``if consteval`` consititute an immediate function context (PR #91939)

2024-05-13 Thread via cfe-commits


@@ -7964,6 +7964,15 @@ TreeTransform::TransformIfStmt(IfStmt *S) {
   // Transform the "then" branch.
   StmtResult Then;
   if (!ConstexprConditionValue || *ConstexprConditionValue) {
+Sema::ExpressionEvaluationContext Context =
+S->isNonNegatedConsteval()
+? Sema::ExpressionEvaluationContext::ImmediateFunctionContext
+: Sema::ExpressionEvaluationContext::PotentiallyEvaluated;
+
+EnterExpressionEvaluationContext Ctx(
+getSema(), Context, nullptr,
+Sema::ExpressionEvaluationContextRecord::EK_Other);

cor3ntin wrote:

You are right, it's nicer this way, thanks.

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


[clang] [Clang] Add attribute for consteval builtins; Declare constexpr builtins as constexpr in C++ (PR #91894)

2024-05-13 Thread Mital Ashok via cfe-commits


@@ -14,13 +14,18 @@ void __builtin_va_copy(double d);
 // expected-error@+2 {{cannot redeclare builtin function '__builtin_va_end'}}
 // expected-note@+1 {{'__builtin_va_end' is a builtin with type}}
 void __builtin_va_end(__builtin_va_list);
-// RUN: %clang_cc1 %s -fsyntax-only -verify 
-// RUN: %clang_cc1 %s -fsyntax-only -verify -x c
 
 void __va_start(__builtin_va_list*, ...);
 
+  void *__builtin_assume_aligned(const void *, size_t, ...);
 #ifdef __cplusplus
-void *__builtin_assume_aligned(const void *, size_t, ...) noexcept;
-#else
-void *__builtin_assume_aligned(const void *, size_t, ...);
+constexpr void *__builtin_assume_aligned(const void *, size_t, ...);
+  void *__builtin_assume_aligned(const void *, size_t, ...) noexcept;
+constexpr void *__builtin_assume_aligned(const void *, size_t, ...) noexcept;
+  void *__builtin_assume_aligned(const void *, size_t, ...) throw();
+constexpr void *__builtin_assume_aligned(const void *, size_t, ...) throw();
+

MitalAshok wrote:

For backwards compatibility (and compatibility with the same definitions in C 
or with GCC), to allow declarations with or without the `constexpr`. I suspect 
in any real code, it will always be declared without the `constexpr`.

The other solutions is to keep them all as `ConstexprSpecKind::Unspecified` 
like we currently do, but this is asymmetric with `consteval` builtins which 
will be marked `ConstexprSpecKind::Consteval`, and leads to the builtin 
versions of `std::move`/`std::forward`/constexpr cmath functions to have 
differing `getConstexprKind()` from their non-builtin counterparts



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


[clang] [Clang] Fix dependency computation for pack indexing expression (PR #91933)

2024-05-13 Thread via cfe-commits


@@ -376,6 +376,9 @@ ExprDependence clang::computeDependence(PackExpansionExpr 
*E) {
 
 ExprDependence clang::computeDependence(PackIndexingExpr *E) {
   ExprDependence D = E->getIndexExpr()->getDependence();
+  if (D & ExprDependence::Value)
+D |= ExprDependence::TypeInstantiation;

cor3ntin wrote:

> Should E...[N] be treated as type-dependent regardless of the result being 
> always an int?

Yes. (We don't do anything to look at whether all the expressions would have 
the same type)

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


[clang] [Clang] Fix dependency computation for pack indexing expression (PR #91933)

2024-05-13 Thread via cfe-commits


@@ -376,6 +376,9 @@ ExprDependence clang::computeDependence(PackExpansionExpr 
*E) {
 
 ExprDependence clang::computeDependence(PackIndexingExpr *E) {
   ExprDependence D = E->getIndexExpr()->getDependence();
+  if (D & ExprDependence::Value)
+D |= ExprDependence::TypeInstantiation;

cor3ntin wrote:

NVM, you are right, we can simplify this whole thing, I'll do that shortly

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread Thomas Preud'homme via cfe-commits


@@ -58,7 +58,7 @@ CHECK-CNT3-NOT: {{^}}this is duplicate
 CHECK-CNT4-COUNT-5: this is duplicate
 CHECK-CNT4-EMPTY:
 
-Many-label:
+Many-LABEL:

RoboTux wrote:

IMO this makes it harder to spot that this is *not* a FileCheck directive. I 
think we should drop all the changes in this file.

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


[clang-tools-extra] [clang-tidy] Ignore `if consteval` in else-after-return (PR #91588)

2024-05-13 Thread Danny Mösch via cfe-commits


@@ -337,6 +337,10 @@ Changes in existing checks
   ` check by excluding include
   directives that form the filename using macro.
 
+- Improved :doc:`readability-else-after-return
+  ` check to ignore
+  `consteval if` condition, where need to retain the else statement.

SimplyDanny wrote:

```suggestion
  `if consteval` statements, for which the `else` branch must not be removed.
```

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


[clang-tools-extra] [clang-tidy] Ignore `if consteval` in else-after-return (PR #91588)

2024-05-13 Thread Danny Mösch via cfe-commits

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


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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread Matt Arsenault via cfe-commits


@@ -58,7 +58,7 @@ CHECK-CNT3-NOT: {{^}}this is duplicate
 CHECK-CNT4-COUNT-5: this is duplicate
 CHECK-CNT4-EMPTY:
 
-Many-label:
+Many-LABEL:

arsenm wrote:

I would be careful about touching FileCheck tests. The point might be the wrong 
label 

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


[clang] [clang-tools-extra] [flang] [llvm] [mlir] [polly] [test]: fix filecheck annotation typos (PR #91854)

2024-05-13 Thread via cfe-commits


@@ -58,7 +58,7 @@ CHECK-CNT3-NOT: {{^}}this is duplicate
 CHECK-CNT4-COUNT-5: this is duplicate
 CHECK-CNT4-EMPTY:
 
-Many-label:
+Many-LABEL:

klensy wrote:

I think i changed this file accidentally in process of fixing other things, 
i'll remove this changes.

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman commented:

Oops, we used to diagnose this until Clang 17 (I think I accidentally regressed 
this behavior when implementing empty inits for C23). Thank you for the fix!

Please be sure to add a release note to clang/docs/ReleaseNotes.rst so users 
know about the fix.

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Aaron Ballman via cfe-commits


@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s
+// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic -Wno-comment %s

AaronBallman wrote:

Why did this test need to add `-Wno-comment`?

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Aaron Ballman via cfe-commits

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Aaron Ballman via cfe-commits


@@ -3371,6 +3371,8 @@ def err_field_with_address_space : Error<
   "field may not be qualified with an address space">;
 def err_compound_literal_with_address_space : Error<
   "compound literal in function scope may not be qualified with an address 
space">;
+def err_compound_literal_with_vla_type : Error<
+  "compound literal has variable-length array type">;

AaronBallman wrote:

```suggestion
  "compound literal cannot be of variable-length array type">;
```

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


[clang] [clang] Enable C++17 relaxed template template argument matching by default (PR #89807)

2024-05-13 Thread Sam McCall via cfe-commits

sam-mccall wrote:

@mizvekov Thank you! With that patch, clang not only doesn't crash on stdexec 
with `-frelaxed-template-template-args`, but in fact accepts the code.


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


[clang] [Clang] Added check for unexpanded pack in attribute [[assume]] (PR #91893)

2024-05-13 Thread Azmat Yusuf via cfe-commits

azmat-y wrote:

It was a pleasure working on this. 

I have received two emails from llvm build bot regarding failed builds, though 
the commit shows  8 build fails. How to go about investigating the cause of 
failures? Can you give me some pointers regarding this. And do the failures 
means this patch will need to be reverted?

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Jim M . R . Teichgräber via cfe-commits


@@ -3371,6 +3371,8 @@ def err_field_with_address_space : Error<
   "field may not be qualified with an address space">;
 def err_compound_literal_with_address_space : Error<
   "compound literal in function scope may not be qualified with an address 
space">;
+def err_compound_literal_with_vla_type : Error<
+  "compound literal has variable-length array type">;

J-MR-T wrote:

That's clearer, thank you!

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Jim M . R . Teichgräber via cfe-commits

https://github.com/J-MR-T updated 
https://github.com/llvm/llvm-project/pull/91891

From 9aab9284fc094d22e12a2ee1217a3bc99e5837b8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jim=20M=2E=20R=2E=20Teichgr=C3=A4ber?=
 
Date: Sun, 12 May 2024 13:33:37 +0200
Subject: [PATCH 1/2] [clang] Disallow VLA type compound literals C99-C23
 6.5.2.5 says: The type name shall specify an object type or an array of
 unknown size, but not a variable length array type Issue:
 https://github.com/llvm/llvm-project/issues/89835

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 ++
 clang/lib/Sema/SemaExpr.cpp   | 19 +--
 clang/test/C/C2x/n2900_n3011.c|  8 +++-
 clang/test/C/C2x/n2900_n3011_2.c  | 16 
 clang/test/Sema/compound-literal.c| 15 +--
 5 files changed, 35 insertions(+), 25 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d6863f90edb6e..008d7b2a29cd9 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3371,6 +3371,8 @@ def err_field_with_address_space : Error<
   "field may not be qualified with an address space">;
 def err_compound_literal_with_address_space : Error<
   "compound literal in function scope may not be qualified with an address 
space">;
+def err_compound_literal_with_vla_type : Error<
+  "compound literal has variable-length array type">;
 def err_address_space_mismatch_templ_inst : Error<
   "conflicting address space qualifiers are provided between types %0 and %1">;
 def err_attr_objc_ownership_redundant : Error<
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index c688cb21f2364..e62e3f3285e5d 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -7274,12 +7274,19 @@ Sema::BuildCompoundLiteralExpr(SourceLocation 
LParenLoc, TypeSourceInfo *TInfo,
   // init a VLA in C++ in all cases (such as with non-trivial 
constructors).
   // FIXME: should we allow this construct in C++ when it makes sense to do
   // so?
-  std::optional NumInits;
-  if (const auto *ILE = dyn_cast(LiteralExpr))
-NumInits = ILE->getNumInits();
-  if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
-  !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
-   diag::err_variable_object_no_init))
+  //
+  // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
+  // shall specify an object type or an array of unknown size, but not a
+  // variable length array type. This seems odd, as it allows int a[size] =
+  // {}; but forbids int a[size] = (int[size]){}; As this is what the
+  // standard says, this is what's implemented here for C (except for the
+  // extension that permits constant foldable size arrays)
+
+  auto diagID = LangOpts.CPlusPlus
+? diag::err_variable_object_no_init
+: diag::err_compound_literal_with_vla_type;
+  if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
+   diagID))
 return ExprError();
 }
   } else if (!literalType->isDependentType() &&
diff --git a/clang/test/C/C2x/n2900_n3011.c b/clang/test/C/C2x/n2900_n3011.c
index 4350aa140691b..f0be8b9e41861 100644
--- a/clang/test/C/C2x/n2900_n3011.c
+++ b/clang/test/C/C2x/n2900_n3011.c
@@ -27,8 +27,14 @@ void test(void) {
   compat-warning {{use of an empty initializer is 
incompatible with C standards before C23}}
   int vla[i] = {}; // compat-warning {{use of an empty initializer is 
incompatible with C standards before C23}} \
   pedantic-warning {{use of an empty initializer is a C23 
extension}}
+  // C99 6.5.2.5 Compound literals constraint 1: The type name shall specify an
+  // object type or an array of unknown size, but not a variable length array
+  // type.
   int *compound_literal_vla = (int[i]){}; // compat-warning {{use of an empty 
initializer is incompatible with C standards before C23}} \
- pedantic-warning {{use of an 
empty initializer is a C23 extension}}
+ pedantic-warning {{use of an 
empty initializer is a C23 extension}}\
+ compat-error {{compound literal 
has variable-length array type}} \
+ pedantic-error {{compound literal 
has variable-length array type}}\
+
 
   struct T {
int i;
diff --git a/clang/test/C/C2x/n2900_n3011_2.c b/clang/test/C/C2x/n2900_n3011_2.c
index eb15fbf905c86..ab659d636d155 100644
--- a/clang/test/C/C2x/n2900_n3011_2.c
+++ b/clang/test/C/C2x/n2900_n3011_2.c
@@ -76,22 +76,6 @@ void test_zero_size_vla() {
   // CHECK-NEXT: call void @llvm

[clang] [clang][analyzer] Check for label location bindings in `DereferenceChecker` (PR #91119)

2024-05-13 Thread Rajveer Singh Bharadwaj via cfe-commits

Rajveer100 wrote:

Thanks for the approval, could you land this for me?

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Jim M . R . Teichgräber via cfe-commits


@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s
+// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic -Wno-comment %s

J-MR-T wrote:

[This 
line](https://github.com/llvm/llvm-project/pull/91891/files#diff-7d0182b6392ee774cf192fde090a22efd8367b693b28bac42d2e3ae2f8c2d94bR50-R51)
 both warns about the empty initializer being used without `-std=c2x`, and now 
triggers the new diagnostic. As I understand `-verify`, this cannot be tested 
using `//` on subsequent lines, so I used the `\` syntax to chain these checks, 
as some other tests do. Without `-Wno-comment`, this would lead to an 
additional warning for the multiline `// ... \` comment.

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


[clang] efe91cf - [clang][analyzer] Check for label location bindings in `DereferenceChecker` (#91119)

2024-05-13 Thread via cfe-commits

Author: Rajveer Singh Bharadwaj
Date: 2024-05-13T13:43:35+02:00
New Revision: efe91cf78bccda90637c817e3e592b5f34e891d0

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

LOG: [clang][analyzer] Check for label location bindings in 
`DereferenceChecker` (#91119)

Resolves #89264

Values should not be stored in addresses of labels, this throws a fatal
error when this happens.

-

Co-authored-by: Balazs Benics 

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
clang/test/Analysis/gh-issue-89185.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
index 1cebfbbee77da..0355eede75eae 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
@@ -31,11 +31,13 @@ class DereferenceChecker
 : public Checker< check::Location,
   check::Bind,
   EventDispatcher > {
-  enum DerefKind { NullPointer, UndefinedPointerValue };
+  enum DerefKind { NullPointer, UndefinedPointerValue, AddressOfLabel };
 
   BugType BT_Null{this, "Dereference of null pointer", categories::LogicError};
   BugType BT_Undef{this, "Dereference of undefined pointer value",
categories::LogicError};
+  BugType BT_Label{this, "Dereference of the address of a label",
+   categories::LogicError};
 
   void reportBug(DerefKind K, ProgramStateRef State, const Stmt *S,
  CheckerContext &C) const;
@@ -167,6 +169,11 @@ void DereferenceChecker::reportBug(DerefKind K, 
ProgramStateRef State,
 DerefStr1 = " results in an undefined pointer dereference";
 DerefStr2 = " results in a dereference of an undefined pointer value";
 break;
+  case DerefKind::AddressOfLabel:
+BT = &BT_Label;
+DerefStr1 = " results in an undefined pointer dereference";
+DerefStr2 = " results in a dereference of an address of a label";
+break;
   };
 
   // Generate an error node.
@@ -287,6 +294,12 @@ void DereferenceChecker::checkBind(SVal L, SVal V, const 
Stmt *S,
   if (V.isUndef())
 return;
 
+  // One should never write to label addresses.
+  if (auto Label = L.getAs()) {
+reportBug(DerefKind::AddressOfLabel, C.getState(), S, C);
+return;
+  }
+
   const MemRegion *MR = L.getAsRegion();
   const TypedValueRegion *TVR = dyn_cast_or_null(MR);
   if (!TVR)

diff  --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 984755fa7e502..487a3bd16b674 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -113,6 +113,9 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
   if (const Expr *Inner = peelOffPointerArithmetic(B)) {
 E = Inner;
+  } else if (B->isAssignmentOp()) {
+// Follow LHS of assignments: '*p = 404' -> 'p'.
+E = B->getLHS();
   } else {
 // Probably more arithmetic can be pattern-matched here,
 // but for now give up.

diff  --git a/clang/test/Analysis/gh-issue-89185.c 
b/clang/test/Analysis/gh-issue-89185.c
index 8a907f198a5fd..49526d2daa866 100644
--- a/clang/test/Analysis/gh-issue-89185.c
+++ b/clang/test/Analysis/gh-issue-89185.c
@@ -1,14 +1,13 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -verify 
%s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-analyzer-output text -verify %s 
 
-void clang_analyzer_dump(char);
-void clang_analyzer_dump_ptr(char*);
+void clang_analyzer_warnIfReached(void);
 
 // https://github.com/llvm/llvm-project/issues/89185
 void binding_to_label_loc() {
-  char *b = &&MyLabel;
+  char *b = &&MyLabel; // expected-note {{'b' initialized here}}
 MyLabel:
-  *b = 0; // no-crash
-  clang_analyzer_dump_ptr(b); // expected-warning {{&&MyLabel}}
-  clang_analyzer_dump(*b); // expected-warning {{Unknown}}
-  // FIXME: We should never reach here, as storing to a label is invalid.
+  *b = 0;
+  // expected-warning@-1 {{Dereference of the address of a label}}
+  // expected-note@-2{{Dereference of the address of a label}}
+  clang_analyzer_warnIfReached(); // no-warning: Unreachable due to fatal 
error.
 }



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


[clang] [clang][analyzer] Check for label location bindings in `DereferenceChecker` (PR #91119)

2024-05-13 Thread Donát Nagy via cfe-commits

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


[clang] [clang-tools-extra] Reapply "[Clang][Sema] Diagnose class member access expressions naming non-existent members of the current instantiation prior to instantiation in the absence of dependent

2024-05-13 Thread via cfe-commits

eaeltsin wrote:

Hi,

This seems to break the following combination with overloaded -> operator - 
https://godbolt.org/z/jc6chKTdv

```
template 
class Clone {
  public:
Clone(const Clone&);
T* operator->() const;
T* ptr_;
};

// Assume T* T::clone()
template 
inline Clone::Clone(const Clone& t)
: ptr_(t->clone()) {}

template 
inline T* Clone::operator->() const {
return ptr_;
}
```


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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Jim M . R . Teichgräber via cfe-commits

J-MR-T wrote:

> Please be sure to add a release note to clang/docs/ReleaseNotes.rst so users 
> know about the fix.

Oh, sorry, I didn't find anything know how release notes were handled - will do!

A question on that, would you classify this as a breaking change? Technically, 
it could break the compilation of programs previously compiled with Clang 17 
that compile VLA type compound literals, but never execute the code that 
they're used in; is that enough for it to be listed as a breaking change? If 
so, would this go under the `C/C++ Language Potentially Breaking Changes` 
header? Or should I create a new `C Language Potentially Breaking Changes` 
header, as this does not affect Clang's C++ behavior itself in any way?

PS: I hope multiple commits in this PR are fine, they are squashed at the end 
anyway, right?


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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Aaron Ballman via cfe-commits


@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s
+// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic -Wno-comment %s

AaronBallman wrote:

Ah! That's a perfectly fine reason to use `-Wno-comment` and you can leave the 
test as-is if you'd like, but another option is to use relative verify lines, 
as in:
```
bad_code();
// expected-warning@-1 {{you did the bad thing}}
// expected-note@-2 {{you should feel bad about that}}
```


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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Aaron Ballman via cfe-commits

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman commented:

Btw, you can probably move this PR out of Draft status, it seems awfully close 
to finished

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


[clang] [clang] Enable C++17 relaxed template template argument matching by default (PR #89807)

2024-05-13 Thread Sam McCall via cfe-commits

sam-mccall wrote:

I'm sorry that I wasn't able to more usefully reduce the failure cases. When 
such regressions show up, we usually don't have any meaningful context on the 
code. For our own code, we have guidelines to try to limit complexity which 
makes reduction more tractable, but third-party libraries are harder.

For publicly-available code, it's not clear to me how much of the burden should 
fall on people that identify the problem.
I want to do as much of this work as I can, it's difficult to balance the 
urgency of providing some reproducer (it gets hard to push for a fix if we wait 
a week for a good reproducers), the quality of reduction, and other 
work/deadlines. (As mentioned, the timing was difficult this time as this 
landed just before a holiday).

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Jim M . R . Teichgräber via cfe-commits

https://github.com/J-MR-T updated 
https://github.com/llvm/llvm-project/pull/91891

From 9aab9284fc094d22e12a2ee1217a3bc99e5837b8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jim=20M=2E=20R=2E=20Teichgr=C3=A4ber?=
 
Date: Sun, 12 May 2024 13:33:37 +0200
Subject: [PATCH 1/3] [clang] Disallow VLA type compound literals C99-C23
 6.5.2.5 says: The type name shall specify an object type or an array of
 unknown size, but not a variable length array type Issue:
 https://github.com/llvm/llvm-project/issues/89835

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 ++
 clang/lib/Sema/SemaExpr.cpp   | 19 +--
 clang/test/C/C2x/n2900_n3011.c|  8 +++-
 clang/test/C/C2x/n2900_n3011_2.c  | 16 
 clang/test/Sema/compound-literal.c| 15 +--
 5 files changed, 35 insertions(+), 25 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d6863f90edb6e..008d7b2a29cd9 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3371,6 +3371,8 @@ def err_field_with_address_space : Error<
   "field may not be qualified with an address space">;
 def err_compound_literal_with_address_space : Error<
   "compound literal in function scope may not be qualified with an address 
space">;
+def err_compound_literal_with_vla_type : Error<
+  "compound literal has variable-length array type">;
 def err_address_space_mismatch_templ_inst : Error<
   "conflicting address space qualifiers are provided between types %0 and %1">;
 def err_attr_objc_ownership_redundant : Error<
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index c688cb21f2364..e62e3f3285e5d 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -7274,12 +7274,19 @@ Sema::BuildCompoundLiteralExpr(SourceLocation 
LParenLoc, TypeSourceInfo *TInfo,
   // init a VLA in C++ in all cases (such as with non-trivial 
constructors).
   // FIXME: should we allow this construct in C++ when it makes sense to do
   // so?
-  std::optional NumInits;
-  if (const auto *ILE = dyn_cast(LiteralExpr))
-NumInits = ILE->getNumInits();
-  if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
-  !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
-   diag::err_variable_object_no_init))
+  //
+  // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
+  // shall specify an object type or an array of unknown size, but not a
+  // variable length array type. This seems odd, as it allows int a[size] =
+  // {}; but forbids int a[size] = (int[size]){}; As this is what the
+  // standard says, this is what's implemented here for C (except for the
+  // extension that permits constant foldable size arrays)
+
+  auto diagID = LangOpts.CPlusPlus
+? diag::err_variable_object_no_init
+: diag::err_compound_literal_with_vla_type;
+  if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
+   diagID))
 return ExprError();
 }
   } else if (!literalType->isDependentType() &&
diff --git a/clang/test/C/C2x/n2900_n3011.c b/clang/test/C/C2x/n2900_n3011.c
index 4350aa140691b..f0be8b9e41861 100644
--- a/clang/test/C/C2x/n2900_n3011.c
+++ b/clang/test/C/C2x/n2900_n3011.c
@@ -27,8 +27,14 @@ void test(void) {
   compat-warning {{use of an empty initializer is 
incompatible with C standards before C23}}
   int vla[i] = {}; // compat-warning {{use of an empty initializer is 
incompatible with C standards before C23}} \
   pedantic-warning {{use of an empty initializer is a C23 
extension}}
+  // C99 6.5.2.5 Compound literals constraint 1: The type name shall specify an
+  // object type or an array of unknown size, but not a variable length array
+  // type.
   int *compound_literal_vla = (int[i]){}; // compat-warning {{use of an empty 
initializer is incompatible with C standards before C23}} \
- pedantic-warning {{use of an 
empty initializer is a C23 extension}}
+ pedantic-warning {{use of an 
empty initializer is a C23 extension}}\
+ compat-error {{compound literal 
has variable-length array type}} \
+ pedantic-error {{compound literal 
has variable-length array type}}\
+
 
   struct T {
int i;
diff --git a/clang/test/C/C2x/n2900_n3011_2.c b/clang/test/C/C2x/n2900_n3011_2.c
index eb15fbf905c86..ab659d636d155 100644
--- a/clang/test/C/C2x/n2900_n3011_2.c
+++ b/clang/test/C/C2x/n2900_n3011_2.c
@@ -76,22 +76,6 @@ void test_zero_size_vla() {
   // CHECK-NEXT: call void @llvm

[clang] [clang-tools-extra] [clang-tidy][dataflow] Add `bugprone-null-check-after-dereference` check (PR #84166)

2024-05-13 Thread via cfe-commits

Discookie wrote:

Should be ready for another round of review.

Simplified a lot of the logic, implemented most of the changes requested, added 
support for `p != nullptr`, and `void f(int **ptr)` invalidating the value of 
`*ptr`.

I've been experimenting with trying to remove `TK_IgnoreUnlessSpelledInSource`, 
without much luck. I need to be able to set a new `Value` to all of my 
pointers, and currently the framework doesn't let me set it in a persistent 
manner.
I'm still yet to refactor handling `Top`, currently it's used in early returns 
where possible, but I still need to think of a clear way to make central 
functions for it.


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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Jim M . R . Teichgräber via cfe-commits


@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s
+// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic -Wno-comment %s

J-MR-T wrote:

Ah, that's good to know! Seeing as I had to modify the test again anyway, it 
seems nicer to use this syntax.

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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread Jim M . R . Teichgräber via cfe-commits

J-MR-T wrote:

> Btw, you can probably move this PR out of Draft status, it seems awfully 
> close to finished

I'll finish implementing your suggestions, run the tests again locally and then 
move it out of draft, if that's alright with you :).


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


[clang] [clang] Disallow VLA type compound literals (PR #91891)

2024-05-13 Thread via cfe-commits
Jim M. R. =?utf-8?q?Teichgräber?=,Jim M. R. =?utf-8?q?Teichgräber?Message-ID:
In-Reply-To: 


Sirraide wrote:

> A question on that, would you classify this as a breaking change?

This is just a bug fix, so no. Rejecting code that we would erroneously accept 
(and miscompile in the process) is not really a breaking change.

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


[clang] Implementation of '#pragma STDC FENV_ROUND' (PR #89617)

2024-05-13 Thread Serge Pavlov via cfe-commits

https://github.com/spavloff updated 
https://github.com/llvm/llvm-project/pull/89617

>From ec8838685fb7af618445c3ff1bae953778996c37 Mon Sep 17 00:00:00 2001
From: Serge Pavlov 
Date: Thu, 14 Apr 2022 18:00:14 +0700
Subject: [PATCH 1/3] Implementation of '#pragma STDC FENV_ROUND'

This pragma is introduced by forthcoming C2x standard and can be used to
set particular rounding mode without need to call 'fesetmode' or accessing
control mode registers directly. Previously this pragma was implemented in
clang partially, only for the purpose of using in constant expressions and
making tests.

This change implements the pragma according to the standard draft. It sets
up dynamic rounding mode in the compound statement where the pragma acts.
This is inevitable for targets that set rounding mode by changing some
control register. Targets that support static rounding mode encoded in
instructions can have more efficient implementation, it is not
implemented in this change.

The implementation uses intrinsic functions 'get_rounding' and
'set_rounding' to save/restore dynamic rounding mode. In some cases
using functions that operate entire set of control modes or even FP
environment may give more efficient implementation. This optimization is
not a part of this change.
---
 clang/include/clang/AST/Stmt.h|   9 +
 .../clang/Basic/DiagnosticParseKinds.td   |   3 -
 clang/include/clang/Basic/LangOptions.h   |   6 +
 clang/lib/CodeGen/CGStmt.cpp  |  56 ++
 clang/lib/CodeGen/CodeGenFunction.h   |   3 +
 clang/lib/Parse/ParsePragma.cpp   |   3 -
 clang/test/CodeGen/complex-strictfp.c |  60 ---
 clang/test/CodeGen/math-errno.c   |   6 +-
 clang/test/CodeGen/pragma-fenv_access.c   |  45 -
 clang/test/CodeGen/pragma-fenv_round.c| 160 ++
 clang/test/Parser/pragma-fenv_round.c |   1 -
 11 files changed, 315 insertions(+), 37 deletions(-)
 create mode 100644 clang/test/CodeGen/pragma-fenv_round.c

diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index 9cd7a364cd3f1..6eceecd93e59c 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -1658,6 +1658,15 @@ class CompoundStmt final
 return *getTrailingObjects();
   }
 
+  /// Get FPOptions inside this statement. They may differ from the outer
+  /// options due to pragmas.
+  /// \param CurFPOptions FPOptions outside this statement.
+  FPOptions getNewFPOptions(FPOptions CurFPOptions) const {
+return hasStoredFPFeatures()
+   ? getStoredFPFeatures().applyOverrides(CurFPOptions)
+   : CurFPOptions;
+  }
+
   using body_iterator = Stmt **;
   using body_range = llvm::iterator_range;
 
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 44bc4e0e130de..c9b0c0e616c71 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1266,9 +1266,6 @@ def ext_stdc_pragma_ignored : ExtWarn<"unknown pragma in 
STDC namespace">,
 // The C standard 7.6.1p2 says "The [FENV_ACCESS] pragma shall occur either
 // outside external declarations or preceding all explicit declarations and
 // statements inside a compound statement.
-def warn_stdc_fenv_round_not_supported :
-   Warning<"pragma STDC FENV_ROUND is not supported">,
-   InGroup;
 def warn_stdc_unknown_rounding_mode : Warning<
   "invalid or unsupported rounding mode in '#pragma STDC FENV_ROUND' - 
ignored">,
   InGroup;
diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index e2a2aa71b880b..53c498f1c4017 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -846,6 +846,12 @@ class FPOptions {
getAllowFEnvAccess();
   }
 
+  /// Checks if the rounding mode is unknown at compile-time.
+  bool isRoundingModeDynamic() const {
+return (getConstRoundingMode() == RoundingMode::Dynamic) &&
+   (getAllowFEnvAccess() || getRoundingMath());
+  }
+
   RoundingMode getRoundingMode() const {
 RoundingMode RM = getConstRoundingMode();
 if (RM == RoundingMode::Dynamic) {
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 576fe2f7a2d46..4fbc906afaeed 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -486,6 +486,56 @@ bool CodeGenFunction::EmitSimpleStmt(const Stmt *S,
   return true;
 }
 
+namespace {
+/// Cleanup action that restores floating-point control modes upon leaving
+/// a scope.
+struct FPControlModesCleanup final : EHScopeStack::Cleanup {
+  llvm::Value *PreviousModes;
+  FPControlModesCleanup(llvm::Value *M) : PreviousModes(M) {}
+  void Emit(CodeGenFunction &CGF, Flags flags) override {
+CGF.Builder.CreateIntrinsic(llvm::Intrinsic::set_rounding, {},
+{PreviousModes});
+  }
+};
+} // namespace

  1   2   3   4   5   6   >