[clang] [clang-tools-extra] [llvm] [InstCombine] Convert or concat to fshl if opposite or concat exists (PR #68502)

2023-11-10 Thread Wei Xiao via cfe-commits

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

LGTM.

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] 5bd0f0d - [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (#71162)

2023-11-10 Thread via cfe-commits

Author: Björn Pettersson
Date: 2023-11-11T01:53:18-05:00
New Revision: 5bd0f0d9d635617b335dd0b259e971a605ad6776

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

LOG: [clangd] Check for valid location in ExtractionContext::exprIsValidOutside 
(#71162)

If the code has a call to an implicitly declared function, an expression
could end up referencing declarations without valid source locations. So
when doing the exprIsValidOutside check we could end up calling
SourceManager::isPointWithin using invalid source locations, and then a
debug build would crash with an assertion failure in
SourceManager::isBeforeInTranslationUnit.

This patch make sure that we deal with the invalid locations (by
considering a ReferencedDecl with invalid location as not being inside
the Scope).

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
index 1e4edc6d6b4bb39..79bf962544242bb 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
@@ -176,7 +176,8 @@ bool ExtractionContext::exprIsValidOutside(const 
clang::Stmt *Scope) const {
   SourceLocation ScopeBegin = Scope->getBeginLoc();
   SourceLocation ScopeEnd = Scope->getEndLoc();
   for (const Decl *ReferencedDecl : ReferencedDecls) {
-if (SM.isPointWithin(ReferencedDecl->getBeginLoc(), ScopeBegin, ScopeEnd) 
&&
+if (ReferencedDecl->getBeginLoc().isValid() &&
+SM.isPointWithin(ReferencedDecl->getBeginLoc(), ScopeBegin, ScopeEnd) 
&&
 SM.isPointWithin(ReferencedDecl->getEndLoc(), ScopeBegin, ScopeEnd))
   return false;
   }

diff  --git 
a/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
index 3d74a941071f849..eb5b06cfee43166 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
@@ -64,6 +64,14 @@ TEST_F(ExtractVariableTest, Test) {
   int x = [[1]];
 })cpp";
   EXPECT_AVAILABLE(AvailableC);
+
+  ExtraArgs = {"-xc"};
+  const char *NoCrashCasesC = R"cpp(
+// error-ok: broken code, but shouldn't crash
+int x = [[foo()]];
+)cpp";
+  EXPECT_UNAVAILABLE(NoCrashCasesC);
+
   ExtraArgs = {"-xobjective-c"};
   const char *AvailableObjC = R"cpp(
 __attribute__((objc_root_class))



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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits

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

Thanks!

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


[PATCH] D123235: [OpenMP] atomic compare fail : Parser & AST support

2023-11-10 Thread Sunil K via Phabricator via cfe-commits
koops updated this revision to Diff 558076.
koops added a comment.

Removing default from switch statements.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123235/new/

https://reviews.llvm.org/D123235

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/OpenMPKinds.def
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_ast_print.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -209,6 +209,7 @@
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
 def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
+def OMPC_Fail : Clause<"fail"> { let clangClass = "OMPFailClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -637,7 +638,8 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_Target : Directive<"target"> {
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -2227,6 +2227,7 @@
 CHECK_SIMPLE_CLAUSE(Doacross, OMPC_doacross)
 CHECK_SIMPLE_CLAUSE(OmpxAttribute, OMPC_ompx_attribute)
 CHECK_SIMPLE_CLAUSE(OmpxBare, OMPC_ompx_bare)
+CHECK_SIMPLE_CLAUSE(Fail, OMPC_fail)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2402,6 +2402,8 @@
 
 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
 
+void OMPClauseEnqueue::VisitOMPFailClause(const OMPFailClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -958,6 +958,24 @@
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}}
 #pragma omp atomic compare compare capture capture
   { v = a; if (a > b) a = b; }
+// expected-error@+1 {{expected 'compare' clause with the 'fail' modifier}}
+#pragma omp atomic fail(seq_cst)
+  if(v == a) { v = a; }
+// expected-error@+1 {{expected '(' after 'fail'}}
+#pragma omp atomic compare fail
+  if(v < a) { v = a; }
+// expected-error@+1 {{expected a memory order clause}}
+#pragma omp atomic compare fail(capture)
+  if(v < a) { v = a; }
+ // expected-error@+2 {{expected ')'}}
+ // expected-note@+1 {{to match this '('}}
+#pragma omp atomic compare fail(seq_cst | acquire)
+  if(v < a) { v = a; }
+// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'fail' clause}}
+#pragma omp atomic compare fail(relaxed) fail(seq_cst)
+  if(v < a) { v = a; }
+
+
 #endif
   // expected-note@+1 {{in instantiation of function template specialization 'mixed' requested here}}
   return mixed();
Index: clang/test/OpenMP/atomic_ast_print.cpp
===
--- clang/test/OpenMP/atomic_ast_print.cpp
+++ clang/test/OpenMP/atomic_ast_print.cpp
@@ -226,6 +226,16 @@
   { v = a; if (a < b) { a = b; } }
 #pragma omp atomic compare capture hint(6)
   { v = a == b; if (v) a = c; }
+#pragma omp atomic compare fail(acq_rel)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(acquire)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(release)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(relaxed)
+  { if (a < c) { a = c; } }
+#pragma omp atomic compare fail(seq_cst)
+  { if (a < c) { a = c; } }
 #endif
   return T();
 }
@@ -1099,6 +1109,16 @@
   { v = a; if (a < b) { a = b; } }
 #pragma omp atomic 

[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-10 Thread Younan Zhang via cfe-commits

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

>From d73a8e2ee683e6812c21cb1de7363b14565a96d1 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 4 Nov 2023 18:43:58 +0800
Subject: [PATCH 1/3] [clangd] Resolve the dependent type from its single
 instantiation. Take 1

This is an enhancement to the HeuristicResolver, trying to extract
the deduced type from the single instantiation for a template. This
partially addresses the point #1 from
https://github.com/clangd/clangd/issues/1768.

This patch doesn't tackle CXXUnresolvedConstructExpr or similarities
since I feel that is more arduous and would prefer to leave it for
my future work.
---
 .../clangd/HeuristicResolver.cpp  | 101 ++
 .../clangd/unittests/XRefsTests.cpp   |  48 +
 2 files changed, 149 insertions(+)

diff --git a/clang-tools-extra/clangd/HeuristicResolver.cpp 
b/clang-tools-extra/clangd/HeuristicResolver.cpp
index 3c147b6b582bf0b..d3dced9b325367a 100644
--- a/clang-tools-extra/clangd/HeuristicResolver.cpp
+++ b/clang-tools-extra/clangd/HeuristicResolver.cpp
@@ -7,10 +7,14 @@
 
//===--===//
 
 #include "HeuristicResolver.h"
+#include "AST.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/CXXInheritance.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 
 namespace clang {
@@ -46,6 +50,98 @@ const Type *resolveDeclsToType(const std::vector ,
   return nullptr;
 }
 
+// Visitor that helps to extract deduced type from instantiated entities.
+// This merely performs the source location comparison against each Decl
+// until it finds a Decl with the same location as the
+// dependent one. Its associated type will then be extracted.
+struct InstantiatedDeclVisitor : RecursiveASTVisitor {
+
+  InstantiatedDeclVisitor(NamedDecl *DependentDecl) : 
DependentDecl(DependentDecl) {}
+
+  bool shouldVisitTemplateInstantiations() const { return true; }
+
+  bool shouldVisitLambdaBody() const { return true; }
+
+  bool shouldVisitImplicitCode() const { return true; }
+
+  template 
+  bool onDeclVisited(D *MaybeInstantiated) {
+if (MaybeInstantiated->getDeclContext()->isDependentContext())
+  return true;
+auto *Dependent = dyn_cast(DependentDecl);
+if (!Dependent)
+  return true;
+auto LHS = MaybeInstantiated->getTypeSourceInfo(),
+ RHS = Dependent->getTypeSourceInfo();
+if (!LHS || !RHS)
+  return true;
+if (LHS->getTypeLoc().getSourceRange() !=
+RHS->getTypeLoc().getSourceRange())
+  return true;
+DeducedType = MaybeInstantiated->getType();
+return false;
+  }
+
+  bool VisitFieldDecl(FieldDecl *FD) {
+return onDeclVisited(FD);
+  }
+
+  bool VisitVarDecl(VarDecl *VD) {
+return onDeclVisited(VD);
+  }
+
+  NamedDecl *DependentDecl;
+  QualType DeducedType;
+};
+
+/// Attempt to resolve the dependent type from the surrounding context for 
which
+/// a single instantiation is available.
+const Type *
+resolveTypeFromInstantiatedTemplate(const CXXDependentScopeMemberExpr *Expr) {
+  if (Expr->isImplicitAccess())
+return nullptr;
+
+  auto *Base = Expr->getBase();
+  NamedDecl *ND = nullptr;
+  if (auto *CXXMember = dyn_cast(Base))
+ND = CXXMember->getMemberDecl();
+
+  if (auto *DRExpr = dyn_cast(Base))
+ND = DRExpr->getFoundDecl();
+
+  // FIXME: Handle CXXUnresolvedConstructExpr. This kind of type doesn't have
+  // available Decls to be matched against. Which inhibits the current 
heuristic
+  // from resolving expressions such as `T().fo^o()`, where T is a
+  // single-instantiated template parameter.
+  if (!ND)
+return nullptr;
+
+  NamedDecl *Instantiation = nullptr;
+
+  // Find out a single instantiation that we can start with. The enclosing
+  // context for the current Decl might not be a templated entity (e.g. a 
member
+  // function inside a class template), hence we shall walk up the decl
+  // contexts first.
+  for (auto *EnclosingContext = ND->getDeclContext(); EnclosingContext;
+   EnclosingContext = EnclosingContext->getParent()) {
+if (auto *ND = dyn_cast(EnclosingContext)) {
+  Instantiation = getOnlyInstantiation(ND);
+  if (Instantiation)
+break;
+}
+  }
+
+  if (!Instantiation)
+return nullptr;
+
+  // This will traverse down the instantiation entity, visit each Decl, and
+  // extract the deduced type for the undetermined Decl `ND`.
+  InstantiatedDeclVisitor Visitor(ND);
+  Visitor.TraverseDecl(Instantiation);
+
+  return Visitor.DeducedType.getTypePtrOrNull();
+}
+
 } // namespace
 
 // Helper function for HeuristicResolver::resolveDependentMember()
@@ -150,6 +246,11 @@ std::vector 
HeuristicResolver::resolveMemberExpr(
   if (ME->isArrow()) {
 BaseType = getPointeeType(BaseType);
   }
+
+  if 

[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-10 Thread Younan Zhang via cfe-commits


@@ -150,6 +246,11 @@ std::vector 
HeuristicResolver::resolveMemberExpr(
   if (ME->isArrow()) {
 BaseType = getPointeeType(BaseType);
   }
+
+  if (BaseType->isDependentType())

zyn0217 wrote:

I don't know if I should assume the non-nullity for `BaseType`: All of the 
construction points appear to create expressions with valid base types. Except 
for ASTImporter and ASTReader, where an empty expression may be created. But 
would we somehow end up resolving expressions created from these two places? I 
suppose we might encounter these inside a preamble, but I don't think this is 
where the heuristic resolver would work.

Anyway, I moved this statement after the non-null check. Thanks for spotting it!

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


[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-10 Thread Younan Zhang via cfe-commits

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

>From d73a8e2ee683e6812c21cb1de7363b14565a96d1 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 4 Nov 2023 18:43:58 +0800
Subject: [PATCH 1/2] [clangd] Resolve the dependent type from its single
 instantiation. Take 1

This is an enhancement to the HeuristicResolver, trying to extract
the deduced type from the single instantiation for a template. This
partially addresses the point #1 from
https://github.com/clangd/clangd/issues/1768.

This patch doesn't tackle CXXUnresolvedConstructExpr or similarities
since I feel that is more arduous and would prefer to leave it for
my future work.
---
 .../clangd/HeuristicResolver.cpp  | 101 ++
 .../clangd/unittests/XRefsTests.cpp   |  48 +
 2 files changed, 149 insertions(+)

diff --git a/clang-tools-extra/clangd/HeuristicResolver.cpp 
b/clang-tools-extra/clangd/HeuristicResolver.cpp
index 3c147b6b582bf0b..d3dced9b325367a 100644
--- a/clang-tools-extra/clangd/HeuristicResolver.cpp
+++ b/clang-tools-extra/clangd/HeuristicResolver.cpp
@@ -7,10 +7,14 @@
 
//===--===//
 
 #include "HeuristicResolver.h"
+#include "AST.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/CXXInheritance.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 
 namespace clang {
@@ -46,6 +50,98 @@ const Type *resolveDeclsToType(const std::vector ,
   return nullptr;
 }
 
+// Visitor that helps to extract deduced type from instantiated entities.
+// This merely performs the source location comparison against each Decl
+// until it finds a Decl with the same location as the
+// dependent one. Its associated type will then be extracted.
+struct InstantiatedDeclVisitor : RecursiveASTVisitor {
+
+  InstantiatedDeclVisitor(NamedDecl *DependentDecl) : 
DependentDecl(DependentDecl) {}
+
+  bool shouldVisitTemplateInstantiations() const { return true; }
+
+  bool shouldVisitLambdaBody() const { return true; }
+
+  bool shouldVisitImplicitCode() const { return true; }
+
+  template 
+  bool onDeclVisited(D *MaybeInstantiated) {
+if (MaybeInstantiated->getDeclContext()->isDependentContext())
+  return true;
+auto *Dependent = dyn_cast(DependentDecl);
+if (!Dependent)
+  return true;
+auto LHS = MaybeInstantiated->getTypeSourceInfo(),
+ RHS = Dependent->getTypeSourceInfo();
+if (!LHS || !RHS)
+  return true;
+if (LHS->getTypeLoc().getSourceRange() !=
+RHS->getTypeLoc().getSourceRange())
+  return true;
+DeducedType = MaybeInstantiated->getType();
+return false;
+  }
+
+  bool VisitFieldDecl(FieldDecl *FD) {
+return onDeclVisited(FD);
+  }
+
+  bool VisitVarDecl(VarDecl *VD) {
+return onDeclVisited(VD);
+  }
+
+  NamedDecl *DependentDecl;
+  QualType DeducedType;
+};
+
+/// Attempt to resolve the dependent type from the surrounding context for 
which
+/// a single instantiation is available.
+const Type *
+resolveTypeFromInstantiatedTemplate(const CXXDependentScopeMemberExpr *Expr) {
+  if (Expr->isImplicitAccess())
+return nullptr;
+
+  auto *Base = Expr->getBase();
+  NamedDecl *ND = nullptr;
+  if (auto *CXXMember = dyn_cast(Base))
+ND = CXXMember->getMemberDecl();
+
+  if (auto *DRExpr = dyn_cast(Base))
+ND = DRExpr->getFoundDecl();
+
+  // FIXME: Handle CXXUnresolvedConstructExpr. This kind of type doesn't have
+  // available Decls to be matched against. Which inhibits the current 
heuristic
+  // from resolving expressions such as `T().fo^o()`, where T is a
+  // single-instantiated template parameter.
+  if (!ND)
+return nullptr;
+
+  NamedDecl *Instantiation = nullptr;
+
+  // Find out a single instantiation that we can start with. The enclosing
+  // context for the current Decl might not be a templated entity (e.g. a 
member
+  // function inside a class template), hence we shall walk up the decl
+  // contexts first.
+  for (auto *EnclosingContext = ND->getDeclContext(); EnclosingContext;
+   EnclosingContext = EnclosingContext->getParent()) {
+if (auto *ND = dyn_cast(EnclosingContext)) {
+  Instantiation = getOnlyInstantiation(ND);
+  if (Instantiation)
+break;
+}
+  }
+
+  if (!Instantiation)
+return nullptr;
+
+  // This will traverse down the instantiation entity, visit each Decl, and
+  // extract the deduced type for the undetermined Decl `ND`.
+  InstantiatedDeclVisitor Visitor(ND);
+  Visitor.TraverseDecl(Instantiation);
+
+  return Visitor.DeducedType.getTypePtrOrNull();
+}
+
 } // namespace
 
 // Helper function for HeuristicResolver::resolveDependentMember()
@@ -150,6 +246,11 @@ std::vector 
HeuristicResolver::resolveMemberExpr(
   if (ME->isArrow()) {
 BaseType = getPointeeType(BaseType);
   }
+
+  if 

[clang-tools-extra] [llvm] [clang] [LLVM] Add IRNormalizer Pass (PR #68176)

2023-11-10 Thread Michal Paszkowski via cfe-commits

michalpaszkowski wrote:

[Here are the 
slides](https://llvm.org/devmtg/2019-10/slides/Paszkowski-LLVMCanon.pdf) that 
were presented at the LLVM Dev Meeting in 2019. It might be useful to include 
the link in the commit message for reference.

@nikic Thanks for catching more things in the review! Especially the 
commutative ordering of operands/arguments.

When it comes to including hashes in the naming algorithm (renaming is 
controlled using an option for already named values), the ideas is that by just 
looking at an instruction further down (a use) you can tell whether any inputs 
are different. And the other way around, by looking at initial instructions you 
can see how their "output footprint" has changed after transformations.

The example below is a bit outdated, but reflects the general idea we had when 
considering naming algorithms:
https://github.com/llvm/llvm-project/assets/13875746/fdb85b98-bce9-48df-91c0-35ffd115bae0;>
https://github.com/llvm/llvm-project/assets/13875746/24d74cf1-ad21-47c0-9057-6065c7a4f472;>


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


[clang-tools-extra] [llvm] [clang] [InstCombine] Convert or concat to fshl if opposite or concat exists (PR #68502)

2023-11-10 Thread via cfe-commits

HaohaiWen wrote:

I'd like to merge it if no any more comments.

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


[clang] [clang][analyzer] Restrict 'fopen' modeling to POSIX versions in SimpleStreamChecker (PR #72016)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




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

Author: Ben Shi (benshi001)


Changes



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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp (+21-29) 
- (modified) clang/test/Analysis/stream-non-posix-function.c (+1) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
index 32d95e944195390..d78761b0ea4553b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
@@ -1,4 +1,4 @@
-//===-- SimpleStreamChecker.cpp -*- 
C++ -*--//
+//===-- SimpleStreamChecker.cpp ---*- C++ 
-*--//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -31,7 +31,7 @@ typedef SmallVector SymbolVector;
 struct StreamState {
 private:
   enum Kind { Opened, Closed } K;
-  StreamState(Kind InK) : K(InK) { }
+  StreamState(Kind InK) : K(InK) {}
 
 public:
   bool isOpened() const { return K == Opened; }
@@ -40,25 +40,19 @@ struct StreamState {
   static StreamState getOpened() { return StreamState(Opened); }
   static StreamState getClosed() { return StreamState(Closed); }
 
-  bool operator==(const StreamState ) const {
-return K == X.K;
-  }
-  void Profile(llvm::FoldingSetNodeID ) const {
-ID.AddInteger(K);
-  }
+  bool operator==(const StreamState ) const { return K == X.K; }
+  void Profile(llvm::FoldingSetNodeID ) const { ID.AddInteger(K); }
 };
 
-class SimpleStreamChecker : public Checker {
+class SimpleStreamChecker
+: public Checker {
   CallDescription OpenFn, CloseFn;
 
   std::unique_ptr DoubleCloseBugType;
   std::unique_ptr LeakBugType;
 
-  void reportDoubleClose(SymbolRef FileDescSym,
- const CallEvent ,
+  void reportDoubleClose(SymbolRef FileDescSym, const CallEvent ,
  CheckerContext ) const;
 
   void reportLeaks(ArrayRef LeakedStreams, CheckerContext ,
@@ -78,9 +72,9 @@ class SimpleStreamChecker : public Checker 
LeakedStreams,
   }
 }
 
-bool SimpleStreamChecker::guaranteedNotToCloseFile(const CallEvent ) 
const{
+bool SimpleStreamChecker::guaranteedNotToCloseFile(
+const CallEvent ) const {
   // If it's not in a system header, assume it might close a file.
   if (!Call.isInSystemHeader())
 return false;
@@ -229,11 +223,9 @@ bool SimpleStreamChecker::guaranteedNotToCloseFile(const 
CallEvent ) const{
 
 // If the pointer we are tracking escaped, do not track the symbol as
 // we cannot reason about it anymore.
-ProgramStateRef
-SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
-const InvalidatedSymbols ,
-const CallEvent *Call,
-PointerEscapeKind Kind) const {
+ProgramStateRef SimpleStreamChecker::checkPointerEscape(
+ProgramStateRef State, const InvalidatedSymbols ,
+const CallEvent *Call, PointerEscapeKind Kind) const {
   // If we know that the call cannot close a file, there is nothing to do.
   if (Kind == PSK_DirectEscapeOnCall && guaranteedNotToCloseFile(*Call)) {
 return State;
diff --git a/clang/test/Analysis/stream-non-posix-function.c 
b/clang/test/Analysis/stream-non-posix-function.c
index 70b3ab25d026532..ab7c60a2c6c76e6 100644
--- a/clang/test/Analysis/stream-non-posix-function.c
+++ b/clang/test/Analysis/stream-non-posix-function.c
@@ -1,4 +1,5 @@
 // RUN: %clang_analyze_cc1 -fno-builtin 
-analyzer-checker=core,alpha.unix.Stream -verify %s
+// RUN: %clang_analyze_cc1 -fno-builtin 
-analyzer-checker=core,alpha.unix.SimpleStream -verify %s
 // expected-no-diagnostics
 
 typedef struct _FILE FILE;

``




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


[clang] [clang][analyzer] Restrict 'fopen' modeling to POSIX versions in SimpleStreamChecker (PR #72016)

2023-11-10 Thread Ben Shi via cfe-commits

https://github.com/benshi001 created 
https://github.com/llvm/llvm-project/pull/72016

None

>From 327374741e5b73943a78879c0425eaf1abac1273 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Sat, 11 Nov 2023 11:31:57 +0800
Subject: [PATCH] [clang][analyzer] Restrict 'fopen' modeling to POSIX versions
 in SimpleStreamChecker

---
 .../Checkers/SimpleStreamChecker.cpp  | 50 ---
 .../test/Analysis/stream-non-posix-function.c |  1 +
 2 files changed, 22 insertions(+), 29 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
index 32d95e944195390..d78761b0ea4553b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
@@ -1,4 +1,4 @@
-//===-- SimpleStreamChecker.cpp -*- 
C++ -*--//
+//===-- SimpleStreamChecker.cpp ---*- C++ 
-*--//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -31,7 +31,7 @@ typedef SmallVector SymbolVector;
 struct StreamState {
 private:
   enum Kind { Opened, Closed } K;
-  StreamState(Kind InK) : K(InK) { }
+  StreamState(Kind InK) : K(InK) {}
 
 public:
   bool isOpened() const { return K == Opened; }
@@ -40,25 +40,19 @@ struct StreamState {
   static StreamState getOpened() { return StreamState(Opened); }
   static StreamState getClosed() { return StreamState(Closed); }
 
-  bool operator==(const StreamState ) const {
-return K == X.K;
-  }
-  void Profile(llvm::FoldingSetNodeID ) const {
-ID.AddInteger(K);
-  }
+  bool operator==(const StreamState ) const { return K == X.K; }
+  void Profile(llvm::FoldingSetNodeID ) const { ID.AddInteger(K); }
 };
 
-class SimpleStreamChecker : public Checker {
+class SimpleStreamChecker
+: public Checker {
   CallDescription OpenFn, CloseFn;
 
   std::unique_ptr DoubleCloseBugType;
   std::unique_ptr LeakBugType;
 
-  void reportDoubleClose(SymbolRef FileDescSym,
- const CallEvent ,
+  void reportDoubleClose(SymbolRef FileDescSym, const CallEvent ,
  CheckerContext ) const;
 
   void reportLeaks(ArrayRef LeakedStreams, CheckerContext ,
@@ -78,9 +72,9 @@ class SimpleStreamChecker : public Checker 
LeakedStreams,
   }
 }
 
-bool SimpleStreamChecker::guaranteedNotToCloseFile(const CallEvent ) 
const{
+bool SimpleStreamChecker::guaranteedNotToCloseFile(
+const CallEvent ) const {
   // If it's not in a system header, assume it might close a file.
   if (!Call.isInSystemHeader())
 return false;
@@ -229,11 +223,9 @@ bool SimpleStreamChecker::guaranteedNotToCloseFile(const 
CallEvent ) const{
 
 // If the pointer we are tracking escaped, do not track the symbol as
 // we cannot reason about it anymore.
-ProgramStateRef
-SimpleStreamChecker::checkPointerEscape(ProgramStateRef State,
-const InvalidatedSymbols ,
-const CallEvent *Call,
-PointerEscapeKind Kind) const {
+ProgramStateRef SimpleStreamChecker::checkPointerEscape(
+ProgramStateRef State, const InvalidatedSymbols ,
+const CallEvent *Call, PointerEscapeKind Kind) const {
   // If we know that the call cannot close a file, there is nothing to do.
   if (Kind == PSK_DirectEscapeOnCall && guaranteedNotToCloseFile(*Call)) {
 return State;
diff --git a/clang/test/Analysis/stream-non-posix-function.c 
b/clang/test/Analysis/stream-non-posix-function.c
index 70b3ab25d026532..ab7c60a2c6c76e6 100644
--- a/clang/test/Analysis/stream-non-posix-function.c
+++ b/clang/test/Analysis/stream-non-posix-function.c
@@ -1,4 +1,5 @@
 // RUN: %clang_analyze_cc1 -fno-builtin 
-analyzer-checker=core,alpha.unix.Stream -verify %s
+// RUN: %clang_analyze_cc1 -fno-builtin 
-analyzer-checker=core,alpha.unix.SimpleStream -verify %s
 // expected-no-diagnostics
 
 typedef struct _FILE FILE;

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


[llvm] [clang-tools-extra] [clang] [LLVM] Add IRNormalizer Pass (PR #68176)

2023-11-10 Thread Justin Fargnoli via cfe-commits

https://github.com/justinfargnoli updated 
https://github.com/llvm/llvm-project/pull/68176

>From f792a030ac1761a96176332fea906cd2d1826c7b Mon Sep 17 00:00:00 2001
From: justinfargnoli 
Date: Sat, 12 Aug 2023 10:58:45 -0700
Subject: [PATCH 01/30] Add IRCanonicalizer.cpp

---
 llvm/lib/Transforms/Utils/CMakeLists.txt  |   1 +
 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp | 632 ++
 2 files changed, 633 insertions(+)
 create mode 100644 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp

diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt 
b/llvm/lib/Transforms/Utils/CMakeLists.txt
index a870071f3f641dc..7866e7a8c09c3be 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -34,6 +34,7 @@ add_llvm_component_library(LLVMTransformUtils
   InjectTLIMappings.cpp
   InstructionNamer.cpp
   IntegerDivision.cpp
+  IRCanonicalizer.cpp
   LCSSA.cpp
   LibCallsShrinkWrap.cpp
   Local.cpp
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
new file mode 100644
index 000..58e2dce0b96685b
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -0,0 +1,632 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer : public FunctionPass {
+public:
+  static char ID;
+
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  /// Constructor for the IRCanonicalizer.
+  IRCanonicalizer() : FunctionPass(ID) {}
+
+  bool runOnFunction(Function ) override;
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+char IRCanonicalizer::ID = 0;
+static RegisterPass X("canon", "Canonicalize the IR",
+   false /* Only looks at CFG */,
+   false /* Analysis Pass */);
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions 

[llvm] [clang-tools-extra] [clang] [LLVM] Add IRNormalizer Pass (PR #68176)

2023-11-10 Thread Justin Fargnoli via cfe-commits

https://github.com/justinfargnoli updated 
https://github.com/llvm/llvm-project/pull/68176

>From f792a030ac1761a96176332fea906cd2d1826c7b Mon Sep 17 00:00:00 2001
From: justinfargnoli 
Date: Sat, 12 Aug 2023 10:58:45 -0700
Subject: [PATCH 01/29] Add IRCanonicalizer.cpp

---
 llvm/lib/Transforms/Utils/CMakeLists.txt  |   1 +
 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp | 632 ++
 2 files changed, 633 insertions(+)
 create mode 100644 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp

diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt 
b/llvm/lib/Transforms/Utils/CMakeLists.txt
index a870071f3f641dc..7866e7a8c09c3be 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -34,6 +34,7 @@ add_llvm_component_library(LLVMTransformUtils
   InjectTLIMappings.cpp
   InstructionNamer.cpp
   IntegerDivision.cpp
+  IRCanonicalizer.cpp
   LCSSA.cpp
   LibCallsShrinkWrap.cpp
   Local.cpp
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
new file mode 100644
index 000..58e2dce0b96685b
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -0,0 +1,632 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer : public FunctionPass {
+public:
+  static char ID;
+
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  /// Constructor for the IRCanonicalizer.
+  IRCanonicalizer() : FunctionPass(ID) {}
+
+  bool runOnFunction(Function ) override;
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+char IRCanonicalizer::ID = 0;
+static RegisterPass X("canon", "Canonicalize the IR",
+   false /* Only looks at CFG */,
+   false /* Analysis Pass */);
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions 

[llvm] [clang] Add RunTimeLang to Class and Enumeration DIBuilder functions (PR #72011)

2023-11-10 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff bdd396f353582b50d0a9af5e5e809aeacc2848bf 
82e6fefc0df010539519fefcae22c49d6c2a1459 -- clang/lib/CodeGen/CGDebugInfo.cpp 
llvm/include/llvm/IR/DIBuilder.h llvm/lib/IR/DIBuilder.cpp 
llvm/lib/IR/DebugInfo.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index 9c8646c8a544..884e99300d2f 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -581,7 +581,8 @@ namespace llvm {
 /// \param UnderlyingType Underlying type of a C++11/ObjC fixed enum.
 /// \param RunTimeLang  Optional parameter, Objective-C runtime version.
 /// \param UniqueIdentifier A unique identifier for the enum.
-/// \param IsScoped Boolean flag indicate if this is C++11/ObjC 'enum 
class'.
+/// \param IsScoped Boolean flag indicate if this is C++11/ObjC 'enum
+/// class'.
 DICompositeType *createEnumerationType(
 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
 uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,

``




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


[clang] [clang-format][NFC] Simplify parseBracedList() (PR #72010)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes



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


2 Files Affected:

- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+14-22) 
- (modified) clang/lib/Format/UnwrappedLineParser.h (+1-2) 


``diff
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 018bc6c165485e2..e6a333fdc4e42ce 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2017,8 +2017,7 @@ void UnwrappedLineParser::parseStructuralElement(
   } else if (Style.Language == FormatStyle::LK_Proto &&
  FormatTok->is(tok::less)) {
 nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
+parseBracedList();
   }
   break;
 case tok::l_square:
@@ -2379,9 +2378,10 @@ bool UnwrappedLineParser::tryToParseChildBlock() {
   return true;
 }
 
-bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
-  bool IsEnum,
-  tok::TokenKind ClosingBraceKind) {
+bool UnwrappedLineParser::parseBracedList(bool IsEnum) {
+  const auto *OpeningBrace = FormatTok->getPreviousNonComment();
+  const bool IsAngleBracket = OpeningBrace && OpeningBrace->is(tok::less);
+
   bool HasError = false;
 
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
@@ -2403,7 +2403,7 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
 parseChildBlock();
   }
 }
-if (FormatTok->Tok.getKind() == ClosingBraceKind) {
+if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
   if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
 addUnwrappedLine();
   nextToken();
@@ -2434,14 +2434,9 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
   parseBracedList();
   break;
 case tok::less:
-  if (Style.Language == FormatStyle::LK_Proto ||
-  ClosingBraceKind == tok::greater) {
-nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
-  } else {
-nextToken();
-  }
+  nextToken();
+  if (IsAngleBracket)
+parseBracedList();
   break;
 case tok::semi:
   // JavaScript (or more precisely TypeScript) can have semicolons in 
braced
@@ -2453,8 +2448,8 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
 break;
   }
   HasError = true;
-  if (!ContinueOnSemicolons)
-return !HasError;
+  if (!IsEnum)
+return false;
   nextToken();
   break;
 case tok::comma:
@@ -3618,8 +3613,7 @@ void UnwrappedLineParser::parseConstraintExpression() {
 return;
 
   nextToken();
-  parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-  /*ClosingBraceKind=*/tok::greater);
+  parseBracedList();
   break;
 
 default:
@@ -3650,8 +3644,7 @@ void UnwrappedLineParser::parseConstraintExpression() {
   nextToken();
   if (FormatTok->is(tok::less)) {
 nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
+parseBracedList();
   }
   TopLevelParensAllowed = false;
   break;
@@ -3732,8 +3725,7 @@ bool UnwrappedLineParser::parseEnum() {
 addUnwrappedLine();
 Line->Level += 1;
   }
-  bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true,
-   /*IsEnum=*/true);
+  bool HasError = !parseBracedList(/*IsEnum=*/true);
   if (!Style.AllowShortEnumsOnASingleLine)
 Line->Level -= 1;
   if (HasError) {
diff --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index c31f25fdd8f83c9..61ec04578955ce6 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -151,8 +151,7 @@ class UnwrappedLineParser {
   bool *HasDoWhile = nullptr,
   bool *HasLabel = nullptr);
   bool tryToParseBracedList();
-  bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false,
-   tok::TokenKind ClosingBraceKind = tok::r_brace);
+  bool parseBracedList(bool IsEnum = false);
   bool parseParens(TokenType AmpAmpTokenType = TT_Unknown);
   void parseSquare(bool LambdaIntroducer = false);
   void keepAncestorBraces();

``




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


[clang] [llvm] Add RunTimeLang to Class and Enumeration DIBuilder functions (PR #72011)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-ir

Author: Augusto Noronha (augusto2112)


Changes

RunTimeLang is already supported by DICompositeType, and already used by 
structs and unions. Add a new parameter in the class and enumeration create 
methods, so they can use the RunTimeLang attribute as well.

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


4 Files Affected:

- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+3-3) 
- (modified) llvm/include/llvm/IR/DIBuilder.h (+6-4) 
- (modified) llvm/lib/IR/DIBuilder.cpp (+11-8) 
- (modified) llvm/lib/IR/DebugInfo.cpp (+6-7) 


``diff
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 84a166d3ac3659c..fc8088da998ddbd 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3385,9 +3385,9 @@ llvm::DIType *CGDebugInfo::CreateTypeDefinition(const 
EnumType *Ty) {
   unsigned Line = getLineNumber(ED->getLocation());
   llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
   llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
-  return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
-Line, Size, Align, EltArray, ClassTy,
-Identifier, ED->isScoped());
+  return DBuilder.createEnumerationType(
+  EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, 
ClassTy,
+  /*RunTimeLang=*/0, Identifier, ED->isScoped());
 }
 
 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index ecd6dd7b0a4f822..9c8646c8a544b74 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -424,6 +424,7 @@ namespace llvm {
 /// \param OffsetInBits Member offset.
 /// \param FlagsFlags to encode member attribute, e.g. private
 /// \param Elements class members.
+/// \param RunTimeLang  Optional parameter, Objective-C runtime version.
 /// \param VTableHolder Debug info of the base class that contains vtable
 /// for this type. This is used in
 /// DW_AT_containing_type. See DWARF documentation
@@ -434,8 +435,8 @@ namespace llvm {
 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
-DIType *VTableHolder = nullptr, MDNode *TemplateParms = nullptr,
-StringRef UniqueIdentifier = "");
+unsigned RunTimeLang = 0, DIType *VTableHolder = nullptr,
+MDNode *TemplateParms = nullptr, StringRef UniqueIdentifier = "");
 
 /// Create debugging information entry for a struct.
 /// \param ScopeScope in which this struct is defined.
@@ -578,13 +579,14 @@ namespace llvm {
 /// \param AlignInBitsMember alignment.
 /// \param Elements   Enumeration elements.
 /// \param UnderlyingType Underlying type of a C++11/ObjC fixed enum.
+/// \param RunTimeLang  Optional parameter, Objective-C runtime version.
 /// \param UniqueIdentifier A unique identifier for the enum.
 /// \param IsScoped Boolean flag indicate if this is C++11/ObjC 'enum 
class'.
 DICompositeType *createEnumerationType(
 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
 uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
-DIType *UnderlyingType, StringRef UniqueIdentifier = "", bool IsScoped 
= false);
-
+DIType *UnderlyingType, unsigned RunTimeLang = 0,
+StringRef UniqueIdentifier = "", bool IsScoped = false);
 /// Create debugging information entry for a set.
 /// \param Scope  Scope in which this set is defined.
 /// \param Name   Set name.
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 1ce8c17f8a880f6..b466018e9a7d998 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -477,14 +477,15 @@ DICompositeType *DIBuilder::createClassType(
 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
-DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
+unsigned RunTimeLang, DIType *VTableHolder, MDNode *TemplateParams,
+StringRef UniqueIdentifier) {
   assert((!Context || isa(Context)) &&
  "createClassType should be called with a valid Context");
 
   auto *R = DICompositeType::get(
   VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
   getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
-  OffsetInBits, Flags, Elements, 0, VTableHolder,
+  OffsetInBits, Flags, 

[clang] [llvm] Add RunTimeLang to Class and Enumeration DIBuilder functions (PR #72011)

2023-11-10 Thread Augusto Noronha via cfe-commits

https://github.com/augusto2112 created 
https://github.com/llvm/llvm-project/pull/72011

RunTimeLang is already supported by DICompositeType, and already used by 
structs and unions. Add a new parameter in the class and enumeration create 
methods, so they can use the RunTimeLang attribute as well.

>From 82e6fefc0df010539519fefcae22c49d6c2a1459 Mon Sep 17 00:00:00 2001
From: Augusto Noronha 
Date: Fri, 10 Nov 2023 17:42:47 -0800
Subject: [PATCH] Add RunTimeLang to Class and Enumeration DIBuilder functions

RunTimeLang is already supported by DICompositeType, and already used by
structs and unions. Add a new parameter in the class and enumeration
create methods, so they can use the RunTimeLang attribute as well.
---
 clang/lib/CodeGen/CGDebugInfo.cpp |  6 +++---
 llvm/include/llvm/IR/DIBuilder.h  | 10 ++
 llvm/lib/IR/DIBuilder.cpp | 19 +++
 llvm/lib/IR/DebugInfo.cpp | 13 ++---
 4 files changed, 26 insertions(+), 22 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 84a166d3ac3659c..fc8088da998ddbd 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3385,9 +3385,9 @@ llvm::DIType *CGDebugInfo::CreateTypeDefinition(const 
EnumType *Ty) {
   unsigned Line = getLineNumber(ED->getLocation());
   llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
   llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
-  return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
-Line, Size, Align, EltArray, ClassTy,
-Identifier, ED->isScoped());
+  return DBuilder.createEnumerationType(
+  EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, 
ClassTy,
+  /*RunTimeLang=*/0, Identifier, ED->isScoped());
 }
 
 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index ecd6dd7b0a4f822..9c8646c8a544b74 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -424,6 +424,7 @@ namespace llvm {
 /// \param OffsetInBits Member offset.
 /// \param FlagsFlags to encode member attribute, e.g. private
 /// \param Elements class members.
+/// \param RunTimeLang  Optional parameter, Objective-C runtime version.
 /// \param VTableHolder Debug info of the base class that contains vtable
 /// for this type. This is used in
 /// DW_AT_containing_type. See DWARF documentation
@@ -434,8 +435,8 @@ namespace llvm {
 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
-DIType *VTableHolder = nullptr, MDNode *TemplateParms = nullptr,
-StringRef UniqueIdentifier = "");
+unsigned RunTimeLang = 0, DIType *VTableHolder = nullptr,
+MDNode *TemplateParms = nullptr, StringRef UniqueIdentifier = "");
 
 /// Create debugging information entry for a struct.
 /// \param ScopeScope in which this struct is defined.
@@ -578,13 +579,14 @@ namespace llvm {
 /// \param AlignInBitsMember alignment.
 /// \param Elements   Enumeration elements.
 /// \param UnderlyingType Underlying type of a C++11/ObjC fixed enum.
+/// \param RunTimeLang  Optional parameter, Objective-C runtime version.
 /// \param UniqueIdentifier A unique identifier for the enum.
 /// \param IsScoped Boolean flag indicate if this is C++11/ObjC 'enum 
class'.
 DICompositeType *createEnumerationType(
 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
 uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
-DIType *UnderlyingType, StringRef UniqueIdentifier = "", bool IsScoped 
= false);
-
+DIType *UnderlyingType, unsigned RunTimeLang = 0,
+StringRef UniqueIdentifier = "", bool IsScoped = false);
 /// Create debugging information entry for a set.
 /// \param Scope  Scope in which this set is defined.
 /// \param Name   Set name.
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 1ce8c17f8a880f6..b466018e9a7d998 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -477,14 +477,15 @@ DICompositeType *DIBuilder::createClassType(
 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
-DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
+unsigned RunTimeLang, DIType *VTableHolder, MDNode *TemplateParams,
+StringRef UniqueIdentifier) {
   

[clang] [clang-format][NFC] Simplify parseBracedList() (PR #72010)

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

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

None

>From f3f303d80a40b9ce8a13721cfa108b4094b8b2c3 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 10 Nov 2023 17:34:06 -0800
Subject: [PATCH] [clang-format][NFC] Simplify parseBracedList()

---
 clang/lib/Format/UnwrappedLineParser.cpp | 36 +---
 clang/lib/Format/UnwrappedLineParser.h   |  3 +-
 2 files changed, 15 insertions(+), 24 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 018bc6c165485e2..e6a333fdc4e42ce 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2017,8 +2017,7 @@ void UnwrappedLineParser::parseStructuralElement(
   } else if (Style.Language == FormatStyle::LK_Proto &&
  FormatTok->is(tok::less)) {
 nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
+parseBracedList();
   }
   break;
 case tok::l_square:
@@ -2379,9 +2378,10 @@ bool UnwrappedLineParser::tryToParseChildBlock() {
   return true;
 }
 
-bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
-  bool IsEnum,
-  tok::TokenKind ClosingBraceKind) {
+bool UnwrappedLineParser::parseBracedList(bool IsEnum) {
+  const auto *OpeningBrace = FormatTok->getPreviousNonComment();
+  const bool IsAngleBracket = OpeningBrace && OpeningBrace->is(tok::less);
+
   bool HasError = false;
 
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
@@ -2403,7 +2403,7 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
 parseChildBlock();
   }
 }
-if (FormatTok->Tok.getKind() == ClosingBraceKind) {
+if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
   if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
 addUnwrappedLine();
   nextToken();
@@ -2434,14 +2434,9 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
   parseBracedList();
   break;
 case tok::less:
-  if (Style.Language == FormatStyle::LK_Proto ||
-  ClosingBraceKind == tok::greater) {
-nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
-  } else {
-nextToken();
-  }
+  nextToken();
+  if (IsAngleBracket)
+parseBracedList();
   break;
 case tok::semi:
   // JavaScript (or more precisely TypeScript) can have semicolons in 
braced
@@ -2453,8 +2448,8 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
 break;
   }
   HasError = true;
-  if (!ContinueOnSemicolons)
-return !HasError;
+  if (!IsEnum)
+return false;
   nextToken();
   break;
 case tok::comma:
@@ -3618,8 +3613,7 @@ void UnwrappedLineParser::parseConstraintExpression() {
 return;
 
   nextToken();
-  parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-  /*ClosingBraceKind=*/tok::greater);
+  parseBracedList();
   break;
 
 default:
@@ -3650,8 +3644,7 @@ void UnwrappedLineParser::parseConstraintExpression() {
   nextToken();
   if (FormatTok->is(tok::less)) {
 nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
+parseBracedList();
   }
   TopLevelParensAllowed = false;
   break;
@@ -3732,8 +3725,7 @@ bool UnwrappedLineParser::parseEnum() {
 addUnwrappedLine();
 Line->Level += 1;
   }
-  bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true,
-   /*IsEnum=*/true);
+  bool HasError = !parseBracedList(/*IsEnum=*/true);
   if (!Style.AllowShortEnumsOnASingleLine)
 Line->Level -= 1;
   if (HasError) {
diff --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index c31f25fdd8f83c9..61ec04578955ce6 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -151,8 +151,7 @@ class UnwrappedLineParser {
   bool *HasDoWhile = nullptr,
   bool *HasLabel = nullptr);
   bool tryToParseBracedList();
-  bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false,
-   tok::TokenKind ClosingBraceKind = tok::r_brace);
+  bool parseBracedList(bool IsEnum = false);
   bool parseParens(TokenType AmpAmpTokenType = TT_Unknown);
   void parseSquare(bool LambdaIntroducer = false);
   void keepAncestorBraces();

___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[clang] [clang-tools-extra] [llvm] [LLVM] Add IRNormalizer Pass (PR #68176)

2023-11-10 Thread Justin Fargnoli via cfe-commits

https://github.com/justinfargnoli updated 
https://github.com/llvm/llvm-project/pull/68176

>From f792a030ac1761a96176332fea906cd2d1826c7b Mon Sep 17 00:00:00 2001
From: justinfargnoli 
Date: Sat, 12 Aug 2023 10:58:45 -0700
Subject: [PATCH 01/28] Add IRCanonicalizer.cpp

---
 llvm/lib/Transforms/Utils/CMakeLists.txt  |   1 +
 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp | 632 ++
 2 files changed, 633 insertions(+)
 create mode 100644 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp

diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt 
b/llvm/lib/Transforms/Utils/CMakeLists.txt
index a870071f3f641dc..7866e7a8c09c3be 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -34,6 +34,7 @@ add_llvm_component_library(LLVMTransformUtils
   InjectTLIMappings.cpp
   InstructionNamer.cpp
   IntegerDivision.cpp
+  IRCanonicalizer.cpp
   LCSSA.cpp
   LibCallsShrinkWrap.cpp
   Local.cpp
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
new file mode 100644
index 000..58e2dce0b96685b
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -0,0 +1,632 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer : public FunctionPass {
+public:
+  static char ID;
+
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  /// Constructor for the IRCanonicalizer.
+  IRCanonicalizer() : FunctionPass(ID) {}
+
+  bool runOnFunction(Function ) override;
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+char IRCanonicalizer::ID = 0;
+static RegisterPass X("canon", "Canonicalize the IR",
+   false /* Only looks at CFG */,
+   false /* Analysis Pass */);
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions 

[clang] [Clang][Sema] Differentiate between partial/explicit specializations when diagnosing unexpanded packs (PR #72015)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Krystian Stasiowski (sdkrystian)


Changes



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


4 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3-3) 
- (modified) clang/include/clang/Sema/Sema.h (+3) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+6-2) 
- (modified) clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp (+32-3) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4614324babb1c91..0c8f07b095b1eaa 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5655,9 +5655,9 @@ def err_unexpanded_parameter_pack : Error<
   "%select{expression|base type|declaration type|data member type|bit-field "
   "size|static assertion|fixed underlying type|enumerator value|"
   "using declaration|friend declaration|qualifier|initializer|default 
argument|"
-  "non-type template parameter type|exception type|partial specialization|"
-  "__if_exists name|__if_not_exists name|lambda|block|type constraint|"
-  "requirement|requires clause}0 "
+  "non-type template parameter type|exception type|explicit specialization|"
+  "partial specialization|__if_exists name|__if_not_exists name|lambda|block|"
+  "type constraint|requirement|requires clause}0 "
   "contains%plural{0: an|:}1 unexpanded parameter pack"
   "%plural{0:|1: %2|2:s %2 and %3|:s %2, %3, ...}1">;
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index f69f366c1750918..e59827b8c281ea1 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8839,6 +8839,9 @@ class Sema final {
 /// The type of an exception.
 UPPC_ExceptionType,
 
+/// Explicit specialization.
+UPPC_ExplicitSpecialization,
+
 /// Partial specialization.
 UPPC_PartialSpecialization,
 
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 6865e04b94b2050..766ebd90fded0c4 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4559,7 +4559,9 @@ DeclResult Sema::ActOnVarTemplateSpecialization(
   // Check for unexpanded parameter packs in any of the template arguments.
   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
-UPPC_PartialSpecialization))
+IsPartialSpecialization
+? UPPC_PartialSpecialization
+: UPPC_ExplicitSpecialization))
   return true;
 
   // Check that the template argument list is well-formed for this
@@ -8744,7 +8746,9 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   // Check for unexpanded parameter packs in any of the template arguments.
   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
-UPPC_PartialSpecialization))
+isPartialSpecialization
+? UPPC_PartialSpecialization
+: UPPC_ExplicitSpecialization))
   return true;
 
   // Check that the template argument list is well-formed for this
diff --git a/clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp 
b/clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
index 7536339c14a2e08..d00630b0258a734 100644
--- a/clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
+++ b/clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
@@ -369,9 +369,38 @@ void test_unexpanded_exprs(Types ...values) {
   void f(int arg = values); // expected-error{{default argument contains 
unexpanded parameter pack 'values'}}
 }
 
-// Test unexpanded parameter packs in partial specializations.
-template
-struct TestUnexpandedDecls; // expected-error{{partial 
specialization contains unexpanded parameter pack 'Types'}}
+// Test unexpanded parameter packs in partial/explicit specializations.
+namespace Specializations {
+  template
+  struct PrimaryClass;
+
+  template
+  constexpr int PrimaryVar = 0;
+
+  template
+  struct PrimaryClass; // expected-error{{partial specialization contains 
unexpanded parameter pack 'Ts'}}
+
+  template
+  constexpr int PrimaryVar = 0; // expected-error{{partial specialization 
contains unexpanded parameter pack 'Ts'}}
+
+  template
+  struct OuterClass {
+template
+struct InnerClass;
+template
+constexpr static int InnerVar = 0;
+
+template<>
+struct InnerClass; // expected-error{{explicit specialization contains 
unexpanded parameter pack 'Ts'}}
+template<>
+constexpr static int InnerVar = 0; // expected-error{{explicit 
specialization contains unexpanded parameter pack 'Ts'}}
+
+template
+struct InnerClass; 

[clang] [Clang][Sema] Differentiate between partial/explicit specializations when diagnosing unexpanded packs (PR #72015)

2023-11-10 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian created 
https://github.com/llvm/llvm-project/pull/72015

None

>From 394e2e0eed84f0102d194174a7c60048556c56dc Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 10 Nov 2023 20:51:12 -0500
Subject: [PATCH] [Clang] Differentiate between partial/explicit
 specializations when diagnosing unexpanded packs

---
 .../clang/Basic/DiagnosticSemaKinds.td|  6 ++--
 clang/include/clang/Sema/Sema.h   |  3 ++
 clang/lib/Sema/SemaTemplate.cpp   |  8 +++--
 .../CXX/temp/temp.decls/temp.variadic/p5.cpp  | 35 +--
 4 files changed, 44 insertions(+), 8 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4614324babb1c91..0c8f07b095b1eaa 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5655,9 +5655,9 @@ def err_unexpanded_parameter_pack : Error<
   "%select{expression|base type|declaration type|data member type|bit-field "
   "size|static assertion|fixed underlying type|enumerator value|"
   "using declaration|friend declaration|qualifier|initializer|default 
argument|"
-  "non-type template parameter type|exception type|partial specialization|"
-  "__if_exists name|__if_not_exists name|lambda|block|type constraint|"
-  "requirement|requires clause}0 "
+  "non-type template parameter type|exception type|explicit specialization|"
+  "partial specialization|__if_exists name|__if_not_exists name|lambda|block|"
+  "type constraint|requirement|requires clause}0 "
   "contains%plural{0: an|:}1 unexpanded parameter pack"
   "%plural{0:|1: %2|2:s %2 and %3|:s %2, %3, ...}1">;
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index f69f366c1750918..e59827b8c281ea1 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8839,6 +8839,9 @@ class Sema final {
 /// The type of an exception.
 UPPC_ExceptionType,
 
+/// Explicit specialization.
+UPPC_ExplicitSpecialization,
+
 /// Partial specialization.
 UPPC_PartialSpecialization,
 
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 6865e04b94b2050..766ebd90fded0c4 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4559,7 +4559,9 @@ DeclResult Sema::ActOnVarTemplateSpecialization(
   // Check for unexpanded parameter packs in any of the template arguments.
   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
-UPPC_PartialSpecialization))
+IsPartialSpecialization
+? UPPC_PartialSpecialization
+: UPPC_ExplicitSpecialization))
   return true;
 
   // Check that the template argument list is well-formed for this
@@ -8744,7 +8746,9 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   // Check for unexpanded parameter packs in any of the template arguments.
   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
-UPPC_PartialSpecialization))
+isPartialSpecialization
+? UPPC_PartialSpecialization
+: UPPC_ExplicitSpecialization))
   return true;
 
   // Check that the template argument list is well-formed for this
diff --git a/clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp 
b/clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
index 7536339c14a2e08..d00630b0258a734 100644
--- a/clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
+++ b/clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
@@ -369,9 +369,38 @@ void test_unexpanded_exprs(Types ...values) {
   void f(int arg = values); // expected-error{{default argument contains 
unexpanded parameter pack 'values'}}
 }
 
-// Test unexpanded parameter packs in partial specializations.
-template
-struct TestUnexpandedDecls; // expected-error{{partial 
specialization contains unexpanded parameter pack 'Types'}}
+// Test unexpanded parameter packs in partial/explicit specializations.
+namespace Specializations {
+  template
+  struct PrimaryClass;
+
+  template
+  constexpr int PrimaryVar = 0;
+
+  template
+  struct PrimaryClass; // expected-error{{partial specialization contains 
unexpanded parameter pack 'Ts'}}
+
+  template
+  constexpr int PrimaryVar = 0; // expected-error{{partial specialization 
contains unexpanded parameter pack 'Ts'}}
+
+  template
+  struct OuterClass {
+template
+struct InnerClass;
+template
+constexpr static int InnerVar = 0;
+
+template<>
+struct InnerClass; // expected-error{{explicit specialization contains 
unexpanded parameter pack 

[clang-tools-extra] [clangd] Let DefineOutline tweak create a definition from scratch (PR #71950)

2023-11-10 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

This implements clangd/clangd#445

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


[clang] 3bb7ecc - Revert "[Clang] Generate test checks (NFC)"

2023-11-10 Thread Shoaib Meenai via cfe-commits

Author: Shoaib Meenai
Date: 2023-11-10T17:08:35-08:00
New Revision: 3bb7ecc5a515d2ddd2708257096e14e3fe3b839d

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

LOG: Revert "[Clang] Generate test checks (NFC)"

This reverts commit cd7ba9f3d090afb5d3b15b0dcf379d15d1e11e33.

This is causing test failures on builds without assertions:

/data/users/smeenai/llvm-project/clang/test/Analysis/builtin_signbit.cpp:14:21: 
error: CHECK-BE32-NEXT: expected string not found in input
// CHECK-BE32-NEXT: entry:
^

Bots are also failing, e.g. 
https://lab.llvm.org/buildbot/#/builders/67/builds/13266/steps/7/logs/stdio

Added: 


Modified: 
clang/test/Analysis/builtin_signbit.cpp

Removed: 




diff  --git a/clang/test/Analysis/builtin_signbit.cpp 
b/clang/test/Analysis/builtin_signbit.cpp
index a0bf7a45be1302b..251391952f9c586 100644
--- a/clang/test/Analysis/builtin_signbit.cpp
+++ b/clang/test/Analysis/builtin_signbit.cpp
@@ -1,113 +1,46 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 3
 // RUN: %clang -target powerpc-linux-gnu -emit-llvm -S -mabi=ibmlongdouble \
-// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK-BE32
+// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-BE
 // RUN: %clang -target powerpc64-linux-gnu -emit-llvm -S -mabi=ibmlongdouble \
-// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK-BE64
+// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-BE
 // RUN: %clang -target powerpc64le-linux-gnu -emit-llvm -S -mabi=ibmlongdouble 
\
-// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK-LE
+// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-LE
 
 bool b;
 double d = -1.0;
 long double ld = -1.0L;
-// CHECK-BE32-LABEL: define dso_local void @_Z12test_signbitv(
-// CHECK-BE32-SAME: ) #[[ATTR0:[0-9]+]] {
-// CHECK-BE32-NEXT:  entry:
-// CHECK-BE32-NEXT:[[FROMBOOL:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
-// CHECK-BE32-NEXT:store i8 [[FROMBOOL]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP0:%.*]] = load ppc_fp128, ptr @ld, align 16
-// CHECK-BE32-NEXT:[[TMP1:%.*]] = bitcast ppc_fp128 [[TMP0]] to i128
-// CHECK-BE32-NEXT:[[TMP2:%.*]] = lshr i128 [[TMP1]], 64
-// CHECK-BE32-NEXT:[[TMP3:%.*]] = trunc i128 [[TMP2]] to i64
-// CHECK-BE32-NEXT:[[TMP4:%.*]] = icmp slt i64 [[TMP3]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL1:%.*]] = zext i1 [[TMP4]] to i8
-// CHECK-BE32-NEXT:store i8 [[FROMBOOL1]], ptr @b, align 1
-// CHECK-BE32-NEXT:store i8 0, ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP5:%.*]] = load double, ptr @d, align 8
-// CHECK-BE32-NEXT:[[CONV:%.*]] = fptrunc double [[TMP5]] to float
-// CHECK-BE32-NEXT:[[TMP6:%.*]] = bitcast float [[CONV]] to i32
-// CHECK-BE32-NEXT:[[TMP7:%.*]] = icmp slt i32 [[TMP6]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL2:%.*]] = zext i1 [[TMP7]] to i8
-// CHECK-BE32-NEXT:store i8 [[FROMBOOL2]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[FROMBOOL3:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
-// CHECK-BE32-NEXT:store i8 [[FROMBOOL3]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP8:%.*]] = load ppc_fp128, ptr @ld, align 16
-// CHECK-BE32-NEXT:[[TMP9:%.*]] = bitcast ppc_fp128 [[TMP8]] to i128
-// CHECK-BE32-NEXT:[[TMP10:%.*]] = lshr i128 [[TMP9]], 64
-// CHECK-BE32-NEXT:[[TMP11:%.*]] = trunc i128 [[TMP10]] to i64
-// CHECK-BE32-NEXT:[[TMP12:%.*]] = icmp slt i64 [[TMP11]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL4:%.*]] = zext i1 [[TMP12]] to i8
-// CHECK-BE32-NEXT:store i8 [[FROMBOOL4]], ptr @b, align 1
-// CHECK-BE32-NEXT:ret void
-//
-// CHECK-BE64-LABEL: define dso_local void @_Z12test_signbitv(
-// CHECK-BE64-SAME: ) #[[ATTR0:[0-9]+]] {
-// CHECK-BE64-NEXT:  entry:
-// CHECK-BE64-NEXT:[[FROMBOOL:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
-// CHECK-BE64-NEXT:store i8 [[FROMBOOL]], ptr @b, align 1
-// CHECK-BE64-NEXT:[[TMP0:%.*]] = load ppc_fp128, ptr @ld, align 16
-// CHECK-BE64-NEXT:[[TMP1:%.*]] = bitcast ppc_fp128 [[TMP0]] to i128
-// CHECK-BE64-NEXT:[[TMP2:%.*]] = lshr i128 [[TMP1]], 64
-// CHECK-BE64-NEXT:[[TMP3:%.*]] = trunc i128 [[TMP2]] to i64
-// CHECK-BE64-NEXT:[[TMP4:%.*]] = icmp slt i64 [[TMP3]], 0
-// CHECK-BE64-NEXT:[[FROMBOOL1:%.*]] = zext i1 [[TMP4]] to i8
-// CHECK-BE64-NEXT:store i8 [[FROMBOOL1]], ptr @b, align 1
-// CHECK-BE64-NEXT:store i8 0, ptr @b, align 1
-// CHECK-BE64-NEXT:  

[clang] 8ee07a4 - Revert "[IR] Mark lshr and ashr constant expressions as undesirable"

2023-11-10 Thread Shoaib Meenai via cfe-commits

Author: Shoaib Meenai
Date: 2023-11-10T17:08:35-08:00
New Revision: 8ee07a4be7f7d8654ecf25e7ce0a680975649544

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

LOG: Revert "[IR] Mark lshr and ashr constant expressions as undesirable"

This reverts commit 82f68a992b9f89036042d57a5f6345cb2925b2c1.

cd7ba9f3d090afb5d3b15b0dcf379d15d1e11e33 needs to be reverted to fix
test failures on builds without assertions, and this one needs to be
reverted first for that.

Added: 


Modified: 
clang/test/Analysis/builtin_signbit.cpp
llvm/lib/IR/Constants.cpp
llvm/test/CodeGen/AArch64/stack-tagging-initializer-merge.ll

Removed: 




diff  --git a/clang/test/Analysis/builtin_signbit.cpp 
b/clang/test/Analysis/builtin_signbit.cpp
index e02802c5a514b0b..a0bf7a45be1302b 100644
--- a/clang/test/Analysis/builtin_signbit.cpp
+++ b/clang/test/Analysis/builtin_signbit.cpp
@@ -12,72 +12,60 @@ long double ld = -1.0L;
 // CHECK-BE32-LABEL: define dso_local void @_Z12test_signbitv(
 // CHECK-BE32-SAME: ) #[[ATTR0:[0-9]+]] {
 // CHECK-BE32-NEXT:  entry:
-// CHECK-BE32-NEXT:[[TMP0:%.*]] = lshr i128 bitcast (ppc_fp128 
0xM3FF0 to i128), 64
-// CHECK-BE32-NEXT:[[TMP1:%.*]] = trunc i128 [[TMP0]] to i64
-// CHECK-BE32-NEXT:[[TMP2:%.*]] = icmp slt i64 [[TMP1]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL:%.*]] = zext i1 [[TMP2]] to i8
+// CHECK-BE32-NEXT:[[FROMBOOL:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP3:%.*]] = load ppc_fp128, ptr @ld, align 16
-// CHECK-BE32-NEXT:[[TMP4:%.*]] = bitcast ppc_fp128 [[TMP3]] to i128
-// CHECK-BE32-NEXT:[[TMP5:%.*]] = lshr i128 [[TMP4]], 64
-// CHECK-BE32-NEXT:[[TMP6:%.*]] = trunc i128 [[TMP5]] to i64
-// CHECK-BE32-NEXT:[[TMP7:%.*]] = icmp slt i64 [[TMP6]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL1:%.*]] = zext i1 [[TMP7]] to i8
+// CHECK-BE32-NEXT:[[TMP0:%.*]] = load ppc_fp128, ptr @ld, align 16
+// CHECK-BE32-NEXT:[[TMP1:%.*]] = bitcast ppc_fp128 [[TMP0]] to i128
+// CHECK-BE32-NEXT:[[TMP2:%.*]] = lshr i128 [[TMP1]], 64
+// CHECK-BE32-NEXT:[[TMP3:%.*]] = trunc i128 [[TMP2]] to i64
+// CHECK-BE32-NEXT:[[TMP4:%.*]] = icmp slt i64 [[TMP3]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL1:%.*]] = zext i1 [[TMP4]] to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL1]], ptr @b, align 1
 // CHECK-BE32-NEXT:store i8 0, ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP8:%.*]] = load double, ptr @d, align 8
-// CHECK-BE32-NEXT:[[CONV:%.*]] = fptrunc double [[TMP8]] to float
-// CHECK-BE32-NEXT:[[TMP9:%.*]] = bitcast float [[CONV]] to i32
-// CHECK-BE32-NEXT:[[TMP10:%.*]] = icmp slt i32 [[TMP9]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL2:%.*]] = zext i1 [[TMP10]] to i8
+// CHECK-BE32-NEXT:[[TMP5:%.*]] = load double, ptr @d, align 8
+// CHECK-BE32-NEXT:[[CONV:%.*]] = fptrunc double [[TMP5]] to float
+// CHECK-BE32-NEXT:[[TMP6:%.*]] = bitcast float [[CONV]] to i32
+// CHECK-BE32-NEXT:[[TMP7:%.*]] = icmp slt i32 [[TMP6]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL2:%.*]] = zext i1 [[TMP7]] to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL2]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP11:%.*]] = lshr i128 bitcast (ppc_fp128 
0xM3FF0 to i128), 64
-// CHECK-BE32-NEXT:[[TMP12:%.*]] = trunc i128 [[TMP11]] to i64
-// CHECK-BE32-NEXT:[[TMP13:%.*]] = icmp slt i64 [[TMP12]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL3:%.*]] = zext i1 [[TMP13]] to i8
+// CHECK-BE32-NEXT:[[FROMBOOL3:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL3]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP14:%.*]] = load ppc_fp128, ptr @ld, align 16
-// CHECK-BE32-NEXT:[[TMP15:%.*]] = bitcast ppc_fp128 [[TMP14]] to i128
-// CHECK-BE32-NEXT:[[TMP16:%.*]] = lshr i128 [[TMP15]], 64
-// CHECK-BE32-NEXT:[[TMP17:%.*]] = trunc i128 [[TMP16]] to i64
-// CHECK-BE32-NEXT:[[TMP18:%.*]] = icmp slt i64 [[TMP17]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL4:%.*]] = zext i1 [[TMP18]] to i8
+// CHECK-BE32-NEXT:[[TMP8:%.*]] = load ppc_fp128, ptr @ld, align 16
+// CHECK-BE32-NEXT:[[TMP9:%.*]] = bitcast ppc_fp128 [[TMP8]] to i128
+// CHECK-BE32-NEXT:[[TMP10:%.*]] = lshr i128 [[TMP9]], 64
+// CHECK-BE32-NEXT:[[TMP11:%.*]] = trunc i128 [[TMP10]] to i64
+// CHECK-BE32-NEXT:[[TMP12:%.*]] = icmp slt i64 [[TMP11]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL4:%.*]] = zext i1 [[TMP12]] to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL4]], ptr @b, align 1
 // 

[clang] bdd396f - [Analysis] Make test require asserts

2023-11-10 Thread Shoaib Meenai via cfe-commits

Author: Shoaib Meenai
Date: 2023-11-10T17:29:32-08:00
New Revision: bdd396f353582b50d0a9af5e5e809aeacc2848bf

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

LOG: [Analysis] Make test require asserts

This is a hacky fix to get the bots green, because just reverting the
original commit causes more failures. This should be replaced with a
proper fix by the author.

Added: 


Modified: 
clang/test/Analysis/builtin_signbit.cpp

Removed: 




diff  --git a/clang/test/Analysis/builtin_signbit.cpp 
b/clang/test/Analysis/builtin_signbit.cpp
index e02802c5a514b0b..c10aebbc8d176cc 100644
--- a/clang/test/Analysis/builtin_signbit.cpp
+++ b/clang/test/Analysis/builtin_signbit.cpp
@@ -5,6 +5,7 @@
 // RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK-BE64
 // RUN: %clang -target powerpc64le-linux-gnu -emit-llvm -S -mabi=ibmlongdouble 
\
 // RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK-LE
+// REQUIRES: asserts
 
 bool b;
 double d = -1.0;



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


[clang] c5dd1bb - Revert "Revert "[IR] Mark lshr and ashr constant expressions as undesirable""

2023-11-10 Thread Shoaib Meenai via cfe-commits

Author: Shoaib Meenai
Date: 2023-11-10T17:26:14-08:00
New Revision: c5dd1bbcc37e8811e7c6050159014d084eac6438

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

LOG: Revert "Revert "[IR] Mark lshr and ashr constant expressions as 
undesirable""

This reverts commit 8ee07a4be7f7d8654ecf25e7ce0a680975649544.

The revert is breaking AMDGPU backend tests (which I didn't have
enabled), and I don't want to risk breakages over the weekend, so just
revert for now.

Added: 


Modified: 
clang/test/Analysis/builtin_signbit.cpp
llvm/lib/IR/Constants.cpp
llvm/test/CodeGen/AArch64/stack-tagging-initializer-merge.ll

Removed: 




diff  --git a/clang/test/Analysis/builtin_signbit.cpp 
b/clang/test/Analysis/builtin_signbit.cpp
index a0bf7a45be1302b..e02802c5a514b0b 100644
--- a/clang/test/Analysis/builtin_signbit.cpp
+++ b/clang/test/Analysis/builtin_signbit.cpp
@@ -12,60 +12,72 @@ long double ld = -1.0L;
 // CHECK-BE32-LABEL: define dso_local void @_Z12test_signbitv(
 // CHECK-BE32-SAME: ) #[[ATTR0:[0-9]+]] {
 // CHECK-BE32-NEXT:  entry:
-// CHECK-BE32-NEXT:[[FROMBOOL:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
+// CHECK-BE32-NEXT:[[TMP0:%.*]] = lshr i128 bitcast (ppc_fp128 
0xM3FF0 to i128), 64
+// CHECK-BE32-NEXT:[[TMP1:%.*]] = trunc i128 [[TMP0]] to i64
+// CHECK-BE32-NEXT:[[TMP2:%.*]] = icmp slt i64 [[TMP1]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL:%.*]] = zext i1 [[TMP2]] to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP0:%.*]] = load ppc_fp128, ptr @ld, align 16
-// CHECK-BE32-NEXT:[[TMP1:%.*]] = bitcast ppc_fp128 [[TMP0]] to i128
-// CHECK-BE32-NEXT:[[TMP2:%.*]] = lshr i128 [[TMP1]], 64
-// CHECK-BE32-NEXT:[[TMP3:%.*]] = trunc i128 [[TMP2]] to i64
-// CHECK-BE32-NEXT:[[TMP4:%.*]] = icmp slt i64 [[TMP3]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL1:%.*]] = zext i1 [[TMP4]] to i8
+// CHECK-BE32-NEXT:[[TMP3:%.*]] = load ppc_fp128, ptr @ld, align 16
+// CHECK-BE32-NEXT:[[TMP4:%.*]] = bitcast ppc_fp128 [[TMP3]] to i128
+// CHECK-BE32-NEXT:[[TMP5:%.*]] = lshr i128 [[TMP4]], 64
+// CHECK-BE32-NEXT:[[TMP6:%.*]] = trunc i128 [[TMP5]] to i64
+// CHECK-BE32-NEXT:[[TMP7:%.*]] = icmp slt i64 [[TMP6]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL1:%.*]] = zext i1 [[TMP7]] to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL1]], ptr @b, align 1
 // CHECK-BE32-NEXT:store i8 0, ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP5:%.*]] = load double, ptr @d, align 8
-// CHECK-BE32-NEXT:[[CONV:%.*]] = fptrunc double [[TMP5]] to float
-// CHECK-BE32-NEXT:[[TMP6:%.*]] = bitcast float [[CONV]] to i32
-// CHECK-BE32-NEXT:[[TMP7:%.*]] = icmp slt i32 [[TMP6]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL2:%.*]] = zext i1 [[TMP7]] to i8
+// CHECK-BE32-NEXT:[[TMP8:%.*]] = load double, ptr @d, align 8
+// CHECK-BE32-NEXT:[[CONV:%.*]] = fptrunc double [[TMP8]] to float
+// CHECK-BE32-NEXT:[[TMP9:%.*]] = bitcast float [[CONV]] to i32
+// CHECK-BE32-NEXT:[[TMP10:%.*]] = icmp slt i32 [[TMP9]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL2:%.*]] = zext i1 [[TMP10]] to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL2]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[FROMBOOL3:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
+// CHECK-BE32-NEXT:[[TMP11:%.*]] = lshr i128 bitcast (ppc_fp128 
0xM3FF0 to i128), 64
+// CHECK-BE32-NEXT:[[TMP12:%.*]] = trunc i128 [[TMP11]] to i64
+// CHECK-BE32-NEXT:[[TMP13:%.*]] = icmp slt i64 [[TMP12]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL3:%.*]] = zext i1 [[TMP13]] to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL3]], ptr @b, align 1
-// CHECK-BE32-NEXT:[[TMP8:%.*]] = load ppc_fp128, ptr @ld, align 16
-// CHECK-BE32-NEXT:[[TMP9:%.*]] = bitcast ppc_fp128 [[TMP8]] to i128
-// CHECK-BE32-NEXT:[[TMP10:%.*]] = lshr i128 [[TMP9]], 64
-// CHECK-BE32-NEXT:[[TMP11:%.*]] = trunc i128 [[TMP10]] to i64
-// CHECK-BE32-NEXT:[[TMP12:%.*]] = icmp slt i64 [[TMP11]], 0
-// CHECK-BE32-NEXT:[[FROMBOOL4:%.*]] = zext i1 [[TMP12]] to i8
+// CHECK-BE32-NEXT:[[TMP14:%.*]] = load ppc_fp128, ptr @ld, align 16
+// CHECK-BE32-NEXT:[[TMP15:%.*]] = bitcast ppc_fp128 [[TMP14]] to i128
+// CHECK-BE32-NEXT:[[TMP16:%.*]] = lshr i128 [[TMP15]], 64
+// CHECK-BE32-NEXT:[[TMP17:%.*]] = trunc i128 [[TMP16]] to i64
+// CHECK-BE32-NEXT:[[TMP18:%.*]] = icmp slt i64 [[TMP17]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL4:%.*]] = zext i1 [[TMP18]] to i8
 // CHECK-BE32-NEXT:store i8 [[FROMBOOL4]], ptr @b, align 1
 // 

[clang] 55ac332 - Revert "Revert "[Clang] Generate test checks (NFC)""

2023-11-10 Thread Shoaib Meenai via cfe-commits

Author: Shoaib Meenai
Date: 2023-11-10T17:24:39-08:00
New Revision: 55ac33235db3635a797f98f4539d665bfacf92df

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

LOG: Revert "Revert "[Clang] Generate test checks (NFC)""

This reverts commit 3bb7ecc5a515d2ddd2708257096e14e3fe3b839d.

The revert breaks AMDGPU backend tests (which I didn't have enabled
locally), and I don't want to risk more breakages before the weekend, so
just restore things as they were.

Added: 


Modified: 
clang/test/Analysis/builtin_signbit.cpp

Removed: 




diff  --git a/clang/test/Analysis/builtin_signbit.cpp 
b/clang/test/Analysis/builtin_signbit.cpp
index 251391952f9c586..a0bf7a45be1302b 100644
--- a/clang/test/Analysis/builtin_signbit.cpp
+++ b/clang/test/Analysis/builtin_signbit.cpp
@@ -1,46 +1,113 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 3
 // RUN: %clang -target powerpc-linux-gnu -emit-llvm -S -mabi=ibmlongdouble \
-// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-BE
+// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK-BE32
 // RUN: %clang -target powerpc64-linux-gnu -emit-llvm -S -mabi=ibmlongdouble \
-// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-BE
+// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK-BE64
 // RUN: %clang -target powerpc64le-linux-gnu -emit-llvm -S -mabi=ibmlongdouble 
\
-// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-LE
+// RUN:   -O0 %s -o - | FileCheck %s --check-prefixes=CHECK-LE
 
 bool b;
 double d = -1.0;
 long double ld = -1.0L;
+// CHECK-BE32-LABEL: define dso_local void @_Z12test_signbitv(
+// CHECK-BE32-SAME: ) #[[ATTR0:[0-9]+]] {
+// CHECK-BE32-NEXT:  entry:
+// CHECK-BE32-NEXT:[[FROMBOOL:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
+// CHECK-BE32-NEXT:store i8 [[FROMBOOL]], ptr @b, align 1
+// CHECK-BE32-NEXT:[[TMP0:%.*]] = load ppc_fp128, ptr @ld, align 16
+// CHECK-BE32-NEXT:[[TMP1:%.*]] = bitcast ppc_fp128 [[TMP0]] to i128
+// CHECK-BE32-NEXT:[[TMP2:%.*]] = lshr i128 [[TMP1]], 64
+// CHECK-BE32-NEXT:[[TMP3:%.*]] = trunc i128 [[TMP2]] to i64
+// CHECK-BE32-NEXT:[[TMP4:%.*]] = icmp slt i64 [[TMP3]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL1:%.*]] = zext i1 [[TMP4]] to i8
+// CHECK-BE32-NEXT:store i8 [[FROMBOOL1]], ptr @b, align 1
+// CHECK-BE32-NEXT:store i8 0, ptr @b, align 1
+// CHECK-BE32-NEXT:[[TMP5:%.*]] = load double, ptr @d, align 8
+// CHECK-BE32-NEXT:[[CONV:%.*]] = fptrunc double [[TMP5]] to float
+// CHECK-BE32-NEXT:[[TMP6:%.*]] = bitcast float [[CONV]] to i32
+// CHECK-BE32-NEXT:[[TMP7:%.*]] = icmp slt i32 [[TMP6]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL2:%.*]] = zext i1 [[TMP7]] to i8
+// CHECK-BE32-NEXT:store i8 [[FROMBOOL2]], ptr @b, align 1
+// CHECK-BE32-NEXT:[[FROMBOOL3:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
+// CHECK-BE32-NEXT:store i8 [[FROMBOOL3]], ptr @b, align 1
+// CHECK-BE32-NEXT:[[TMP8:%.*]] = load ppc_fp128, ptr @ld, align 16
+// CHECK-BE32-NEXT:[[TMP9:%.*]] = bitcast ppc_fp128 [[TMP8]] to i128
+// CHECK-BE32-NEXT:[[TMP10:%.*]] = lshr i128 [[TMP9]], 64
+// CHECK-BE32-NEXT:[[TMP11:%.*]] = trunc i128 [[TMP10]] to i64
+// CHECK-BE32-NEXT:[[TMP12:%.*]] = icmp slt i64 [[TMP11]], 0
+// CHECK-BE32-NEXT:[[FROMBOOL4:%.*]] = zext i1 [[TMP12]] to i8
+// CHECK-BE32-NEXT:store i8 [[FROMBOOL4]], ptr @b, align 1
+// CHECK-BE32-NEXT:ret void
+//
+// CHECK-BE64-LABEL: define dso_local void @_Z12test_signbitv(
+// CHECK-BE64-SAME: ) #[[ATTR0:[0-9]+]] {
+// CHECK-BE64-NEXT:  entry:
+// CHECK-BE64-NEXT:[[FROMBOOL:%.*]] = zext i1 icmp slt (i64 trunc (i128 
lshr (i128 bitcast (ppc_fp128 0xM3FF0 to i128), 
i128 64) to i64), i64 0) to i8
+// CHECK-BE64-NEXT:store i8 [[FROMBOOL]], ptr @b, align 1
+// CHECK-BE64-NEXT:[[TMP0:%.*]] = load ppc_fp128, ptr @ld, align 16
+// CHECK-BE64-NEXT:[[TMP1:%.*]] = bitcast ppc_fp128 [[TMP0]] to i128
+// CHECK-BE64-NEXT:[[TMP2:%.*]] = lshr i128 [[TMP1]], 64
+// CHECK-BE64-NEXT:[[TMP3:%.*]] = trunc i128 [[TMP2]] to i64
+// CHECK-BE64-NEXT:[[TMP4:%.*]] = icmp slt i64 [[TMP3]], 0
+// CHECK-BE64-NEXT:[[FROMBOOL1:%.*]] = zext i1 [[TMP4]] to i8
+// CHECK-BE64-NEXT:store i8 [[FROMBOOL1]], ptr @b, align 1
+// CHECK-BE64-NEXT:store i8 0, ptr @b, align 1
+// CHECK-BE64-NEXT:[[TMP5:%.*]] = load double, ptr @d, align 8
+// CHECK-BE64-NEXT:[[CONV:%.*]] = fptrunc double [[TMP5]] to float
+// CHECK-BE64-NEXT:[[TMP6:%.*]] = bitcast float 

[clang] [clang-tools-extra] [clang][AST] Fix crash in MatchChildASTVisitor::TraverseLambdaExpr (PR #70962)

2023-11-10 Thread via cfe-commits

cor3ntin wrote:

+ @AaronBallman Having a nullptr init capture seems fishy, do we actually mean 
to allow capturing vla by reference here?

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


[clang] [clang] Print static_assert values of arithmetic binary operators (PR #71671)

2023-11-10 Thread via cfe-commits


@@ -17219,10 +17219,10 @@ static bool UsefulToPrintExpr(const Expr *E) {
   if (const auto *UnaryOp = dyn_cast(E))
 return UsefulToPrintExpr(UnaryOp->getSubExpr());
 
-  // Ignore nested binary operators. This could be a FIXME for improvements
-  // to the diagnostics in the future.
-  if (isa(E))
-return false;
+  // Only print nested arithmetic operators.
+  if (const auto *BO = dyn_cast(E))
+return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() 
||
+BO->isBitwiseOp());
 

cor3ntin wrote:

Maybe isComparisonOp too?

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


[clang] [clang][Sema] Avoid non-empty unexpanded pack assertion for FunctionParmPackExpr (PR #69224)

2023-11-10 Thread via cfe-commits

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

LGTM, thanks

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


[llvm] [clang] [clang-tools-extra] [clang] Fix false positive -Wmissing-field-initializer for anonymous unions (PR #70829)

2023-11-10 Thread via cfe-commits


@@ -654,11 +655,17 @@ void InitListChecker::FillInEmptyInitForBase(
   }
 }
 
-void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
-const InitializedEntity ,
-  InitListExpr *ILE,
-  bool ,
-  bool FillWithNoInit) {
+static bool hasAnyDesignatedInits(const InitListExpr *IL) {
+  for (const Stmt *Init : *IL)
+if (isa_and_nonnull(Init))
+  return true;
+  return false;

cor3ntin wrote:

Can you use llvm::any_of ?

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


[clang] [analyzer] Move security.cert.env.InvalidPtr out of alpha (PR #71912)

2023-11-10 Thread Endre Fülöp via cfe-commits

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


[clang] [clang][Interp] Handle SizeOfPackExprs (PR #71929)

2023-11-10 Thread via cfe-commits

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

LGTM, thanks

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


[lldb] [mlir] [flang] [llvm] [libc] [libcxx] [openmp] [clang-tools-extra] [clang] GlobalISel: Guide return in llvm::getIConstantSplatVal (PR #71989)

2023-11-10 Thread Changpeng Fang via cfe-commits

changpeng wrote:

> Any tests?
Encountered this issue during a downstream branch testing. No test for trunk 
yet but think the issue should be here.  

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


[lldb] [clang] Reland "[clang][DebugInfo] Emit global variable definitions for static data members with constant initializers" (PR #71780)

2023-11-10 Thread Michael Buch via cfe-commits

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

>From e5bc858c35b479d29174c9945c6c67f4d2dc085b Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Thu, 9 Nov 2023 01:13:21 +
Subject: [PATCH 1/4] Reland "[clang][DebugInfo] Emit global variable
 definitions for static data members with constant initializers"

---
 clang/lib/CodeGen/CGDebugInfo.cpp | 58 +++
 clang/lib/CodeGen/CGDebugInfo.h   |  6 ++
 clang/test/CodeGenCXX/debug-info-class.cpp| 13 +++--
 .../CodeGenCXX/debug-info-static-member.cpp   | 52 ++---
 .../TestConstStaticIntegralMember.py  |  7 ++-
 .../lldb-dap/variables/TestDAP_variables.py   |  9 +--
 6 files changed, 103 insertions(+), 42 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 84a166d3ac3659c..245f7516640d098 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1677,22 +1677,13 @@ CGDebugInfo::CreateRecordStaticField(const VarDecl 
*Var, llvm::DIType *RecordTy,
 
   unsigned LineNumber = getLineNumber(Var->getLocation());
   StringRef VName = Var->getName();
-  llvm::Constant *C = nullptr;
-  if (Var->getInit()) {
-const APValue *Value = Var->evaluateValue();
-if (Value) {
-  if (Value->isInt())
-C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
-  if (Value->isFloat())
-C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
-}
-  }
 
   llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
   auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
   llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
-  RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
+  RecordTy, VName, VUnit, LineNumber, VTy, Flags, /* Val */ nullptr, 
Align);
   StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
+  StaticDataMemberDefinitionsToEmit.push_back(Var->getCanonicalDecl());
   return GV;
 }
 
@@ -5596,6 +5587,39 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl 
*VD, const APValue ) {
   TemplateParameters, Align));
 }
 
+void CGDebugInfo::EmitGlobalVariable(const VarDecl *VD) {
+  assert(VD->hasInit());
+  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  if (VD->hasAttr())
+return;
+
+  auto  = DeclCache[VD];
+  if (GV)
+return;
+
+  auto const *InitVal = VD->evaluateValue();
+  if (!InitVal)
+return;
+
+  llvm::DIFile *Unit = nullptr;
+  llvm::DIScope *DContext = nullptr;
+  unsigned LineNo;
+  StringRef DeclName, LinkageName;
+  QualType T;
+  llvm::MDTuple *TemplateParameters = nullptr;
+  collectVarDeclProps(VD, Unit, LineNo, T, DeclName, LinkageName,
+  TemplateParameters, DContext);
+
+  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
+  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
+  llvm::DIExpression *InitExpr = createConstantValueExpression(VD, *InitVal);
+
+  GV.reset(DBuilder.createGlobalVariableExpression(
+  TheCU, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
+  true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VD),
+  TemplateParameters, Align, Annotations));
+}
+
 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
const VarDecl *D) {
   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
@@ -5800,6 +5824,18 @@ void CGDebugInfo::setDwoId(uint64_t Signature) {
 }
 
 void CGDebugInfo::finalize() {
+  for (auto const *VD : StaticDataMemberDefinitionsToEmit) {
+assert(VD->isStaticDataMember());
+
+if (DeclCache.contains(VD))
+  continue;
+
+if (!VD->hasInit())
+  continue;
+
+EmitGlobalVariable(VD);
+  }
+
   // Creating types might create further types - invalidating the current
   // element and the size(), so don't cache/reference them.
   for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 7b60e94555d0608..3e4c133b7f2b9f1 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -161,6 +161,9 @@ class CGDebugInfo {
   llvm::DenseMap>
   StaticDataMemberCache;
 
+  /// Keeps track of static data members for which we should emit a definition.
+  std::vector StaticDataMemberDefinitionsToEmit;
+
   using ParamDecl2StmtTy = llvm::DenseMap;
   using Param2DILocTy =
   llvm::DenseMap;
@@ -526,6 +529,9 @@ class CGDebugInfo {
   /// Emit a constant global variable's debug info.
   void EmitGlobalVariable(const ValueDecl *VD, const APValue );
 
+  /// Emit debug-info for a variable with a constant initializer.
+  void EmitGlobalVariable(const VarDecl *VD);
+
   /// Emit information about an external variable.
   void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
 
diff --git a/clang/test/CodeGenCXX/debug-info-class.cpp 

[PATCH] D138846: MC/DC in LLVM Source-Based Code Coverage: LLVM back-end and compiler-rt

2023-11-10 Thread Alan Phipps via Phabricator via cfe-commits
alanphipps added a comment.

In D138846#4656594 , @hans wrote:

> Just a heads up that we're seeing crashes in the Rust compiler which bisects 
> to this change. Investigating in 
> https://bugs.chromium.org/p/chromium/issues/detail?id=1500558

Thank you for the repro!  This was a very straightforward fix; effectively the 
inlining of an instrumented function into multiple functions led to the 
creation of duplicate data variables, ultimately leading to a segfault in 
emitNamedata() when eraseFromParent() was called multiple times from the same 
NamePtr.  Prior to my change to abstract the creation of the data variable, 
there was no explicit check for this, but it was inadvertently avoided by 
checking that multiple counter sections were not created.

I created a pull request for the fix here: 
https://github.com/llvm/llvm-project/pull/71998


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D138846/new/

https://reviews.llvm.org/D138846

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


[clang-tools-extra] [mlir] [libcxx] [llvm] [libc] [flang] [openmp] [clang] [lldb] GlobalISel: Guide return in llvm::getIConstantSplatVal (PR #71989)

2023-11-10 Thread Stanislav Mekhanoshin via cfe-commits

rampitec wrote:

Any tests?

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


[PATCH] D147073: [Coverage] Handle invalid end location of an expression/statement.

2023-11-10 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu added inline comments.



Comment at: clang/lib/CodeGen/CoverageMappingGen.cpp:607
+// compiler has broken.
+assert((!StartLoc || StartLoc->isValid()) && "Start location is not 
valid");
+assert((!EndLoc || EndLoc->isValid()) && "End location is not valid");

MaskRay wrote:
> Is this workaround still needed after 
> b0e61de7075942ef5ac8af9ca1ec918317f62152 (with a test 
> `clang/test/Coverage/unresolved-ctor-expr.cpp`)?
I think this workaround can be removed, verified it no longer crashes if 
reverting this change.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D147073/new/

https://reviews.llvm.org/D147073

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


[clang-tools-extra] [llvm] [clang] [LLVM] Add IRNormalizer Pass (PR #68176)

2023-11-10 Thread Justin Fargnoli via cfe-commits

https://github.com/justinfargnoli updated 
https://github.com/llvm/llvm-project/pull/68176

>From f792a030ac1761a96176332fea906cd2d1826c7b Mon Sep 17 00:00:00 2001
From: justinfargnoli 
Date: Sat, 12 Aug 2023 10:58:45 -0700
Subject: [PATCH 01/26] Add IRCanonicalizer.cpp

---
 llvm/lib/Transforms/Utils/CMakeLists.txt  |   1 +
 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp | 632 ++
 2 files changed, 633 insertions(+)
 create mode 100644 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp

diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt 
b/llvm/lib/Transforms/Utils/CMakeLists.txt
index a870071f3f641dc..7866e7a8c09c3be 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -34,6 +34,7 @@ add_llvm_component_library(LLVMTransformUtils
   InjectTLIMappings.cpp
   InstructionNamer.cpp
   IntegerDivision.cpp
+  IRCanonicalizer.cpp
   LCSSA.cpp
   LibCallsShrinkWrap.cpp
   Local.cpp
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
new file mode 100644
index 000..58e2dce0b96685b
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -0,0 +1,632 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer : public FunctionPass {
+public:
+  static char ID;
+
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  /// Constructor for the IRCanonicalizer.
+  IRCanonicalizer() : FunctionPass(ID) {}
+
+  bool runOnFunction(Function ) override;
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+char IRCanonicalizer::ID = 0;
+static RegisterPass X("canon", "Canonicalize the IR",
+   false /* Only looks at CFG */,
+   false /* Analysis Pass */);
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions 

[llvm] [compiler-rt] [clang] [Profile] Refactor profile correlation. (PR #70856)

2023-11-10 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Chatted with @MaskRay offline, we come to an agreement that it's not good to 
use relying on the bit in __llvm_profile_raw_version to decide whether or not 
to dump data/name sections at runtime for the reasons mentioned above. Sent a 
PR: #71996

> Even if we have a way to fix that, we still need the mode bit at llvm-profile 
> merging step to indicate if the raw profile need debug info/binary to 
> correlate. However, we can get ride of the runtime checking 
> __llvm_profile_has_correlation to allow code compiled w/wo debug-info linked 
> together works well.

I take back this word. When we do `llvm-profdata merge`, we use `-debug-info` 
to provide debug info file for correlation and the same could apply to binary 
correlation, a different flag. So, we know which correlation mode we are using.

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


[llvm] [clang-tools-extra] [clang] [LLVM] Add IRNormalizer Pass (PR #68176)

2023-11-10 Thread Justin Fargnoli via cfe-commits

https://github.com/justinfargnoli updated 
https://github.com/llvm/llvm-project/pull/68176

>From f792a030ac1761a96176332fea906cd2d1826c7b Mon Sep 17 00:00:00 2001
From: justinfargnoli 
Date: Sat, 12 Aug 2023 10:58:45 -0700
Subject: [PATCH 01/25] Add IRCanonicalizer.cpp

---
 llvm/lib/Transforms/Utils/CMakeLists.txt  |   1 +
 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp | 632 ++
 2 files changed, 633 insertions(+)
 create mode 100644 llvm/lib/Transforms/Utils/IRCanonicalizer.cpp

diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt 
b/llvm/lib/Transforms/Utils/CMakeLists.txt
index a870071f3f641dc..7866e7a8c09c3be 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -34,6 +34,7 @@ add_llvm_component_library(LLVMTransformUtils
   InjectTLIMappings.cpp
   InstructionNamer.cpp
   IntegerDivision.cpp
+  IRCanonicalizer.cpp
   LCSSA.cpp
   LibCallsShrinkWrap.cpp
   Local.cpp
diff --git a/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp 
b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
new file mode 100644
index 000..58e2dce0b96685b
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/IRCanonicalizer.cpp
@@ -0,0 +1,632 @@
+//===--- IRCanonicalizer.cpp - IR Canonicalizer 
---===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This file implements the IRCanonicalizer class which aims to transform LLVM
+/// Modules into a canonical form by reordering and renaming instructions while
+/// preserving the same semantics. The canonicalizer makes it easier to spot
+/// semantic differences while diffing two modules which have undergone
+/// different passes.
+///
+//===--===//
+
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Module.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/PassRegistry.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Transforms/Utils.h"
+#include 
+#include 
+
+#define DEBUG_TYPE "canon"
+
+using namespace llvm;
+
+namespace {
+/// IRCanonicalizer aims to transform LLVM IR into canonical form.
+class IRCanonicalizer : public FunctionPass {
+public:
+  static char ID;
+
+  /// \name Canonicalizer flags.
+  /// @{
+  /// Preserves original order of instructions.
+  static cl::opt PreserveOrder;
+  /// Renames all instructions (including user-named).
+  static cl::opt RenameAll;
+  /// Folds all regular instructions (including pre-outputs).
+  static cl::opt FoldPreoutputs;
+  /// Sorts and reorders operands in commutative instructions.
+  static cl::opt ReorderOperands;
+  /// @}
+
+  /// Constructor for the IRCanonicalizer.
+  IRCanonicalizer() : FunctionPass(ID) {}
+
+  bool runOnFunction(Function ) override;
+
+private:
+  // Random constant for hashing, so the state isn't zero.
+  const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
+
+  /// \name Naming.
+  /// @{
+  void nameFunctionArguments(Function );
+  void nameBasicBlocks(Function );
+  void nameInstruction(Instruction *I);
+  void nameAsInitialInstruction(Instruction *I);
+  void nameAsRegularInstruction(Instruction *I);
+  void foldInstructionName(Instruction *I);
+  /// @}
+
+  /// \name Reordering.
+  /// @{
+  void reorderInstructions(SmallVector );
+  void reorderInstruction(Instruction *Used, Instruction *User,
+  SmallPtrSet );
+  void reorderInstructionOperandsByNames(Instruction *I);
+  void reorderPHIIncomingValues(PHINode *PN);
+  /// @}
+
+  /// \name Utility methods.
+  /// @{
+  SmallVector collectOutputInstructions(Function );
+  bool isOutput(const Instruction *I);
+  bool isInitialInstruction(const Instruction *I);
+  bool hasOnlyImmediateOperands(const Instruction *I);
+  SetVector
+  getOutputFootprint(Instruction *I,
+ SmallPtrSet );
+  /// @}
+};
+} // namespace
+
+char IRCanonicalizer::ID = 0;
+static RegisterPass X("canon", "Canonicalize the IR",
+   false /* Only looks at CFG */,
+   false /* Analysis Pass */);
+
+cl::opt IRCanonicalizer::PreserveOrder(
+"preserve-order", cl::Hidden,
+cl::desc("Preserves original instruction order"));
+cl::opt IRCanonicalizer::RenameAll(
+"rename-all", cl::Hidden,
+cl::desc("Renames all instructions (including user-named)"));
+cl::opt IRCanonicalizer::FoldPreoutputs(
+"fold-all", cl::Hidden,
+cl::desc("Folds all regular instructions 

[clang] [clang-format] Handle control statements in BreakAfterAttributes (PR #71995)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

This patch doesn't work for do-while loops.

Fixed #64474.

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


4 Files Affected:

- (modified) clang/docs/ClangFormatStyleOptions.rst (+50-2) 
- (modified) clang/include/clang/Format/Format.h (+50-2) 
- (modified) clang/lib/Format/TokenAnnotator.cpp (+21-12) 
- (modified) clang/unittests/Format/FormatTest.cpp (+64) 


``diff
diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index d496fc85f7ae71a..2e9297879684aa5 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2049,8 +2049,10 @@ the configuration (without a prefix: ``Auto``).
 .. _BreakAfterAttributes:
 
 **BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16` :ref:`¶ `
-  Break after a group of C++11 attributes before a variable/function
-  (including constructor/destructor) declaration/definition name.
+  Break after a group of C++11 attributes before variable or function
+  (including constructor/destructor) declaration/definition names or before
+  control statements, i.e. ``if``, ``switch`` (including ``case`` and
+  ``default``labels), ``for``, and ``while`` statements.
 
   Possible values:
 
@@ -2063,11 +2065,28 @@ the configuration (without a prefix: ``Auto``).
   const int i;
   [[gnu::const]] [[maybe_unused]]
   int j;
+
   [[nodiscard]]
   inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
 
+  [[likely]]
+  if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]]
+  case 1:
+++b;
+break;
+  [[likely]]
+  default:
+return;
+  }
+
   * ``ABS_Leave`` (in configuration: ``Leave``)
 Leave the line breaking after attributes as is.
 
@@ -2076,10 +2095,25 @@ the configuration (without a prefix: ``Auto``).
   [[maybe_unused]] const int i;
   [[gnu::const]] [[maybe_unused]]
   int j;
+
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
 
+  [[likely]] if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]] case 1:
+++b;
+break;
+  [[likely]]
+  default:
+return;
+  }
+
   * ``ABS_Never`` (in configuration: ``Never``)
 Never break after attributes.
 
@@ -2087,9 +2121,23 @@ the configuration (without a prefix: ``Auto``).
 
   [[maybe_unused]] const int i;
   [[gnu::const]] [[maybe_unused]] int j;
+
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]] int g();
 
+  [[likely]] if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]] case 1:
+++b;
+break;
+  [[likely]] default:
+return;
+  }
+
 
 
 .. _BreakAfterJavaFieldAnnotations:
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 9442344000e142b..55ba46d45c142ab 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1432,10 +1432,27 @@ struct FormatStyle {
 ///   const int i;
 ///   [[gnu::const]] [[maybe_unused]]
 ///   int j;
+///
 ///   [[nodiscard]]
 ///   inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
+///
+///   [[likely]]
+///   if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   [[unlikely]]
+///   case 1:
+/// ++b;
+/// break;
+///   [[likely]]
+///   default:
+/// return;
+///   }
 /// \endcode
 ABS_Always,
 /// Leave the line breaking after attributes as is.
@@ -1443,23 +1460,54 @@ struct FormatStyle {
 ///   [[maybe_unused]] const int i;
 ///   [[gnu::const]] [[maybe_unused]]
 ///   int j;
+///
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
+///
+///   [[likely]] if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   [[unlikely]] case 1:
+/// ++b;
+/// break;
+///   [[likely]]
+///   default:
+/// return;
+///   }
 /// \endcode
 ABS_Leave,
 /// Never break after attributes.
 /// \code
 ///   [[maybe_unused]] const int i;
 ///   [[gnu::const]] [[maybe_unused]] int j;
+///
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]] int g();
+///
+///   [[likely]] if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   [[unlikely]] case 1:
+/// ++b;
+/// break;
+///   [[likely]] default:
+/// return;
+///   }
 /// \endcode
 ABS_Never,
   };
 
-  /// Break after a group of C++11 attributes before a variable/function
-  /// 

[clang] [clang-format] Handle control statements in BreakAfterAttributes (PR #71995)

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

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

This patch doesn't work for do-while loops.

Fixed #64474.

>From b67ea36d180e700cc6b0661e8f2390eda515c566 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 10 Nov 2023 00:21:58 -0800
Subject: [PATCH] [clang-format] Handle control statements in
 BreakAfterAttributes

This patch doesn't work for do-while loops.

Fixed #64474.
---
 clang/docs/ClangFormatStyleOptions.rst | 52 -
 clang/include/clang/Format/Format.h| 52 -
 clang/lib/Format/TokenAnnotator.cpp| 33 -
 clang/unittests/Format/FormatTest.cpp  | 64 ++
 4 files changed, 185 insertions(+), 16 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index d496fc85f7ae71a..2e9297879684aa5 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2049,8 +2049,10 @@ the configuration (without a prefix: ``Auto``).
 .. _BreakAfterAttributes:
 
 **BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16` :ref:`¶ `
-  Break after a group of C++11 attributes before a variable/function
-  (including constructor/destructor) declaration/definition name.
+  Break after a group of C++11 attributes before variable or function
+  (including constructor/destructor) declaration/definition names or before
+  control statements, i.e. ``if``, ``switch`` (including ``case`` and
+  ``default``labels), ``for``, and ``while`` statements.
 
   Possible values:
 
@@ -2063,11 +2065,28 @@ the configuration (without a prefix: ``Auto``).
   const int i;
   [[gnu::const]] [[maybe_unused]]
   int j;
+
   [[nodiscard]]
   inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
 
+  [[likely]]
+  if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]]
+  case 1:
+++b;
+break;
+  [[likely]]
+  default:
+return;
+  }
+
   * ``ABS_Leave`` (in configuration: ``Leave``)
 Leave the line breaking after attributes as is.
 
@@ -2076,10 +2095,25 @@ the configuration (without a prefix: ``Auto``).
   [[maybe_unused]] const int i;
   [[gnu::const]] [[maybe_unused]]
   int j;
+
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
 
+  [[likely]] if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]] case 1:
+++b;
+break;
+  [[likely]]
+  default:
+return;
+  }
+
   * ``ABS_Never`` (in configuration: ``Never``)
 Never break after attributes.
 
@@ -2087,9 +2121,23 @@ the configuration (without a prefix: ``Auto``).
 
   [[maybe_unused]] const int i;
   [[gnu::const]] [[maybe_unused]] int j;
+
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]] int g();
 
+  [[likely]] if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]] case 1:
+++b;
+break;
+  [[likely]] default:
+return;
+  }
+
 
 
 .. _BreakAfterJavaFieldAnnotations:
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 9442344000e142b..55ba46d45c142ab 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1432,10 +1432,27 @@ struct FormatStyle {
 ///   const int i;
 ///   [[gnu::const]] [[maybe_unused]]
 ///   int j;
+///
 ///   [[nodiscard]]
 ///   inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
+///
+///   [[likely]]
+///   if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   [[unlikely]]
+///   case 1:
+/// ++b;
+/// break;
+///   [[likely]]
+///   default:
+/// return;
+///   }
 /// \endcode
 ABS_Always,
 /// Leave the line breaking after attributes as is.
@@ -1443,23 +1460,54 @@ struct FormatStyle {
 ///   [[maybe_unused]] const int i;
 ///   [[gnu::const]] [[maybe_unused]]
 ///   int j;
+///
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
+///
+///   [[likely]] if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   [[unlikely]] case 1:
+/// ++b;
+/// break;
+///   [[likely]]
+///   default:
+/// return;
+///   }
 /// \endcode
 ABS_Leave,
 /// Never break after attributes.
 /// \code
 ///   [[maybe_unused]] const int i;
 ///   [[gnu::const]] [[maybe_unused]] int j;
+///
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]] int g();
+///
+///   [[likely]] if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   

[clang] 7318fe6 - [OpenMP][FIX] Ensure device reduction geps work for multi-var reductions

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

Author: Johannes Doerfert
Date: 2023-11-10T14:34:46-08:00
New Revision: 7318fe633487f9b9187e18c7ebd4c6516ded9a22

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

LOG: [OpenMP][FIX] Ensure device reduction geps work for multi-var reductions

If we have more than one reduction variable we need to be consistent
wrt. indexing. In 3de645efe30b83ba1b6d7e500486c4f441a17a61 we broke this
as the buffer type was reduced to a singleton but the index computation
was not adjusted to account for that offset. This fixes it by
interleaving the reduction variables properly in a array-of-struct
style. We can revert it back to struct-of-array in a follow up if turns
out to be a problem. I doubt it since half the accesses should benefit
from the locallity this layout offers and only the other half were
consecutive before.

Added: 
openmp/libomptarget/test/offloading/multiple_reductions_simple.c

Modified: 
clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
clang/test/OpenMP/nvptx_teams_reduction_codegen.cpp
clang/test/OpenMP/target_teams_generic_loop_codegen.cpp
openmp/libomptarget/DeviceRTL/src/Reduction.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index a13d74743c3bd3f..abecf5250f4cf96 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -153,9 +153,11 @@ static RecordDecl *buildRecordForGlobalizedVars(
   Field->addAttr(*I);
   }
 } else {
-  llvm::APInt ArraySize(32, BufSize);
-  Type = C.getConstantArrayType(Type, ArraySize, nullptr,
-ArraySizeModifier::Normal, 0);
+  if (BufSize > 1) {
+llvm::APInt ArraySize(32, BufSize);
+Type = C.getConstantArrayType(Type, ArraySize, nullptr,
+  ArraySizeModifier::Normal, 0);
+  }
   Field = FieldDecl::Create(
   C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
   C.getTrivialTypeSourceInfo(Type, SourceLocation()),
@@ -2205,8 +2207,7 @@ static llvm::Value *emitListToGlobalCopyFunction(
   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
   CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, 
Loc),
   LLVMReductionsBufferTy->getPointerTo());
-  llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
- CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(),
+  llvm::Value *Idxs[] = {CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(),
   /*Volatile=*/false, C.IntTy,
   Loc)};
   unsigned Idx = 0;
@@ -2224,12 +2225,12 @@ static llvm::Value *emitListToGlobalCopyFunction(
 const ValueDecl *VD = cast(Private)->getDecl();
 // Global = Buffer.VD[Idx];
 const FieldDecl *FD = VarFieldMap.lookup(VD);
+llvm::Value *BufferPtr =
+Bld.CreateInBoundsGEP(LLVMReductionsBufferTy, BufferArrPtr, Idxs);
 LValue GlobLVal = CGF.EmitLValueForField(
-CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
+CGF.MakeNaturalAlignAddrLValue(BufferPtr, StaticTy), FD);
 Address GlobAddr = GlobLVal.getAddress(CGF);
-llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobAddr.getElementType(),
-   GlobAddr.getPointer(), 
Idxs);
-GlobLVal.setAddress(Address(BufferPtr,
+GlobLVal.setAddress(Address(GlobAddr.getPointer(),
 CGF.ConvertTypeForMem(Private->getType()),
 GlobAddr.getAlignment()));
 switch (CGF.getEvaluationKind(Private->getType())) {
@@ -2316,8 +2317,7 @@ static llvm::Value *emitListToGlobalReduceFunction(
   Address ReductionList =
   CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
   auto IPriv = Privates.begin();
-  llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
- CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(),
+  llvm::Value *Idxs[] = {CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(),
   /*Volatile=*/false, C.IntTy,
   Loc)};
   unsigned Idx = 0;
@@ -2326,12 +2326,13 @@ static llvm::Value *emitListToGlobalReduceFunction(
 // Global = Buffer.VD[Idx];
 const ValueDecl *VD = cast(*IPriv)->getDecl();
 const FieldDecl *FD = VarFieldMap.lookup(VD);
+llvm::Value *BufferPtr =
+Bld.CreateInBoundsGEP(LLVMReductionsBufferTy, BufferArrPtr, Idxs);
 LValue GlobLVal = CGF.EmitLValueForField(
-CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
+CGF.MakeNaturalAlignAddrLValue(BufferPtr, StaticTy), FD);
   

[clang] [clang] Enable --gcc-install-dir for RISCV baremetal toolchains (PR #71803)

2023-11-10 Thread via cfe-commits

mihailo-stojanovic wrote:

I believe that more information can be found in the 
[commit](https://github.com/llvm/llvm-project/commit/45ba2392d7e00aedd4d9fb04070dbae8a7fbbeeb)
 which added the `RISCVToolChain::hasGCCToolchain` method. As far as I could 
gather, before this was merged, the only option for baremetal compilation was 
to provide an existing GCC installation, as `toolchains::RISCVToolChain` 
expects one to be present.

My patch just makes sure that `--gcc-install-dir` works as intended with RISCV 
baremetal triples, as the option is currently useless, and I believe the 
`-gcc-toolchain` option is deprecated.

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


[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-10 Thread via cfe-commits


@@ -150,6 +246,11 @@ std::vector 
HeuristicResolver::resolveMemberExpr(
   if (ME->isArrow()) {
 BaseType = getPointeeType(BaseType);
   }
+
+  if (BaseType->isDependentType())

sr-tream wrote:

Check BaseType before access (line 254)

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits


@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *MethodDecl =
+dyn_cast_or_null(OpCallExpr->getDirectCallee()))
+  return !MethodDecl->isConst();

schenker wrote:

I see

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


[lldb] [mlir] [flang] [libc] [openmp] [llvm] [clang] [libcxx] [clang-tools-extra] GlobalISel: Guide return in llvm::getIConstantSplatVal (PR #71989)

2023-11-10 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 0448a1c0dc131835301a59db7138d504b836a591 
23d34569183f405fdae0a8a665be8b7772addebe -- 
llvm/lib/CodeGen/GlobalISel/Utils.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/CodeGen/GlobalISel/Utils.cpp 
b/llvm/lib/CodeGen/GlobalISel/Utils.cpp
index eaf829f562b2..e4a69a1600c5 100644
--- a/llvm/lib/CodeGen/GlobalISel/Utils.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/Utils.cpp
@@ -1117,7 +1117,7 @@ llvm::getIConstantSplatVal(const Register Reg, const 
MachineRegisterInfo ) {
   if (auto SplatValAndReg =
   getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) {
 if (std::optional ValAndVReg =
-getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI))
+getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI))
   return ValAndVReg->Value;
   }
 

``




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


[llvm] [compiler-rt] [clang-tools-extra] [clang] [clang] Add support for new loop attribute [[clang::code_align()]] (PR #70762)

2023-11-10 Thread via cfe-commits

https://github.com/smanna12 updated 
https://github.com/llvm/llvm-project/pull/70762

>From 93d46d40f46663cfa30fc01da965887508684e25 Mon Sep 17 00:00:00 2001
From: "Manna, Soumi" 
Date: Mon, 30 Oct 2023 21:41:00 -0700
Subject: [PATCH 01/11] [clang] Add support for new loop attribute
 [[clang::code_align()]]

---
 clang/include/clang/Basic/Attr.td |   9 ++
 clang/include/clang/Basic/AttrDocs.td |  43 ++
 .../clang/Basic/DiagnosticSemaKinds.td|   4 +
 clang/include/clang/Sema/Sema.h   |   2 +
 clang/lib/CodeGen/CGLoopInfo.cpp  |  29 +++-
 clang/lib/CodeGen/CGLoopInfo.h|   6 +
 clang/lib/Sema/SemaStmtAttr.cpp   |  53 
 clang/lib/Sema/SemaTemplateInstantiate.cpp|   8 +-
 clang/test/CodeGen/code_align.c   |  61 +
 clang/test/Sema/code_align.c  | 124 ++
 clang/test/Sema/code_align_ast.c  |  91 +
 11 files changed, 426 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/CodeGen/code_align.c
 create mode 100644 clang/test/Sema/code_align.c
 create mode 100644 clang/test/Sema/code_align_ast.c

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 25231c5b82b907c..e25bea67bf9e86e 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4280,3 +4280,12 @@ def PreferredType: InheritableAttr {
   let Args = [TypeArgument<"Type", 1>];
   let Documentation = [PreferredTypeDocumentation];
 }
+
+def CodeAlign: StmtAttr {
+  let Spellings = [CXX11<"clang", "code_align">,
+   C23<"clang", "code_align">];
+  let Subjects = SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt],
+  ErrorDiag, "'for', 'while', and 'do' 
statements">;
+  let Args = [ExprArgument<"NExpr">];
+  let Documentation = [CodeAlignAttrDocs];
+}
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 05703df2129f612..5ee224e117d049c 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7416,3 +7416,46 @@ that ``p->array`` must have at least ``p->count`` number 
of elements available:
 
   }];
 }
+
+def CodeAlignAttrDocs : Documentation {
+  let Category = DocCatVariable;
+  let Heading = "clang::code_align";
+  let Content = [{
+The ``clang::code_align(N)`` attribute applies to a loop and it specifies the
+byte alignment for a loop. The attribute accepts a positive integer constant
+initialization expression indicating the number of bytes for the minimum
+alignment boundary. Its value must be a power of 2, between 1 and 4096, such as
+1, 2, 4, 8, and so on. This attribute sets ``llvm.loop.align`` loop metadata
+when it applies on a loop statement.
+
+.. code-block:: c++
+
+  void foo() {
+int var = 0;
+[[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
+  }
+
+  void Array(int *array, size_t n) {
+[[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
+  }
+
+  void count () {
+  int a1[10], int i = 0;
+  [[clang::code_align(32)]] while (i < 10) {
+a1[i] += 3;
+  }
+
+  void check() {
+int a = 10;
+[[clang::code_align(8)]] do {
+  a = a + 1;
+} while (a < 20);
+  }
+
+  template
+  void func() {
+[[clang::code_align(A)]] for(;;) { }
+  }
+
+  }];
+}
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 224c0df7f1fb71f..4b0f24d25e3e902 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10026,6 +10026,10 @@ def err_duplicate_case_differing_expr : Error<
 def warn_case_empty_range : Warning<"empty case range specified">;
 def warn_missing_case_for_condition :
   Warning<"no case matching constant switch condition '%0'">;
+def err_loop_attr_duplication : Error<
+  "duplicate loop attribute %0">;
+def err_attribute_argument_not_power_of_two : Error<
+  "%0 attribute argument must be a constant power of two greater than zero">;
 
 def warn_def_missing_case : Warning<"%plural{"
   "1:enumeration value %1 not explicitly handled in switch|"
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1e9752345ffd173..376335e9bbe70ca 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2096,6 +2096,8 @@ class Sema final {
   QualType BuildAddressSpaceAttr(QualType , Expr *AddrSpace,
  SourceLocation AttrLoc);
 
+  CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo , Expr *E);
+
   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
 
   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
diff --git a/clang/lib/CodeGen/CGLoopInfo.cpp b/clang/lib/CodeGen/CGLoopInfo.cpp
index e5d9db273c2d336..a7cae301ba7bfda 100644
--- a/clang/lib/CodeGen/CGLoopInfo.cpp
+++ 

[compiler-rt] [clang] [llvm] [HIP] support 128 bit int division (PR #71978)

2023-11-10 Thread Artem Belevich via cfe-commits

Artem-B wrote:

Would it be feasible to consider switching to the new offloading driver mode 
and really link with the library instead? It may be a conveniently isolated use 
case with little/no existing users that would disrupt.


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


[openmp] [clang-tools-extra] [libcxx] [libc] [mlir] [lldb] [llvm] [flang] [clang] GlobalISel: Guide return in llvm::getIConstantSplatVal (PR #71989)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-globalisel

Author: Changpeng Fang (changpeng)


Changes

getIConstantVRegValWithLookThrough could return NULL.

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


1 Files Affected:

- (modified) llvm/lib/CodeGen/GlobalISel/Utils.cpp (+3-3) 


``diff
diff --git a/llvm/lib/CodeGen/GlobalISel/Utils.cpp 
b/llvm/lib/CodeGen/GlobalISel/Utils.cpp
index 473c3f452f8b1d9..eaf829f562b2dc9 100644
--- a/llvm/lib/CodeGen/GlobalISel/Utils.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/Utils.cpp
@@ -1116,9 +1116,9 @@ std::optional
 llvm::getIConstantSplatVal(const Register Reg, const MachineRegisterInfo ) 
{
   if (auto SplatValAndReg =
   getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) {
-std::optional ValAndVReg =
-getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI);
-return ValAndVReg->Value;
+if (std::optional ValAndVReg =
+getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI))
+  return ValAndVReg->Value;
   }
 
   return std::nullopt;

``




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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

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


@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *MethodDecl =
+dyn_cast_or_null(OpCallExpr->getDirectCallee()))
+  return !MethodDecl->isConst();

PiotrZSL wrote:

On std::shared_ptr yes, but not on std::optional

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


[clang] [clang] Allow __attribute__((swiftcall)) on all targets (PR #71986)

2023-11-10 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 199fc973ced20016b04ba540cf63a1d4914fa513 
d2df2830b4417c0ecc9690c4092053bf465a5d44 -- 
clang/include/clang/Basic/TargetInfo.h clang/lib/CodeGen/ABIInfo.cpp 
clang/lib/CodeGen/ABIInfo.h clang/lib/CodeGen/TargetInfo.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/ABIInfo.cpp b/clang/lib/CodeGen/ABIInfo.cpp
index 86897504b..4608535a1 100644
--- a/clang/lib/CodeGen/ABIInfo.cpp
+++ b/clang/lib/CodeGen/ABIInfo.cpp
@@ -33,9 +33,7 @@ const CodeGenOptions ::getCodeGenOpts() const {
   return CGT.getCodeGenOpts();
 }
 
-CodeGen::CodeGenTypes ::getCodeGenTypes() const {
-  return CGT;
-}
+CodeGen::CodeGenTypes ::getCodeGenTypes() const { return CGT; }
 
 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
 

``




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


[clang] [clang] Allow __attribute__((swiftcall)) on all targets (PR #71986)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kuba (Brecka) Mracek (kubamracek)


Changes

With Embedded Swift, https://forums.swift.org/t/embedded-swift/67057;, 
it becomes possible and useful to produce Swift code for a whole range of CPU 
targets. This change allows using the 'swiftcall' and 'swiftasynccall)' 
attributes on any Clang supported target. This isn't in any way adding complete 
support for those calling conventions for all targets, it's merely removing one 
obstacle from adding new targets to Swift.

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


4 Files Affected:

- (modified) clang/include/clang/Basic/TargetInfo.h (+2) 
- (modified) clang/lib/CodeGen/ABIInfo.cpp (+4) 
- (modified) clang/lib/CodeGen/ABIInfo.h (+1) 
- (modified) clang/lib/CodeGen/TargetInfo.cpp (+3-1) 


``diff
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 41f3c2e403cbef6..308d2ae830bf263 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1606,6 +1606,8 @@ class TargetInfo : public TransferrableTargetInfo,
   default:
 return CCCR_Warning;
   case CC_C:
+  case CC_Swift:
+  case CC_SwiftAsync:
 return CCCR_OK;
 }
   }
diff --git a/clang/lib/CodeGen/ABIInfo.cpp b/clang/lib/CodeGen/ABIInfo.cpp
index 1b56cf7c596d067..86897504b0ad267 100644
--- a/clang/lib/CodeGen/ABIInfo.cpp
+++ b/clang/lib/CodeGen/ABIInfo.cpp
@@ -33,6 +33,10 @@ const CodeGenOptions ::getCodeGenOpts() const {
   return CGT.getCodeGenOpts();
 }
 
+CodeGen::CodeGenTypes ::getCodeGenTypes() const {
+  return CGT;
+}
+
 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
 
 bool ABIInfo::isOHOSFamily() const {
diff --git a/clang/lib/CodeGen/ABIInfo.h b/clang/lib/CodeGen/ABIInfo.h
index b9a5ef6e4366936..99b262bdb529684 100644
--- a/clang/lib/CodeGen/ABIInfo.h
+++ b/clang/lib/CodeGen/ABIInfo.h
@@ -60,6 +60,7 @@ class ABIInfo {
   const llvm::DataLayout () const;
   const TargetInfo () const;
   const CodeGenOptions () const;
+  CodeGen::CodeGenTypes () const;
 
   /// Return the calling convention to use for system runtime
   /// functions.
diff --git a/clang/lib/CodeGen/TargetInfo.cpp b/clang/lib/CodeGen/TargetInfo.cpp
index 3d79f92137abc79..fdcf77ef9ce547c 100644
--- a/clang/lib/CodeGen/TargetInfo.cpp
+++ b/clang/lib/CodeGen/TargetInfo.cpp
@@ -67,7 +67,9 @@ LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
 }
 
 TargetCodeGenInfo::TargetCodeGenInfo(std::unique_ptr Info)
-: Info(std::move(Info)) {}
+: Info(std::move(Info)),
+  SwiftInfo(std::make_unique(
+  this->Info->getCodeGenTypes(), /*SwiftErrorInRegister*/ false)) {}
 
 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
 

``




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


[clang] [clang] Allow __attribute__((swiftcall)) on all targets (PR #71986)

2023-11-10 Thread Kuba Mracek via cfe-commits

https://github.com/kubamracek created 
https://github.com/llvm/llvm-project/pull/71986

With Embedded Swift, , it 
becomes possible and useful to produce Swift code for a whole range of CPU 
targets. This change allows using the 'swiftcall' and 'swiftasynccall)' 
attributes on any Clang supported target. This isn't in any way adding complete 
support for those calling conventions for all targets, it's merely removing one 
obstacle from adding new targets to Swift.

>From d2df2830b4417c0ecc9690c4092053bf465a5d44 Mon Sep 17 00:00:00 2001
From: Kuba Mracek 
Date: Fri, 10 Nov 2023 13:25:13 -0800
Subject: [PATCH] [clang] Allow __attribute__((swiftcall)) on all targets

With Embedded Swift, , it
becomes possible and useful to produce Swift code for a whole range of CPU
targets. This change allows using the 'swiftcall' and 'swiftasynccall)'
attributes on any Clang supported target. This isn't in any way adding complete
support for those calling conventions for all targets, it's merely removing one
obstacle from adding new targets to Swift.
---
 clang/include/clang/Basic/TargetInfo.h | 2 ++
 clang/lib/CodeGen/ABIInfo.cpp  | 4 
 clang/lib/CodeGen/ABIInfo.h| 1 +
 clang/lib/CodeGen/TargetInfo.cpp   | 4 +++-
 4 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 41f3c2e403cbef6..308d2ae830bf263 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1606,6 +1606,8 @@ class TargetInfo : public TransferrableTargetInfo,
   default:
 return CCCR_Warning;
   case CC_C:
+  case CC_Swift:
+  case CC_SwiftAsync:
 return CCCR_OK;
 }
   }
diff --git a/clang/lib/CodeGen/ABIInfo.cpp b/clang/lib/CodeGen/ABIInfo.cpp
index 1b56cf7c596d067..86897504b0ad267 100644
--- a/clang/lib/CodeGen/ABIInfo.cpp
+++ b/clang/lib/CodeGen/ABIInfo.cpp
@@ -33,6 +33,10 @@ const CodeGenOptions ::getCodeGenOpts() const {
   return CGT.getCodeGenOpts();
 }
 
+CodeGen::CodeGenTypes ::getCodeGenTypes() const {
+  return CGT;
+}
+
 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
 
 bool ABIInfo::isOHOSFamily() const {
diff --git a/clang/lib/CodeGen/ABIInfo.h b/clang/lib/CodeGen/ABIInfo.h
index b9a5ef6e4366936..99b262bdb529684 100644
--- a/clang/lib/CodeGen/ABIInfo.h
+++ b/clang/lib/CodeGen/ABIInfo.h
@@ -60,6 +60,7 @@ class ABIInfo {
   const llvm::DataLayout () const;
   const TargetInfo () const;
   const CodeGenOptions () const;
+  CodeGen::CodeGenTypes () const;
 
   /// Return the calling convention to use for system runtime
   /// functions.
diff --git a/clang/lib/CodeGen/TargetInfo.cpp b/clang/lib/CodeGen/TargetInfo.cpp
index 3d79f92137abc79..fdcf77ef9ce547c 100644
--- a/clang/lib/CodeGen/TargetInfo.cpp
+++ b/clang/lib/CodeGen/TargetInfo.cpp
@@ -67,7 +67,9 @@ LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
 }
 
 TargetCodeGenInfo::TargetCodeGenInfo(std::unique_ptr Info)
-: Info(std::move(Info)) {}
+: Info(std::move(Info)),
+  SwiftInfo(std::make_unique(
+  this->Info->getCodeGenTypes(), /*SwiftErrorInRegister*/ false)) {}
 
 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
 

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


[clang] [clang] Make `-fvisibility={}` and `-ftype-visibility={}` benign options. (PR #71985)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Juergen Ributzka (ributzka)


Changes

Both options do not affect the AST content that is serialized into the PCM. This
commit includes the following changes:

1.) Mark `-fvisibility={}` and `-ftype-visibility={}` as benign options. That
means they are no longer considered part of the module hash, which can
reduce the number of module variants.

2.) Add a test to clang-scan-deps to ensure only one module is build, even if
the above mentioned options are used.

This fixes rdar://118246054.


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


2 Files Affected:

- (modified) clang/include/clang/Basic/LangOptions.def (+2-2) 
- (added) clang/test/ClangScanDeps/strip-visibility.c (+59) 


``diff
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c541ccefdd5fbe1..6ad6ccbe4a78c5f 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -349,9 +349,9 @@ LANGOPT(
 "type's inheritance model would be determined under the Microsoft ABI")
 
 ENUM_LANGOPT(GC, GCMode, 2, NonGC, "Objective-C Garbage Collection mode")
-ENUM_LANGOPT(ValueVisibilityMode, Visibility, 3, DefaultVisibility,
+BENIGN_ENUM_LANGOPT(ValueVisibilityMode, Visibility, 3, DefaultVisibility,
  "default visibility for functions and variables [-fvisibility]")
-ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, DefaultVisibility,
+BENIGN_ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, DefaultVisibility,
  "default visibility for types [-ftype-visibility]")
 LANGOPT(SetVisibilityForExternDecls, 1, 0,
 "apply global symbol visibility to external declarations without an 
explicit visibility")
diff --git a/clang/test/ClangScanDeps/strip-visibility.c 
b/clang/test/ClangScanDeps/strip-visibility.c
new file mode 100644
index 000..3c8de700b12bab1
--- /dev/null
+++ b/clang/test/ClangScanDeps/strip-visibility.c
@@ -0,0 +1,59 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full -mode preprocess-dependency-directives > %t/result.txt
+
+// RUN: FileCheck %s -input-file %t/result.txt
+
+// Verify that there's a single version of module A.
+
+// CHECK:"modules": [
+// CHECK-NEXT: {
+// CHECK:"command-line": [
+// CHECK-NOT:  "-fvisibility="
+// CHECK-NOT:  "-ftype-visibility="
+// CHECK:]
+// CHECK:"name": "A"
+// CHECK:  }
+// CHECK-NOT:"name": "A"
+// CHECK:"translation-units"
+
+//--- cdb.json.template
+[
+  {
+"directory": "DIR",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -fimplicit-module-maps 
-fsyntax-only DIR/t1.c",
+"file": "DIR/t1.c"
+  },
+  {
+"directory": "DIR",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -fimplicit-module-maps 
-fvisibility=hidden -fsyntax-only DIR/t2.c",
+"file": "DIR/t2.c"
+  },
+  {
+"directory": "DIR",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -fimplicit-module-maps 
-fvisibility=hidden -fvisibility-ms-compat -fsyntax-only DIR/t3.c",
+"file": "DIR/t3.c"
+  }
+]
+
+//--- modules/A/module.modulemap
+
+module A {
+  umbrella header "A.h"
+}
+
+//--- modules/A/A.h
+
+typedef int A_t;
+extern int a(void);
+
+//--- t1.c
+#include "A.h"
+
+//--- t2.c
+#include "A.h"
+
+//--- t3.c
+#include "A.h"

``




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


[clang] [clang] Make `-fvisibility={}` and `-ftype-visibility={}` benign options. (PR #71985)

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

https://github.com/ributzka created 
https://github.com/llvm/llvm-project/pull/71985

Both options do not affect the AST content that is serialized into the PCM. This
commit includes the following changes:

1.) Mark `-fvisibility={}` and `-ftype-visibility={}` as benign options. That
means they are no longer considered part of the module hash, which can
reduce the number of module variants.

2.) Add a test to clang-scan-deps to ensure only one module is build, even if
the above mentioned options are used.

This fixes rdar://118246054.


>From f6aa9a9e2e7e98bebec82a7b1ed2c11a5ed3d2a6 Mon Sep 17 00:00:00 2001
From: Juergen Ributzka 
Date: Fri, 10 Nov 2023 12:39:16 -0800
Subject: [PATCH] [clang] Make `-fvisibility={}` and `-ftype-visibility={}`
 benign options.

Both options do not affect the AST content that is serialized into the PCM. This
commit includes the following changes:

1.) Mark `-fvisibility={}` and `-ftype-visibility={}` as benign options. That
means they are no longer considered part of the module hash, which can
reduce the number of module variants.

2.) Add a test to clang-scan-deps to ensure only one module is build, even if
the above mentioned options are used.

This fixes rdar://118246054.
---
 clang/include/clang/Basic/LangOptions.def   |  4 +-
 clang/test/ClangScanDeps/strip-visibility.c | 59 +
 2 files changed, 61 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/ClangScanDeps/strip-visibility.c

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c541ccefdd5fbe1..6ad6ccbe4a78c5f 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -349,9 +349,9 @@ LANGOPT(
 "type's inheritance model would be determined under the Microsoft ABI")
 
 ENUM_LANGOPT(GC, GCMode, 2, NonGC, "Objective-C Garbage Collection mode")
-ENUM_LANGOPT(ValueVisibilityMode, Visibility, 3, DefaultVisibility,
+BENIGN_ENUM_LANGOPT(ValueVisibilityMode, Visibility, 3, DefaultVisibility,
  "default visibility for functions and variables [-fvisibility]")
-ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, DefaultVisibility,
+BENIGN_ENUM_LANGOPT(TypeVisibilityMode, Visibility, 3, DefaultVisibility,
  "default visibility for types [-ftype-visibility]")
 LANGOPT(SetVisibilityForExternDecls, 1, 0,
 "apply global symbol visibility to external declarations without an 
explicit visibility")
diff --git a/clang/test/ClangScanDeps/strip-visibility.c 
b/clang/test/ClangScanDeps/strip-visibility.c
new file mode 100644
index 000..3c8de700b12bab1
--- /dev/null
+++ b/clang/test/ClangScanDeps/strip-visibility.c
@@ -0,0 +1,59 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full -mode preprocess-dependency-directives > %t/result.txt
+
+// RUN: FileCheck %s -input-file %t/result.txt
+
+// Verify that there's a single version of module A.
+
+// CHECK:"modules": [
+// CHECK-NEXT: {
+// CHECK:"command-line": [
+// CHECK-NOT:  "-fvisibility="
+// CHECK-NOT:  "-ftype-visibility="
+// CHECK:]
+// CHECK:"name": "A"
+// CHECK:  }
+// CHECK-NOT:"name": "A"
+// CHECK:"translation-units"
+
+//--- cdb.json.template
+[
+  {
+"directory": "DIR",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -fimplicit-module-maps 
-fsyntax-only DIR/t1.c",
+"file": "DIR/t1.c"
+  },
+  {
+"directory": "DIR",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -fimplicit-module-maps 
-fvisibility=hidden -fsyntax-only DIR/t2.c",
+"file": "DIR/t2.c"
+  },
+  {
+"directory": "DIR",
+"command": "clang -Imodules/A -fmodules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -fimplicit-module-maps 
-fvisibility=hidden -fvisibility-ms-compat -fsyntax-only DIR/t3.c",
+"file": "DIR/t3.c"
+  }
+]
+
+//--- modules/A/module.modulemap
+
+module A {
+  umbrella header "A.h"
+}
+
+//--- modules/A/A.h
+
+typedef int A_t;
+extern int a(void);
+
+//--- t1.c
+#include "A.h"
+
+//--- t2.c
+#include "A.h"
+
+//--- t3.c
+#include "A.h"

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


[llvm] [clang-tools-extra] [clang] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71935)

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

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


[clang] 199fc97 - [clang-format] Handle variable declarations in BreakAfterAttributes (#71935)

2023-11-10 Thread via cfe-commits

Author: Owen Pan
Date: 2023-11-10T13:25:57-08:00
New Revision: 199fc973ced20016b04ba540cf63a1d4914fa513

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

LOG: [clang-format] Handle variable declarations in BreakAfterAttributes 
(#71935)

Also fixed a bug in `isStartOfName()` and cleaned up some old test
cases.

Fixed #71563.

This is a rework of #71755.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 21342e1b89ea866..d496fc85f7ae71a 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2049,8 +2049,8 @@ the configuration (without a prefix: ``Auto``).
 .. _BreakAfterAttributes:
 
 **BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16` :ref:`¶ `
-  Break after a group of C++11 attributes before a function
-  declaration/definition name.
+  Break after a group of C++11 attributes before a variable/function
+  (including constructor/destructor) declaration/definition name.
 
   Possible values:
 
@@ -2059,6 +2059,10 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]]
+  const int i;
+  [[gnu::const]] [[maybe_unused]]
+  int j;
   [[nodiscard]]
   inline int f();
   [[gnu::const]] [[nodiscard]]
@@ -2069,6 +2073,9 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]] const int i;
+  [[gnu::const]] [[maybe_unused]]
+  int j;
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
@@ -2078,6 +2085,8 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
+  [[maybe_unused]] const int i;
+  [[gnu::const]] [[maybe_unused]] int j;
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]] int g();
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 3e9d1915badd87f..9442344000e142b 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1428,6 +1428,10 @@ struct FormatStyle {
   enum AttributeBreakingStyle : int8_t {
 /// Always break after attributes.
 /// \code
+///   [[maybe_unused]]
+///   const int i;
+///   [[gnu::const]] [[maybe_unused]]
+///   int j;
 ///   [[nodiscard]]
 ///   inline int f();
 ///   [[gnu::const]] [[nodiscard]]
@@ -1436,6 +1440,9 @@ struct FormatStyle {
 ABS_Always,
 /// Leave the line breaking after attributes as is.
 /// \code
+///   [[maybe_unused]] const int i;
+///   [[gnu::const]] [[maybe_unused]]
+///   int j;
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
@@ -1443,14 +1450,16 @@ struct FormatStyle {
 ABS_Leave,
 /// Never break after attributes.
 /// \code
+///   [[maybe_unused]] const int i;
+///   [[gnu::const]] [[maybe_unused]] int j;
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]] int g();
 /// \endcode
 ABS_Never,
   };
 
-  /// Break after a group of C++11 attributes before a function
-  /// declaration/definition name.
+  /// Break after a group of C++11 attributes before a variable/function
+  /// (including constructor/destructor) declaration/definition name.
   /// \version 16
   AttributeBreakingStyle BreakAfterAttributes;
 

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index d648e441f23fe9e..725f02a37581d24 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1997,6 +1997,10 @@ class AnnotatingParser {
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
   Contexts.back().FirstStartOfName = 
   Current.setType(TT_StartOfName);
+  if (auto *PrevNonComment = Current.getPreviousNonComment();
+  PrevNonComment && PrevNonComment->is(TT_StartOfName)) {
+PrevNonComment->setType(TT_Unknown);
+  }
 } else if (Current.is(tok::semi)) {
   // Reset FirstStartOfName after finding a semicolon so that a for loop
   // with multiple increment statements is not confused with a for loop
@@ -2184,6 +2188,11 @@ class AnnotatingParser {
 if (Tok.isNot(tok::identifier) || !Tok.Previous)
   return false;
 
+if (const auto *NextNonComment = Tok.getNextNonComment();
+!NextNonComment || NextNonComment->isPointerOrReference()) {
+  return false;
+}
+
 if 

[llvm] [clang-tools-extra] [clang] [clang] Add support for new loop attribute [[clang::code_align()]] (PR #70762)

2023-11-10 Thread via cfe-commits

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


[clang-tools-extra] [libcxx] [lldb] [flang] [lld] [llvm] [libc] [clang] [compiler-rt] [asan] Report executable/DSO name for report_globals=2 and odr-violation checking (PR #71879)

2023-11-10 Thread Fangrui Song via cfe-commits

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits

schenker wrote:

> I'm not sure now if this wont cause too much false-positives, after all this 
> is why CheckFunctionCalls option were added. Sometimes object can have 2 same 
> operators, one const and one not, in such case depend on "this" type, 
> non-const could be used, this would be false-positive.

You are right, I misunderstood `CheckFunctionCalls` and it's trickier than I 
thought. Anyways, I think it would make sense to treat method calls and method 
operator calls the same way.

I will rething my imlementation, thanks for reviewing!



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


[llvm] [clang] [openmp] [OpenMP] Rework handling of global ctor/dtors in OpenMP (PR #71739)

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

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


[clang] 237adfc - [OpenMP] Rework handling of global ctor/dtors in OpenMP (#71739)

2023-11-10 Thread via cfe-commits

Author: Joseph Huber
Date: 2023-11-10T14:53:53-06:00
New Revision: 237adfca4ef8d94b7d3d8817da615c5e5897c3da

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

LOG:  [OpenMP] Rework handling of global ctor/dtors in OpenMP (#71739)

Summary:
This patch reworks how we handle global constructors in OpenMP.
Previously, we emitted individual kernels that were all registered and
called individually. In order to provide more generic support, this
patch moves all handling of this to the target backend and the runtime
plugin. This has the benefit of supporting the GNU extensions for
constructors an destructors, removing a class of failures related to
shared library destruction order, and allows targets other than OpenMP
to use the same support without needing to change the frontend.

This is primarily done by calling kernels that the backend emits to
iterate a list of ctor / dtor functions. For x64, this is automatic and
we get it for free with the standard `dlopen` handling. For AMDGPU, we
emit `amdgcn.device.init` and `amdgcn.device.fini` functions which
handle everything atuomatically and simply need to be called. For NVPTX,
a patch https://github.com/llvm/llvm-project/pull/71549 provides the
kernels to call, but the runtime needs to set up the array manually by
pulling out all the known constructor / destructor functions.

One concession that this patch requires is the change that for GPU
targets in OpenMP offloading we will use `llvm.global_dtors` instead of
using `atexit`. This is because `atexit` is a separate runtime function
that does not mesh well with the handling we're trying to do here. This
should be equivalent in all cases except for cases where we would need
to destruct manually such as:

```
struct S { ~S() { foo(); } };
void foo() {
  static S s;
}
```

However this is broken in many other ways on the GPU, so it is not
regressing any support, simply increasing the scope of what we can
handle.

This changes the handling of ctors / dtors. This patch now outputs a
information message regarding the deprecation if the old format is used.
This will be completely removed in a later release.

Depends on: https://github.com/llvm/llvm-project/pull/71549

Added: 
openmp/libomptarget/test/libc/global_ctor_dtor.cpp

Modified: 
clang/include/clang/Basic/LangOptions.h
clang/lib/CodeGen/CGDeclCXX.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/CodeGen/CodeGenModule.h
clang/lib/CodeGen/ItaniumCXXABI.cpp
clang/test/Headers/amdgcn_openmp_device_math_constexpr.cpp
clang/test/OpenMP/amdgcn_target_global_constructor.cpp
clang/test/OpenMP/declare_target_codegen.cpp
clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp
openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp
openmp/libomptarget/plugins-nextgen/common/PluginInterface/GlobalHandler.h

openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp
openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.h
openmp/libomptarget/plugins-nextgen/cuda/src/rtl.cpp
openmp/libomptarget/src/rtl.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 20a8ada60e0fe51..ae99357eeea7f41 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -597,6 +597,9 @@ class LangOptions : public LangOptionsBase {
 return !requiresStrictPrototypes() && !OpenCL;
   }
 
+  /// Returns true if the language supports calling the 'atexit' function.
+  bool hasAtExit() const { return !(OpenMP && OpenMPIsTargetDevice); }
+
   /// Returns true if implicit int is part of the language requirements.
   bool isImplicitIntRequired() const { return !CPlusPlus && !C99; }
 

diff  --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index 3fa28b343663f61..e08a1e5f42df20c 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -327,6 +327,15 @@ void CodeGenFunction::registerGlobalDtorWithAtExit(const 
VarDecl ,
   registerGlobalDtorWithAtExit(dtorStub);
 }
 
+/// Register a global destructor using the LLVM 'llvm.global_dtors' global.
+void CodeGenFunction::registerGlobalDtorWithLLVM(const VarDecl ,
+ llvm::FunctionCallee Dtor,
+ llvm::Constant *Addr) {
+  // Create a function which calls the destructor.
+  llvm::Function *dtorStub = createAtExitStub(VD, Dtor, Addr);
+  CGM.AddGlobalDtor(dtorStub);
+}
+
 void 

[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits


@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *MethodDecl =
+dyn_cast_or_null(OpCallExpr->getDirectCallee()))
+  return !MethodDecl->isConst();

schenker wrote:

I think if the -> operator is implemented correctly, it has to be marked as 
const, even if it returns something that is not const.

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits


@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
+  if (const auto *MethodDecl = dyn_cast(FuncDecl))
+return !MethodDecl->isConst();

schenker wrote:

this makes we wonder if we need the comparisons agains the different operator 
kinds at all, or if we should treat all operators the same, based on their 
constness.

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits

https://github.com/schenker updated 
https://github.com/llvm/llvm-project/pull/71974

>From dabfdee1a982000605e4b33930ba433c63d1684f Mon Sep 17 00:00:00 2001
From: Thomas Schenker 
Date: Fri, 10 Nov 2023 18:58:26 +0100
Subject: [PATCH 1/3] [clang-tidy] bugprone-assert-side-effect non-const
 operator methods

With this PR, `bugprone-assert-side-effect` assumes that operator methods
that are not marked as `const` have side effects. This matches the
existing rule for non-operator methods.

E.g. the following snippet is now reported and was previously not:
```
std::stringstream ss;
assert(ss << 1);
```
---
 .../clang-tidy/bugprone/AssertSideEffectCheck.cpp   |  4 
 .../checkers/bugprone/assert-side-effect.cpp| 13 -
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 07a987359d4d8d7..599f5ac70e7a229 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
+  if (const auto *MethodDecl = dyn_cast(FuncDecl))
+return !MethodDecl->isConst();
+
 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
index 6c41e1e320adeac..49d3d456deb9d35 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
@@ -11,7 +11,7 @@ class MyClass {
 
   MyClass =(const MyClass ) { return *this; }
 
-  int operator-() { return 1; }
+  int operator-() const { return 1; }
 
   operator bool() const { return true; }
 
@@ -84,5 +84,16 @@ int main() {
   msvc_assert(mc2 = mc);
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in msvc_assert() 
condition discarded in release builds
 
+  struct {
+int operator<<(int i) const { return i; }
+  } constOp;
+  assert(constOp << 1);
+
+  struct {
+int operator<<(int i) { return i; }
+  } nonConstOp;
+  assert(nonConstOp << 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in assert() 
condition discarded in release builds
+
   return 0;
 }

>From 071e24c78d551301b14e7bbeebd7d1f36466a8e7 Mon Sep 17 00:00:00 2001
From: Thomas Schenker 
Date: Fri, 10 Nov 2023 21:07:39 +0100
Subject: [PATCH 2/3] use dyn_cast_or_null and add release note

---
 .../clang-tidy/bugprone/AssertSideEffectCheck.cpp   | 6 +++---
 clang-tools-extra/docs/ReleaseNotes.rst | 4 
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 599f5ac70e7a229..a6c01704b3d909f 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,9 +41,9 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
-if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
-  if (const auto *MethodDecl = dyn_cast(FuncDecl))
-return !MethodDecl->isConst();
+if (const auto *MethodDecl =
+dyn_cast_or_null(OpCallExpr->getDirectCallee()))
+  return !MethodDecl->isConst();
 
 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index c79aafdc0f06e69..846a029810454f1 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -208,6 +208,10 @@ New check aliases
 Changes in existing checks
 ^^
 
+- Improved :doc:`bugprone-assert-side-effect
+  ` check to report usage of
+  non-const operator methods in assertions.
+
 - Improved :doc:`bugprone-dangling-handle
   ` check to support functional
   casting during type conversions at variable initialization, now with improved

>From 68048c10877eec6b9ae86c050d1a406b2c0f7cea Mon Sep 17 00:00:00 2001
From: Thomas Schenker 
Date: Fri, 10 Nov 2023 21:45:52 +0100
Subject: [PATCH 3/3] test const overload

---
 .../checkers/bugprone/assert-side-effect.cpp  | 15 ---
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp 

[llvm] [clang] [compiler-rt] [HIP] support 128 bit int division (PR #71978)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Yaxun (Sam) Liu (yxsamliu)


Changes

Currently nvcc supports 128 bit int division in device code. This patch adds 
support of 128 bit int division to HIP.

It builds lib functions for 128 bit division in compiler-rt for amdgcn target.

Then links compiler-rt with -mlink-bitcode-file.

It adds support of archive of bitcode to -mlink-bitcode-file.

It adds support of call of lib function in amdgcn backend.

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

Fixes: SWDEV-426193

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


9 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenAction.cpp (+91-12) 
- (modified) clang/lib/Driver/ToolChains/HIPAMD.cpp (+5) 
- (modified) compiler-rt/cmake/Modules/CompilerRTUtils.cmake (+2) 
- (modified) compiler-rt/cmake/base-config-ix.cmake (+5) 
- (modified) compiler-rt/cmake/builtin-config-ix.cmake (+2-1) 
- (modified) compiler-rt/lib/builtins/CMakeLists.txt (+16) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp (+3-1) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp (+1) 
- (modified) llvm/lib/Target/AMDGPU/SIISelLowering.cpp (+11-3) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenAction.cpp 
b/clang/lib/CodeGen/CodeGenAction.cpp
index a31a271ed77d1ca..f5a3274fbdd2c3e 100644
--- a/clang/lib/CodeGen/CodeGenAction.cpp
+++ b/clang/lib/CodeGen/CodeGenAction.cpp
@@ -41,6 +41,7 @@
 #include "llvm/IRReader/IRReader.h"
 #include "llvm/LTO/LTOBackend.h"
 #include "llvm/Linker/Linker.h"
+#include "llvm/Object/Archive.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
@@ -937,27 +938,105 @@ bool CodeGenAction::loadLinkModules(CompilerInstance 
) {
 
   for (const CodeGenOptions::BitcodeFileToLink  :
CI.getCodeGenOpts().LinkBitcodeFiles) {
-auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
-if (!BCBuf) {
+
+auto BCBufOrErr = CI.getFileManager().getBufferForFile(F.Filename);
+if (!BCBufOrErr) {
   CI.getDiagnostics().Report(diag::err_cannot_open_file)
-  << F.Filename << BCBuf.getError().message();
+  << F.Filename << BCBufOrErr.getError().message();
   LinkModules.clear();
   return true;
 }
 
+auto  = *BCBufOrErr;
+
 Expected> ModuleOrErr =
-getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
-if (!ModuleOrErr) {
-  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase ) {
+getOwningLazyBitcodeModule(std::move(BCBuf), *VMContext);
+
+if (ModuleOrErr) {
+  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
+ F.Internalize, F.LinkFlags});
+  continue;
+} else {
+  // If parsing as bitcode failed, clear the error and try to parse as an
+  // archive.
+  handleAllErrors(ModuleOrErr.takeError(),
+  [&](const llvm::ErrorInfoBase ) {});
+
+  Expected> BinOrErr =
+  llvm::object::createBinary(BCBuf->getMemBufferRef(), VMContext);
+
+  if (!BinOrErr) {
+handleAllErrors(BinOrErr.takeError(),
+[&](const llvm::ErrorInfoBase ) {
+  
CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+LinkModules.clear();
+return true;
+  }
+
+  std::unique_ptr  = *BinOrErr;
+
+  if (Bin->isArchive()) {
+llvm::object::Archive *Archive =
+llvm::cast(Bin.get());
+Error Err = Error::success();
+
+for (auto  : Archive->children(Err)) {
+  Expected ChildBufOrErr =
+  Child.getMemoryBufferRef();
+  if (!ChildBufOrErr) {
+handleAllErrors(
+ChildBufOrErr.takeError(), [&](const llvm::ErrorInfoBase ) 
{
+  CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+continue;
+  }
+  auto ChildBuffer = llvm::MemoryBuffer::getMemBufferCopy(
+  ChildBufOrErr->getBuffer(), 
ChildBufOrErr->getBufferIdentifier());
+
+  if (!ChildBuffer) {
+handleAllErrors(
+ChildBufOrErr.takeError(), [&](const llvm::ErrorInfoBase ) 
{
+  CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+continue;
+  }
+
+  Expected> ChildModuleOrErr =
+  getOwningLazyBitcodeModule(std::move(ChildBuffer), *VMContext);
+  if (!ChildModuleOrErr) {
+handleAllErrors(
+ChildModuleOrErr.takeError(),
+[&](const llvm::ErrorInfoBase ) {
+  CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << 

[compiler-rt] [clang] [llvm] [HIP] support 128 bit int division (PR #71978)

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

https://github.com/yxsamliu created 
https://github.com/llvm/llvm-project/pull/71978

Currently nvcc supports 128 bit int division in device code. This patch adds 
support of 128 bit int division to HIP.

It builds lib functions for 128 bit division in compiler-rt for amdgcn target.

Then links compiler-rt with -mlink-bitcode-file.

It adds support of archive of bitcode to -mlink-bitcode-file.

It adds support of call of lib function in amdgcn backend.

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

Fixes: SWDEV-426193

>From 39ec509a5e8ca93c64949653d57d959d87de8da6 Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Fri, 10 Nov 2023 13:51:58 -0500
Subject: [PATCH] [HIP] support 128 bit int division

Currently nvcc supports 128 bit int division in device code.
This patch adds support of 128 bit int division to HIP.

It builds lib functions for 128 bit division in compiler-rt
for amdgcn target.

Then links compiler-rt with -mlink-bitcode-file.

It adds support of archive of bitcode to -mlink-bitcode-file.

It adds support of call of lib function in amdgcn backend.

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

Fixes: SWDEV-426193
---
 clang/lib/CodeGen/CodeGenAction.cpp   | 103 --
 clang/lib/Driver/ToolChains/HIPAMD.cpp|   5 +
 .../cmake/Modules/CompilerRTUtils.cmake   |   2 +
 compiler-rt/cmake/base-config-ix.cmake|   5 +
 compiler-rt/cmake/builtin-config-ix.cmake |   3 +-
 compiler-rt/lib/builtins/CMakeLists.txt   |  16 +++
 llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp |   4 +-
 .../lib/Target/AMDGPU/AMDGPUTargetMachine.cpp |   1 +
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp |  14 ++-
 9 files changed, 136 insertions(+), 17 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenAction.cpp 
b/clang/lib/CodeGen/CodeGenAction.cpp
index a31a271ed77d1ca..f5a3274fbdd2c3e 100644
--- a/clang/lib/CodeGen/CodeGenAction.cpp
+++ b/clang/lib/CodeGen/CodeGenAction.cpp
@@ -41,6 +41,7 @@
 #include "llvm/IRReader/IRReader.h"
 #include "llvm/LTO/LTOBackend.h"
 #include "llvm/Linker/Linker.h"
+#include "llvm/Object/Archive.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
@@ -937,27 +938,105 @@ bool CodeGenAction::loadLinkModules(CompilerInstance 
) {
 
   for (const CodeGenOptions::BitcodeFileToLink  :
CI.getCodeGenOpts().LinkBitcodeFiles) {
-auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
-if (!BCBuf) {
+
+auto BCBufOrErr = CI.getFileManager().getBufferForFile(F.Filename);
+if (!BCBufOrErr) {
   CI.getDiagnostics().Report(diag::err_cannot_open_file)
-  << F.Filename << BCBuf.getError().message();
+  << F.Filename << BCBufOrErr.getError().message();
   LinkModules.clear();
   return true;
 }
 
+auto  = *BCBufOrErr;
+
 Expected> ModuleOrErr =
-getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
-if (!ModuleOrErr) {
-  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase ) {
+getOwningLazyBitcodeModule(std::move(BCBuf), *VMContext);
+
+if (ModuleOrErr) {
+  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
+ F.Internalize, F.LinkFlags});
+  continue;
+} else {
+  // If parsing as bitcode failed, clear the error and try to parse as an
+  // archive.
+  handleAllErrors(ModuleOrErr.takeError(),
+  [&](const llvm::ErrorInfoBase ) {});
+
+  Expected> BinOrErr =
+  llvm::object::createBinary(BCBuf->getMemBufferRef(), VMContext);
+
+  if (!BinOrErr) {
+handleAllErrors(BinOrErr.takeError(),
+[&](const llvm::ErrorInfoBase ) {
+  
CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+LinkModules.clear();
+return true;
+  }
+
+  std::unique_ptr  = *BinOrErr;
+
+  if (Bin->isArchive()) {
+llvm::object::Archive *Archive =
+llvm::cast(Bin.get());
+Error Err = Error::success();
+
+for (auto  : Archive->children(Err)) {
+  Expected ChildBufOrErr =
+  Child.getMemoryBufferRef();
+  if (!ChildBufOrErr) {
+handleAllErrors(
+ChildBufOrErr.takeError(), [&](const llvm::ErrorInfoBase ) 
{
+  CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+continue;
+  }
+  auto ChildBuffer = llvm::MemoryBuffer::getMemBufferCopy(
+  ChildBufOrErr->getBuffer(), 
ChildBufOrErr->getBufferIdentifier());
+
+  if (!ChildBuffer) {
+handleAllErrors(
+ChildBufOrErr.takeError(), [&](const llvm::ErrorInfoBase ) 
{
+  

[clang] [-Wunsafe-buffer-usage] Add FixableGadget for AddAssign in UnspecifiedUntypedContext (PR #71862)

2023-11-10 Thread Artem Dergachev via cfe-commits

https://github.com/haoNoQ commented:

Very nice!!

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


[clang] [-Wunsafe-buffer-usage] Add FixableGadget for AddAssign in UnspecifiedUntypedContext (PR #71862)

2023-11-10 Thread Artem Dergachev via cfe-commits


@@ -1028,6 +1028,50 @@ class UPCPreIncrementGadget : public FixableGadget {
   }
 };
 
+// Representing a pointer type expression of the form `Ptr += n` in an
+// Unspecified Untyped Context (UUC):
+class UUCAddAssignGadget : public FixableGadget {
+private:
+  static constexpr const char *const UUCAddAssignTag =
+  "PointerAddAssignUnderUUC";
+  static constexpr const char *const IntOffsetTag = "IntOffset";
+  static constexpr const char *const OffsetTag = "Offset";
+
+  const BinaryOperator *Node; // the `Ptr += n` node
+  const IntegerLiteral *IntOffset = nullptr;
+  const DeclRefExpr *Offset = nullptr;
+
+public:
+  UUCAddAssignGadget(const MatchFinder::MatchResult )
+  : FixableGadget(Kind::UUCAddAssign),
+Node(Result.Nodes.getNodeAs(UUCAddAssignTag)),
+IntOffset(Result.Nodes.getNodeAs(IntOffsetTag)),
+Offset(Result.Nodes.getNodeAs(OffsetTag)) {
+assert(Node != nullptr && "Expecting a non-null matching result");
+  }
+
+  static bool classof(const Gadget *G) {
+return G->getKind() == Kind::UUCAddAssign;
+  }
+
+  static Matcher matcher() {
+return stmt(isInUnspecifiedUntypedContext(expr(ignoringImpCasts(
+binaryOperator(
+hasOperatorName("+="), hasLHS(declRefExpr(toSupportedVariable())),
+hasRHS(expr(anyOf(ignoringImpCasts(declRefExpr().bind(OffsetTag)),
+  integerLiteral().bind(IntOffsetTag)

haoNoQ wrote:

Does the exact shape of the offset expression really matter? Why not simply 
preserve it textually regardless of shape?

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


[clang] [-Wunsafe-buffer-usage] Add FixableGadget for AddAssign in UnspecifiedUntypedContext (PR #71862)

2023-11-10 Thread Artem Dergachev via cfe-commits

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


[clang] 09273d4 - Fix WebKit static analyzers to support ref and deref methods to be defined on different classes. (#69985)

2023-11-10 Thread via cfe-commits

Author: Ryosuke Niwa
Date: 2023-11-10T12:21:36-08:00
New Revision: 09273d408da97022f3146cfd11328c1a8ce50d10

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

LOG: Fix WebKit static analyzers to support ref and deref methods to be defined 
on different classes. (#69985)

Added: 

clang/test/Analysis/Checkers/WebKit/ref-cntbl-base-virtual-dtor-ref-deref-on-diff-classes.cpp

clang/test/Analysis/Checkers/WebKit/uncounted-members-ref-deref-on-diff-classes.cpp

Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index c1f180f31338cb3..d2b663410580008 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -18,24 +18,15 @@ using namespace clang;
 
 namespace {
 
-bool hasPublicRefAndDeref(const CXXRecordDecl *R) {
+bool hasPublicMethodInBaseClass(const CXXRecordDecl *R,
+const char *NameToMatch) {
   assert(R);
   assert(R->hasDefinition());
 
-  bool hasRef = false;
-  bool hasDeref = false;
   for (const CXXMethodDecl *MD : R->methods()) {
 const auto MethodName = safeGetName(MD);
-
-if (MethodName == "ref" && MD->getAccess() == AS_public) {
-  if (hasDeref)
-return true;
-  hasRef = true;
-} else if (MethodName == "deref" && MD->getAccess() == AS_public) {
-  if (hasRef)
-return true;
-  hasDeref = true;
-}
+if (MethodName == NameToMatch && MD->getAccess() == AS_public)
+  return true;
   }
   return false;
 }
@@ -44,9 +35,8 @@ bool hasPublicRefAndDeref(const CXXRecordDecl *R) {
 
 namespace clang {
 
-std::optional
-isRefCountable(const CXXBaseSpecifier* Base)
-{
+std::optional
+hasPublicMethodInBase(const CXXBaseSpecifier *Base, const char *NameToMatch) {
   assert(Base);
 
   const Type *T = Base->getType().getTypePtrOrNull();
@@ -59,7 +49,7 @@ isRefCountable(const CXXBaseSpecifier* Base)
   if (!R->hasDefinition())
 return std::nullopt;
 
-  return hasPublicRefAndDeref(R) ? R : nullptr;
+  return hasPublicMethodInBaseClass(R, NameToMatch) ? R : nullptr;
 }
 
 std::optional isRefCountable(const CXXRecordDecl* R)
@@ -70,29 +60,45 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   if (!R)
 return std::nullopt;
 
-  if (hasPublicRefAndDeref(R))
+  bool hasRef = hasPublicMethodInBaseClass(R, "ref");
+  bool hasDeref = hasPublicMethodInBaseClass(R, "deref");
+  if (hasRef && hasDeref)
 return true;
 
   CXXBasePaths Paths;
   Paths.setOrigin(const_cast(R));
 
   bool AnyInconclusiveBase = false;
-  const auto isRefCountableBase =
-  [](const CXXBaseSpecifier* Base, CXXBasePath&) {
-  std::optional IsRefCountable = 
clang::isRefCountable(Base);
-  if (!IsRefCountable) {
-  AnyInconclusiveBase = true;
-  return false;
-  }
-  return (*IsRefCountable) != nullptr;
+  const auto hasPublicRefInBase =
+  [](const CXXBaseSpecifier *Base, CXXBasePath &) {
+auto hasRefInBase = clang::hasPublicMethodInBase(Base, "ref");
+if (!hasRefInBase) {
+  AnyInconclusiveBase = true;
+  return false;
+}
+return (*hasRefInBase) != nullptr;
   };
 
-  bool BasesResult = R->lookupInBases(isRefCountableBase, Paths,
+  hasRef = hasRef || R->lookupInBases(hasPublicRefInBase, Paths,
   /*LookupInDependent =*/true);
   if (AnyInconclusiveBase)
 return std::nullopt;
 
-  return BasesResult;
+  const auto hasPublicDerefInBase =
+  [](const CXXBaseSpecifier *Base, CXXBasePath &) {
+auto hasDerefInBase = clang::hasPublicMethodInBase(Base, "deref");
+if (!hasDerefInBase) {
+  AnyInconclusiveBase = true;
+  return false;
+}
+return (*hasDerefInBase) != nullptr;
+  };
+  hasDeref = hasDeref || R->lookupInBases(hasPublicDerefInBase, Paths,
+  /*LookupInDependent =*/true);
+  if (AnyInconclusiveBase)
+return std::nullopt;
+
+  return hasRef && hasDeref;
 }
 
 bool isCtorOfRefCounted(const clang::FunctionDecl *F) {

diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index 91e3ccf2ec3047e..45b21cc0918443b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -26,10 +26,10 @@ 

[clang] Fix WebKit static analyzers to support ref and deref methods to be defined on different classes. (PR #69985)

2023-11-10 Thread Artem Dergachev via cfe-commits

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

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

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

I'm not sure now if this wont cause too much false-positives, after all this is 
why CheckFunctionCalls option were added. Sometimes object can have 2 same 
operators, one const and one not, in such case depend on "this" type, non-const 
could be used, this would be false-positive.

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

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


@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *MethodDecl =
+dyn_cast_or_null(OpCallExpr->getDirectCallee()))
+  return !MethodDecl->isConst();

PiotrZSL wrote:

What if called operator is ->, for example in assert we call -> operator on 
std::shared_ptr just to get member, and then we call const method, this could 
cause false-positive.

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

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

PiotrZSL wrote:

One more question, there is option for this check:
"CheckFunctionCalls
Whether to treat non-const member and non-member functions as they produce side 
effects. Disabled by default because it can increase the number of false 
positive warnings."

Won't this overlap this change ?

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits

https://github.com/schenker updated 
https://github.com/llvm/llvm-project/pull/71974

>From dabfdee1a982000605e4b33930ba433c63d1684f Mon Sep 17 00:00:00 2001
From: Thomas Schenker 
Date: Fri, 10 Nov 2023 18:58:26 +0100
Subject: [PATCH 1/2] [clang-tidy] bugprone-assert-side-effect non-const
 operator methods

With this PR, `bugprone-assert-side-effect` assumes that operator methods
that are not marked as `const` have side effects. This matches the
existing rule for non-operator methods.

E.g. the following snippet is now reported and was previously not:
```
std::stringstream ss;
assert(ss << 1);
```
---
 .../clang-tidy/bugprone/AssertSideEffectCheck.cpp   |  4 
 .../checkers/bugprone/assert-side-effect.cpp| 13 -
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 07a987359d4d8d7..599f5ac70e7a229 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
+  if (const auto *MethodDecl = dyn_cast(FuncDecl))
+return !MethodDecl->isConst();
+
 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
index 6c41e1e320adeac..49d3d456deb9d35 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
@@ -11,7 +11,7 @@ class MyClass {
 
   MyClass =(const MyClass ) { return *this; }
 
-  int operator-() { return 1; }
+  int operator-() const { return 1; }
 
   operator bool() const { return true; }
 
@@ -84,5 +84,16 @@ int main() {
   msvc_assert(mc2 = mc);
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in msvc_assert() 
condition discarded in release builds
 
+  struct {
+int operator<<(int i) const { return i; }
+  } constOp;
+  assert(constOp << 1);
+
+  struct {
+int operator<<(int i) { return i; }
+  } nonConstOp;
+  assert(nonConstOp << 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in assert() 
condition discarded in release builds
+
   return 0;
 }

>From 071e24c78d551301b14e7bbeebd7d1f36466a8e7 Mon Sep 17 00:00:00 2001
From: Thomas Schenker 
Date: Fri, 10 Nov 2023 21:07:39 +0100
Subject: [PATCH 2/2] use dyn_cast_or_null and add release note

---
 .../clang-tidy/bugprone/AssertSideEffectCheck.cpp   | 6 +++---
 clang-tools-extra/docs/ReleaseNotes.rst | 4 
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 599f5ac70e7a229..a6c01704b3d909f 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,9 +41,9 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
-if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
-  if (const auto *MethodDecl = dyn_cast(FuncDecl))
-return !MethodDecl->isConst();
+if (const auto *MethodDecl =
+dyn_cast_or_null(OpCallExpr->getDirectCallee()))
+  return !MethodDecl->isConst();
 
 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index c79aafdc0f06e69..846a029810454f1 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -208,6 +208,10 @@ New check aliases
 Changes in existing checks
 ^^
 
+- Improved :doc:`bugprone-assert-side-effect
+  ` check to report usage of
+  non-const operator methods in assertions.
+
 - Improved :doc:`bugprone-dangling-handle
   ` check to support functional
   casting during type conversions at variable initialization, now with improved

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits

https://github.com/schenker updated 
https://github.com/llvm/llvm-project/pull/71974

>From dabfdee1a982000605e4b33930ba433c63d1684f Mon Sep 17 00:00:00 2001
From: Thomas Schenker 
Date: Fri, 10 Nov 2023 18:58:26 +0100
Subject: [PATCH 1/2] [clang-tidy] bugprone-assert-side-effect non-const
 operator methods

With this PR, `bugprone-assert-side-effect` assumes that operator methods
that are not marked as `const` have side effects. This matches the
existing rule for non-operator methods.

E.g. the following snippet is now reported and was previously not:
```
std::stringstream ss;
assert(ss << 1);
```
---
 .../clang-tidy/bugprone/AssertSideEffectCheck.cpp   |  4 
 .../checkers/bugprone/assert-side-effect.cpp| 13 -
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 07a987359d4d8d7..599f5ac70e7a229 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
+  if (const auto *MethodDecl = dyn_cast(FuncDecl))
+return !MethodDecl->isConst();
+
 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
index 6c41e1e320adeac..49d3d456deb9d35 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
@@ -11,7 +11,7 @@ class MyClass {
 
   MyClass =(const MyClass ) { return *this; }
 
-  int operator-() { return 1; }
+  int operator-() const { return 1; }
 
   operator bool() const { return true; }
 
@@ -84,5 +84,16 @@ int main() {
   msvc_assert(mc2 = mc);
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in msvc_assert() 
condition discarded in release builds
 
+  struct {
+int operator<<(int i) const { return i; }
+  } constOp;
+  assert(constOp << 1);
+
+  struct {
+int operator<<(int i) { return i; }
+  } nonConstOp;
+  assert(nonConstOp << 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in assert() 
condition discarded in release builds
+
   return 0;
 }

>From e71a99fcce8e05f198d356a03eb84bc82fcb8941 Mon Sep 17 00:00:00 2001
From: Thomas Schenker 
Date: Fri, 10 Nov 2023 21:07:39 +0100
Subject: [PATCH 2/2] use dyn_cast_or_null and add release note

---
 .../clang-tidy/bugprone/AssertSideEffectCheck.cpp   | 6 +++---
 clang-tools-extra/docs/ReleaseNotes.rst | 3 +++
 2 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 599f5ac70e7a229..a6c01704b3d909f 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,9 +41,9 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
-if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
-  if (const auto *MethodDecl = dyn_cast(FuncDecl))
-return !MethodDecl->isConst();
+if (const auto *MethodDecl =
+dyn_cast_or_null(OpCallExpr->getDirectCallee()))
+  return !MethodDecl->isConst();
 
 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index c79aafdc0f06e69..4fa44ac473c5aff 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -208,6 +208,9 @@ New check aliases
 Changes in existing checks
 ^^
 
+- Improved :doc:`bugprone-assert-side-effect
+  ` check to report usage of 
non-const operator methods in assertions.
+
 - Improved :doc:`bugprone-dangling-handle
   ` check to support functional
   casting during type conversions at variable initialization, now with improved

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


[clang] [-Wunsafe-buffer-usage] Add FixableGadget for AddAssign in UnspecifiedUntypedContext (PR #71862)

2023-11-10 Thread Rashmi Mudduluru via cfe-commits

https://github.com/t-rasmud updated 
https://github.com/llvm/llvm-project/pull/71862

>From 6636745d1c444747a33c91b366a730d81ca5db5a Mon Sep 17 00:00:00 2001
From: Rashmi Mudduluru 
Date: Wed, 1 Nov 2023 13:43:12 -0700
Subject: [PATCH 1/6] [-Wunsafe-buffer-usage][WIP] Fixable gadget for AddAssign

---
 .../Analyses/UnsafeBufferUsageGadgets.def |  1 +
 clang/lib/Analysis/UnsafeBufferUsage.cpp  | 65 +++
 ...-unsafe-buffer-usage-fixits-add-assign.cpp | 38 +++
 3 files changed, 104 insertions(+)
 create mode 100644 
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-add-assign.cpp

diff --git a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def 
b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def
index ff687a0d178bdea..757ee452ced7488 100644
--- a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def
+++ b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def
@@ -36,6 +36,7 @@ FIXABLE_GADGET(PointerDereference)
 FIXABLE_GADGET(UPCAddressofArraySubscript) // '[any]' in an Unspecified 
Pointer Context
 FIXABLE_GADGET(UPCStandalonePointer)
 FIXABLE_GADGET(UPCPreIncrement)// '++Ptr' in an Unspecified 
Pointer Context
+FIXABLE_GADGET(UUCAddAssign)// 'Ptr += n' in an Unspecified 
Untyped Context
 FIXABLE_GADGET(PointerAssignment)
 FIXABLE_GADGET(PointerInit)
 
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index e332a3609290aac..7b79f5360c79d6e 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1028,6 +1028,42 @@ class UPCPreIncrementGadget : public FixableGadget {
   }
 };
 
+// Representing a pointer type expression of the form `Ptr += n` in an
+// Unspecified Untyped Context (UUC):
+class UUCAddAssignGadget : public FixableGadget {
+private:
+  static constexpr const char *const UUCAddAssignTag =
+"PointerAddAssignUnderUUC";
+  const BinaryOperator *Node; // the `Ptr += n` node
+
+public:
+  UUCAddAssignGadget(const MatchFinder::MatchResult )
+: FixableGadget(Kind::UUCAddAssign),
+  Node(Result.Nodes.getNodeAs(UUCAddAssignTag)) {
+assert(Node != nullptr && "Expecting a non-null matching result");
+  }
+
+  static bool classof(const Gadget *G) {
+return G->getKind() == Kind::UUCAddAssign;
+  }
+
+  static Matcher matcher() {
+return stmt(isInUnspecifiedUntypedContext(expr(ignoringImpCasts(
+binaryOperator(hasOperatorName("+="),
+  hasLHS(declRefExpr(
+toSupportedVariable()))
+  ).bind(UUCAddAssignTag);
+  }
+
+  virtual std::optional getFixits(const Strategy ) const override;
+
+  virtual const Stmt *getBaseStmt() const override { return Node; }
+
+  virtual DeclUseList getClaimedVarUseSites() const override {
+return {dyn_cast(Node->getLHS())};
+  }
+};
+
 // Representing a fixable expression of the form `*(ptr + 123)` or `*(123 +
 // ptr)`:
 class DerefSimplePtrArithFixableGadget : public FixableGadget {
@@ -1766,6 +1802,35 @@ fixUPCAddressofArraySubscriptWithSpan(const 
UnaryOperator *Node) {
   FixItHint::CreateReplacement(Node->getSourceRange(), SS.str())};
 }
 
+std::optional UUCAddAssignGadget::getFixits(const Strategy ) 
const {
+  DeclUseList DREs = getClaimedVarUseSites();
+
+  if (DREs.size() != 1)
+return std::nullopt; // In cases of `Ptr += n` where `Ptr` is not a DRE, we
+ // give up
+  if (const VarDecl *VD = dyn_cast(DREs.front()->getDecl())) {
+if (S.lookup(VD) == Strategy::Kind::Span) {
+  FixItList Fixes;
+  std::stringstream SS;
+  const Stmt *AddAssignNode = getBaseStmt();
+  StringRef varName = VD->getName();
+  const ASTContext  = VD->getASTContext();
+
+  // To transform UUC(p += n) to UUC((p = p.subspan(1)).data()):
+  SS << varName.data() << " = " << varName.data()
+ << ".subspan(" << getUserFillPlaceHolder() << ")";
+  std::optional AddAssignLocation =
+  getEndCharLoc(AddAssignNode, Ctx.getSourceManager(), 
Ctx.getLangOpts());
+  if (!AddAssignLocation)
+return std::nullopt;
+
+  Fixes.push_back(FixItHint::CreateReplacement(
+  SourceRange(AddAssignNode->getBeginLoc(), *AddAssignLocation), 
SS.str()));
+  return Fixes;
+}
+  }
+  return std::nullopt; // Not in the cases that we can handle for now, give up.
+}
 
 std::optional UPCPreIncrementGadget::getFixits(const Strategy ) 
const {
   DeclUseList DREs = getClaimedVarUseSites();
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-add-assign.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-add-assign.cpp
new file mode 100644
index 000..e2b9a43dee9b3c3
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-add-assign.cpp
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage \
+// RUN:

[clang] [llvm] [Instcombine] use zext's nneg flag for icmp folding (PR #70845)

2023-11-10 Thread Léonard Oest O'Leary via cfe-commits

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


[clang] [llvm] [Instcombine] use zext's nneg flag for icmp folding (PR #70845)

2023-11-10 Thread Léonard Oest O'Leary via cfe-commits

https://github.com/leo-ard updated 
https://github.com/llvm/llvm-project/pull/70845

From 00d0c18b5414ffe7222e1ee0ad5ecfdb8783704e Mon Sep 17 00:00:00 2001
From: leo-ard 
Date: Mon, 30 Oct 2023 18:01:27 -0400
Subject: [PATCH 01/13] Add NonNeg check for InstCombine

---
 llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp | 8 ++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index 7c2ad92f919a3cc..cd287d757fdfd23 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -5554,11 +5554,15 @@ Instruction 
*InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst ) {
 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
 Constant::getNullValue(X->getType()));
 
+  // Treat "zext nneg" as "sext"
+  bool IsNonNeg0 = isa(ICmp.getOperand(0));
+  bool IsNonNeg1 = isa(ICmp.getOperand(1));
+
   // If we have mismatched casts, treat the zext of a non-negative source 
as
   // a sext to simulate matching casts. Otherwise, we are done.
   // TODO: Can we handle some predicates (equality) without non-negative?
-  if ((IsZext0 && isKnownNonNegative(X, DL, 0, , , )) ||
-  (IsZext1 && isKnownNonNegative(Y, DL, 0, , , )))
+  if ((IsZext0 && (IsNonNeg0 || isKnownNonNegative(X, DL, 0, , , 
))) ||
+  (IsZext1 && (IsNonNeg1 || isKnownNonNegative(Y, DL, 0, , , 

 IsSignedExt = true;
   else
 return nullptr;

From ee1978946530e28ff79f924bcc5ffd73dc590549 Mon Sep 17 00:00:00 2001
From: leo-ard 
Date: Mon, 30 Oct 2023 18:03:44 -0400
Subject: [PATCH 02/13] Add tests for min/max

---
 clang/test/CodeGen/X86/min_max.c  |  19 ++
 .../Transforms/SCCP/icmp-fold-with-cast.ll| 185 ++
 2 files changed, 204 insertions(+)
 create mode 100644 clang/test/CodeGen/X86/min_max.c
 create mode 100644 llvm/test/Transforms/SCCP/icmp-fold-with-cast.ll

diff --git a/clang/test/CodeGen/X86/min_max.c b/clang/test/CodeGen/X86/min_max.c
new file mode 100644
index 000..7af8181cc9ff367
--- /dev/null
+++ b/clang/test/CodeGen/X86/min_max.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 %s -O2 -triple=x86_64-apple-darwin -emit-llvm -o - | 
FileCheck %s
+
+short vecreduce_smax_v2i16(int n, short* v)
+{
+  // CHECK: @llvm.smax
+  short p = 0;
+  for (int i = 0; i < n; ++i)
+p = p < v[i] ? v[i] : p;
+  return p;
+}
+
+short vecreduce_smin_v2i16(int n, short* v)
+{
+  // CHECK: @llvm.smin
+  short p = 0;
+  for (int i = 0; i < n; ++i)
+p = p > v[i] ? v[i] : p;
+  return p;
+}
\ No newline at end of file
diff --git a/llvm/test/Transforms/SCCP/icmp-fold-with-cast.ll 
b/llvm/test/Transforms/SCCP/icmp-fold-with-cast.ll
new file mode 100644
index 000..90b2c123081fb49
--- /dev/null
+++ b/llvm/test/Transforms/SCCP/icmp-fold-with-cast.ll
@@ -0,0 +1,185 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --tool ./bin/opt --version 3
+; See PRXXX for more details
+; RUN: opt < %s -S -passes=ipsccp | FileCheck %s
+
+
+define signext i32 @sext_sext(i16 %x, i16 %y) {
+; CHECK-LABEL: define signext i32 @sext_sext(
+; CHECK-SAME: i16 [[X:%.*]], i16 [[Y:%.*]]) {
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[CONV:%.*]] = sext i16 [[X]] to i32
+; CHECK-NEXT:[[CONV1:%.*]] = sext i16 [[Y]] to i32
+; CHECK-NEXT:[[CMP2:%.*]] = icmp sgt i16 [[X]], [[Y]]
+; CHECK-NEXT:br i1 [[CMP2]], label [[COND_TRUE:%.*]], label 
[[COND_FALSE:%.*]]
+; CHECK:   cond.true:
+; CHECK-NEXT:br label [[COND_END:%.*]]
+; CHECK:   cond.false:
+; CHECK-NEXT:br label [[COND_END]]
+; CHECK:   cond.end:
+; CHECK-NEXT:[[COND:%.*]] = phi i32 [ 0, [[COND_TRUE]] ], [ 1, 
[[COND_FALSE]] ]
+; CHECK-NEXT:ret i32 [[COND]]
+;
+entry:
+  %conv = sext i16 %x to i32
+  %conv1 = sext i16 %y to i32
+  %cmp2 = icmp sgt i32 %conv, %conv1
+  br i1 %cmp2, label %cond.true, label %cond.false
+
+cond.true:; preds = %for.body
+  br label %cond.end
+
+cond.false:   ; preds = %for.body
+  br label %cond.end
+
+cond.end: ; preds = %cond.false, 
%cond.true
+  %cond = phi i32 [ 0, %cond.true ], [ 1, %cond.false ]
+  ret i32 %cond
+}
+
+
+define signext i32 @zext_zext(i16 %x, i16 %y) {
+; CHECK-LABEL: define signext i32 @zext_zext(
+; CHECK-SAME: i16 [[X:%.*]], i16 [[Y:%.*]]) {
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[CONV:%.*]] = zext i16 [[X]] to i32
+; CHECK-NEXT:[[CONV1:%.*]] = zext i16 [[Y]] to i32
+; CHECK-NEXT:[[CMP2:%.*]] = icmp sgt i16 [[X]], [[Y]]
+; CHECK-NEXT:br i1 [[CMP2]], label [[COND_TRUE:%.*]], label 
[[COND_FALSE:%.*]]
+; CHECK:   cond.true:
+; CHECK-NEXT:br label [[COND_END:%.*]]
+; CHECK:   cond.false:
+; CHECK-NEXT:br label 

[llvm] [clang] [Instcombine] use zext's nneg flag for icmp folding (PR #70845)

2023-11-10 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 3f906f513edea5c21867586d92151c4268230fe4 
3f2ad99f9a6d177ea2747bfc0e559aad1faf8639 -- 
llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index b003b65955ac..03bc0f16c893 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -5554,8 +5554,8 @@ Instruction 
*InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst ) {
 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
 Constant::getNullValue(X->getType()));
 
-  // If we have mismatched casts and zext has the nneg flag, we can 
-  //  treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit. 
+  // If we have mismatched casts and zext has the nneg flag, we can
+  //  treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
 
   auto *NonNegInst0 = dyn_cast(ICmp.getOperand(0));
   auto *NonNegInst1 = dyn_cast(ICmp.getOperand(1));

``




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


[llvm] [clang] [Instcombine] use zext's nneg flag for icmp folding (PR #70845)

2023-11-10 Thread Léonard Oest O'Leary via cfe-commits


@@ -0,0 +1,175 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 3
+; See PR-70845 for more details
+; RUN: opt < %s -S -passes=instcombine | FileCheck %s
+
+
+define signext i32 @sext_sext(i16 %x, i16 %y) {

leo-ard wrote:

The technique of commenting and seeing which tests crashed worked really well. 
Thanks for the trick

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


[llvm] [clang] [Instcombine] use zext's nneg flag for icmp folding (PR #70845)

2023-11-10 Thread Léonard Oest O'Leary via cfe-commits


@@ -247,6 +355,19 @@ define i1 @sext_zext_uge_op0_wide(i16 %x, i8 %y) {
   ret i1 %c
 }
 
+
+define i1 @sext_zext_nneg_uge_op0_wide(i16 %x, i8 %y) {
+; CHECK-LABEL: @sext_zext_nneg_uge_op0_wide(
+; CHECK-NEXT:[[TMP1:%.*]] = sext i8 [[Y:%.*]] to i16
+; CHECK-NEXT:[[C:%.*]] = icmp ule i16 [[TMP1]], [[X:%.*]]
+; CHECK-NEXT:ret i1 [[C]]
+;
+  %a = sext i16 %x to i32
+  %b = zext nneg i8 %y to i32
+  %c = icmp uge i32 %a, %b
+  ret i1 %c
+}
+
 define i1 @zext_sext_sgt_known_nonneg(i8 %x, i8 %y) {
 ; CHECK-LABEL: @zext_sext_sgt_known_nonneg(

leo-ard wrote:

Every test in this test-file has an `known_nonneg` variant for mismatched 
zext/sext. I was wondering on the relevance of this variant as we now have the 
nneg flag on zext. It would make more sense to have specialized tests for zext 
-> zext nneg folding with value-tracking and another test for icmp with zext 
nneg/sext folding into icmp (what I just added). FYI, this test dates from this 
PR, when there where no nneg flag : https://reviews.llvm.org/D124419. 

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


[clang] [clang-tools-extra] [llvm] [clang-format] Handle variable declarations in BreakAfterAttributes (PR #71935)

2023-11-10 Thread Björn Schäpers via cfe-commits

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


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


[llvm] [clang] [Instcombine] use zext's nneg flag for icmp folding (PR #70845)

2023-11-10 Thread Léonard Oest O'Leary via cfe-commits


@@ -0,0 +1,175 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 3
+; See PR-70845 for more details
+; RUN: opt < %s -S -passes=instcombine | FileCheck %s
+
+
+define signext i32 @sext_sext(i16 %x, i16 %y) {
+; CHECK-LABEL: define signext i32 @sext_sext(
+; CHECK-SAME: i16 [[X:%.*]], i16 [[Y:%.*]]) {
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[CMP2:%.*]] = icmp sgt i16 [[X]], [[Y]]
+; CHECK-NEXT:br i1 [[CMP2]], label [[COND_TRUE:%.*]], label 
[[COND_FALSE:%.*]]
+; CHECK:   cond.true:
+; CHECK-NEXT:br label [[COND_END:%.*]]
+; CHECK:   cond.false:
+; CHECK-NEXT:br label [[COND_END]]
+; CHECK:   cond.end:
+; CHECK-NEXT:[[COND:%.*]] = phi i32 [ 0, [[COND_TRUE]] ], [ 1, 
[[COND_FALSE]] ]
+; CHECK-NEXT:ret i32 [[COND]]
+;
+entry:
+  %conv = sext i16 %x to i32
+  %conv1 = sext i16 %y to i32
+  %cmp2 = icmp sgt i32 %conv, %conv1
+  br i1 %cmp2, label %cond.true, label %cond.false
+
+cond.true:; preds = %for.body
+  br label %cond.end
+
+cond.false:   ; preds = %for.body
+  br label %cond.end
+
+cond.end: ; preds = %cond.false, 
%cond.true
+  %cond = phi i32 [ 0, %cond.true ], [ 1, %cond.false ]
+  ret i32 %cond
+}
+
+
+define signext i32 @zext_zext(i16 %x, i16 %y) {
+; CHECK-LABEL: define signext i32 @zext_zext(
+; CHECK-SAME: i16 [[X:%.*]], i16 [[Y:%.*]]) {
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[CMP2:%.*]] = icmp ugt i16 [[X]], [[Y]]
+; CHECK-NEXT:br i1 [[CMP2]], label [[COND_TRUE:%.*]], label 
[[COND_FALSE:%.*]]
+; CHECK:   cond.true:
+; CHECK-NEXT:br label [[COND_END:%.*]]
+; CHECK:   cond.false:
+; CHECK-NEXT:br label [[COND_END]]
+; CHECK:   cond.end:
+; CHECK-NEXT:[[COND:%.*]] = phi i32 [ 0, [[COND_TRUE]] ], [ 1, 
[[COND_FALSE]] ]
+; CHECK-NEXT:ret i32 [[COND]]
+;
+entry:
+  %conv = zext i16 %x to i32
+  %conv1 = zext i16 %y to i32
+  %cmp2 = icmp sgt i32 %conv, %conv1
+  br i1 %cmp2, label %cond.true, label %cond.false
+
+cond.true:; preds = %for.body
+  br label %cond.end
+
+cond.false:   ; preds = %for.body
+  br label %cond.end
+
+cond.end: ; preds = %cond.false, 
%cond.true
+  %cond = phi i32 [ 0, %cond.true ], [ 1, %cond.false ]
+  ret i32 %cond
+}
+
+
+define signext i16 @zext_positive_and_sext(i32 noundef %n, ptr noundef %v) {
+; CHECK-LABEL: define signext i16 @zext_positive_and_sext(
+; CHECK-SAME: i32 noundef [[N:%.*]], ptr noundef [[V:%.*]]) {
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:br label [[FOR_COND:%.*]]
+; CHECK:   for.cond:
+; CHECK-NEXT:[[P_0:%.*]] = phi i16 [ 0, [[ENTRY:%.*]] ], [ 
[[COND_OFF0:%.*]], [[COND_END:%.*]] ]
+; CHECK-NEXT:[[I_0:%.*]] = phi i32 [ 0, [[ENTRY]] ], [ [[INC:%.*]], 
[[COND_END]] ]
+; CHECK-NEXT:[[CMP:%.*]] = icmp slt i32 [[I_0]], [[N]]
+; CHECK-NEXT:br i1 [[CMP]], label [[FOR_BODY:%.*]], label 
[[FOR_COND_CLEANUP:%.*]]
+; CHECK:   for.body:
+; CHECK-NEXT:[[IDXPROM:%.*]] = zext nneg i32 [[I_0]] to i64
+; CHECK-NEXT:[[ARRAYIDX:%.*]] = getelementptr i16, ptr [[V]], i64 
[[IDXPROM]]
+; CHECK-NEXT:[[TMP0:%.*]] = load i16, ptr [[ARRAYIDX]], align 2
+; CHECK-NEXT:[[CMP2:%.*]] = icmp slt i16 [[P_0]], [[TMP0]]
+; CHECK-NEXT:br i1 [[CMP2]], label [[COND_TRUE:%.*]], label 
[[COND_FALSE:%.*]]
+; CHECK:   cond.true:
+; CHECK-NEXT:br label [[COND_END]]
+; CHECK:   cond.false:
+; CHECK-NEXT:br label [[COND_END]]
+; CHECK:   for.cond.cleanup:
+; CHECK-NEXT:ret i16 [[P_0]]
+; CHECK:   cond.end:
+; CHECK-NEXT:[[COND_OFF0]] = phi i16 [ [[TMP0]], [[COND_TRUE]] ], [ 
[[P_0]], [[COND_FALSE]] ]
+; CHECK-NEXT:[[INC]] = add nuw nsw i32 [[I_0]], 1
+; CHECK-NEXT:br label [[FOR_COND]]
+;
+entry:
+  br label %for.cond
+
+for.cond: ; preds = %cond.end, %entry
+  %p.0 = phi i16 [ 0, %entry ], [ %conv8, %cond.end ]
+  %i.0 = phi i32 [ 0, %entry ], [ %inc, %cond.end ]
+  %cmp = icmp slt i32 %i.0, %n
+  br i1 %cmp, label %for.body, label %for.cond.cleanup
+
+for.body: ; preds = %for.cond
+  %conv = zext nneg i16 %p.0 to i32;; %p.0 is always 
positive here
+  %idxprom = sext i32 %i.0 to i64
+  %arrayidx = getelementptr i16, ptr %v, i64 %idxprom
+  %0 = load i16, ptr %arrayidx, align 2
+  %conv1 = sext i16 %0 to i32
+  %cmp2 = icmp slt i32 %conv, %conv1
+  br i1 %cmp2, label %cond.true, label %cond.false
+
+cond.true:; preds = %for.body
+  br label %cond.end
+
+cond.false:   ; preds = %for.body
+  br label %cond.end
+
+for.cond.cleanup: ; preds = %for.cond
+  ret i16 %p.0
+
+cond.end: ; preds = %cond.false, 

[llvm] [clang] [Instcombine] use zext's nneg flag for icmp folding (PR #70845)

2023-11-10 Thread Léonard Oest O'Leary via cfe-commits

https://github.com/leo-ard updated 
https://github.com/llvm/llvm-project/pull/70845

From 00d0c18b5414ffe7222e1ee0ad5ecfdb8783704e Mon Sep 17 00:00:00 2001
From: leo-ard 
Date: Mon, 30 Oct 2023 18:01:27 -0400
Subject: [PATCH 01/12] Add NonNeg check for InstCombine

---
 llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp | 8 ++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index 7c2ad92f919a3cc..cd287d757fdfd23 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -5554,11 +5554,15 @@ Instruction 
*InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst ) {
 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
 Constant::getNullValue(X->getType()));
 
+  // Treat "zext nneg" as "sext"
+  bool IsNonNeg0 = isa(ICmp.getOperand(0));
+  bool IsNonNeg1 = isa(ICmp.getOperand(1));
+
   // If we have mismatched casts, treat the zext of a non-negative source 
as
   // a sext to simulate matching casts. Otherwise, we are done.
   // TODO: Can we handle some predicates (equality) without non-negative?
-  if ((IsZext0 && isKnownNonNegative(X, DL, 0, , , )) ||
-  (IsZext1 && isKnownNonNegative(Y, DL, 0, , , )))
+  if ((IsZext0 && (IsNonNeg0 || isKnownNonNegative(X, DL, 0, , , 
))) ||
+  (IsZext1 && (IsNonNeg1 || isKnownNonNegative(Y, DL, 0, , , 

 IsSignedExt = true;
   else
 return nullptr;

From ee1978946530e28ff79f924bcc5ffd73dc590549 Mon Sep 17 00:00:00 2001
From: leo-ard 
Date: Mon, 30 Oct 2023 18:03:44 -0400
Subject: [PATCH 02/12] Add tests for min/max

---
 clang/test/CodeGen/X86/min_max.c  |  19 ++
 .../Transforms/SCCP/icmp-fold-with-cast.ll| 185 ++
 2 files changed, 204 insertions(+)
 create mode 100644 clang/test/CodeGen/X86/min_max.c
 create mode 100644 llvm/test/Transforms/SCCP/icmp-fold-with-cast.ll

diff --git a/clang/test/CodeGen/X86/min_max.c b/clang/test/CodeGen/X86/min_max.c
new file mode 100644
index 000..7af8181cc9ff367
--- /dev/null
+++ b/clang/test/CodeGen/X86/min_max.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 %s -O2 -triple=x86_64-apple-darwin -emit-llvm -o - | 
FileCheck %s
+
+short vecreduce_smax_v2i16(int n, short* v)
+{
+  // CHECK: @llvm.smax
+  short p = 0;
+  for (int i = 0; i < n; ++i)
+p = p < v[i] ? v[i] : p;
+  return p;
+}
+
+short vecreduce_smin_v2i16(int n, short* v)
+{
+  // CHECK: @llvm.smin
+  short p = 0;
+  for (int i = 0; i < n; ++i)
+p = p > v[i] ? v[i] : p;
+  return p;
+}
\ No newline at end of file
diff --git a/llvm/test/Transforms/SCCP/icmp-fold-with-cast.ll 
b/llvm/test/Transforms/SCCP/icmp-fold-with-cast.ll
new file mode 100644
index 000..90b2c123081fb49
--- /dev/null
+++ b/llvm/test/Transforms/SCCP/icmp-fold-with-cast.ll
@@ -0,0 +1,185 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --tool ./bin/opt --version 3
+; See PRXXX for more details
+; RUN: opt < %s -S -passes=ipsccp | FileCheck %s
+
+
+define signext i32 @sext_sext(i16 %x, i16 %y) {
+; CHECK-LABEL: define signext i32 @sext_sext(
+; CHECK-SAME: i16 [[X:%.*]], i16 [[Y:%.*]]) {
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[CONV:%.*]] = sext i16 [[X]] to i32
+; CHECK-NEXT:[[CONV1:%.*]] = sext i16 [[Y]] to i32
+; CHECK-NEXT:[[CMP2:%.*]] = icmp sgt i16 [[X]], [[Y]]
+; CHECK-NEXT:br i1 [[CMP2]], label [[COND_TRUE:%.*]], label 
[[COND_FALSE:%.*]]
+; CHECK:   cond.true:
+; CHECK-NEXT:br label [[COND_END:%.*]]
+; CHECK:   cond.false:
+; CHECK-NEXT:br label [[COND_END]]
+; CHECK:   cond.end:
+; CHECK-NEXT:[[COND:%.*]] = phi i32 [ 0, [[COND_TRUE]] ], [ 1, 
[[COND_FALSE]] ]
+; CHECK-NEXT:ret i32 [[COND]]
+;
+entry:
+  %conv = sext i16 %x to i32
+  %conv1 = sext i16 %y to i32
+  %cmp2 = icmp sgt i32 %conv, %conv1
+  br i1 %cmp2, label %cond.true, label %cond.false
+
+cond.true:; preds = %for.body
+  br label %cond.end
+
+cond.false:   ; preds = %for.body
+  br label %cond.end
+
+cond.end: ; preds = %cond.false, 
%cond.true
+  %cond = phi i32 [ 0, %cond.true ], [ 1, %cond.false ]
+  ret i32 %cond
+}
+
+
+define signext i32 @zext_zext(i16 %x, i16 %y) {
+; CHECK-LABEL: define signext i32 @zext_zext(
+; CHECK-SAME: i16 [[X:%.*]], i16 [[Y:%.*]]) {
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[CONV:%.*]] = zext i16 [[X]] to i32
+; CHECK-NEXT:[[CONV1:%.*]] = zext i16 [[Y]] to i32
+; CHECK-NEXT:[[CMP2:%.*]] = icmp sgt i16 [[X]], [[Y]]
+; CHECK-NEXT:br i1 [[CMP2]], label [[COND_TRUE:%.*]], label 
[[COND_FALSE:%.*]]
+; CHECK:   cond.true:
+; CHECK-NEXT:br label [[COND_END:%.*]]
+; CHECK:   cond.false:
+; CHECK-NEXT:br label 

[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

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


@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *FuncDecl = OpCallExpr->getDirectCallee())

PiotrZSL wrote:

Merge this FuncDecl with MethodDecl by using dyn_cast_or_null

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

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


@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
+  if (const auto *MethodDecl = dyn_cast(FuncDecl))
+return !MethodDecl->isConst();

PiotrZSL wrote:

should it be `if (MethodDecl->isConst()) return false`; otherwise code in line 
49 could be a dead code.

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

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

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

Update documentation of this check to mention this, and update release notes.
Code looks fine.

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


[clang] [clang][CodeGen] Ensure consistent `mustprogress` attribute emission across all paths (PR #71452)

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

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

LGTM

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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: None (schenker)


Changes

With this PR, `bugprone-assert-side-effect` assumes that operator methods that 
are not marked as `const` have side effects. This matches the existing rule for 
non-operator methods.

E.g. the following snippet is now reported and was previously not:
```
std::stringstream ss;
assert(ss  1);
```

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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
(+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp 
(+12-1) 


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 07a987359d4d8d7..599f5ac70e7a229 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
+  if (const auto *MethodDecl = dyn_cast(FuncDecl))
+return !MethodDecl->isConst();
+
 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
index 6c41e1e320adeac..49d3d456deb9d35 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
@@ -11,7 +11,7 @@ class MyClass {
 
   MyClass =(const MyClass ) { return *this; }
 
-  int operator-() { return 1; }
+  int operator-() const { return 1; }
 
   operator bool() const { return true; }
 
@@ -84,5 +84,16 @@ int main() {
   msvc_assert(mc2 = mc);
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in msvc_assert() 
condition discarded in release builds
 
+  struct {
+int operator<<(int i) const { return i; }
+  } constOp;
+  assert(constOp << 1);
+
+  struct {
+int operator<<(int i) { return i; }
+  } nonConstOp;
+  assert(nonConstOp << 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in assert() 
condition discarded in release builds
+
   return 0;
 }

``




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


[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect non-const operator methods (PR #71974)

2023-11-10 Thread via cfe-commits

https://github.com/schenker created 
https://github.com/llvm/llvm-project/pull/71974

With this PR, `bugprone-assert-side-effect` assumes that operator methods that 
are not marked as `const` have side effects. This matches the existing rule for 
non-operator methods.

E.g. the following snippet is now reported and was previously not:
```
std::stringstream ss;
assert(ss << 1);
```

>From dabfdee1a982000605e4b33930ba433c63d1684f Mon Sep 17 00:00:00 2001
From: Thomas Schenker 
Date: Fri, 10 Nov 2023 18:58:26 +0100
Subject: [PATCH] [clang-tidy] bugprone-assert-side-effect non-const operator
 methods

With this PR, `bugprone-assert-side-effect` assumes that operator methods
that are not marked as `const` have side effects. This matches the
existing rule for non-operator methods.

E.g. the following snippet is now reported and was previously not:
```
std::stringstream ss;
assert(ss << 1);
```
---
 .../clang-tidy/bugprone/AssertSideEffectCheck.cpp   |  4 
 .../checkers/bugprone/assert-side-effect.cpp| 13 -
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
index 07a987359d4d8d7..599f5ac70e7a229 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp
@@ -41,6 +41,10 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls,
   }
 
   if (const auto *OpCallExpr = dyn_cast(E)) {
+if (const auto *FuncDecl = OpCallExpr->getDirectCallee())
+  if (const auto *MethodDecl = dyn_cast(FuncDecl))
+return !MethodDecl->isConst();
+
 OverloadedOperatorKind OpKind = OpCallExpr->getOperator();
 return OpKind == OO_Equal || OpKind == OO_PlusEqual ||
OpKind == OO_MinusEqual || OpKind == OO_StarEqual ||
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
index 6c41e1e320adeac..49d3d456deb9d35 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp
@@ -11,7 +11,7 @@ class MyClass {
 
   MyClass =(const MyClass ) { return *this; }
 
-  int operator-() { return 1; }
+  int operator-() const { return 1; }
 
   operator bool() const { return true; }
 
@@ -84,5 +84,16 @@ int main() {
   msvc_assert(mc2 = mc);
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in msvc_assert() 
condition discarded in release builds
 
+  struct {
+int operator<<(int i) const { return i; }
+  } constOp;
+  assert(constOp << 1);
+
+  struct {
+int operator<<(int i) { return i; }
+  } nonConstOp;
+  assert(nonConstOp << 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in assert() 
condition discarded in release builds
+
   return 0;
 }

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


[llvm] [openmp] [clang] [OpenMP] Rework handling of global ctor/dtors in OpenMP (PR #71739)

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

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/71739

>From e0281fc280385286c3d5da7de619e793bd3b6bea Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 7 Nov 2023 17:12:31 -0600
Subject: [PATCH] [OpenMP] Rework handling of global ctor/dtors in OpenMP

Summary:
This patch reworks how we handle global constructors in OpenMP.
Previously, we emitted individual kernels that were all registered and
called individually. In order to provide more generic support, this
patch moves all handling of this to the target backend and the runtime
plugin. This has the benefit of supporting the GNU extensions for
constructors an destructors, removing a class of failures related to
shared library destruction order, and allows targets other than OpenMP
to use the same support without needing to change the frontend.

This is primarily done by calling kernels that the backend emits to
iterate a list of ctor / dtor functions. For x64, this is automatic and
we get it for free with the standard `dlopen` handling. For AMDGPU, we
emit `amdgcn.device.init` and `amdgcn.device.fini` functions which
handle everything atuomatically and simply need to be called. For NVPTX,
a patch https://github.com/llvm/llvm-project/pull/71549 provides the
kernels to call, but the runtime needs to set up the array manually by
pulling out all the known constructor / destructor functions.

One concession that this patch requires is the change that for GPU
targets in OpenMP offloading we will use `llvm.global_dtors` instead of
using `atexit`. This is because `atexit` is a separate runtime function
that does not mesh well with the handling we're trying to do here. This
should be equivalent in all cases except for cases where we would need
to destruct manually such as:

```
struct S { ~S() { foo(); } };
void foo() {
  static S s;
}
```

However this is broken in many other ways on the GPU, so it is not
regressing any support, simply increasing the scope of what we can
handle.

This changes the handling of ctors / dtors. This patch now outputs a
information message regarding the deprecation if the old format is used.
This will be completely removed in a later release.

Depends on: https://github.com/llvm/llvm-project/pull/71549

Add LangOption for atexit usage

Summary:
This method isn't 1-to-1 but it's more functional than not having it.
---
 clang/include/clang/Basic/LangOptions.h   |   3 +
 clang/lib/CodeGen/CGDeclCXX.cpp   |  13 +-
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 130 --
 clang/lib/CodeGen/CGOpenMPRuntime.h   |   8 --
 clang/lib/CodeGen/CodeGenFunction.h   |   5 +
 clang/lib/CodeGen/CodeGenModule.h |  14 +-
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |   8 ++
 .../amdgcn_openmp_device_math_constexpr.cpp   |  48 +--
 .../amdgcn_target_global_constructor.cpp  |  30 ++--
 clang/test/OpenMP/declare_target_codegen.cpp  |   1 -
 ...x_declare_target_var_ctor_dtor_codegen.cpp |  35 +
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   |   4 -
 llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp |   7 +-
 .../plugins-nextgen/amdgpu/src/rtl.cpp|  42 ++
 .../common/PluginInterface/GlobalHandler.h|  10 +-
 .../PluginInterface/PluginInterface.cpp   |   7 +
 .../common/PluginInterface/PluginInterface.h  |  14 ++
 .../plugins-nextgen/cuda/src/rtl.cpp  | 110 +++
 openmp/libomptarget/src/rtl.cpp   |   9 +-
 .../test/libc/global_ctor_dtor.cpp|  37 +
 20 files changed, 318 insertions(+), 217 deletions(-)
 create mode 100644 openmp/libomptarget/test/libc/global_ctor_dtor.cpp

diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 20a8ada60e0fe51..ae99357eeea7f41 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -597,6 +597,9 @@ class LangOptions : public LangOptionsBase {
 return !requiresStrictPrototypes() && !OpenCL;
   }
 
+  /// Returns true if the language supports calling the 'atexit' function.
+  bool hasAtExit() const { return !(OpenMP && OpenMPIsTargetDevice); }
+
   /// Returns true if implicit int is part of the language requirements.
   bool isImplicitIntRequired() const { return !CPlusPlus && !C99; }
 
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index 3fa28b343663f61..e08a1e5f42df20c 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -327,6 +327,15 @@ void CodeGenFunction::registerGlobalDtorWithAtExit(const 
VarDecl ,
   registerGlobalDtorWithAtExit(dtorStub);
 }
 
+/// Register a global destructor using the LLVM 'llvm.global_dtors' global.
+void CodeGenFunction::registerGlobalDtorWithLLVM(const VarDecl ,
+ llvm::FunctionCallee Dtor,
+ llvm::Constant *Addr) {
+  // Create a function which calls the destructor.
+  

[llvm] [compiler-rt] [clang] [Profile] Refactor profile correlation. (PR #70856)

2023-11-10 Thread Fangrui Song via cfe-commits

MaskRay wrote:

I am nervous with new `if (hasCorrelation())` conditions as well.


If you use the same name for a non-SHF_ALLOC section and a SHF_ALLOC section, 
the linked output has the SHF_ALLOC flag and you cannot tell what components 
were non-SHF_ALLOC.
```
.section aa,"",@progbits,unique,1
.quad 0

.section aa,"a",@progbits,unique,2
.quad 0
```

Usually, the better idea is to use different section names. It may require some 
trial and error to see how much complexity this scheme will bring.

> I feel like this is a bug in lld as _start/_stop symbols for non allocated 
> sections should be null. 

It isn't. This is "undefined behavior, no diagnostic required".

For
```
extern char __start___llvm_covfun __attribute__((weak));
extern char __stop___llvm_covfun __attribute__((weak));

int main() {
  printf("%p, %p\n", &__start___llvm_covfun, &__stop___llvm_covfun);
  return 0;
}
```

The program is ill-formed when `__llvm_covfun` does not have the SHF_ALLOC flag.
`__start_`/`__stop_` symbols were not designed to be used with non-SHF_ALLOC 
output sections.
It's invalid to reference a non-SHF_ALLOC section from SHF_ALLOC code. The 
regular undefined weak rule (handwavy "Unresolved weak symbols have a zero 
value." in the specification) does not necessarily apply.

I noticed that GNU ld defines `__start_`/`__stop_` as well and its linked a.out 
prints non-zero addresses, just like lld.


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


[PATCH] D101617: [clang-tidy] Tweak diag ranges for bugprone-sizeof-expression

2023-11-10 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL updated this revision to Diff 558075.
PiotrZSL added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D101617/new/

https://reviews.llvm.org/D101617

Files:
  clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
  clang-tools-extra/clangd/test/diagnostics-tidy.test
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression-warn-on-sizeof-pointer-to-aggregate.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
@@ -77,7 +77,7 @@
   sum += sizeof(LEN + 1);
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(K)'
   sum += sizeof(sum, LEN);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(..., ...)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: suspicious usage of 'sizeof(..., ...)'
   sum += sizeof(AsBool());
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof()' on an expression that results in an integer
   sum += sizeof(AsInt());
@@ -103,41 +103,41 @@
   sum += sizeof(LEN + - + -sizeof(X));
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(sizeof(...))'
   sum += sizeof(char) / sizeof(char);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T)/sizeof(T)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: suspicious usage of sizeof pointer 'sizeof(T)/sizeof(T)'
   sum += sizeof(A) / sizeof(S);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator
   sum += sizeof(char) / sizeof(int);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator
   sum += sizeof(char) / sizeof(A);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator
   sum += sizeof(B[0]) / sizeof(A);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator
+  // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator
   sum += sizeof(ptr) / sizeof(char);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)'
   sum += sizeof(ptr) / sizeof(ptr[0]);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)'
   sum += sizeof(ptr) / sizeof(char*);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)'
   sum += sizeof(ptr) / sizeof(void*);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)'
   sum += sizeof(ptr) / sizeof(const void volatile*);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)'
   sum += sizeof(ptr) / sizeof(char);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)'
   sum += sizeof(ptr) / sizeof(ptr[0]);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)'
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)'
   sum += sizeof(int) * sizeof(char);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious 'sizeof' by 'sizeof' multiplication
+  // CHECK-MESSAGES: 

[PATCH] D101617: [clang-tidy] Tweak diag ranges for bugprone-sizeof-expression

2023-11-10 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added a comment.
This revision is now accepted and ready to land.
Herald added a project: All.

LGTM


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D101617/new/

https://reviews.llvm.org/D101617

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


[libc] [compiler-rt] [clang-tools-extra] [flang] [libcxx] [llvm] [clang] [libcxx] Unifying __is_trivial_equality_predicate and __is_trivial_plus_operation into __desugars_to (PR #68642)

2023-11-10 Thread Anton Rydahl via cfe-commits

https://github.com/AntonRydahl updated 
https://github.com/llvm/llvm-project/pull/68642

>From f0d93cc6a5cd485c654ab38221691db038bacc7d Mon Sep 17 00:00:00 2001
From: AntonRydahl 
Date: Mon, 9 Oct 2023 15:13:22 -0700
Subject: [PATCH 01/13] Merged __is_trivial_equality_predicate and
 __is_trivial_plus_operation into __desugars_to

---
 libcxx/include/CMakeLists.txt |  1 -
 libcxx/include/__algorithm/comp.h |  7 ++---
 libcxx/include/__algorithm/equal.h| 22 
 .../cpu_backends/transform_reduce.h   | 23 
 libcxx/include/__functional/operations.h  | 15 +--
 .../include/__functional/ranges_operations.h  |  7 ++---
 .../include/__numeric/pstl_transform_reduce.h |  2 +-
 .../include/__type_traits/operation_traits.h  |  4 +--
 .../include/__type_traits/predicate_traits.h  | 26 ---
 libcxx/include/module.modulemap.in|  1 -
 10 files changed, 40 insertions(+), 68 deletions(-)
 delete mode 100644 libcxx/include/__type_traits/predicate_traits.h

diff --git a/libcxx/include/CMakeLists.txt b/libcxx/include/CMakeLists.txt
index 340353f8ebb41c4..7eb09a06ccd482e 100644
--- a/libcxx/include/CMakeLists.txt
+++ b/libcxx/include/CMakeLists.txt
@@ -813,7 +813,6 @@ set(files
   __type_traits/negation.h
   __type_traits/noexcept_move_assign_container.h
   __type_traits/operation_traits.h
-  __type_traits/predicate_traits.h
   __type_traits/promote.h
   __type_traits/rank.h
   __type_traits/remove_all_extents.h
diff --git a/libcxx/include/__algorithm/comp.h 
b/libcxx/include/__algorithm/comp.h
index 9474536615ffb67..0993c37cce36a6b 100644
--- a/libcxx/include/__algorithm/comp.h
+++ b/libcxx/include/__algorithm/comp.h
@@ -10,8 +10,9 @@
 #define _LIBCPP___ALGORITHM_COMP_H
 
 #include <__config>
+#include <__functional/operations.h>
 #include <__type_traits/integral_constant.h>
-#include <__type_traits/predicate_traits.h>
+#include <__type_traits/operation_traits.h>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #  pragma GCC system_header
@@ -26,8 +27,8 @@ struct __equal_to {
   }
 };
 
-template 
-struct __is_trivial_equality_predicate<__equal_to, _Lhs, _Rhs> : true_type {};
+template <>
+struct __desugars_to<__equal_to, std::equal_to<>> : true_type {};
 
 // The definition is required because __less is part of the ABI, but it's empty
 // because all comparisons should be transparent.
diff --git a/libcxx/include/__algorithm/equal.h 
b/libcxx/include/__algorithm/equal.h
index b69aeff92bb9289..35e82da15e4d058 100644
--- a/libcxx/include/__algorithm/equal.h
+++ b/libcxx/include/__algorithm/equal.h
@@ -15,6 +15,7 @@
 #include <__config>
 #include <__functional/identity.h>
 #include <__functional/invoke.h>
+#include <__functional/operations.h>
 #include <__iterator/distance.h>
 #include <__iterator/iterator_traits.h>
 #include <__string/constexpr_c_functions.h>
@@ -23,7 +24,7 @@
 #include <__type_traits/is_constant_evaluated.h>
 #include <__type_traits/is_equality_comparable.h>
 #include <__type_traits/is_volatile.h>
-#include <__type_traits/predicate_traits.h>
+#include <__type_traits/operation_traits.h>
 #include <__utility/move.h>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -41,13 +42,12 @@ _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI 
_LIBCPP_CONSTEXPR_SINCE_CXX20 boo
   return true;
 }
 
-template <
-class _Tp,
-class _Up,
-class _BinaryPredicate,
-__enable_if_t<__is_trivial_equality_predicate<_BinaryPredicate, _Tp, 
_Up>::value && !is_volatile<_Tp>::value &&
-  !is_volatile<_Up>::value && 
__libcpp_is_trivially_equality_comparable<_Tp, _Up>::value,
-  int> = 0>
+template < class _Tp,
+   class _Up,
+   class _BinaryPredicate,
+   __enable_if_t<__desugars_to<_BinaryPredicate, 
std::equal_to<>>::value && !is_volatile<_Tp>::value &&
+ !is_volatile<_Up>::value && 
__libcpp_is_trivially_equality_comparable<_Tp, _Up>::value,
+ int> = 0>
 _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 
bool
 __equal_iter_impl(_Tp* __first1, _Tp* __last1, _Up* __first2, 
_BinaryPredicate&) {
   return std::__constexpr_memcmp_equal(__first1, __first2, 
__element_count(__last1 - __first1));
@@ -94,12 +94,12 @@ template ::value && __is_identity<_Proj1>::value &&
+  __enable_if_t<__desugars_to<_Pred, std::equal_to<>>::value && 
__is_identity<_Proj1>::value &&
 __is_identity<_Proj2>::value && 
!is_volatile<_Tp>::value && !is_volatile<_Up>::value &&
 __libcpp_is_trivially_equality_comparable<_Tp, 
_Up>::value,
 int> = 0>
-_LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 
bool __equal_impl(
-_Tp* __first1, _Tp* __last1, _Up* __first2, _Up*, _Pred&, _Proj1&, 
_Proj2&) {
+_LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 

  1   2   3   >