[clang-tools-extra] [clang-tidy][IncludeCleaner] Fix analysis supression in presence of verbatim spellings (PR #68185)

2023-10-04 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet created 
https://github.com/llvm/llvm-project/pull/68185

None

From 91ce80c89689518c20f18efd172628a51aebb769 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Wed, 4 Oct 2023 09:38:28 +0200
Subject: [PATCH] [clang-tidy][IncludeCleaner] Fix analysis supression in
 presence of verbatim spellings

---
 .../clang-tidy/misc/IncludeCleanerCheck.cpp   | 20 ---
 .../clang-tidy/IncludeCleanerTest.cpp | 16 ---
 2 files changed, 26 insertions(+), 10 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
index fed19bdcc291436..a95a1feb9852b99 100644
--- a/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
@@ -30,6 +30,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Tooling/Core/Replacement.h"
 #include "clang/Tooling/Inclusions/HeaderIncludes.h"
+#include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
@@ -97,9 +98,12 @@ bool IncludeCleanerCheck::shouldIgnore(const 
include_cleaner::Header &H) {
   return llvm::any_of(IgnoreHeadersRegex, [&H](const llvm::Regex &R) {
 switch (H.kind()) {
 case include_cleaner::Header::Standard:
+  // We don't trim braces around standard library headers deliberately, so
+  // that they are only matched as , otherwise having just
+  // `.*/vector` might yield false positives.
   return R.match(H.standard().name());
 case include_cleaner::Header::Verbatim:
-  return R.match(H.verbatim());
+  return R.match(H.verbatim().trim("<>\""));
 case include_cleaner::Header::Physical:
   return R.match(H.physical().getFileEntry().tryGetRealPathName());
 }
@@ -179,12 +183,14 @@ void IncludeCleanerCheck::check(const 
MatchFinder::MatchResult &Result) {
   if (getCurrentMainFile().endswith(PHeader))
 continue;
 }
-
-if (llvm::none_of(
-IgnoreHeadersRegex,
-[Resolved = (*I.Resolved).getFileEntry().tryGetRealPathName()](
-const llvm::Regex &R) { return R.match(Resolved); }))
-  Unused.push_back(&I);
+auto StdHeader = tooling::stdlib::Header::named(
+I.quote(), PP->getLangOpts().CPlusPlus ? tooling::stdlib::Lang::CXX
+   : tooling::stdlib::Lang::C);
+if (StdHeader && shouldIgnore(*StdHeader))
+  continue;
+if (shouldIgnore(*I.Resolved))
+  continue;
+Unused.push_back(&I);
   }
 
   llvm::StringRef Code = SM->getBufferData(SM->getMainFileID());
diff --git a/clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp 
b/clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
index 0c29b469b617b7c..8da1051a860a8c7 100644
--- a/clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
@@ -59,18 +59,20 @@ TEST(IncludeCleanerCheckTest, SuppressUnusedIncludes) {
 #include "foo/qux.h"
 #include "baz/qux/qux.h"
 #include 
+#include 
 )";
 
   const char *PostCode = R"(
 #include "bar.h"
 #include "foo/qux.h"
 #include 
+#include 
 )";
 
   std::vector Errors;
   ClangTidyOptions Opts;
   Opts.CheckOptions["IgnoreHeaders"] = llvm::StringRef{llvm::formatv(
-  "bar.h;{0};{1};vector",
+  "bar.h;{0};{1};vector;;",
   llvm::Regex::escape(appendPathFileSystemIndependent({"foo", "qux.h"})),
   llvm::Regex::escape(appendPathFileSystemIndependent({"baz", "qux"})))};
   EXPECT_EQ(
@@ -79,6 +81,7 @@ TEST(IncludeCleanerCheckTest, SuppressUnusedIncludes) {
   PreCode, &Errors, "file.cpp", std::nullopt, Opts,
   {{"bar.h", "#pragma once"},
{"vector", "#pragma once"},
+   {"list", "#pragma once"},
{appendPathFileSystemIndependent({"foo", "qux.h"}), "#pragma once"},
{appendPathFileSystemIndependent({"baz", "qux", "qux.h"}),
 "#pragma once"}}));
@@ -163,11 +166,13 @@ TEST(IncludeCleanerCheckTest, SuppressMissingIncludes) {
 int BarResult = bar();
 int BazResult = baz();
 int QuxResult = qux();
+int PrivResult = test();
+std::vector x;
 )";
 
   ClangTidyOptions Opts;
   Opts.CheckOptions["IgnoreHeaders"] = llvm::StringRef{
-  "baz.h;" +
+  "public.h;;baz.h;" +
   llvm::Regex::escape(appendPathFileSystemIndependent({"foo", "qux.h"}))};
   std::vector Errors;
   EXPECT_EQ(PreCode, runCheckOnCode(
@@ -175,18 +180,23 @@ int QuxResult = qux();
  {{"bar.h", R"(#pragma once
   #include "baz.h"
   #include "foo/qux.h"
+  #include "private.h"
   int bar();
+  namespace std { struct vector {}; }
)"},
   {"baz.h", R"(#pragma once
  

[clang] [Clang] Fix missing diagnostic for non-standard layout type in `offsetof` (PR #65246)

2023-10-04 Thread via cfe-commits

https://github.com/kasuga-fj updated 
https://github.com/llvm/llvm-project/pull/65246

>From 1c2f558a80635333655011c723af69371d3587af Mon Sep 17 00:00:00 2001
From: "kasuga.ryotaro" 
Date: Wed, 30 Aug 2023 13:26:31 +0900
Subject: [PATCH 01/12] [Clang] Fix missing diagnostic for non-standard layout
 type in `offsetof`

Fixes #64619

Clang warns diagnostic for non-standard layout types in `offsetof` only
if they are in evaluated context. With this patch, you'll also get
  diagnostic if you use `offsetof` on non-standard layout types in any
  other contexts
---
 clang/lib/Sema/SemaExpr.cpp |  9 -
 clang/test/SemaCXX/class-layout.cpp | 30 ++---
 clang/test/SemaCXX/ms_struct.cpp|  5 ++---
 clang/test/SemaCXX/offsetof.cpp | 10 +-
 4 files changed, 26 insertions(+), 28 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 797b71bffbb451e..c978a2d90f0d877 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -16796,12 +16796,11 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation 
BuiltinLoc,
 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
 : diag::ext_offsetof_non_pod_type;
 
-  if (!IsSafe && !DidWarnAboutNonPOD &&
-  DiagRuntimeBehavior(BuiltinLoc, nullptr,
-  PDiag(DiagID)
-  << SourceRange(Components[0].LocStart, OC.LocEnd)
-  << CurrentType))
+  if (!IsSafe && !DidWarnAboutNonPOD) {
+Diag(BuiltinLoc, DiagID)
+<< SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
 DidWarnAboutNonPOD = true;
+  }
 }
 
 // Look for the field.
diff --git a/clang/test/SemaCXX/class-layout.cpp 
b/clang/test/SemaCXX/class-layout.cpp
index 9782ff08100b2d6..23b3dbe24249378 100644
--- a/clang/test/SemaCXX/class-layout.cpp
+++ b/clang/test/SemaCXX/class-layout.cpp
@@ -1,18 +1,18 @@
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++98 -Wno-inaccessible-base -Wno-c++11-extensions
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base
-// RUN: %clang_cc1 -triple x86_64-apple-darwin%s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple x86_64-scei-ps4%s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-sie-ps5 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=6 -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=14 -DCLANG_ABI_COMPAT=14
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=16 -DCLANG_ABI_COMPAT=16
-// RUN: %clang_cc1 -triple powerpc-ibm-aix7.3.0.0 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple powerpc-ibm-aix7.3.0.0 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple powerpc64-ibm-aix7.3.0.0 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple powerpc64-ibm-aix7.3.0.0 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple s390x-none-zos %s -fsyntax-only -verify -std=c++11 
-Wno-inaccessible-base
-// RUN: %clang_cc1 -triple s390x-none-zos %s -fsyntax-only -verify -std=c++11 
-Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++98 -Wno-inaccessible-base -Wno-invalid-offsetof -Wno-c++11-extensions
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof
+// RUN: %clang_cc1 -triple x86_64-apple-darwin%s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -triple x86_64-scei-ps4%s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -triple x86_64-sie-ps5 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof -fclang-abi-compat

[clang-tools-extra] [IPSCCP] Variable not visible at Og: (PR #66745)

2023-10-04 Thread Carlos Alberto Enciso via cfe-commits

https://github.com/CarlosAlbertoEnciso updated 
https://github.com/llvm/llvm-project/pull/66745

>From b24943f63025822a5c5ba90c4a7b47f7123ec4db Mon Sep 17 00:00:00 2001
From: Carlos Alberto Enciso 
Date: Mon, 18 Sep 2023 12:29:17 +0100
Subject: [PATCH 1/4] [IPSCCP] Variable not visible at Og:

https://bugs.llvm.org/show_bug.cgi?id=51559
https://github.com/llvm/llvm-project/issues/50901

IPSCCP pass removes the global variable and does not
create a constant expression for the initializer value.
---
 llvm/lib/Transforms/IPO/SCCP.cpp |  47 +++
 llvm/test/Transforms/SCCP/pr50901.ll | 184 +++
 2 files changed, 231 insertions(+)
 create mode 100644 llvm/test/Transforms/SCCP/pr50901.ll

diff --git a/llvm/lib/Transforms/IPO/SCCP.cpp b/llvm/lib/Transforms/IPO/SCCP.cpp
index 84f5bbf7039416b..e09769e00148143 100644
--- a/llvm/lib/Transforms/IPO/SCCP.cpp
+++ b/llvm/lib/Transforms/IPO/SCCP.cpp
@@ -22,6 +22,7 @@
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/Constants.h"
+#include "llvm/IR/DIBuilder.h"
 #include "llvm/IR/IntrinsicInst.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ModRef.h"
@@ -371,6 +372,52 @@ static bool runIPSCCP(
   StoreInst *SI = cast(GV->user_back());
   SI->eraseFromParent();
 }
+
+// Try to create a debug constant expression for the glbal variable
+// initializer value.
+SmallVector GVEs;
+GV->getDebugInfo(GVEs);
+if (GVEs.size() == 1) {
+  DIBuilder DIB(M);
+
+  // Create integer constant expression.
+  auto createIntExpression = [&DIB](const Constant *CV) -> DIExpression * {
+const APInt &API = dyn_cast(CV)->getValue();
+std::optional InitIntOpt;
+if (API.isNonNegative())
+  InitIntOpt = API.tryZExtValue();
+else if (auto Temp = API.trySExtValue(); Temp.has_value())
+  // Transform a signed optional to unsigned optional.
+  InitIntOpt = (uint64_t)Temp.value();
+return DIB.createConstantValueExpression(InitIntOpt.value());
+  };
+
+  const Constant *CV = GV->getInitializer();
+  Type *Ty = GV->getValueType();
+  if (Ty->isIntegerTy()) {
+GVEs[0]->replaceOperandWith(1, createIntExpression(CV));
+  } else if (Ty->isFloatTy() || Ty->isDoubleTy()) {
+const APFloat &APF = dyn_cast(CV)->getValueAPF();
+DIExpression *NewExpr = DIB.createConstantValueExpression(
+APF.bitcastToAPInt().getZExtValue());
+GVEs[0]->replaceOperandWith(1, NewExpr);
+  } else if (Ty->isPointerTy()) {
+if (isa(CV)) {
+  GVEs[0]->replaceOperandWith(1, DIB.createConstantValueExpression(0));
+} else {
+  if (const ConstantExpr *CE = dyn_cast(CV)) {
+if (CE->getNumOperands() == 1) {
+  const Value *V = CE->getOperand(0);
+  const Constant *CV = dyn_cast(V);
+  if (CV && !isa(CV))
+if (const ConstantInt *CI = dyn_cast(CV))
+  GVEs[0]->replaceOperandWith(1, createIntExpression(CI));
+}
+  }
+}
+  }
+}
+
 MadeChanges = true;
 M.eraseGlobalVariable(GV);
 ++NumGlobalConst;
diff --git a/llvm/test/Transforms/SCCP/pr50901.ll 
b/llvm/test/Transforms/SCCP/pr50901.ll
new file mode 100644
index 000..56961d2e32db41c
--- /dev/null
+++ b/llvm/test/Transforms/SCCP/pr50901.ll
@@ -0,0 +1,184 @@
+; RUN: opt -passes=ipsccp -S -o - < %s | FileCheck %s
+
+; Global variables g_11, g_22, g_33, g_44, g_55, g_66 and g_77
+; are not visible in the debugger.
+
+;  1   int   g_1 = -4;
+;  2   float g_2 = 4.44;
+;  3   char  g_3 = 'a';
+;  4   unsigned  g_4 = 4;
+;  5   bool  g_5 = true;
+;  6   int  *g_6 = nullptr;
+;  7   float*g_7 = nullptr;
+;  8
+;  9   static int   g_11 = -5;
+; 10   static float g_22 = 5.55;
+; 11   static char  g_33 = 'b';
+; 12   static unsigned  g_44 = 5;
+; 13   static bool  g_55 = true;
+; 14   static int  *g_66 = nullptr;
+; 15   static float*g_77 = (float *)(55 + 15);
+; 16
+; 17   void bar() {
+; 18 g_1 = g_11;
+; 19 g_2 = g_22;
+; 20 g_3 = g_33;
+; 21 g_4 = g_44;
+; 22 g_5 = g_55;
+; 23 g_6 = g_66;
+; 24 g_7 = g_77;
+; 25   }
+; 26
+; 27   int main() {
+; 28 {
+; 29   bar();
+; 30 }
+; 31   }
+
+; CHECK: ![[G1:[0-9]+]] = !DIGlobalVariableExpression(var: ![[DBG1:[0-9]+]], 
expr: !DIExpression(DW_OP_constu, 18446744073709551611, DW_OP_stack_value))
+; CHECK-DAG: ![[DBG1]] = distinct !DIGlobalVariable(name: "g_11", {{.*}}
+; CHECK: ![[G2:[0-9]+]] = !DIGlobalVariableExpression(var: ![[DBG2:[0-9]+]], 
expr: !DIExpression(DW_OP_constu, 1085381018, DW_OP_stack_value))
+; CHECK-DAG: ![[DBG2]] = distinct !DIGlobalVariable(name: "g_22", {{.*}}
+; CHECK: ![[G3:[0-9]+]] = !DIGlobalVariableExpression(var: ![[DBG3:[0-9]+]], 
expr: !DIExpression(DW_OP_constu, 98, DW_OP_stack_value))
+; CHECK-DAG: ![[DBG3]] = distin

[clang-tools-extra] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-04 Thread Botond István Hprváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/66487

From 258462cc65403af147bb47cbeb95210df8e18cd3 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Fri, 15 Sep 2023 09:28:21 +0200
Subject: [PATCH 1/4] Choose the correct deduction guide

If there are two guides, one of them generated from a non-templated constructor
and the other from a templated constructor, then the standard gives priority to
the first. Clang detected ambiguity before, now the correct guide is chosen.

As an unrelated minor change, fix the issue #64020, which could've led to
incorrect behavior if further development inserted code after a call to
isAddressSpaceSubsetOf() which specified the two parameters in the wrong order.
---
 clang/lib/Sema/SemaOverload.cpp | 17 -
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp  | 10 ++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 45a9e5dc98c032d..1bb81238520173a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10153,6 +10153,21 @@ bool clang::isBetterOverloadCandidate(
   //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
   if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
 return true;
+  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
+return false;
+
+  //  --F1 is generated from a non-template constructor and F2 is generated
+  //  from a constructor template
+  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
+  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
+  if (Constructor1 && Constructor2) {
+bool isC1Templated = Constructor1->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+bool isC2Templated = Constructor2->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+if (isC1Templated != isC2Templated)
+  return isC2Templated;
+  }
 }
   }
 
@@ -10196,7 +10211,7 @@ bool clang::isBetterOverloadCandidate(
 if (AS1 != AS2) {
   if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
 return true;
-  if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
+  if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
 return false;
 }
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9e5f85b0f9166bd..b9c4a9db842b9ee 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2129,7 +2129,7 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(
 Function = CXXDeductionGuideDecl::Create(
 SemaRef.Context, DC, D->getInnerLocStart(),
 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
-D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
+D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
 DGuide->getDeductionCandidateKind());
 Function->setAccess(D->getAccess());
   } else {
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index 4eac0a1ac510f1d..d939d724dc7a0fd 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{
+template  struct A {
+  A(T, T, int);
+  template
+A(int, T, U);
+};
+
+A x(1, 2, 3);   // no-error
+}

From 877678b01d05eb301ac49a2a39186a743ca9012d Mon Sep 17 00:00:00 2001
From: hobois 
Date: Tue, 3 Oct 2023 18:20:11 +0200
Subject: [PATCH 2/4] Added the fix to relasenotes

---
 clang/docs/ReleaseNotes.rst | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6be824771c583be..84eb3301deb4b37 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -390,6 +390,11 @@ Bug Fixes to C++ Support
   we now produce a diagnostic. Fixes:
   (`#65522 `_)
 
+- Fixed a bug where clang incorrectly considered implicitly generated deduction
+  guides from a non-templated constructor and a templated constructor as 
ambiguous,
+  rather than prefer the non-templated constructor as specified in 
+  [standard.group]p3
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

From fc425a9be52b9278cd66e123019da2aaa3a0ee9f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Hprv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Tue, 3 Oct 

[libclc] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-04 Thread Botond István Hprváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/66487

From 258462cc65403af147bb47cbeb95210df8e18cd3 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Fri, 15 Sep 2023 09:28:21 +0200
Subject: [PATCH 1/4] Choose the correct deduction guide

If there are two guides, one of them generated from a non-templated constructor
and the other from a templated constructor, then the standard gives priority to
the first. Clang detected ambiguity before, now the correct guide is chosen.

As an unrelated minor change, fix the issue #64020, which could've led to
incorrect behavior if further development inserted code after a call to
isAddressSpaceSubsetOf() which specified the two parameters in the wrong order.
---
 clang/lib/Sema/SemaOverload.cpp | 17 -
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp  | 10 ++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 45a9e5dc98c032d..1bb81238520173a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10153,6 +10153,21 @@ bool clang::isBetterOverloadCandidate(
   //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
   if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
 return true;
+  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
+return false;
+
+  //  --F1 is generated from a non-template constructor and F2 is generated
+  //  from a constructor template
+  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
+  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
+  if (Constructor1 && Constructor2) {
+bool isC1Templated = Constructor1->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+bool isC2Templated = Constructor2->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+if (isC1Templated != isC2Templated)
+  return isC2Templated;
+  }
 }
   }
 
@@ -10196,7 +10211,7 @@ bool clang::isBetterOverloadCandidate(
 if (AS1 != AS2) {
   if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
 return true;
-  if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
+  if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
 return false;
 }
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9e5f85b0f9166bd..b9c4a9db842b9ee 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2129,7 +2129,7 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(
 Function = CXXDeductionGuideDecl::Create(
 SemaRef.Context, DC, D->getInnerLocStart(),
 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
-D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
+D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
 DGuide->getDeductionCandidateKind());
 Function->setAccess(D->getAccess());
   } else {
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index 4eac0a1ac510f1d..d939d724dc7a0fd 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{
+template  struct A {
+  A(T, T, int);
+  template
+A(int, T, U);
+};
+
+A x(1, 2, 3);   // no-error
+}

From 877678b01d05eb301ac49a2a39186a743ca9012d Mon Sep 17 00:00:00 2001
From: hobois 
Date: Tue, 3 Oct 2023 18:20:11 +0200
Subject: [PATCH 2/4] Added the fix to relasenotes

---
 clang/docs/ReleaseNotes.rst | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6be824771c583be..84eb3301deb4b37 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -390,6 +390,11 @@ Bug Fixes to C++ Support
   we now produce a diagnostic. Fixes:
   (`#65522 `_)
 
+- Fixed a bug where clang incorrectly considered implicitly generated deduction
+  guides from a non-templated constructor and a templated constructor as 
ambiguous,
+  rather than prefer the non-templated constructor as specified in 
+  [standard.group]p3
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

From fc425a9be52b9278cd66e123019da2aaa3a0ee9f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Hprv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Tue, 3 Oct 

[clang] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-04 Thread Botond István Hprváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/66487

From 258462cc65403af147bb47cbeb95210df8e18cd3 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Fri, 15 Sep 2023 09:28:21 +0200
Subject: [PATCH 1/4] Choose the correct deduction guide

If there are two guides, one of them generated from a non-templated constructor
and the other from a templated constructor, then the standard gives priority to
the first. Clang detected ambiguity before, now the correct guide is chosen.

As an unrelated minor change, fix the issue #64020, which could've led to
incorrect behavior if further development inserted code after a call to
isAddressSpaceSubsetOf() which specified the two parameters in the wrong order.
---
 clang/lib/Sema/SemaOverload.cpp | 17 -
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp  | 10 ++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 45a9e5dc98c032d..1bb81238520173a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10153,6 +10153,21 @@ bool clang::isBetterOverloadCandidate(
   //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
   if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
 return true;
+  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
+return false;
+
+  //  --F1 is generated from a non-template constructor and F2 is generated
+  //  from a constructor template
+  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
+  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
+  if (Constructor1 && Constructor2) {
+bool isC1Templated = Constructor1->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+bool isC2Templated = Constructor2->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+if (isC1Templated != isC2Templated)
+  return isC2Templated;
+  }
 }
   }
 
@@ -10196,7 +10211,7 @@ bool clang::isBetterOverloadCandidate(
 if (AS1 != AS2) {
   if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
 return true;
-  if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
+  if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
 return false;
 }
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9e5f85b0f9166bd..b9c4a9db842b9ee 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2129,7 +2129,7 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(
 Function = CXXDeductionGuideDecl::Create(
 SemaRef.Context, DC, D->getInnerLocStart(),
 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
-D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
+D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
 DGuide->getDeductionCandidateKind());
 Function->setAccess(D->getAccess());
   } else {
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index 4eac0a1ac510f1d..d939d724dc7a0fd 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{
+template  struct A {
+  A(T, T, int);
+  template
+A(int, T, U);
+};
+
+A x(1, 2, 3);   // no-error
+}

From 877678b01d05eb301ac49a2a39186a743ca9012d Mon Sep 17 00:00:00 2001
From: hobois 
Date: Tue, 3 Oct 2023 18:20:11 +0200
Subject: [PATCH 2/4] Added the fix to relasenotes

---
 clang/docs/ReleaseNotes.rst | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6be824771c583be..84eb3301deb4b37 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -390,6 +390,11 @@ Bug Fixes to C++ Support
   we now produce a diagnostic. Fixes:
   (`#65522 `_)
 
+- Fixed a bug where clang incorrectly considered implicitly generated deduction
+  guides from a non-templated constructor and a templated constructor as 
ambiguous,
+  rather than prefer the non-templated constructor as specified in 
+  [standard.group]p3
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

From fc425a9be52b9278cd66e123019da2aaa3a0ee9f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Hprv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Tue, 3 Oct 

[clang-tools-extra] [IPSCCP] Variable not visible at Og: (PR #66745)

2023-10-04 Thread Carlos Alberto Enciso via cfe-commits

CarlosAlbertoEnciso wrote:

@jryans, @felipepiovezan, @nikic, @dwblaikie:
Thanks for all your feedback. I have uploaded a new patch that addresses all 
your points.
I am sorry if there are extra commits on this branch. This is the first update 
since moving to GitHub.

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


[clang-tools-extra] [IPSCCP] Variable not visible at Og. (PR #66745)

2023-10-04 Thread Carlos Alberto Enciso via cfe-commits

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


[clang-tools-extra] [clang-tidy][IncludeCleaner] Fix analysis supression in presence of verbatim spellings (PR #68185)

2023-10-04 Thread via cfe-commits


@@ -97,9 +98,12 @@ bool IncludeCleanerCheck::shouldIgnore(const 
include_cleaner::Header &H) {
   return llvm::any_of(IgnoreHeadersRegex, [&H](const llvm::Regex &R) {
 switch (H.kind()) {
 case include_cleaner::Header::Standard:
+  // We don't trim braces around standard library headers deliberately, so

VitaNuo wrote:

s/braces/angle brackets/

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


[PATCH] D155775: [HIP][Clang][Driver][RFC] Add driver support for C++ Parallel Algorithm Offload

2023-10-04 Thread Rainer Orth via Phabricator via cfe-commits
ro added a comment.

In D155775#4652785 , @AlexVlx wrote:

> In D155775#4652780 , @dyung wrote:
>
>> 



>> At this point, would it be easier to add a REQUIRES line for the target the 
>> test should support rather than just whack-a-mole for the targets it does 
>> not?
>
> Oh, it definitely would be MUCH easier to add a `REQUIRES` line, however I'd 
> have had to have thought about that, which I did not, so thank you for the 
> wake up call. I'll update this in a few minutes.

Unfortunately, this is still not done after almost a day, leaving quite a 
number of buildbots broken.  Please fix or revert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155775

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


[clang-tools-extra] [clang-tidy][IncludeCleaner] Fix analysis supression in presence of verbatim spellings (PR #68185)

2023-10-04 Thread via cfe-commits


@@ -179,12 +183,14 @@ void IncludeCleanerCheck::check(const 
MatchFinder::MatchResult &Result) {
   if (getCurrentMainFile().endswith(PHeader))
 continue;
 }
-
-if (llvm::none_of(
-IgnoreHeadersRegex,
-[Resolved = (*I.Resolved).getFileEntry().tryGetRealPathName()](
-const llvm::Regex &R) { return R.match(Resolved); }))
-  Unused.push_back(&I);
+auto StdHeader = tooling::stdlib::Header::named(

VitaNuo wrote:

I believe you could move this passage into the handling of standard headers in 
`shouldIgnore`. Then the below could also be simplified. 

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


[clang-tools-extra] [clang-tidy][IncludeCleaner] Fix analysis supression in presence of verbatim spellings (PR #68185)

2023-10-04 Thread via cfe-commits

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

Thank you. What was the bug that triggered this? It seems like the verbatim 
headers were only matched if they were specified as quoted in the ignore config?

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


[clang-tools-extra] [clang-tidy][libc] Fix namespace check with macro (PR #68134)

2023-10-04 Thread Guillaume Chatelet via cfe-commits

gchatelet wrote:

It would be ideal to move the [following lines](
https://github.com/llvm/llvm-project/blob/b3c710beda5b45dc18a5cbd74e141c1169971450/clang-tools-extra/clang-tidy/llvmlibc/ImplementationInNamespaceCheck.cpp#L17-L18)
  to a shared header and use them in both implementations.

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


[clang] [analyzer] Extend EnumCastOutOfRange diagnostics (PR #68191)

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

https://github.com/gamesh411 created 
https://github.com/llvm/llvm-project/pull/68191

EnumCastOutOfRange checker now reports the name of the enum in the warning 
message. Additionally, a note-tag is placed to highlight the location of the 
declaration.

From 6b70c3246747b5a1204062f40f91273f60a38600 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= 
Date: Wed, 4 Oct 2023 10:38:00 +0200
Subject: [PATCH] [analyzer] Extend EnumCastOutOfRange diagnostics

EnumCastOutOfRange checker now reports the name of the enum in the
warning message. Additionally, a note-tag is placed to highlight the
location of the declaration.
---
 .../Checkers/EnumCastOutOfRangeChecker.cpp|  33 --
 clang/test/Analysis/enum-cast-out-of-range.c  |  13 ++-
 .../test/Analysis/enum-cast-out-of-range.cpp  | 108 +-
 3 files changed, 87 insertions(+), 67 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
index 89be6a47250a245..6163f7a23804091 100644
--- a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
@@ -59,7 +59,7 @@ class ConstraintBasedEQEvaluator {
 // value can be matching.
 class EnumCastOutOfRangeChecker : public Checker> {
   mutable std::unique_ptr EnumValueCastOutOfRange;
-  void reportWarning(CheckerContext &C) const;
+  void reportWarning(CheckerContext &C, const EnumDecl *E) const;
 
 public:
   void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
@@ -72,21 +72,36 @@ EnumValueVector getDeclValuesForEnum(const EnumDecl *ED) {
   EnumValueVector DeclValues(
   std::distance(ED->enumerator_begin(), ED->enumerator_end()));
   llvm::transform(ED->enumerators(), DeclValues.begin(),
- [](const EnumConstantDecl *D) { return D->getInitVal(); });
+  [](const EnumConstantDecl *D) { return D->getInitVal(); });
   return DeclValues;
 }
 } // namespace
 
-void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C) const {
+void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C,
+  const EnumDecl *E) const {
+  assert(E && "valid EnumDecl* is expected");
   if (const ExplodedNode *N = C.generateNonFatalErrorNode()) {
 if (!EnumValueCastOutOfRange)
   EnumValueCastOutOfRange.reset(
   new BugType(this, "Enum cast out of range"));
-constexpr llvm::StringLiteral Msg =
-"The value provided to the cast expression is not in the valid range"
-" of values for the enum";
-C.emitReport(std::make_unique(
-*EnumValueCastOutOfRange, Msg, N));
+
+llvm::SmallString<128> Msg{"The value provided to the cast expression is "
+   "not in the valid range of values for "};
+StringRef EnumName{E->getName()};
+if (EnumName.empty()) {
+  Msg += "the enum";
+} else {
+  Msg += '\'';
+  Msg += EnumName;
+  Msg += '\'';
+}
+
+auto BR = 
std::make_unique(*EnumValueCastOutOfRange,
+   Msg, N);
+BR->addNote("enum declared here",
+PathDiagnosticLocation::create(E, C.getSourceManager()),
+{E->getSourceRange()});
+C.emitReport(std::move(BR));
   }
 }
 
@@ -144,7 +159,7 @@ void EnumCastOutOfRangeChecker::checkPreStmt(const CastExpr 
*CE,
   // If there is no value that can possibly match any of the enum values, then
   // warn.
   if (!PossibleValueMatch)
-reportWarning(C);
+reportWarning(C, ED);
 }
 
 void ento::registerEnumCastOutOfRangeChecker(CheckerManager &mgr) {
diff --git a/clang/test/Analysis/enum-cast-out-of-range.c 
b/clang/test/Analysis/enum-cast-out-of-range.c
index 3282cba653d7125..6d3afa3fcf9885f 100644
--- a/clang/test/Analysis/enum-cast-out-of-range.c
+++ b/clang/test/Analysis/enum-cast-out-of-range.c
@@ -2,6 +2,7 @@
 // RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \
 // RUN:   -verify %s
 
+// expected-note@+1 6 {{enum declared here}}
 enum En_t {
   En_0 = -4,
   En_1,
@@ -11,17 +12,17 @@ enum En_t {
 };
 
 void unscopedUnspecifiedCStyle(void) {
-  enum En_t Below = (enum En_t)(-5);// expected-warning {{not in the valid 
range}}
+  enum En_t Below = (enum En_t)(-5);// expected-warning {{not in the valid 
range of values for 'En_t'}}
   enum En_t NegVal1 = (enum En_t)(-4);  // OK.
   enum En_t NegVal2 = (enum En_t)(-3);  // OK.
-  enum En_t InRange1 = (enum En_t)(-2); // expected-warning {{not in the valid 
range}}
-  enum En_t InRange2 = (enum En_t)(-1); // expected-warning {{not in the valid 
range}}
-  enum En_t InRange3 = (enum En_t)(0);  // expected-warning {{not in the valid 
range}}
+  enum En_t InRange1 = (enum En_t)(-2); // expected-warning {{not in the valid 
range of values for 'En_t'}}
+  enum En_t InRange2 = (enum En_t)(-1); // expected-warning {{not in the valid 
range of v

[clang] [analyzer] Extend EnumCastOutOfRange diagnostics (PR #68191)

2023-10-04 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

EnumCastOutOfRange checker now reports the name of the enum in the warning 
message. Additionally, a note-tag is placed to highlight the location of the 
declaration.

---

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


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp 
(+24-9) 
- (modified) clang/test/Analysis/enum-cast-out-of-range.c (+7-6) 
- (modified) clang/test/Analysis/enum-cast-out-of-range.cpp (+56-52) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
index 89be6a47250a245..6163f7a23804091 100644
--- a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
@@ -59,7 +59,7 @@ class ConstraintBasedEQEvaluator {
 // value can be matching.
 class EnumCastOutOfRangeChecker : public Checker> {
   mutable std::unique_ptr EnumValueCastOutOfRange;
-  void reportWarning(CheckerContext &C) const;
+  void reportWarning(CheckerContext &C, const EnumDecl *E) const;
 
 public:
   void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
@@ -72,21 +72,36 @@ EnumValueVector getDeclValuesForEnum(const EnumDecl *ED) {
   EnumValueVector DeclValues(
   std::distance(ED->enumerator_begin(), ED->enumerator_end()));
   llvm::transform(ED->enumerators(), DeclValues.begin(),
- [](const EnumConstantDecl *D) { return D->getInitVal(); });
+  [](const EnumConstantDecl *D) { return D->getInitVal(); });
   return DeclValues;
 }
 } // namespace
 
-void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C) const {
+void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C,
+  const EnumDecl *E) const {
+  assert(E && "valid EnumDecl* is expected");
   if (const ExplodedNode *N = C.generateNonFatalErrorNode()) {
 if (!EnumValueCastOutOfRange)
   EnumValueCastOutOfRange.reset(
   new BugType(this, "Enum cast out of range"));
-constexpr llvm::StringLiteral Msg =
-"The value provided to the cast expression is not in the valid range"
-" of values for the enum";
-C.emitReport(std::make_unique(
-*EnumValueCastOutOfRange, Msg, N));
+
+llvm::SmallString<128> Msg{"The value provided to the cast expression is "
+   "not in the valid range of values for "};
+StringRef EnumName{E->getName()};
+if (EnumName.empty()) {
+  Msg += "the enum";
+} else {
+  Msg += '\'';
+  Msg += EnumName;
+  Msg += '\'';
+}
+
+auto BR = 
std::make_unique(*EnumValueCastOutOfRange,
+   Msg, N);
+BR->addNote("enum declared here",
+PathDiagnosticLocation::create(E, C.getSourceManager()),
+{E->getSourceRange()});
+C.emitReport(std::move(BR));
   }
 }
 
@@ -144,7 +159,7 @@ void EnumCastOutOfRangeChecker::checkPreStmt(const CastExpr 
*CE,
   // If there is no value that can possibly match any of the enum values, then
   // warn.
   if (!PossibleValueMatch)
-reportWarning(C);
+reportWarning(C, ED);
 }
 
 void ento::registerEnumCastOutOfRangeChecker(CheckerManager &mgr) {
diff --git a/clang/test/Analysis/enum-cast-out-of-range.c 
b/clang/test/Analysis/enum-cast-out-of-range.c
index 3282cba653d7125..6d3afa3fcf9885f 100644
--- a/clang/test/Analysis/enum-cast-out-of-range.c
+++ b/clang/test/Analysis/enum-cast-out-of-range.c
@@ -2,6 +2,7 @@
 // RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \
 // RUN:   -verify %s
 
+// expected-note@+1 6 {{enum declared here}}
 enum En_t {
   En_0 = -4,
   En_1,
@@ -11,17 +12,17 @@ enum En_t {
 };
 
 void unscopedUnspecifiedCStyle(void) {
-  enum En_t Below = (enum En_t)(-5);// expected-warning {{not in the valid 
range}}
+  enum En_t Below = (enum En_t)(-5);// expected-warning {{not in the valid 
range of values for 'En_t'}}
   enum En_t NegVal1 = (enum En_t)(-4);  // OK.
   enum En_t NegVal2 = (enum En_t)(-3);  // OK.
-  enum En_t InRange1 = (enum En_t)(-2); // expected-warning {{not in the valid 
range}}
-  enum En_t InRange2 = (enum En_t)(-1); // expected-warning {{not in the valid 
range}}
-  enum En_t InRange3 = (enum En_t)(0);  // expected-warning {{not in the valid 
range}}
+  enum En_t InRange1 = (enum En_t)(-2); // expected-warning {{not in the valid 
range of values for 'En_t'}}
+  enum En_t InRange2 = (enum En_t)(-1); // expected-warning {{not in the valid 
range of values for 'En_t'}}
+  enum En_t InRange3 = (enum En_t)(0);  // expected-warning {{not in the valid 
range of values for 'En_t'}}
   enum En_t PosVal1 = (enum En_t)(1);   // OK.
   enum En_t PosVal2 = (enum En_t)(2);   // OK.
-  enum En_t InRange4 = (enum En_t)(3);  // expect

[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-04 Thread Mariya Podchishchaeva via cfe-commits

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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-04 Thread Mariya Podchishchaeva via cfe-commits

https://github.com/Fznamznon commented:

Probably needs a release note.

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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-04 Thread Mariya Podchishchaeva via cfe-commits


@@ -8367,7 +8367,13 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (auto *MD = cast(Info.CurrentCall->Callee);

Fznamznon wrote:

Should it be a `dyn_cast` instead?
```suggestion
  if (auto *MD = dyn_cast(Info.CurrentCall->Callee);
```

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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-04 Thread Mariya Podchishchaeva via cfe-commits


@@ -8367,7 +8367,13 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (auto *MD = cast(Info.CurrentCall->Callee);
+  MD->isExplicitObjectMemberFunction()) {
+APValue *RefValue =
+Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
+Result.setFrom(Info.Ctx, *RefValue);
+  } else
+Result = *Info.CurrentCall->This;

Fznamznon wrote:

I think LLVM code style suggests curleys in case other branch had them
```suggestion
  } else {
Result = *Info.CurrentCall->This;
  }
```

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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-04 Thread Mariya Podchishchaeva via cfe-commits


@@ -8367,7 +8367,13 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (auto *MD = cast(Info.CurrentCall->Callee);

Fznamznon wrote:

Otherwise if `CXXMethodDecl` is expected it doesn't need a non-null check.

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


[clang-tools-extra] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-04 Thread Botond István Hprváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/66487

From 258462cc65403af147bb47cbeb95210df8e18cd3 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Fri, 15 Sep 2023 09:28:21 +0200
Subject: [PATCH 1/5] Choose the correct deduction guide

If there are two guides, one of them generated from a non-templated constructor
and the other from a templated constructor, then the standard gives priority to
the first. Clang detected ambiguity before, now the correct guide is chosen.

As an unrelated minor change, fix the issue #64020, which could've led to
incorrect behavior if further development inserted code after a call to
isAddressSpaceSubsetOf() which specified the two parameters in the wrong order.
---
 clang/lib/Sema/SemaOverload.cpp | 17 -
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp  | 10 ++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 45a9e5dc98c032d..1bb81238520173a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10153,6 +10153,21 @@ bool clang::isBetterOverloadCandidate(
   //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
   if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
 return true;
+  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
+return false;
+
+  //  --F1 is generated from a non-template constructor and F2 is generated
+  //  from a constructor template
+  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
+  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
+  if (Constructor1 && Constructor2) {
+bool isC1Templated = Constructor1->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+bool isC2Templated = Constructor2->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+if (isC1Templated != isC2Templated)
+  return isC2Templated;
+  }
 }
   }
 
@@ -10196,7 +10211,7 @@ bool clang::isBetterOverloadCandidate(
 if (AS1 != AS2) {
   if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
 return true;
-  if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
+  if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
 return false;
 }
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9e5f85b0f9166bd..b9c4a9db842b9ee 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2129,7 +2129,7 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(
 Function = CXXDeductionGuideDecl::Create(
 SemaRef.Context, DC, D->getInnerLocStart(),
 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
-D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
+D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
 DGuide->getDeductionCandidateKind());
 Function->setAccess(D->getAccess());
   } else {
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index 4eac0a1ac510f1d..d939d724dc7a0fd 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{
+template  struct A {
+  A(T, T, int);
+  template
+A(int, T, U);
+};
+
+A x(1, 2, 3);   // no-error
+}

From 877678b01d05eb301ac49a2a39186a743ca9012d Mon Sep 17 00:00:00 2001
From: hobois 
Date: Tue, 3 Oct 2023 18:20:11 +0200
Subject: [PATCH 2/5] Added the fix to relasenotes

---
 clang/docs/ReleaseNotes.rst | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6be824771c583be..84eb3301deb4b37 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -390,6 +390,11 @@ Bug Fixes to C++ Support
   we now produce a diagnostic. Fixes:
   (`#65522 `_)
 
+- Fixed a bug where clang incorrectly considered implicitly generated deduction
+  guides from a non-templated constructor and a templated constructor as 
ambiguous,
+  rather than prefer the non-templated constructor as specified in 
+  [standard.group]p3
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

From fc425a9be52b9278cd66e123019da2aaa3a0ee9f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Hprv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Tue, 3 Oct 

[libclc] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-04 Thread Botond István Hprváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/66487

From 258462cc65403af147bb47cbeb95210df8e18cd3 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Fri, 15 Sep 2023 09:28:21 +0200
Subject: [PATCH 1/5] Choose the correct deduction guide

If there are two guides, one of them generated from a non-templated constructor
and the other from a templated constructor, then the standard gives priority to
the first. Clang detected ambiguity before, now the correct guide is chosen.

As an unrelated minor change, fix the issue #64020, which could've led to
incorrect behavior if further development inserted code after a call to
isAddressSpaceSubsetOf() which specified the two parameters in the wrong order.
---
 clang/lib/Sema/SemaOverload.cpp | 17 -
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp  | 10 ++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 45a9e5dc98c032d..1bb81238520173a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10153,6 +10153,21 @@ bool clang::isBetterOverloadCandidate(
   //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
   if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
 return true;
+  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
+return false;
+
+  //  --F1 is generated from a non-template constructor and F2 is generated
+  //  from a constructor template
+  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
+  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
+  if (Constructor1 && Constructor2) {
+bool isC1Templated = Constructor1->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+bool isC2Templated = Constructor2->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+if (isC1Templated != isC2Templated)
+  return isC2Templated;
+  }
 }
   }
 
@@ -10196,7 +10211,7 @@ bool clang::isBetterOverloadCandidate(
 if (AS1 != AS2) {
   if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
 return true;
-  if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
+  if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
 return false;
 }
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9e5f85b0f9166bd..b9c4a9db842b9ee 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2129,7 +2129,7 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(
 Function = CXXDeductionGuideDecl::Create(
 SemaRef.Context, DC, D->getInnerLocStart(),
 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
-D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
+D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
 DGuide->getDeductionCandidateKind());
 Function->setAccess(D->getAccess());
   } else {
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index 4eac0a1ac510f1d..d939d724dc7a0fd 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{
+template  struct A {
+  A(T, T, int);
+  template
+A(int, T, U);
+};
+
+A x(1, 2, 3);   // no-error
+}

From 877678b01d05eb301ac49a2a39186a743ca9012d Mon Sep 17 00:00:00 2001
From: hobois 
Date: Tue, 3 Oct 2023 18:20:11 +0200
Subject: [PATCH 2/5] Added the fix to relasenotes

---
 clang/docs/ReleaseNotes.rst | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6be824771c583be..84eb3301deb4b37 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -390,6 +390,11 @@ Bug Fixes to C++ Support
   we now produce a diagnostic. Fixes:
   (`#65522 `_)
 
+- Fixed a bug where clang incorrectly considered implicitly generated deduction
+  guides from a non-templated constructor and a templated constructor as 
ambiguous,
+  rather than prefer the non-templated constructor as specified in 
+  [standard.group]p3
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

From fc425a9be52b9278cd66e123019da2aaa3a0ee9f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Hprv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Tue, 3 Oct 

[clang] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-04 Thread Botond István Hprváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/66487

From 258462cc65403af147bb47cbeb95210df8e18cd3 Mon Sep 17 00:00:00 2001
From: hobois 
Date: Fri, 15 Sep 2023 09:28:21 +0200
Subject: [PATCH 1/5] Choose the correct deduction guide

If there are two guides, one of them generated from a non-templated constructor
and the other from a templated constructor, then the standard gives priority to
the first. Clang detected ambiguity before, now the correct guide is chosen.

As an unrelated minor change, fix the issue #64020, which could've led to
incorrect behavior if further development inserted code after a call to
isAddressSpaceSubsetOf() which specified the two parameters in the wrong order.
---
 clang/lib/Sema/SemaOverload.cpp | 17 -
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp  | 10 ++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 45a9e5dc98c032d..1bb81238520173a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10153,6 +10153,21 @@ bool clang::isBetterOverloadCandidate(
   //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
   if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
 return true;
+  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
+return false;
+
+  //  --F1 is generated from a non-template constructor and F2 is generated
+  //  from a constructor template
+  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
+  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
+  if (Constructor1 && Constructor2) {
+bool isC1Templated = Constructor1->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+bool isC2Templated = Constructor2->getTemplatedKind() !=
+ FunctionDecl::TemplatedKind::TK_NonTemplate;
+if (isC1Templated != isC2Templated)
+  return isC2Templated;
+  }
 }
   }
 
@@ -10196,7 +10211,7 @@ bool clang::isBetterOverloadCandidate(
 if (AS1 != AS2) {
   if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
 return true;
-  if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
+  if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2))
 return false;
 }
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 9e5f85b0f9166bd..b9c4a9db842b9ee 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2129,7 +2129,7 @@ Decl *TemplateDeclInstantiator::VisitFunctionDecl(
 Function = CXXDeductionGuideDecl::Create(
 SemaRef.Context, DC, D->getInnerLocStart(),
 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
-D->getSourceRange().getEnd(), /*Ctor=*/nullptr,
+D->getSourceRange().getEnd(), DGuide->getCorrespondingConstructor(),
 DGuide->getDeductionCandidateKind());
 Function->setAccess(D->getAccess());
   } else {
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
index 4eac0a1ac510f1d..d939d724dc7a0fd 100644
--- 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
+++ 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.class.deduct/p2.cpp
@@ -85,3 +85,13 @@ int main() {
 
 
 }
+
+namespace deduceTemplatedConstructor{
+template  struct A {
+  A(T, T, int);
+  template
+A(int, T, U);
+};
+
+A x(1, 2, 3);   // no-error
+}

From 877678b01d05eb301ac49a2a39186a743ca9012d Mon Sep 17 00:00:00 2001
From: hobois 
Date: Tue, 3 Oct 2023 18:20:11 +0200
Subject: [PATCH 2/5] Added the fix to relasenotes

---
 clang/docs/ReleaseNotes.rst | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6be824771c583be..84eb3301deb4b37 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -390,6 +390,11 @@ Bug Fixes to C++ Support
   we now produce a diagnostic. Fixes:
   (`#65522 `_)
 
+- Fixed a bug where clang incorrectly considered implicitly generated deduction
+  guides from a non-templated constructor and a templated constructor as 
ambiguous,
+  rather than prefer the non-templated constructor as specified in 
+  [standard.group]p3
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.

From fc425a9be52b9278cd66e123019da2aaa3a0ee9f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Hprv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Tue, 3 Oct 

[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-04 Thread via cfe-commits


@@ -8367,7 +8367,13 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (auto *MD = cast(Info.CurrentCall->Callee);

cor3ntin wrote:

Because we have established it's a lambda call operator (which can't even be 
static because we have capture), we know it's a `CXXMethodDecl` (and we don't 
check MD isn't null)

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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-04 Thread via cfe-commits


@@ -8367,7 +8367,13 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   // Start with 'Result' referring to the complete closure object...
-  Result = *Info.CurrentCall->This;
+  if (auto *MD = cast(Info.CurrentCall->Callee);
+  MD->isExplicitObjectMemberFunction()) {
+APValue *RefValue =
+Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
+Result.setFrom(Info.Ctx, *RefValue);
+  } else
+Result = *Info.CurrentCall->This;

cor3ntin wrote:

Will fix, thanks!

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


[clang-tools-extra] [clang-tidy][IncludeCleaner] Fix analysis supression in presence of verbatim spellings (PR #68185)

2023-10-04 Thread kadir çetinkaya via cfe-commits


@@ -179,12 +183,14 @@ void IncludeCleanerCheck::check(const 
MatchFinder::MatchResult &Result) {
   if (getCurrentMainFile().endswith(PHeader))
 continue;
 }
-
-if (llvm::none_of(
-IgnoreHeadersRegex,
-[Resolved = (*I.Resolved).getFileEntry().tryGetRealPathName()](
-const llvm::Regex &R) { return R.match(Resolved); }))
-  Unused.push_back(&I);
+auto StdHeader = tooling::stdlib::Header::named(

kadircet wrote:

ATM `shouldIgnore` is operating on an `include_cleaner::Header` (for good 
reason, as we need to use it both for missing and unused includes). Hence we 
can't really go from a physical Header to a stdlib one inside `shouldIgnore`. 
We can add overloads to accept both a Header and an Include, then we can move 
this logic into the relevant overload, but I don't think that'll be any cleaner.

Did you have something else in mind?

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


[clang-tools-extra] [clang-tidy][IncludeCleaner] Fix analysis supression in presence of verbatim spellings (PR #68185)

2023-10-04 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet updated 
https://github.com/llvm/llvm-project/pull/68185

From 91ce80c89689518c20f18efd172628a51aebb769 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Wed, 4 Oct 2023 09:38:28 +0200
Subject: [PATCH 1/2] [clang-tidy][IncludeCleaner] Fix analysis supression in
 presence of verbatim spellings

---
 .../clang-tidy/misc/IncludeCleanerCheck.cpp   | 20 ---
 .../clang-tidy/IncludeCleanerTest.cpp | 16 ---
 2 files changed, 26 insertions(+), 10 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
index fed19bdcc291436..a95a1feb9852b99 100644
--- a/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp
@@ -30,6 +30,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Tooling/Core/Replacement.h"
 #include "clang/Tooling/Inclusions/HeaderIncludes.h"
+#include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
@@ -97,9 +98,12 @@ bool IncludeCleanerCheck::shouldIgnore(const 
include_cleaner::Header &H) {
   return llvm::any_of(IgnoreHeadersRegex, [&H](const llvm::Regex &R) {
 switch (H.kind()) {
 case include_cleaner::Header::Standard:
+  // We don't trim braces around standard library headers deliberately, so
+  // that they are only matched as , otherwise having just
+  // `.*/vector` might yield false positives.
   return R.match(H.standard().name());
 case include_cleaner::Header::Verbatim:
-  return R.match(H.verbatim());
+  return R.match(H.verbatim().trim("<>\""));
 case include_cleaner::Header::Physical:
   return R.match(H.physical().getFileEntry().tryGetRealPathName());
 }
@@ -179,12 +183,14 @@ void IncludeCleanerCheck::check(const 
MatchFinder::MatchResult &Result) {
   if (getCurrentMainFile().endswith(PHeader))
 continue;
 }
-
-if (llvm::none_of(
-IgnoreHeadersRegex,
-[Resolved = (*I.Resolved).getFileEntry().tryGetRealPathName()](
-const llvm::Regex &R) { return R.match(Resolved); }))
-  Unused.push_back(&I);
+auto StdHeader = tooling::stdlib::Header::named(
+I.quote(), PP->getLangOpts().CPlusPlus ? tooling::stdlib::Lang::CXX
+   : tooling::stdlib::Lang::C);
+if (StdHeader && shouldIgnore(*StdHeader))
+  continue;
+if (shouldIgnore(*I.Resolved))
+  continue;
+Unused.push_back(&I);
   }
 
   llvm::StringRef Code = SM->getBufferData(SM->getMainFileID());
diff --git a/clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp 
b/clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
index 0c29b469b617b7c..8da1051a860a8c7 100644
--- a/clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/IncludeCleanerTest.cpp
@@ -59,18 +59,20 @@ TEST(IncludeCleanerCheckTest, SuppressUnusedIncludes) {
 #include "foo/qux.h"
 #include "baz/qux/qux.h"
 #include 
+#include 
 )";
 
   const char *PostCode = R"(
 #include "bar.h"
 #include "foo/qux.h"
 #include 
+#include 
 )";
 
   std::vector Errors;
   ClangTidyOptions Opts;
   Opts.CheckOptions["IgnoreHeaders"] = llvm::StringRef{llvm::formatv(
-  "bar.h;{0};{1};vector",
+  "bar.h;{0};{1};vector;;",
   llvm::Regex::escape(appendPathFileSystemIndependent({"foo", "qux.h"})),
   llvm::Regex::escape(appendPathFileSystemIndependent({"baz", "qux"})))};
   EXPECT_EQ(
@@ -79,6 +81,7 @@ TEST(IncludeCleanerCheckTest, SuppressUnusedIncludes) {
   PreCode, &Errors, "file.cpp", std::nullopt, Opts,
   {{"bar.h", "#pragma once"},
{"vector", "#pragma once"},
+   {"list", "#pragma once"},
{appendPathFileSystemIndependent({"foo", "qux.h"}), "#pragma once"},
{appendPathFileSystemIndependent({"baz", "qux", "qux.h"}),
 "#pragma once"}}));
@@ -163,11 +166,13 @@ TEST(IncludeCleanerCheckTest, SuppressMissingIncludes) {
 int BarResult = bar();
 int BazResult = baz();
 int QuxResult = qux();
+int PrivResult = test();
+std::vector x;
 )";
 
   ClangTidyOptions Opts;
   Opts.CheckOptions["IgnoreHeaders"] = llvm::StringRef{
-  "baz.h;" +
+  "public.h;;baz.h;" +
   llvm::Regex::escape(appendPathFileSystemIndependent({"foo", "qux.h"}))};
   std::vector Errors;
   EXPECT_EQ(PreCode, runCheckOnCode(
@@ -175,18 +180,23 @@ int QuxResult = qux();
  {{"bar.h", R"(#pragma once
   #include "baz.h"
   #include "foo/qux.h"
+  #include "private.h"
   int bar();
+  namespace std { struct vector {}; }
)"},
   {"baz.h", R"(#pragma once

[clang-tools-extra] [clang-tidy][IncludeCleaner] Fix analysis supression in presence of verbatim spellings (PR #68185)

2023-10-04 Thread kadir çetinkaya via cfe-commits

kadircet wrote:

> Thank you. What was the bug that triggered this? It seems like the verbatim 
> headers were only matched if they were specified as quoted in the ignore 
> config?

I just noticed it while trying to fix an internal issue.

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


[clang] Add Documentation for Execution Results Handling in Clang-Repl (PR #65650)

2023-10-04 Thread Krishna Narayanan via cfe-commits

https://github.com/Krishna-13-cyber updated 
https://github.com/llvm/llvm-project/pull/65650

>From 63b41d9498a71e090cbf1fdca2d87f368aeb809c Mon Sep 17 00:00:00 2001
From: Krishna-13-cyber 
Date: Thu, 7 Sep 2023 22:35:53 +0530
Subject: [PATCH 1/2] Add Documentation for Execution Results Handling in
 Clang-Repl

---
 clang/docs/CMakeLists.txt |   7 +
 clang/docs/ClangRepl.rst  | 405 ++
 clang/docs/conf.py|   1 +
 3 files changed, 413 insertions(+)

diff --git a/clang/docs/CMakeLists.txt b/clang/docs/CMakeLists.txt
index 4163dd2d90ad5b3..356814f994c32cd 100644
--- a/clang/docs/CMakeLists.txt
+++ b/clang/docs/CMakeLists.txt
@@ -103,6 +103,13 @@ function (gen_rst_file_from_td output_file td_option 
source docs_targets)
 endfunction()
 
 if (LLVM_ENABLE_SPHINX)
+  llvm_find_program(dot)
+  if (HAVE_DOT)
+set(DOT ${LLVM_PATH_DOT})
+  else()
+message(FATAL_ERROR "Cannot find DOT")
+  endif()
+
   include(AddSphinxTarget)
   if (SPHINX_FOUND AND (${SPHINX_OUTPUT_HTML} OR ${SPHINX_OUTPUT_MAN}))
 # Copy rst files to build directory before generating the html
diff --git a/clang/docs/ClangRepl.rst b/clang/docs/ClangRepl.rst
index bd99bc82f17..47513dec18f04e7 100644
--- a/clang/docs/ClangRepl.rst
+++ b/clang/docs/ClangRepl.rst
@@ -213,6 +213,411 @@ concept helps support advanced use cases such as template 
instantiations on dema
 automatic language interoperability. It also helps static languages such as 
C/C++ become
 apt for data science.
 
+Execution Results Handling in Clang-Repl
+
+
+Execution Results Handling features discussed below help extend the Clang-Repl
+functionality by creating an interface between the execution results of a
+program and the compiled program.
+
+1. **Capture Execution Results**: This feature helps capture the execution 
results
+of a program and bring them back to the compiled program.
+
+2. **Dump Captured Execution Results**: This feature helps create a temporary 
dump
+for Value Printing/Automatic Printf, that is, to display the value and type of
+the captured data.
+
+
+1. Capture Execution Results
+
+
+In many cases, it is useful to bring back the program execution result to the
+compiled program. This result can be stored in an object of type **Value**.
+
+How Execution Results are captured (Value Synthesis):
+-
+
+The synthesizer chooses which expression to synthesize, and then it replaces
+the original expression with the synthesized expression. Depending on the
+expression type, it may choose to save an object (``LastValue``) of type 
'value'
+while allocating memory to it (``SetValueWithAlloc()``), or not (
+``SetValueNoAlloc()``).
+
+.. graphviz::
+:name: valuesynthesis
+:caption: Value Synthesis
+:alt: Shows how an object of type 'Value' is synthesized
+:align: center
+
+ digraph "valuesynthesis" {
+ rankdir="LR";
+ graph [fontname="Verdana", fontsize="12"];
+ node [fontname="Verdana", fontsize="12"];
+ edge [fontname="Sans", fontsize="9"];
+
+ start [label=" Create an Object \n 'Last Value' \n of type 'Value' ", 
shape="note", fontcolor=white, fillcolor="#ff", style=filled];
+ assign [label=" Assign the result \n to the 'LastValue' \n (based on 
respective \n Memory Allocation \n scenario) ", shape="box"]
+ print [label=" Pretty Print \n the Value Object ", shape="Msquare", 
fillcolor="yellow", style=filled];
+ start -> assign;
+ assign -> print;
+
+   subgraph SynthesizeExpression {
+ synth [label=" SynthesizeExpr() ", shape="note", fontcolor=white, 
fillcolor="#ff", style=filled];
+ mem [label=" New Memory \n Allocation? ", shape="diamond"];
+ withaloc [label=" SetValueWithAlloc() ", shape="box"];
+ noaloc [label=" SetValueNoAlloc() ", shape="box"];
+ right [label=" 1. RValue Structure \n (a temporary value)", 
shape="box"];
+ left2 [label=" 2. LValue Structure \n (a variable with \n an 
address)", shape="box"];
+ left3 [label=" 3. Built-In Type \n (int, float, etc.)", 
shape="box"];
+ output [label=" move to 'Assign' step ", shape="box"];
+
+ synth -> mem;
+ mem -> withaloc [label="Yes"];
+ mem -> noaloc [label="No"];
+ withaloc -> right;
+ noaloc -> left2;
+ noaloc -> left3;
+ right -> output;
+ left2 -> output;
+ left3 -> output;
+  }
+output -> assign
+  }
+
+Where is the captured result stored?
+
+
+``LastValue`` holds the last result of the value printing. It is a class member
+because it can be accessed even after subsequent inputs.
+
+**Note:** If no value printing happens, then it is in an invalid state.
+
+Improving Efficien

[clang] Add Documentation for Execution Results Handling in Clang-Repl (PR #65650)

2023-10-04 Thread Krishna Narayanan via cfe-commits

https://github.com/Krishna-13-cyber updated 
https://github.com/llvm/llvm-project/pull/65650

>From 001c8fe5627bb83c71a11535889d3c717a869df5 Mon Sep 17 00:00:00 2001
From: Krishna-13-cyber 
Date: Thu, 7 Sep 2023 22:35:53 +0530
Subject: [PATCH] Add Documentation for Execution Results Handling in
 Clang-Repl

---
 clang/docs/CMakeLists.txt |   7 +
 clang/docs/ClangRepl.rst  | 405 ++
 clang/docs/conf.py|   1 +
 3 files changed, 413 insertions(+)

diff --git a/clang/docs/CMakeLists.txt b/clang/docs/CMakeLists.txt
index 4163dd2d90ad5b3..356814f994c32cd 100644
--- a/clang/docs/CMakeLists.txt
+++ b/clang/docs/CMakeLists.txt
@@ -103,6 +103,13 @@ function (gen_rst_file_from_td output_file td_option 
source docs_targets)
 endfunction()
 
 if (LLVM_ENABLE_SPHINX)
+  llvm_find_program(dot)
+  if (HAVE_DOT)
+set(DOT ${LLVM_PATH_DOT})
+  else()
+message(FATAL_ERROR "Cannot find DOT")
+  endif()
+
   include(AddSphinxTarget)
   if (SPHINX_FOUND AND (${SPHINX_OUTPUT_HTML} OR ${SPHINX_OUTPUT_MAN}))
 # Copy rst files to build directory before generating the html
diff --git a/clang/docs/ClangRepl.rst b/clang/docs/ClangRepl.rst
index bd99bc82f17..5399036c123fbbf 100644
--- a/clang/docs/ClangRepl.rst
+++ b/clang/docs/ClangRepl.rst
@@ -213,6 +213,411 @@ concept helps support advanced use cases such as template 
instantiations on dema
 automatic language interoperability. It also helps static languages such as 
C/C++ become
 apt for data science.
 
+Execution Results Handling in Clang-Repl
+
+
+Execution Results Handling features discussed below help extend the Clang-Repl
+functionality by creating an interface between the execution results of a
+program and the compiled program.
+
+1. **Capture Execution Results**: This feature helps capture the execution 
results
+of a program and bring them back to the compiled program.
+
+2. **Dump Captured Execution Results**: This feature helps create a temporary 
dump
+for Value Printing/Automatic Printf, that is, to display the value and type of
+the captured data.
+
+
+1. Capture Execution Results
+
+
+In many cases, it is useful to bring back the program execution result to the
+compiled program. This result can be stored in an object of type **Value**.
+
+How Execution Results are captured (Value Synthesis):
+-
+
+The synthesizer chooses which expression to synthesize, and then it replaces
+the original expression with the synthesized expression. Depending on the
+expression type, it may choose to save an object (``LastValue``) of type 
'value'
+while allocating memory to it (``SetValueWithAlloc()``), or not (
+``SetValueNoAlloc()``).
+
+.. graphviz::
+:name: valuesynthesis
+:caption: Value Synthesis
+:alt: Shows how an object of type 'Value' is synthesized
+:align: center
+
+ digraph "valuesynthesis" {
+ rankdir="LR";
+ graph [fontname="Verdana", fontsize="12"];
+ node [fontname="Verdana", fontsize="12"];
+ edge [fontname="Sans", fontsize="9"];
+
+ start [label=" Create an Object \n 'Last Value' \n of type 'Value' ", 
shape="note", fontcolor=white, fillcolor="#ff", style=filled];
+ assign [label=" Assign the result \n to the 'LastValue' \n (based on 
respective \n Memory Allocation \n scenario) ", shape="box"]
+ print [label=" Pretty Print \n the Value Object ", shape="Msquare", 
fillcolor="yellow", style=filled];
+ start -> assign;
+ assign -> print;
+
+   subgraph SynthesizeExpression {
+ synth [label=" SynthesizeExpr() ", shape="note", fontcolor=white, 
fillcolor="#ff", style=filled];
+ mem [label=" New Memory \n Allocation? ", shape="diamond"];
+ withaloc [label=" SetValueWithAlloc() ", shape="box"];
+ noaloc [label=" SetValueNoAlloc() ", shape="box"];
+ right [label=" 1. RValue Structure \n (a temporary value)", 
shape="box"];
+ left2 [label=" 2. LValue Structure \n (a variable with \n an 
address)", shape="box"];
+ left3 [label=" 3. Built-In Type \n (int, float, etc.)", 
shape="box"];
+ output [label=" move to 'Assign' step ", shape="box"];
+
+ synth -> mem;
+ mem -> withaloc [label="Yes"];
+ mem -> noaloc [label="No"];
+ withaloc -> right;
+ noaloc -> left2;
+ noaloc -> left3;
+ right -> output;
+ left2 -> output;
+ left3 -> output;
+  }
+output -> assign
+  }
+
+Where is the captured result stored?
+
+
+``LastValue`` holds the last result of the value printing. It is a class member
+because it can be accessed even after subsequent inputs.
+
+**Note:** If no value printing happens, then it is in an invalid state.
+
+Improving Efficiency a

[clang] [CodeGen] Respect pointer-overflow sanitizer for void pointers (PR #67772)

2023-10-04 Thread Bill Wendling via cfe-commits

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


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


[clang] [X86] Change target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2 (PR #67410)

2023-10-04 Thread via cfe-commits

bgra8 wrote:

@FreddyLeaf functions with `__attribute__((target("avx")))` trigger the newly 
added warning.

Code like this no longer builds and creates a lot of fallout for us (google 
internal code):

```
#include 

__attribute__((target("avx"))) void test(__m128 a, __m128 b) {
  _mm_cmp_ps(a, b, 14);
}
```

Compiler output:
```
test.cc:4:3: error: argument value 14 is outside the valid range [0, 7] 
[-Wargument-outside-range]
4 |   _mm_cmp_ps(a, b, 14);
```

Passing `-mavx` in the compilation command line makes the build green but the 
attribute `target("avx")` should be equivalent.

Please revert


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


[clang] 077e1b8 - [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation (#66641)

2023-10-04 Thread via cfe-commits

Author: zyn0217
Date: 2023-10-04T04:45:46-05:00
New Revision: 077e1b892d9555c503b86d5361278aa999764884

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

LOG: [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation (#66641)

D63960 performs a tree transformation on AST to prevent evaluating
constant expressions eagerly by removing recorded immediate consteval
invocations from subexpressions. (See
https://reviews.llvm.org/D63960#inline-600736 for its motivation.)

However, the UDL node has been replaced with a CallExpr in the default
TreeTransform since ca844ab0 (inadvertently?). This confuses clangd as
it relies on the exact AST node type to decide whether or not to present
inlay hints for an expression.

With regard to the fix, I think it's enough to return the UDL expression
as-is during the transformation: We've bound it to temporary in its
construction, and there's no ConstantExpr to visit under a UDL.

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

Added: 
clang/test/AST/ast-dump-udl-consteval.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4c8b85fc29755c1..65bd5c8300ea387 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -325,6 +325,8 @@ Bug Fixes in This Version
   (`#67722 `_).
 - Fixes a crash when instantiating a lambda with requires clause.
   (`#64462 `_)
+- Fixes a regression where the ``UserDefinedLiteral`` was not properly 
preserved
+  while evaluating consteval functions. (`#63898 
`_).
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 797b71bffbb451e..304aa7d105e269b 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18468,7 +18468,10 @@ static void RemoveNestedImmediateInvocation(
   DRSet.erase(cast(E->getCallee()->IgnoreImplicit()));
   return Base::TransformCXXOperatorCallExpr(E);
 }
-/// Base::TransformInitializer skip ConstantExpr so we need to visit them
+/// Base::TransformUserDefinedLiteral doesn't preserve the
+/// UserDefinedLiteral node.
+ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
+/// Base::TransformInitializer skips ConstantExpr so we need to visit them
 /// here.
 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
   if (!Init)

diff  --git a/clang/test/AST/ast-dump-udl-consteval.cpp 
b/clang/test/AST/ast-dump-udl-consteval.cpp
new file mode 100644
index 000..9da53f725172aba
--- /dev/null
+++ b/clang/test/AST/ast-dump-udl-consteval.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -xc++ -std=c++23 -ast-dump %s | FileCheck %s
+
+int inline consteval operator""_u32(unsigned long long val) {
+  return val;
+}
+
+void udl() {
+  (void)(0_u32 + 1_u32);
+}
+
+// CHECK: `-BinaryOperator {{.+}}  'int' '+'
+// CHECK-NEXT: |-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT: | |-value: Int 0
+// CHECK-NEXT: | `-UserDefinedLiteral {{.+}}  'int'
+// CHECK: `-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT:   |-value: Int 1
+// CHECK-NEXT:   `-UserDefinedLiteral {{.+}}  'int'



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


[clang] [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation (PR #66641)

2023-10-04 Thread via cfe-commits

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


[PATCH] D155775: [HIP][Clang][Driver][RFC] Add driver support for C++ Parallel Algorithm Offload

2023-10-04 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx added a comment.

In D155775#4652851 , @ro wrote:

> In D155775#4652785 , @AlexVlx wrote:
>
>> In D155775#4652780 , @dyung wrote:
>>
>>> 
>
>
>
>>> At this point, would it be easier to add a REQUIRES line for the target the 
>>> test should support rather than just whack-a-mole for the targets it does 
>>> not?
>>
>> Oh, it definitely would be MUCH easier to add a `REQUIRES` line, however I'd 
>> have had to have thought about that, which I did not, so thank you for the 
>> wake up call. I'll update this in a few minutes.
>
> Unfortunately, this is still not done after almost a day, leaving quite a 
> number of buildbots broken.  Please fix or revert.

Apologies, do you have an indication of which buildbots are still broken due to 
this change, after the most recent commit? The ones I was initially aware of, 
as well as those brought up here appear to pass at the moment, and glancing 
through the currently failing builds didn’t point to this as being the culprit 
(I could’ve simply missed it). Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155775

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


[clang] Add Documentation for Execution Results Handling in Clang-Repl (PR #65650)

2023-10-04 Thread via cfe-commits

github-actions[bot] wrote:




:warning: Python code formatter, darker found issues in your code. :warning:



You can test this locally with the following command:


``bash
darker --check --diff -r 
b6f6fe98a856e9ce8ab945ef18d49291a8486acc..001c8fe5627bb83c71a11535889d3c717a869df5
 clang/docs/conf.py
``





View the diff from darker here.


``diff
--- conf.py 2023-10-04 09:37:02.00 +
+++ conf.py 2023-10-04 09:49:21.120871 +
@@ -35,11 +35,11 @@
 
 import sphinx
 
 if sphinx.version_info >= (3, 0):
 extensions.append("myst_parser")
-extensions.append('sphinx.ext.graphviz')
+extensions.append("sphinx.ext.graphviz")
 
 # The encoding of source files.
 # source_encoding = 'utf-8-sig'
 
 # The master toctree document.

``




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


[PATCH] D155775: [HIP][Clang][Driver][RFC] Add driver support for C++ Parallel Algorithm Offload

2023-10-04 Thread Rainer Orth via Phabricator via cfe-commits
ro added a comment.

In D155775#4652872 , @AlexVlx wrote:

> In D155775#4652851 , @ro wrote:
>
>> In D155775#4652785 , @AlexVlx 
>> wrote:
>>
>>> In D155775#4652780 , @dyung wrote:
>>>
 
>>
>>
>>
 At this point, would it be easier to add a REQUIRES line for the target 
 the test should support rather than just whack-a-mole for the targets it 
 does not?
>>>
>>> Oh, it definitely would be MUCH easier to add a `REQUIRES` line, however 
>>> I'd have had to have thought about that, which I did not, so thank you for 
>>> the wake up call. I'll update this in a few minutes.
>>
>> Unfortunately, this is still not done after almost a day, leaving quite a 
>> number of buildbots broken.  Please fix or revert.
>
> Apologies, do you have an indication of which buildbots are still broken due 
> to this change, after the most recent commit? The ones I was initially aware 
> of, as well as those brought up here appear to pass at the moment, and 
> glancing through the currently failing builds didn’t point to this as being 
> the culprit (I could’ve simply missed it). Thank you!

At least the Solaris/sparcv9 and Solaris/amd64 buildbots are still affected.  
However, `XFAIL`ing a long list of targets when it's known that particular 
targets/target properties are required for the test to `PASS` is fundamentally 
wrong!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155775

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


[clang] [mlir][llvm] Fix elem type passing into `getelementptr` (PR #68136)

2023-10-04 Thread Rik Huijzer via cfe-commits

rikhuijzer wrote:

> What are the use cases for allowing either of these two syntaxes?
> The LLVM Dialect tries to closely mirror LLVM proper as much as possible and 
> this would deviate from LLVMs behaviour. While the transition is currently 
> stalled, in the future typed pointers will be removed from the dialect 
> entirely, further discouraging the use of typed-pointers such as shown here.

>From reading , I assume that the use-case is 
>that "MLIR can afford to support both opaque and non-opaque pointers at the 
>same time and simplify the transition". But Alex (@ftynse) is probably the 
>best person to answer this.

Regardless of the big picture, the question might be unrelated to this PR as 
this PR only fixes a bug in the implementation. Currently, there are LLVM 
operations in MLIR that do accept both forms. For example, `llvm.alloca` where

```mlir
llvm.func @main(%sz : i64) {
  "llvm.alloca"(%sz) : (i64) -> !llvm.ptr
  llvm.return
}
```

and 

```mlir
llvm.func @main(%sz : i64) {
  "llvm.alloca"(%sz) { elem_type = i32 } : (i64) -> !llvm.ptr
  llvm.return
}
```
Both are translated to
```llvm
; ModuleID = 'LLVMDialectModule'
source_filename = "LLVMDialectModule"

declare ptr @malloc(i64)

declare void @free(ptr)

define void @main(i64 %0) {
  %2 = alloca i32, i64 %0, align 4
  ret void
}

!llvm.module.flags = !{!0}

!0 = !{i32 2, !"Debug Info Version", i32 3}
```
via
```sh
mlir-translate temp.mlir -mlir-to-llvmir
```
Conversely, `llvm.getelementptr` currently only accepts the attribute (`{ 
elem_type = !llvm.ptr }`). This PR makes things consistent again.

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


[clang-tools-extra] [clang-tidy][IncludeCleaner] Fix analysis supression in presence of verbatim spellings (PR #68185)

2023-10-04 Thread via cfe-commits


@@ -179,12 +183,14 @@ void IncludeCleanerCheck::check(const 
MatchFinder::MatchResult &Result) {
   if (getCurrentMainFile().endswith(PHeader))
 continue;
 }
-
-if (llvm::none_of(
-IgnoreHeadersRegex,
-[Resolved = (*I.Resolved).getFileEntry().tryGetRealPathName()](
-const llvm::Regex &R) { return R.match(Resolved); }))
-  Unused.push_back(&I);
+auto StdHeader = tooling::stdlib::Header::named(

VitaNuo wrote:

Ok, thanks, then what about something like (apologies for small mistakes, just 
typing into the comment window):

```
include_cleaner::Header getHeader(include_cleaner::Include I) {
auto StdHeader = tooling::stdlib::Header::named(I.quote(), 
PP->getLangOpts().CPlusPlus ? tooling::stdlib::Lang::CXX :  
tooling::stdlib::Lang::C);

   if (StdHeader) 
  return include_cleaner::Header(*StdHeader);
   return include_cleaner::Header(I.Resolved);
}

auto Header = getHeader(I);
if (shouldIgnore(Header))
 continue;

```

I'm trying to simplify the flow in the `check` method, as it seems like it's 
getting bogged down in implementation details. WDYT?

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


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits

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

>From ee49cd2bddc21be68f73fca7cb344150cd7ad7a6 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [CLang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 6 ++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3dce7f6a8f9d56e..4e8487d3386e21c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,12 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fenable-llvm-verifier`` and it's complement ``-fdisable-llvm-verifier``.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 61e0729974c24d1..ee464de14f7740b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1905,6 +1905,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fenable_llvm_verifier : Flag<["-"], "fenable-llvm-verifier">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fdisable_llvm_verifier : Flag<["-"], "fdisable-llvm-verifier">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 129adfb9fcc74d1..11abc2cdf34d6a7 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fdisable_llvm_verifier,
+   options::OPT_fenable_llvm_verifier, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..e0764cf0b76830f 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fenable-llvm-verifier %s 2>&1 | FileCheck 
-check-prefix=CHECK-ENABLE-LLVM-VERIFIER %s
+// RUN: %clang -### -S -fdisable-llvm-verifier %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISABLE-LLVM-VERIFIER %s
+// CHECK-ENABLE-LLVM-VERIFIER-NOT: "-disable-llvm-verifier"
+// CHECK-DISABLE-LLVM-VERIFIER: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

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


[clang] [clang][dataflow] HTML logger: Mark iterations that have converged. (PR #68204)

2023-10-04 Thread via cfe-commits

https://github.com/martinboehme created 
https://github.com/llvm/llvm-project/pull/68204

I've eliminated the `logText("Block converged")` call entirely because

a) These logs are associated with an individual `CFGElement`, while convergence
   should be associated with a block, and

b) The log message was being associated with the wrong block: `recordState()`
   dumps all of the pending log messages, but `blockConverged()` is called after
   the last `recordState()` call for a given block, so that the "Block
   converged" log message was being associated with the first element of the
   _next_ block to be processed.


>From 13c53463fe19b5cb89d21c73b2db6c1b61939ff0 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Wed, 4 Oct 2023 11:01:08 +
Subject: [PATCH] [clang][dataflow] HTML logger: Mark iterations that have
 converged.

I've eliminated the `logText("Block converged")` call entirely because

a) These logs are associated with an individual `CFGElement`, while convergence
   should be associated with a block, and

b) The log message was being associated with the wrong block: `recordState()`
   dumps all of the pending log messages, but `blockConverged()` is called after
   the last `recordState()` call for a given block, so that the "Block
   converged" log message was being associated with the first element of the
   _next_ block to be processed.
---
 .../lib/Analysis/FlowSensitive/HTMLLogger.cpp | 20 +++
 .../Analysis/FlowSensitive/HTMLLogger.html|  2 ++
 2 files changed, 14 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index 47915958750d1f4..8aef1d6f46089d2 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -150,6 +150,7 @@ class HTMLLogger : public Logger {
 const CFGBlock *Block;
 unsigned Iter;
 bool PostVisit;
+bool Converged;
   };
 
   StreamFactory Streams;
@@ -159,8 +160,8 @@ class HTMLLogger : public Logger {
   const ControlFlowContext *CFG;
   // Timeline of iterations of CFG block visitation.
   std::vector Iters;
-  // Number of times each CFG block has been seen.
-  llvm::DenseMap> BlockIters;
+  // Indexes  in `Iters` of the iterations for each block.
+  llvm::DenseMap> BlockIters;
   // The messages logged in the current context but not yet written.
   std::string ContextLogs;
   // The number of elements we have visited within the current CFG block.
@@ -207,6 +208,7 @@ class HTMLLogger : public Logger {
   JOS->attribute("block", blockID(E.Block->getBlockID()));
   JOS->attribute("iter", E.Iter);
   JOS->attribute("post_visit", E.PostVisit);
+  JOS->attribute("converged", E.Converged);
 });
   }
 });
@@ -222,10 +224,10 @@ class HTMLLogger : public Logger {
   }
 
   void enterBlock(const CFGBlock &B, bool PostVisit) override {
-llvm::SmallVector &BIter = BlockIters[&B];
+llvm::SmallVector &BIter = BlockIters[&B];
 unsigned IterNum = BIter.size() + 1;
-BIter.push_back({&B, IterNum, PostVisit});
-Iters.push_back({&B, IterNum, PostVisit});
+BIter.push_back(Iters.size());
+Iters.push_back({&B, IterNum, PostVisit, /*Converged=*/false});
 ElementIndex = 0;
   }
   void enterElement(const CFGElement &E) override {
@@ -290,7 +292,7 @@ class HTMLLogger : public Logger {
   }
 });
   }
-  void blockConverged() override { logText("Block converged"); }
+  void blockConverged() override { Iters.back().Converged = true; }
 
   void logText(llvm::StringRef S) override {
 ContextLogs.append(S.begin(), S.end());
@@ -301,13 +303,15 @@ class HTMLLogger : public Logger {
   // Write the CFG block details.
   // Currently this is just the list of elements in execution order.
   // FIXME: an AST dump would be a useful view, too.
-  void writeBlock(const CFGBlock &B, llvm::ArrayRef ItersForB) {
+  void writeBlock(const CFGBlock &B, llvm::ArrayRef ItersForB) {
 JOS->attributeObject(blockID(B.getBlockID()), [&] {
   JOS->attributeArray("iters", [&] {
-for (const auto &Iter : ItersForB) {
+for (size_t IterIdx : ItersForB) {
+  const Iteration &Iter = Iters[IterIdx];
   JOS->object([&] {
 JOS->attribute("iter", Iter.Iter);
 JOS->attribute("post_visit", Iter.PostVisit);
+JOS->attribute("converged", Iter.Converged);
   });
 }
   });
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.html 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
index 6d866d57e144866..ec9d74c71d35d98 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
@@ -45,6 +45,7 @@
 {{entry.block}}
 (post-visit)
 ({{entry.iter}})
+ →|
   
 
 
@@ -62,6 +63,7 @@
 
   Post-visit
   Iteration {{iter.iter}}
+   →|
 
   
 

_

[clang] [clang][dataflow] HTML logger: Mark iterations that have converged. (PR #68204)

2023-10-04 Thread via cfe-commits

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


[clang] [clang][dataflow] HTML logger: Mark iterations that have converged. (PR #68204)

2023-10-04 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

I've eliminated the `logText("Block converged")` call entirely because

a) These logs are associated with an individual `CFGElement`, while convergence
   should be associated with a block, and

b) The log message was being associated with the wrong block: `recordState()`
   dumps all of the pending log messages, but `blockConverged()` is called after
   the last `recordState()` call for a given block, so that the "Block
   converged" log message was being associated with the first element of the
   _next_ block to be processed.

Example:

![image](https://github.com/llvm/llvm-project/assets/29098113/6a19095c-2dbb-4771-9485-e8e45c9d26fb)



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


2 Files Affected:

- (modified) clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp (+12-8) 
- (modified) clang/lib/Analysis/FlowSensitive/HTMLLogger.html (+2) 


``diff
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index 47915958750d1f4..8aef1d6f46089d2 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -150,6 +150,7 @@ class HTMLLogger : public Logger {
 const CFGBlock *Block;
 unsigned Iter;
 bool PostVisit;
+bool Converged;
   };
 
   StreamFactory Streams;
@@ -159,8 +160,8 @@ class HTMLLogger : public Logger {
   const ControlFlowContext *CFG;
   // Timeline of iterations of CFG block visitation.
   std::vector Iters;
-  // Number of times each CFG block has been seen.
-  llvm::DenseMap> BlockIters;
+  // Indexes  in `Iters` of the iterations for each block.
+  llvm::DenseMap> BlockIters;
   // The messages logged in the current context but not yet written.
   std::string ContextLogs;
   // The number of elements we have visited within the current CFG block.
@@ -207,6 +208,7 @@ class HTMLLogger : public Logger {
   JOS->attribute("block", blockID(E.Block->getBlockID()));
   JOS->attribute("iter", E.Iter);
   JOS->attribute("post_visit", E.PostVisit);
+  JOS->attribute("converged", E.Converged);
 });
   }
 });
@@ -222,10 +224,10 @@ class HTMLLogger : public Logger {
   }
 
   void enterBlock(const CFGBlock &B, bool PostVisit) override {
-llvm::SmallVector &BIter = BlockIters[&B];
+llvm::SmallVector &BIter = BlockIters[&B];
 unsigned IterNum = BIter.size() + 1;
-BIter.push_back({&B, IterNum, PostVisit});
-Iters.push_back({&B, IterNum, PostVisit});
+BIter.push_back(Iters.size());
+Iters.push_back({&B, IterNum, PostVisit, /*Converged=*/false});
 ElementIndex = 0;
   }
   void enterElement(const CFGElement &E) override {
@@ -290,7 +292,7 @@ class HTMLLogger : public Logger {
   }
 });
   }
-  void blockConverged() override { logText("Block converged"); }
+  void blockConverged() override { Iters.back().Converged = true; }
 
   void logText(llvm::StringRef S) override {
 ContextLogs.append(S.begin(), S.end());
@@ -301,13 +303,15 @@ class HTMLLogger : public Logger {
   // Write the CFG block details.
   // Currently this is just the list of elements in execution order.
   // FIXME: an AST dump would be a useful view, too.
-  void writeBlock(const CFGBlock &B, llvm::ArrayRef ItersForB) {
+  void writeBlock(const CFGBlock &B, llvm::ArrayRef ItersForB) {
 JOS->attributeObject(blockID(B.getBlockID()), [&] {
   JOS->attributeArray("iters", [&] {
-for (const auto &Iter : ItersForB) {
+for (size_t IterIdx : ItersForB) {
+  const Iteration &Iter = Iters[IterIdx];
   JOS->object([&] {
 JOS->attribute("iter", Iter.Iter);
 JOS->attribute("post_visit", Iter.PostVisit);
+JOS->attribute("converged", Iter.Converged);
   });
 }
   });
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.html 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
index 6d866d57e144866..ec9d74c71d35d98 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
@@ -45,6 +45,7 @@
 {{entry.block}}
 (post-visit)
 ({{entry.iter}})
+ →|
   
 
 
@@ -62,6 +63,7 @@
 
   Post-visit
   Iteration {{iter.iter}}
+   →|
 
   
 

``




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


[clang] [Clang] Fix missing diagnostic for non-standard layout type in `offsetof` (PR #65246)

2023-10-04 Thread via cfe-commits

https://github.com/kasuga-fj updated 
https://github.com/llvm/llvm-project/pull/65246

>From 1c2f558a80635333655011c723af69371d3587af Mon Sep 17 00:00:00 2001
From: "kasuga.ryotaro" 
Date: Wed, 30 Aug 2023 13:26:31 +0900
Subject: [PATCH 01/13] [Clang] Fix missing diagnostic for non-standard layout
 type in `offsetof`

Fixes #64619

Clang warns diagnostic for non-standard layout types in `offsetof` only
if they are in evaluated context. With this patch, you'll also get
  diagnostic if you use `offsetof` on non-standard layout types in any
  other contexts
---
 clang/lib/Sema/SemaExpr.cpp |  9 -
 clang/test/SemaCXX/class-layout.cpp | 30 ++---
 clang/test/SemaCXX/ms_struct.cpp|  5 ++---
 clang/test/SemaCXX/offsetof.cpp | 10 +-
 4 files changed, 26 insertions(+), 28 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 797b71bffbb451e..c978a2d90f0d877 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -16796,12 +16796,11 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation 
BuiltinLoc,
 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
 : diag::ext_offsetof_non_pod_type;
 
-  if (!IsSafe && !DidWarnAboutNonPOD &&
-  DiagRuntimeBehavior(BuiltinLoc, nullptr,
-  PDiag(DiagID)
-  << SourceRange(Components[0].LocStart, OC.LocEnd)
-  << CurrentType))
+  if (!IsSafe && !DidWarnAboutNonPOD) {
+Diag(BuiltinLoc, DiagID)
+<< SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
 DidWarnAboutNonPOD = true;
+  }
 }
 
 // Look for the field.
diff --git a/clang/test/SemaCXX/class-layout.cpp 
b/clang/test/SemaCXX/class-layout.cpp
index 9782ff08100b2d6..23b3dbe24249378 100644
--- a/clang/test/SemaCXX/class-layout.cpp
+++ b/clang/test/SemaCXX/class-layout.cpp
@@ -1,18 +1,18 @@
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++98 -Wno-inaccessible-base -Wno-c++11-extensions
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base
-// RUN: %clang_cc1 -triple x86_64-apple-darwin%s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple x86_64-scei-ps4%s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-sie-ps5 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=6 -DCLANG_ABI_COMPAT=6
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=14 -DCLANG_ABI_COMPAT=14
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=16 -DCLANG_ABI_COMPAT=16
-// RUN: %clang_cc1 -triple powerpc-ibm-aix7.3.0.0 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple powerpc-ibm-aix7.3.0.0 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple powerpc64-ibm-aix7.3.0.0 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple powerpc64-ibm-aix7.3.0.0 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
-// RUN: %clang_cc1 -triple s390x-none-zos %s -fsyntax-only -verify -std=c++11 
-Wno-inaccessible-base
-// RUN: %clang_cc1 -triple s390x-none-zos %s -fsyntax-only -verify -std=c++11 
-Wno-inaccessible-base -fclang-abi-compat=15 -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++98 -Wno-inaccessible-base -Wno-invalid-offsetof -Wno-c++11-extensions
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof
+// RUN: %clang_cc1 -triple x86_64-apple-darwin%s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof -DCLANG_ABI_COMPAT=15
+// RUN: %clang_cc1 -triple x86_64-scei-ps4%s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -triple x86_64-sie-ps5 %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof -DCLANG_ABI_COMPAT=6
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify 
-std=c++11 -Wno-inaccessible-base -Wno-invalid-offsetof -fclang-abi-compat

[clang] 9f406e4 - [HIP][Clang][Driver] Correctly specify test requirements as Linux + x86 + AMDGPU; temporarily retain targeted XFAILs for Hexagon & PS.

2023-10-04 Thread Alex Voicu via cfe-commits

Author: Alex Voicu
Date: 2023-10-04T12:04:13+01:00
New Revision: 9f406e450b6dfebe41be54cc7a7a6861b8eaf618

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

LOG: [HIP][Clang][Driver] Correctly specify test requirements as Linux + x86 + 
AMDGPU; temporarily retain targeted XFAILs for Hexagon & PS.

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

Added: 


Modified: 
clang/test/Driver/hipstdpar.c

Removed: 




diff  --git a/clang/test/Driver/hipstdpar.c b/clang/test/Driver/hipstdpar.c
index f12a6e8d9d25249..69c5b177d170cd8 100644
--- a/clang/test/Driver/hipstdpar.c
+++ b/clang/test/Driver/hipstdpar.c
@@ -1,8 +1,9 @@
-// XFAIL: target={{.*}}-apple{{.*}}
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+// REQUIRES: system-linux
 // XFAIL: target={{.*}}hexagon{{.*}}
 // XFAIL: target={{.*}}-scei{{.*}}
 // XFAIL: target={{.*}}-sie{{.*}}
-// XFAIL: target={{.*}}-windows{{.*}}
 
 // RUN: not %clang -### --hipstdpar -nogpulib -nogpuinc --compile %s 2>&1 | \
 // RUN:   FileCheck --check-prefix=HIPSTDPAR-MISSING-LIB %s



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


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits

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

>From 8a0226386732cea374558a38475c7d629c84ef28 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [CLang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 6 ++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 65bd5c8300ea387..fd4b16a9202e188 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,12 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fenable-llvm-verifier`` and it's complement ``-fdisable-llvm-verifier``.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 61e0729974c24d1..99df825620582bb 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1905,6 +1905,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fverify_intermediate_code : Flag<["-"], "fverify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 129adfb9fcc74d1..4af3ed2dd88ea65 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
+   options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..ebe8a0520bf0fca 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fverify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-VERIFY-INTERMEDIATE-CODE %s
+// RUN: %clang -### -S -fno-verify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-VERIFY-INTERMEDIATE-CODE %s
+// CHECK-VERIFY-INTERMEDIATE-CODE-NOT: "-disable-llvm-verifier"
+// CHECK-NO-VERIFY-INTERMEDIATE-CODE: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

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


[clang] [Clang][Driver] Add new flags to control IR verification (PR #68172)

2023-10-04 Thread Matheus Izvekov via cfe-commits

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

>From 634c0f8ea4acd0694d89c3e2d278e6bcb78b923f Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 4 Oct 2023 04:39:11 +0200
Subject: [PATCH] [Clang][Driver] Add new flags to control IR verification

---
 clang/docs/ReleaseNotes.rst   | 7 +++
 clang/include/clang/Driver/Options.td | 6 ++
 clang/lib/Driver/ToolChains/Clang.cpp | 6 --
 clang/test/Driver/clang_f_opts.c  | 5 +
 4 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 65bd5c8300ea387..804c0fc2e235c77 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -146,6 +146,13 @@ Non-comprehensive list of changes in this release
 
 New Compiler Flags
 --
+* ``-fverify-intermediate-code`` and it's complement 
``-fno-verify-intermediate-code``.
+  Enables or disables verification of the generated LLVM IR.
+  It's strongly encouraged to enable this verification, as it can catch hard to
+  find code generation bugs.
+  Since enabling the verifier adds a non-trivial cost of a few percent impact 
on
+  build times, it's disabled by default, unless your LLVM distribution itself 
is
+  compiled with runtime checks enabled.
 
 Deprecated Compiler Flags
 -
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 61e0729974c24d1..99df825620582bb 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1905,6 +1905,12 @@ defm safe_buffer_usage_suggestions : 
BoolFOption<"safe-buffer-usage-suggestions"
   PosFlag,
   NegFlag>;
+def fverify_intermediate_code : Flag<["-"], "fverify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Enable verification of LLVM IR">, Flags<[NoXarchOption]>;
+def fno_verify_intermediate_code : Flag<["-"], "fno-verify-intermediate-code">,
+  Group, Visibility<[ClangOption, CLOption, DXCOption]>,
+  HelpText<"Disable verification of LLVM IR">, Flags<[NoXarchOption]>;
 def fdiscard_value_names : Flag<["-"], "fdiscard-value-names">,
   Group, Visibility<[ClangOption, DXCOption]>,
   HelpText<"Discard value names in LLVM IR">, Flags<[NoXarchOption]>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 129adfb9fcc74d1..4af3ed2dd88ea65 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5150,9 +5150,11 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   const bool IsAssertBuild = true;
 #endif
 
-  // Disable the verification pass in -asserts builds.
-  if (!IsAssertBuild)
+  // Disable the verification pass in asserts builds unless otherwise 
specified.
+  if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
+   options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
 CmdArgs.push_back("-disable-llvm-verifier");
+  }
 
   // Discard value names in assert builds unless otherwise specified.
   if (Args.hasFlag(options::OPT_fdiscard_value_names,
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 7a3616a2e9f0a48..ebe8a0520bf0fca 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -520,6 +520,11 @@
 // CHECK-COVERAGE-COMPILATION-DIR: "-fcoverage-compilation-dir=."
 // CHECK-COVERAGE-COMPILATION-DIR-NOT: "-ffile-compilation-dir=."
 
+// RUN: %clang -### -S -fverify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-VERIFY-INTERMEDIATE-CODE %s
+// RUN: %clang -### -S -fno-verify-intermediate-code %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-VERIFY-INTERMEDIATE-CODE %s
+// CHECK-VERIFY-INTERMEDIATE-CODE-NOT: "-disable-llvm-verifier"
+// CHECK-NO-VERIFY-INTERMEDIATE-CODE: "-disable-llvm-verifier"
+
 // RUN: %clang -### -S -fdiscard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-DISCARD-NAMES %s
 // RUN: %clang -### -S -fno-discard-value-names %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-DISCARD-NAMES %s
 // CHECK-DISCARD-NAMES: "-discard-value-names"

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


[clang] [clang][dataflow] HTML logger: Mark iterations that have converged. (PR #68204)

2023-10-04 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall approved this pull request.

This is great!

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


[PATCH] D156565: Diagnose use of VLAs in C++ by default

2023-10-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 557575.
aaron.ballman added a comment.

Updated based on review feedback. Specifically:

- Added test cases, fixed handling of parenthesized expressions.


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

https://reviews.llvm.org/D156565

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/Analysis/lambdas.cpp
  clang/test/CXX/basic/basic.types/p10.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.typedef/p2-0x.cpp
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4.cpp
  clang/test/CXX/temp/temp.arg/temp.arg.type/p2.cpp
  clang/test/CXX/temp/temp.decls/temp.variadic/p5.cpp
  clang/test/Misc/warning-wall.c
  clang/test/OpenMP/debug-info-openmp-array.cpp
  clang/test/OpenMP/for_reduction_codegen.cpp
  clang/test/OpenMP/for_reduction_codegen_UDR.cpp
  clang/test/OpenMP/master_taskloop_firstprivate_codegen.cpp
  clang/test/OpenMP/master_taskloop_in_reduction_codegen.cpp
  clang/test/OpenMP/master_taskloop_lastprivate_codegen.cpp
  clang/test/OpenMP/master_taskloop_private_codegen.cpp
  clang/test/OpenMP/master_taskloop_reduction_codegen.cpp
  clang/test/OpenMP/master_taskloop_simd_firstprivate_codegen.cpp
  clang/test/OpenMP/master_taskloop_simd_in_reduction_codegen.cpp
  clang/test/OpenMP/master_taskloop_simd_lastprivate_codegen.cpp
  clang/test/OpenMP/master_taskloop_simd_private_codegen.cpp
  clang/test/OpenMP/master_taskloop_simd_reduction_codegen.cpp
  clang/test/OpenMP/nvptx_target_codegen.cpp
  clang/test/OpenMP/parallel_ast_print.cpp
  clang/test/OpenMP/parallel_codegen.cpp
  clang/test/OpenMP/parallel_firstprivate_codegen.cpp
  clang/test/OpenMP/parallel_for_codegen.cpp
  clang/test/OpenMP/parallel_masked_ast_print.cpp
  clang/test/OpenMP/parallel_master_ast_print.cpp
  clang/test/OpenMP/parallel_master_taskloop_firstprivate_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_lastprivate_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_private_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_reduction_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_simd_firstprivate_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_simd_lastprivate_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_simd_private_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_simd_reduction_codegen.cpp
  clang/test/OpenMP/single_codegen.cpp
  clang/test/OpenMP/target_ast_print.cpp
  clang/test/OpenMP/target_codegen.cpp
  clang/test/OpenMP/target_constant_device_codegen.cpp
  clang/test/OpenMP/target_data_codegen.cpp
  clang/test/OpenMP/target_data_use_device_addr_codegen.cpp
  clang/test/OpenMP/target_defaultmap_codegen_01.cpp
  clang/test/OpenMP/target_defaultmap_messages.cpp
  clang/test/OpenMP/target_depend_codegen.cpp
  clang/test/OpenMP/target_enter_data_codegen.cpp
  clang/test/OpenMP/target_enter_data_depend_codegen.cpp
  clang/test/OpenMP/target_exit_data_codegen.cpp
  clang/test/OpenMP/target_exit_data_depend_codegen.cpp
  clang/test/OpenMP/target_firstprivate_codegen.cpp
  clang/test/OpenMP/target_has_device_addr_codegen_01.cpp
  clang/test/OpenMP/target_in_reduction_codegen.cpp
  clang/test/OpenMP/target_map_codegen_12.cpp
  clang/test/OpenMP/target_map_codegen_18a.cpp
  clang/test/OpenMP/target_map_codegen_18b.cpp
  clang/test/OpenMP/target_map_codegen_18c.cpp
  clang/test/OpenMP/target_map_codegen_18d.cpp
  clang/test/OpenMP/target_map_messages.cpp
  clang/test/OpenMP/target_parallel_codegen.cpp
  clang/test/OpenMP/target_parallel_defaultmap_messages.cpp
  clang/test/OpenMP/target_parallel_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_for_codegen.cpp
  clang/test/OpenMP/target_parallel_for_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_generic_loop_depend_codegen.cpp
  clang/test/OpenMP/target_private_codegen.cpp
  clang/test/OpenMP/target_reduction_codegen.cpp
  clang/test/OpenMP/target_simd_codegen.cpp
  clang/test/OpenMP/target_simd_depend_codegen.cpp
  clang/test/OpenMP/target_teams_codegen.cpp
  clang/test/OpenMP/target_teams_depend_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_collapse_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_depend_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_dist_schedule_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_collapse_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_depend_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_dist_schedule_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_schedule_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_collapse_codegen.cpp
  clang/test/OpenMP/target_team

[clang] 2be7c65 - [clang][dataflow] HTML logger: Mark iterations that have converged. (#68204)

2023-10-04 Thread via cfe-commits

Author: martinboehme
Date: 2023-10-04T13:47:24+02:00
New Revision: 2be7c651c4a221a681b4a668617e73bf4a681a34

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

LOG: [clang][dataflow] HTML logger: Mark iterations that have converged. 
(#68204)

I've eliminated the `logText("Block converged")` call entirely because

a) These logs are associated with an individual `CFGElement`, while
convergence
   should be associated with a block, and

b) The log message was being associated with the wrong block:
`recordState()`
dumps all of the pending log messages, but `blockConverged()` is called
after
   the last `recordState()` call for a given block, so that the "Block
converged" log message was being associated with the first element of
the
   _next_ block to be processed.

Example:


![image](https://github.com/llvm/llvm-project/assets/29098113/6a19095c-2dbb-4771-9485-e8e45c9d26fb)

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
clang/lib/Analysis/FlowSensitive/HTMLLogger.html

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index 47915958750d1f4..8aef1d6f46089d2 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -150,6 +150,7 @@ class HTMLLogger : public Logger {
 const CFGBlock *Block;
 unsigned Iter;
 bool PostVisit;
+bool Converged;
   };
 
   StreamFactory Streams;
@@ -159,8 +160,8 @@ class HTMLLogger : public Logger {
   const ControlFlowContext *CFG;
   // Timeline of iterations of CFG block visitation.
   std::vector Iters;
-  // Number of times each CFG block has been seen.
-  llvm::DenseMap> BlockIters;
+  // Indexes  in `Iters` of the iterations for each block.
+  llvm::DenseMap> BlockIters;
   // The messages logged in the current context but not yet written.
   std::string ContextLogs;
   // The number of elements we have visited within the current CFG block.
@@ -207,6 +208,7 @@ class HTMLLogger : public Logger {
   JOS->attribute("block", blockID(E.Block->getBlockID()));
   JOS->attribute("iter", E.Iter);
   JOS->attribute("post_visit", E.PostVisit);
+  JOS->attribute("converged", E.Converged);
 });
   }
 });
@@ -222,10 +224,10 @@ class HTMLLogger : public Logger {
   }
 
   void enterBlock(const CFGBlock &B, bool PostVisit) override {
-llvm::SmallVector &BIter = BlockIters[&B];
+llvm::SmallVector &BIter = BlockIters[&B];
 unsigned IterNum = BIter.size() + 1;
-BIter.push_back({&B, IterNum, PostVisit});
-Iters.push_back({&B, IterNum, PostVisit});
+BIter.push_back(Iters.size());
+Iters.push_back({&B, IterNum, PostVisit, /*Converged=*/false});
 ElementIndex = 0;
   }
   void enterElement(const CFGElement &E) override {
@@ -290,7 +292,7 @@ class HTMLLogger : public Logger {
   }
 });
   }
-  void blockConverged() override { logText("Block converged"); }
+  void blockConverged() override { Iters.back().Converged = true; }
 
   void logText(llvm::StringRef S) override {
 ContextLogs.append(S.begin(), S.end());
@@ -301,13 +303,15 @@ class HTMLLogger : public Logger {
   // Write the CFG block details.
   // Currently this is just the list of elements in execution order.
   // FIXME: an AST dump would be a useful view, too.
-  void writeBlock(const CFGBlock &B, llvm::ArrayRef ItersForB) {
+  void writeBlock(const CFGBlock &B, llvm::ArrayRef ItersForB) {
 JOS->attributeObject(blockID(B.getBlockID()), [&] {
   JOS->attributeArray("iters", [&] {
-for (const auto &Iter : ItersForB) {
+for (size_t IterIdx : ItersForB) {
+  const Iteration &Iter = Iters[IterIdx];
   JOS->object([&] {
 JOS->attribute("iter", Iter.Iter);
 JOS->attribute("post_visit", Iter.PostVisit);
+JOS->attribute("converged", Iter.Converged);
   });
 }
   });

diff  --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.html 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
index 6d866d57e144866..ec9d74c71d35d98 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.html
@@ -45,6 +45,7 @@
 {{entry.block}}
 (post-visit)
 ({{entry.iter}})
+ →|
   
 
 
@@ -62,6 +63,7 @@
 
   Post-visit
   Iteration {{iter.iter}}
+   →|
 
   
 



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


[clang] [clang][dataflow] HTML logger: Mark iterations that have converged. (PR #68204)

2023-10-04 Thread via cfe-commits

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


[clang] [analyzer] Extend EnumCastOutOfRange diagnostics (PR #68191)

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

https://github.com/gamesh411 updated 
https://github.com/llvm/llvm-project/pull/68191

From 6b70c3246747b5a1204062f40f91273f60a38600 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= 
Date: Wed, 4 Oct 2023 10:38:00 +0200
Subject: [PATCH 1/2] [analyzer] Extend EnumCastOutOfRange diagnostics

EnumCastOutOfRange checker now reports the name of the enum in the
warning message. Additionally, a note-tag is placed to highlight the
location of the declaration.
---
 .../Checkers/EnumCastOutOfRangeChecker.cpp|  33 --
 clang/test/Analysis/enum-cast-out-of-range.c  |  13 ++-
 .../test/Analysis/enum-cast-out-of-range.cpp  | 108 +-
 3 files changed, 87 insertions(+), 67 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
index 89be6a47250a245..6163f7a23804091 100644
--- a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
@@ -59,7 +59,7 @@ class ConstraintBasedEQEvaluator {
 // value can be matching.
 class EnumCastOutOfRangeChecker : public Checker> {
   mutable std::unique_ptr EnumValueCastOutOfRange;
-  void reportWarning(CheckerContext &C) const;
+  void reportWarning(CheckerContext &C, const EnumDecl *E) const;
 
 public:
   void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
@@ -72,21 +72,36 @@ EnumValueVector getDeclValuesForEnum(const EnumDecl *ED) {
   EnumValueVector DeclValues(
   std::distance(ED->enumerator_begin(), ED->enumerator_end()));
   llvm::transform(ED->enumerators(), DeclValues.begin(),
- [](const EnumConstantDecl *D) { return D->getInitVal(); });
+  [](const EnumConstantDecl *D) { return D->getInitVal(); });
   return DeclValues;
 }
 } // namespace
 
-void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C) const {
+void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C,
+  const EnumDecl *E) const {
+  assert(E && "valid EnumDecl* is expected");
   if (const ExplodedNode *N = C.generateNonFatalErrorNode()) {
 if (!EnumValueCastOutOfRange)
   EnumValueCastOutOfRange.reset(
   new BugType(this, "Enum cast out of range"));
-constexpr llvm::StringLiteral Msg =
-"The value provided to the cast expression is not in the valid range"
-" of values for the enum";
-C.emitReport(std::make_unique(
-*EnumValueCastOutOfRange, Msg, N));
+
+llvm::SmallString<128> Msg{"The value provided to the cast expression is "
+   "not in the valid range of values for "};
+StringRef EnumName{E->getName()};
+if (EnumName.empty()) {
+  Msg += "the enum";
+} else {
+  Msg += '\'';
+  Msg += EnumName;
+  Msg += '\'';
+}
+
+auto BR = 
std::make_unique(*EnumValueCastOutOfRange,
+   Msg, N);
+BR->addNote("enum declared here",
+PathDiagnosticLocation::create(E, C.getSourceManager()),
+{E->getSourceRange()});
+C.emitReport(std::move(BR));
   }
 }
 
@@ -144,7 +159,7 @@ void EnumCastOutOfRangeChecker::checkPreStmt(const CastExpr 
*CE,
   // If there is no value that can possibly match any of the enum values, then
   // warn.
   if (!PossibleValueMatch)
-reportWarning(C);
+reportWarning(C, ED);
 }
 
 void ento::registerEnumCastOutOfRangeChecker(CheckerManager &mgr) {
diff --git a/clang/test/Analysis/enum-cast-out-of-range.c 
b/clang/test/Analysis/enum-cast-out-of-range.c
index 3282cba653d7125..6d3afa3fcf9885f 100644
--- a/clang/test/Analysis/enum-cast-out-of-range.c
+++ b/clang/test/Analysis/enum-cast-out-of-range.c
@@ -2,6 +2,7 @@
 // RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \
 // RUN:   -verify %s
 
+// expected-note@+1 6 {{enum declared here}}
 enum En_t {
   En_0 = -4,
   En_1,
@@ -11,17 +12,17 @@ enum En_t {
 };
 
 void unscopedUnspecifiedCStyle(void) {
-  enum En_t Below = (enum En_t)(-5);// expected-warning {{not in the valid 
range}}
+  enum En_t Below = (enum En_t)(-5);// expected-warning {{not in the valid 
range of values for 'En_t'}}
   enum En_t NegVal1 = (enum En_t)(-4);  // OK.
   enum En_t NegVal2 = (enum En_t)(-3);  // OK.
-  enum En_t InRange1 = (enum En_t)(-2); // expected-warning {{not in the valid 
range}}
-  enum En_t InRange2 = (enum En_t)(-1); // expected-warning {{not in the valid 
range}}
-  enum En_t InRange3 = (enum En_t)(0);  // expected-warning {{not in the valid 
range}}
+  enum En_t InRange1 = (enum En_t)(-2); // expected-warning {{not in the valid 
range of values for 'En_t'}}
+  enum En_t InRange2 = (enum En_t)(-1); // expected-warning {{not in the valid 
range of values for 'En_t'}}
+  enum En_t InRange3 = (enum En_t)(0);  // expected-warning {{not in the valid 
range of values for 'En_t'}}
   enum En_t PosVal1 = (enum En_t)(

[clang-tools-extra] [include-cleaner] don't consider the associated header unused (PR #67228)

2023-10-04 Thread kadir çetinkaya via cfe-commits

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


[clang-tools-extra] [include-cleaner] don't consider the associated header unused (PR #67228)

2023-10-04 Thread kadir çetinkaya via cfe-commits


@@ -379,6 +379,54 @@ TEST_F(PragmaIncludeTest, IWYUKeep) {
   EXPECT_TRUE(PI.shouldKeep(FM.getFile("std/set").get()));
 }
 
+TEST_F(PragmaIncludeTest, AssociatedHeader) {
+  createEmptyFiles({"foo/main.h", "bar/main.h", "bar/other.h", "std/vector"});
+  auto IsKeep = [&](llvm::StringRef Name, TestAST &AST) {
+return PI.shouldKeep(AST.fileManager().getFile(Name).get());
+  };
+
+  Inputs.FileName = "main.cc";
+  Inputs.ExtraArgs.push_back("-isystemstd");
+  {
+Inputs.Code = R"cpp(
+  #include "foo/main.h"
+  #include "bar/main.h"
+)cpp";
+auto AST = build();
+EXPECT_TRUE(IsKeep("foo/main.h", AST));
+EXPECT_FALSE(IsKeep("bar/main.h", AST)) << "not first include";
+  }
+
+  {
+Inputs.Code = R"cpp(
+  #include "bar/other.h"
+  #include "bar/main.h"
+)cpp";
+auto AST = build();
+EXPECT_FALSE(IsKeep("bar/other.h", AST));
+EXPECT_FALSE(IsKeep("bar/main.h", AST)) << "not first include";
+  }
+
+  {
+Inputs.Code = R"cpp(
+  #include "foo/main.h"
+  #include "bar/other.h" // IWYU pragma: associated

kadircet wrote:

i think it's worth asserting that multiple associated pragmas are also honored

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


[clang-tools-extra] [include-cleaner] don't consider the associated header unused (PR #67228)

2023-10-04 Thread kadir çetinkaya via cfe-commits


@@ -379,6 +379,54 @@ TEST_F(PragmaIncludeTest, IWYUKeep) {
   EXPECT_TRUE(PI.shouldKeep(FM.getFile("std/set").get()));
 }
 
+TEST_F(PragmaIncludeTest, AssociatedHeader) {
+  createEmptyFiles({"foo/main.h", "bar/main.h", "bar/other.h", "std/vector"});
+  auto IsKeep = [&](llvm::StringRef Name, TestAST &AST) {
+return PI.shouldKeep(AST.fileManager().getFile(Name).get());
+  };
+
+  Inputs.FileName = "main.cc";
+  Inputs.ExtraArgs.push_back("-isystemstd");
+  {
+Inputs.Code = R"cpp(
+  #include "foo/main.h"
+  #include "bar/main.h"
+)cpp";
+auto AST = build();
+EXPECT_TRUE(IsKeep("foo/main.h", AST));
+EXPECT_FALSE(IsKeep("bar/main.h", AST)) << "not first include";
+  }
+
+  {
+Inputs.Code = R"cpp(
+  #include "bar/other.h"
+  #include "bar/main.h"
+)cpp";
+auto AST = build();
+EXPECT_FALSE(IsKeep("bar/other.h", AST));
+EXPECT_FALSE(IsKeep("bar/main.h", AST)) << "not first include";
+  }
+
+  {
+Inputs.Code = R"cpp(
+  #include "foo/main.h"
+  #include "bar/other.h" // IWYU pragma: associated
+)cpp";
+auto AST = build();
+EXPECT_TRUE(IsKeep("foo/main.h", AST));
+EXPECT_TRUE(IsKeep("bar/other.h", AST));
+  }
+
+  Inputs.FileName = "vector.cc";
+  {
+Inputs.Code = R"cpp(
+  #include 
+)cpp";
+auto AST = build();
+EXPECT_FALSE(IsKeep("std/vector", AST)) << "stdlib is never associated";

kadircet wrote:

i think assertion message is a little misleading, we'd still associate it if it 
were to have an associated pragma, right?

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


[clang-tools-extra] [include-cleaner] don't consider the associated header unused (PR #67228)

2023-10-04 Thread kadir çetinkaya via cfe-commits


@@ -276,6 +280,27 @@ class PragmaIncludes::RecordPragma : public PPCallbacks, 
public CommentHandler {
   KeepStack.pop_back(); // Pop immediately for single-line keep pragma.
   }
 
+  // Consider marking H as the "associated header" of the main file.
+  //
+  // Our heuristic:
+  // - it must be the first #include in the main file
+  // - it must have the same name stem as the main file (foo.h and foo.cpp)
+  // (IWYU pragma: associated is also supported, just not by this function).
+  //
+  // We consider the associated header as if it had a keep pragma.
+  // (Unlike IWYU, we don't treat #includes inside the associated header as if
+  // they were written in the main file.)
+  void checkForDeducedAssociated(std::optional H) {
+namespace path = llvm::sys::path;
+if (!InMainFile || SeenAssociatedCandidate)
+  return;
+SeenAssociatedCandidate = true;

kadircet wrote:

i think this is still worth a comment, `Make sure we don't consider anything 
but the first include of the main file` ?

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


[clang-tools-extra] [include-cleaner] don't consider the associated header unused (PR #67228)

2023-10-04 Thread kadir çetinkaya via cfe-commits

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

thanks!

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


[clang] [HIP] Support compressing device binary (PR #67162)

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

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

I think in the long term we need to move away from the bundler, which would 
suggest we probably want something similar in the "new driver". But overall the 
changes here are pretty self contained and the concept is straightforward.

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


[clang] [analyzer][NFC] Remove outdated FIXME comment (PR #68211)

2023-10-04 Thread via cfe-commits

https://github.com/DonatNagyE created 
https://github.com/llvm/llvm-project/pull/68211

This trivial commit removes a 13-year-old FIXME comment from MallocChecker.cpp 
because it was fixed at least 10 years ago when `getConjuredHeapSymbolVal()` 
was added.

>From 70a4adb3ef1444130ddaf9b04d9d7fb88708b4b9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Wed, 4 Oct 2023 14:02:04 +0200
Subject: [PATCH] [analyzer][NFC] Remove outdated FIXME comment

This trivial commit removes a 13-year-old FIXME comment from
MallocChecker.cpp because it was fixed at least 10 years ago when
`getConjuredHeapSymbolVal()` was added.
---
 clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp | 11 ---
 1 file changed, 4 insertions(+), 7 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 18c7f3e4f6e6b92..d3a4020280616b0 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1961,13 +1961,10 @@ ProgramStateRef MallocChecker::FreeMemAux(
   // Parameters, locals, statics, globals, and memory returned by
   // __builtin_alloca() shouldn't be freed.
   if (!isa(MS)) {
-// FIXME: at the time this code was written, malloc() regions were
-// represented by conjured symbols, which are all in UnknownSpaceRegion.
-// This means that there isn't actually anything from HeapSpaceRegion
-// that should be freed, even though we allow it here.
-// Of course, free() can work on memory allocated outside the current
-// function, so UnknownSpaceRegion is always a possibility.
-// False negatives are better than false positives.
+// Regions returned by malloc() are represented by SymbolicRegion objects
+// within HeapSpaceRegion. Of course, free() can work on memory allocated
+// outside the current function, so UnknownSpaceRegion is also a
+// possibility here.
 
 if (isa(R))
   HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());

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


[clang] [analyzer][NFC] Remove outdated FIXME comment (PR #68211)

2023-10-04 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

This trivial commit removes a 13-year-old FIXME comment from MallocChecker.cpp 
because it was fixed at least 10 years ago when `getConjuredHeapSymbolVal()` 
was added.

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (+4-7) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 18c7f3e4f6e6b92..d3a4020280616b0 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1961,13 +1961,10 @@ ProgramStateRef MallocChecker::FreeMemAux(
   // Parameters, locals, statics, globals, and memory returned by
   // __builtin_alloca() shouldn't be freed.
   if (!isa(MS)) {
-// FIXME: at the time this code was written, malloc() regions were
-// represented by conjured symbols, which are all in UnknownSpaceRegion.
-// This means that there isn't actually anything from HeapSpaceRegion
-// that should be freed, even though we allow it here.
-// Of course, free() can work on memory allocated outside the current
-// function, so UnknownSpaceRegion is always a possibility.
-// False negatives are better than false positives.
+// Regions returned by malloc() are represented by SymbolicRegion objects
+// within HeapSpaceRegion. Of course, free() can work on memory allocated
+// outside the current function, so UnknownSpaceRegion is also a
+// possibility here.
 
 if (isa(R))
   HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());

``




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


[clang-tools-extra] [clang-cl] Fix value of __FUNCTION__ in MSVC mode. (PR #67592)

2023-10-04 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/67592

>From 55b67a58ef8b9856e5f0a8f535b8617f59711dec Mon Sep 17 00:00:00 2001
From: Ammarguellat 
Date: Wed, 27 Sep 2023 11:59:04 -0700
Subject: [PATCH 01/11] Fix value of __FUNCTION__ and __func__ in MSVC mode.

---
 clang/lib/AST/Expr.cpp|  9 ++-
 clang/lib/AST/TypePrinter.cpp | 21 +-
 clang/test/Analysis/eval-predefined-exprs.cpp |  4 +-
 .../CodeGenCXX/mangle-nttp-anon-union.cpp |  2 +-
 clang/test/CodeGenCXX/predefined-expr.cpp | 18 -
 clang/test/SemaCXX/source_location.cpp| 72 +++
 6 files changed, 99 insertions(+), 27 deletions(-)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index af82ca0784af413..49f3495c090f191 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -773,8 +773,8 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, const 
Decl *CurrentDecl) {
   }
   if (const FunctionDecl *FD = dyn_cast(CurrentDecl)) {
 const auto &LO = Context.getLangOpts();
-if (((IK == Func || IK == Function) && !LO.MicrosoftExt) ||
-(IK == LFunction && LO.MicrosoftExt))
+if (((IK == Function || IK == Func) && !LO.MicrosoftExt) ||
+((IK == LFunction || IK == Func) && LO.MicrosoftExt))
   return FD->getNameAsString();
 
 SmallString<256> Name;
@@ -804,7 +804,10 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, 
const Decl *CurrentDecl) {
 PrintingPolicy Policy(LO);
 PrettyCallbacks PrettyCB(LO);
 Policy.Callbacks = &PrettyCB;
-Policy.UseClassForTemplateArgument = LO.MicrosoftExt;
+if (IK == Function && LO.MicrosoftExt) {
+  Policy.UseClassForTemplateArgument = LO.MicrosoftExt;
+  Policy.MSVCFormatting = LO.MicrosoftExt;
+}
 std::string Proto;
 llvm::raw_string_ostream POut(Proto);
 
diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index 3771a29f26b173f..8a7cf85cdf126b6 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2195,6 +2195,7 @@ printTo(raw_ostream &OS, ArrayRef Args, const 
PrintingPolicy &Policy,
 llvm::SmallVector OrigArgs;
 for (const TA &A : Args)
   OrigArgs.push_back(getArgument(A));
+
 while (!Args.empty() && getArgument(Args.back()).getIsDefaulted())
   Args = Args.drop_back();
   }
@@ -2218,10 +2219,24 @@ printTo(raw_ostream &OS, ArrayRef Args, const 
PrintingPolicy &Policy,
 } else {
   if (!FirstArg)
 OS << Comma;
-  if (Policy.UseClassForTemplateArgument &&
-  Argument.getKind() == TemplateArgument::Type)
-OS << "class ";
 
+  if (Policy.MSVCFormatting && Policy.UseClassForTemplateArgument &&
+  Argument.getKind() == TemplateArgument::Type &&
+  !Argument.getAsType()->isBuiltinType()) {
+const Type *Ty = Argument.getAsType().getTypePtr();
+const char *kw;
+if (Ty->isStructureType())
+  kw = "struct ";
+else if (Ty->isClassType())
+  kw = "class ";
+else if (Ty->isUnionType())
+  kw = "union ";
+else if (Ty->isEnumeralType())
+  kw = "enum ";
+else
+  llvm_unreachable("argument type not expected");
+OS << kw;
+  }
   // Tries to print the argument with location info if exists.
   printArgument(Arg, Policy, ArgOS,
 TemplateParameterList::shouldIncludeTypeForArgument(
diff --git a/clang/test/Analysis/eval-predefined-exprs.cpp 
b/clang/test/Analysis/eval-predefined-exprs.cpp
index 7be441eb5bad943..a6bac5ee9d486d2 100644
--- a/clang/test/Analysis/eval-predefined-exprs.cpp
+++ b/clang/test/Analysis/eval-predefined-exprs.cpp
@@ -56,7 +56,7 @@ struct A {
 clang_analyzer_dump(__FUNCTION__);
 clang_analyzer_dump(__PRETTY_FUNCTION__);
 #ifdef ANALYZER_MS
-// expected-warning@-4 {{&Element{"A::A",0 S64b,char}}}
+// expected-warning@-4 {{&Element{"A",0 S64b,char}}}
 // expected-warning@-4 {{&Element{"A::A",0 S64b,char}}}
 #else
 // expected-warning@-7 {{&Element{"A",0 S64b,char}}}
@@ -80,7 +80,7 @@ struct A {
 clang_analyzer_dump(__FUNCTION__);
 clang_analyzer_dump(__PRETTY_FUNCTION__);
 #ifdef ANALYZER_MS
-// expected-warning@-4 {{&Element{"A::~A",0 S64b,char}}}
+// expected-warning@-4 {{&Element{"~A",0 S64b,char}}}
 // expected-warning@-4 {{&Element{"A::~A",0 S64b,char}}}
 #else
 // expected-warning@-7 {{&Element{"~A",0 S64b,char}}}
diff --git a/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp 
b/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
index 78fa7c378c88d50..1982a3eeb941291 100644
--- a/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
+++ b/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -std=c++20 -emit-llvm %s -o - -triple=x86_64-linux-gnu | 
FileCheck %s
-// RUN: %clang_cc1 -std=c++20 -emit-llvm %s -o - -triple=x86_64-linux-gnu | 
llvm-cxxfilt -n | FileCheck %s --check-

[clang] [clang-cl] Fix value of __FUNCTION__ in MSVC mode. (PR #67592)

2023-10-04 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/67592

>From 55b67a58ef8b9856e5f0a8f535b8617f59711dec Mon Sep 17 00:00:00 2001
From: Ammarguellat 
Date: Wed, 27 Sep 2023 11:59:04 -0700
Subject: [PATCH 01/11] Fix value of __FUNCTION__ and __func__ in MSVC mode.

---
 clang/lib/AST/Expr.cpp|  9 ++-
 clang/lib/AST/TypePrinter.cpp | 21 +-
 clang/test/Analysis/eval-predefined-exprs.cpp |  4 +-
 .../CodeGenCXX/mangle-nttp-anon-union.cpp |  2 +-
 clang/test/CodeGenCXX/predefined-expr.cpp | 18 -
 clang/test/SemaCXX/source_location.cpp| 72 +++
 6 files changed, 99 insertions(+), 27 deletions(-)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index af82ca0784af413..49f3495c090f191 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -773,8 +773,8 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, const 
Decl *CurrentDecl) {
   }
   if (const FunctionDecl *FD = dyn_cast(CurrentDecl)) {
 const auto &LO = Context.getLangOpts();
-if (((IK == Func || IK == Function) && !LO.MicrosoftExt) ||
-(IK == LFunction && LO.MicrosoftExt))
+if (((IK == Function || IK == Func) && !LO.MicrosoftExt) ||
+((IK == LFunction || IK == Func) && LO.MicrosoftExt))
   return FD->getNameAsString();
 
 SmallString<256> Name;
@@ -804,7 +804,10 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, 
const Decl *CurrentDecl) {
 PrintingPolicy Policy(LO);
 PrettyCallbacks PrettyCB(LO);
 Policy.Callbacks = &PrettyCB;
-Policy.UseClassForTemplateArgument = LO.MicrosoftExt;
+if (IK == Function && LO.MicrosoftExt) {
+  Policy.UseClassForTemplateArgument = LO.MicrosoftExt;
+  Policy.MSVCFormatting = LO.MicrosoftExt;
+}
 std::string Proto;
 llvm::raw_string_ostream POut(Proto);
 
diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index 3771a29f26b173f..8a7cf85cdf126b6 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2195,6 +2195,7 @@ printTo(raw_ostream &OS, ArrayRef Args, const 
PrintingPolicy &Policy,
 llvm::SmallVector OrigArgs;
 for (const TA &A : Args)
   OrigArgs.push_back(getArgument(A));
+
 while (!Args.empty() && getArgument(Args.back()).getIsDefaulted())
   Args = Args.drop_back();
   }
@@ -2218,10 +2219,24 @@ printTo(raw_ostream &OS, ArrayRef Args, const 
PrintingPolicy &Policy,
 } else {
   if (!FirstArg)
 OS << Comma;
-  if (Policy.UseClassForTemplateArgument &&
-  Argument.getKind() == TemplateArgument::Type)
-OS << "class ";
 
+  if (Policy.MSVCFormatting && Policy.UseClassForTemplateArgument &&
+  Argument.getKind() == TemplateArgument::Type &&
+  !Argument.getAsType()->isBuiltinType()) {
+const Type *Ty = Argument.getAsType().getTypePtr();
+const char *kw;
+if (Ty->isStructureType())
+  kw = "struct ";
+else if (Ty->isClassType())
+  kw = "class ";
+else if (Ty->isUnionType())
+  kw = "union ";
+else if (Ty->isEnumeralType())
+  kw = "enum ";
+else
+  llvm_unreachable("argument type not expected");
+OS << kw;
+  }
   // Tries to print the argument with location info if exists.
   printArgument(Arg, Policy, ArgOS,
 TemplateParameterList::shouldIncludeTypeForArgument(
diff --git a/clang/test/Analysis/eval-predefined-exprs.cpp 
b/clang/test/Analysis/eval-predefined-exprs.cpp
index 7be441eb5bad943..a6bac5ee9d486d2 100644
--- a/clang/test/Analysis/eval-predefined-exprs.cpp
+++ b/clang/test/Analysis/eval-predefined-exprs.cpp
@@ -56,7 +56,7 @@ struct A {
 clang_analyzer_dump(__FUNCTION__);
 clang_analyzer_dump(__PRETTY_FUNCTION__);
 #ifdef ANALYZER_MS
-// expected-warning@-4 {{&Element{"A::A",0 S64b,char}}}
+// expected-warning@-4 {{&Element{"A",0 S64b,char}}}
 // expected-warning@-4 {{&Element{"A::A",0 S64b,char}}}
 #else
 // expected-warning@-7 {{&Element{"A",0 S64b,char}}}
@@ -80,7 +80,7 @@ struct A {
 clang_analyzer_dump(__FUNCTION__);
 clang_analyzer_dump(__PRETTY_FUNCTION__);
 #ifdef ANALYZER_MS
-// expected-warning@-4 {{&Element{"A::~A",0 S64b,char}}}
+// expected-warning@-4 {{&Element{"~A",0 S64b,char}}}
 // expected-warning@-4 {{&Element{"A::~A",0 S64b,char}}}
 #else
 // expected-warning@-7 {{&Element{"~A",0 S64b,char}}}
diff --git a/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp 
b/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
index 78fa7c378c88d50..1982a3eeb941291 100644
--- a/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
+++ b/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -std=c++20 -emit-llvm %s -o - -triple=x86_64-linux-gnu | 
FileCheck %s
-// RUN: %clang_cc1 -std=c++20 -emit-llvm %s -o - -triple=x86_64-linux-gnu | 
llvm-cxxfilt -n | FileCheck %s --check-

[clang] [clang-cl] Fix value of __FUNCTION__ in MSVC mode. (PR #67592)

2023-10-04 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman commented:

I'd appreciate some unit tests showing that we print the elaboration in other 
circumstances. e.g.,
```
struct S { int x; };
namespace NS {
class C {};
}

S foo(S s1, NS::C c1) {
  S s12{12};
  using namespace NS;
  C c;
}
```
ensuring that we pretty print that to:
```
struct S { int x; };
namespace NS {
class C {};
}

struct S foo(struct S s1, class NS::C c1) {
  struct S s12{12};
  using namespace NS;
  class NS::C c;
}
```
(Could probably use more test coverage for other situations where the type name 
can appear, like within `sizeof`, etc)

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


[clang-tools-extra] [clang-cl] Fix value of __FUNCTION__ in MSVC mode. (PR #67592)

2023-10-04 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman commented:

I'd appreciate some unit tests showing that we print the elaboration in other 
circumstances. e.g.,
```
struct S { int x; };
namespace NS {
class C {};
}

S foo(S s1, NS::C c1) {
  S s12{12};
  using namespace NS;
  C c;
}
```
ensuring that we pretty print that to:
```
struct S { int x; };
namespace NS {
class C {};
}

struct S foo(struct S s1, class NS::C c1) {
  struct S s12{12};
  using namespace NS;
  class NS::C c;
}
```
(Could probably use more test coverage for other situations where the type name 
can appear, like within `sizeof`, etc)

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


[clang] [Clang] Fix constant evaluating a captured variable in a lambda (PR #68090)

2023-10-04 Thread via cfe-commits

cor3ntin wrote:

> Probably needs a release note.

Nah, this fixes a bug with deducing this I introduced on Monday :)

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


[clang] Fixes and closes #53952. Setting the ASTHasCompilerErrors member variable correctly based on the PP diagnostics. (PR #68127)

2023-10-04 Thread Aaron Ballman via cfe-commits


@@ -4628,6 +4628,12 @@ ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, 
StringRef OutputFile,
   WritingAST = true;
 
   ASTHasCompilerErrors = hasErrors;
+  bool trueHasErrors = 
SemaRef.PP.getDiagnostics().hasUncompilableErrorOccurred();

AaronBallman wrote:

I would rather fix this by disallowing the user from passing `hasErrors` as an 
argument at all. The only callers of this API are all passing the same thing: 
`PP.getDiagnostics().hasUncompilableErrorOccured()`, so let's remove the 
parameter and use this directly. This makes the interface more simple and it 
fixes the crash; WDYT?

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


[PATCH] D148381: [Clang] Implement the 'counted_by' attribute

2023-10-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

In D148381#4652825 , @void wrote:

> Yes, I mean to do it as a direct follow-up. 😊

Okay, let's go that route then. This gets a fairly significant review off Phab 
with incremental progress, so LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148381

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


[clang] [LinkerWrapper] Fix resolution of weak symbols during LTO (PR #68215)

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

https://github.com/jhuber6 created 
https://github.com/llvm/llvm-project/pull/68215

Summary:
Weak symbols are supposed to have the semantics that they can be
overriden by a strong (i.e. global) definition. This wasn't being
respected by the LTO pass because we simply used the first definition
that was available. This patch fixes that logic by doing a first pass
over the symbols to check for strong resolutions that could override a
weak one.

A lot of fake linker logic is ending up in the linker wrapper. If there
were an option to handle this in `lld` it would be a lot cleaner, but
unfortunately supporting NVPTX is a big restriction as their binaries
require the `nvlink` tool.


>From 0fec18f2f745b798fe48ce08c1441c3439d009a6 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Wed, 4 Oct 2023 07:34:01 -0500
Subject: [PATCH] [LinkerWrapper] Fix resolution of weak symbols during LTO

Summary:
Weak symbols are supposed to have the semantics that they can be
overriden by a strong (i.e. global) definition. This wasn't being
respected by the LTO pass because we simply used the first definition
that was available. This patch fixes that logic by doing a first pass
over the symbols to check for strong resolutions that could override a
weak one.

A lot of fake linker logic is ending up in the linker wrapper. If there
were an option to handle this in `lld` it would be a lot cleaner, but
unfortunately supporting NVPTX is a big restriction as their binaries
require the `nvlink` tool.
---
 .../ClangLinkerWrapper.cpp| 14 
 openmp/libomptarget/test/offloading/weak.c| 32 +++
 2 files changed, 46 insertions(+)
 create mode 100644 openmp/libomptarget/test/offloading/weak.c

diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 632e37e3cac8fec..f95b0f8cb317c75 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,6 +595,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
 
   SmallVector BitcodeInputFiles;
+  DenseSet StrongResolutions;
   DenseSet UsedInRegularObj;
   DenseSet UsedInSharedLib;
   BumpPtrAllocator Alloc;
@@ -608,6 +609,18 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
 file_magic Type = identify_magic(Buffer.getBuffer());
 switch (Type) {
 case file_magic::bitcode: {
+  Expected IRSymtabOrErr = readIRSymtab(Buffer);
+  if (!IRSymtabOrErr)
+return IRSymtabOrErr.takeError();
+
+  // Check for any strong resolutions we need to preserve.
+  for (unsigned I = 0; I != IRSymtabOrErr->Mods.size(); ++I) {
+for (const auto &Sym : IRSymtabOrErr->TheReader.module_symbols(I)) {
+  if (!Sym.isFormatSpecific() && Sym.isGlobal() && !Sym.isWeak() &&
+  !Sym.isUndefined())
+StrongResolutions.insert(Saver.save(Sym.Name));
+}
+  }
   BitcodeInputFiles.emplace_back(std::move(File));
   continue;
 }
@@ -696,6 +709,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   // it is undefined or another definition has already been used.
   Res.Prevailing =
   !Sym.isUndefined() &&
+  !(Sym.isWeak() && StrongResolutions.contains(Sym.getName())) &&
   PrevailingSymbols.insert(Saver.save(Sym.getName())).second;
 
   // We need LTO to preseve the following global symbols:
diff --git a/openmp/libomptarget/test/offloading/weak.c 
b/openmp/libomptarget/test/offloading/weak.c
new file mode 100644
index 000..b4f264cee7f2d70
--- /dev/null
+++ b/openmp/libomptarget/test/offloading/weak.c
@@ -0,0 +1,32 @@
+// RUN: %libomptarget-compile-generic -DA -c -o %t-a.o
+// RUN: %libomptarget-compile-generic -DB -c -o %t-b.o
+// RUN: %libomptarget-compile-generic %t-a.o %t-b.o && 
%libomptarget-run-generic | %fcheck-generic
+
+#if defined(A)
+__attribute__((weak)) int x = 999;
+#pragma omp declare target to(x)
+#elif defined(B)
+int x = 42;
+#pragma omp declare target to(x)
+__attribute__((weak)) int y = 42;
+#pragma omp declare target to(y)
+#else
+
+#include 
+
+extern int x;
+#pragma omp declare target to(x)
+extern int y;
+#pragma omp declare target to(y)
+
+int main() {
+  x = 0;
+
+#pragma omp target update from(x)
+#pragma omp target update from(y)
+
+  // CHECK: PASS
+  if (x == 42 && y == 42)
+printf("PASS\n");
+}
+#endif

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


[clang] [LinkerWrapper] Fix resolution of weak symbols during LTO (PR #68215)

2023-10-04 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

Summary:
Weak symbols are supposed to have the semantics that they can be
overriden by a strong (i.e. global) definition. This wasn't being
respected by the LTO pass because we simply used the first definition
that was available. This patch fixes that logic by doing a first pass
over the symbols to check for strong resolutions that could override a
weak one.

A lot of fake linker logic is ending up in the linker wrapper. If there
were an option to handle this in `lld` it would be a lot cleaner, but
unfortunately supporting NVPTX is a big restriction as their binaries
require the `nvlink` tool.


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


2 Files Affected:

- (modified) clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp (+14) 
- (added) openmp/libomptarget/test/offloading/weak.c (+32) 


``diff
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 632e37e3cac8fec..f95b0f8cb317c75 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,6 +595,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
 
   SmallVector BitcodeInputFiles;
+  DenseSet StrongResolutions;
   DenseSet UsedInRegularObj;
   DenseSet UsedInSharedLib;
   BumpPtrAllocator Alloc;
@@ -608,6 +609,18 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
 file_magic Type = identify_magic(Buffer.getBuffer());
 switch (Type) {
 case file_magic::bitcode: {
+  Expected IRSymtabOrErr = readIRSymtab(Buffer);
+  if (!IRSymtabOrErr)
+return IRSymtabOrErr.takeError();
+
+  // Check for any strong resolutions we need to preserve.
+  for (unsigned I = 0; I != IRSymtabOrErr->Mods.size(); ++I) {
+for (const auto &Sym : IRSymtabOrErr->TheReader.module_symbols(I)) {
+  if (!Sym.isFormatSpecific() && Sym.isGlobal() && !Sym.isWeak() &&
+  !Sym.isUndefined())
+StrongResolutions.insert(Saver.save(Sym.Name));
+}
+  }
   BitcodeInputFiles.emplace_back(std::move(File));
   continue;
 }
@@ -696,6 +709,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   // it is undefined or another definition has already been used.
   Res.Prevailing =
   !Sym.isUndefined() &&
+  !(Sym.isWeak() && StrongResolutions.contains(Sym.getName())) &&
   PrevailingSymbols.insert(Saver.save(Sym.getName())).second;
 
   // We need LTO to preseve the following global symbols:
diff --git a/openmp/libomptarget/test/offloading/weak.c 
b/openmp/libomptarget/test/offloading/weak.c
new file mode 100644
index 000..b4f264cee7f2d70
--- /dev/null
+++ b/openmp/libomptarget/test/offloading/weak.c
@@ -0,0 +1,32 @@
+// RUN: %libomptarget-compile-generic -DA -c -o %t-a.o
+// RUN: %libomptarget-compile-generic -DB -c -o %t-b.o
+// RUN: %libomptarget-compile-generic %t-a.o %t-b.o && 
%libomptarget-run-generic | %fcheck-generic
+
+#if defined(A)
+__attribute__((weak)) int x = 999;
+#pragma omp declare target to(x)
+#elif defined(B)
+int x = 42;
+#pragma omp declare target to(x)
+__attribute__((weak)) int y = 42;
+#pragma omp declare target to(y)
+#else
+
+#include 
+
+extern int x;
+#pragma omp declare target to(x)
+extern int y;
+#pragma omp declare target to(y)
+
+int main() {
+  x = 0;
+
+#pragma omp target update from(x)
+#pragma omp target update from(y)
+
+  // CHECK: PASS
+  if (x == 42 && y == 42)
+printf("PASS\n");
+}
+#endif

``




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


[clang] [clang-repl] Disable InterpreterExceptionTest on RISC-V (PR #68216)

2023-10-04 Thread Alex Bradbury via cfe-commits

https://github.com/asb created https://github.com/llvm/llvm-project/pull/68216

This test fails as .eh_frame handling is not yet implemented for RISC-V in 
JITLink. #66067 is proposed to address this.

Skip the test until the issue is resolved. It seems that D159167 enabled this 
test for more than just ppc64. As the test always failed, it just wasn't run 
until now, I think skipping is the correct interim approach (as is already done 
for Arm, Darwin, and others).

>From 6436cffbe1d4767155724b1c28acd8b47bb6be88 Mon Sep 17 00:00:00 2001
From: Alex Bradbury 
Date: Wed, 4 Oct 2023 13:51:20 +0100
Subject: [PATCH] [clang-repl] Disable InterpreterExceptionTest on RISC-V

This test fails as .eh_frame handling is not yet implemented for RISC-V
in JITLink. #66067 is proposed to address this.

Skip the test until the issue is resolved. It seems that D159167
enabled this test for more than just ppc64.
---
 .../Interpreter/ExceptionTests/InterpreterExceptionTest.cpp  | 5 +
 1 file changed, 5 insertions(+)

diff --git 
a/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp 
b/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
index 2f1c4efb381f00b..7b47d93446192ba 100644
--- a/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
+++ b/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
@@ -122,6 +122,11 @@ extern "C" int throw_exception() {
   Triple.getArch() == llvm::Triple::aarch64_32))
 GTEST_SKIP();
 
+  // FIXME: RISC-V fails as .eh_frame handling is not yet implemented in
+  // JITLink for RISC-V. See PR #66067.
+  if (Triple.isRISCV())
+GTEST_SKIP();
+
   llvm::cantFail(Interp->ParseAndExecute(ExceptionCode));
   testing::internal::CaptureStdout();
   auto ThrowException =

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


[clang] [clang-repl] Disable InterpreterExceptionTest on RISC-V (PR #68216)

2023-10-04 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

This test fails as .eh_frame handling is not yet implemented for RISC-V in 
JITLink. #66067 is proposed to address this.

Skip the test until the issue is resolved. It seems that D159167 enabled this 
test for more than just ppc64. As the test always failed, it just wasn't run 
until now, I think skipping is the correct interim approach (as is already done 
for Arm, Darwin, and others).

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


1 Files Affected:

- (modified) 
clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp (+5) 


``diff
diff --git 
a/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp 
b/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
index 2f1c4efb381f00b..7b47d93446192ba 100644
--- a/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
+++ b/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
@@ -122,6 +122,11 @@ extern "C" int throw_exception() {
   Triple.getArch() == llvm::Triple::aarch64_32))
 GTEST_SKIP();
 
+  // FIXME: RISC-V fails as .eh_frame handling is not yet implemented in
+  // JITLink for RISC-V. See PR #66067.
+  if (Triple.isRISCV())
+GTEST_SKIP();
+
   llvm::cantFail(Interp->ParseAndExecute(ExceptionCode));
   testing::internal::CaptureStdout();
   auto ThrowException =

``




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


[clang] [LinkerWrapper] Fix resolution of weak symbols during LTO (PR #68215)

2023-10-04 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 ceec9a7874af2eea8b00b5616fad388ccfa2b4f3 
0fec18f2f745b798fe48ce08c1441c3439d009a6 -- 
openmp/libomptarget/test/offloading/weak.c 
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
``





View the diff from clang-format here.


``diff
diff --git a/openmp/libomptarget/test/offloading/weak.c 
b/openmp/libomptarget/test/offloading/weak.c
index b4f264cee7f2..e36a6e1fded3 100644
--- a/openmp/libomptarget/test/offloading/weak.c
+++ b/openmp/libomptarget/test/offloading/weak.c
@@ -1,6 +1,7 @@
 // RUN: %libomptarget-compile-generic -DA -c -o %t-a.o
 // RUN: %libomptarget-compile-generic -DB -c -o %t-b.o
-// RUN: %libomptarget-compile-generic %t-a.o %t-b.o && 
%libomptarget-run-generic | %fcheck-generic
+// RUN: %libomptarget-compile-generic %t-a.o %t-b.o && 
%libomptarget-run-generic
+// | %fcheck-generic
 
 #if defined(A)
 __attribute__((weak)) int x = 999;

``




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


[clang] Qualify non-dependent types of a class template with its declaration (PR #67566)

2023-10-04 Thread Luca Di sera via cfe-commits

diseraluca wrote:

> > @vgvassilev If that is an acceptable interface for the LLVM interface then, 
> > yes, it would be perfect from our side, and I'm more than happy to update 
> > the PR in the next few days.
> > Just to be sure that I understood your proposal.
> > `getFullyQualified*` calls will accept a new parameter, a callable, that 
> > will be passed down the call chain up to 
> > `createNestedNameSpecifierForScopeOf(const ASTContext &, const Decl *, 
> > ...)` and will be called when the teplate case is encountered? Or are you 
> > thinking more of a callable that replaces the call to 
> > `createNestedNameSpecifierForScopeOf(const ASTContext &, const Decl *, 
> > ...)`?
> 
> I hesitate. Maybe we can pass a custom "policy" option and incorporate your 
> code in there... We reiterate if the solution does not look good?

>From our point of view any solution is acceptable. But do note that  from our 
>side it is not so much about incorporating custom code as much as removing 
>that specific behavior at this point in time.

Could you expand about the policy? Are you talking about a "printing policy" or 
a custom policy for `getFullyQualified`?

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


[PATCH] D159549: [analyzer] Fix false negative when accessing a nonnull property from a nullable object

2023-10-04 Thread tripleCC via Phabricator via cfe-commits
tripleCC added a comment.

merged in https://github.com/llvm/llvm-project/pull/67563#event-10544755217


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159549

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


[clang] Fixes and closes #53952. Setting the ASTHasCompilerErrors member variable correctly based on the PP diagnostics. (PR #68127)

2023-10-04 Thread Rajkumar Ananthu via cfe-commits


@@ -4628,6 +4628,12 @@ ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, 
StringRef OutputFile,
   WritingAST = true;
 
   ASTHasCompilerErrors = hasErrors;
+  bool trueHasErrors = 
SemaRef.PP.getDiagnostics().hasUncompilableErrorOccurred();

rajkumarananthu wrote:

Yeah @AaronBallman, that does sound better, I will remove the argument and 
update the pull request. Thanks for the review.

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


[clang] [CodeGen] Respect pointer-overflow sanitizer for void pointers (PR #67772)

2023-10-04 Thread Nikita Popov via cfe-commits

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


[clang] 39d5532 - [CodeGen] Respect pointer-overflow sanitizer for void pointers (#67772)

2023-10-04 Thread via cfe-commits

Author: Nikita Popov
Date: 2023-10-04T15:16:00+02:00
New Revision: 39d55321bd0b8ce436d6fcd8e5ba51b8bf535559

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

LOG: [CodeGen] Respect pointer-overflow sanitizer for void pointers (#67772)

Pointer arithmetic on void pointers (a GNU extension) was going through
a different code path and bypassed the pointer-overflow sanitizer.

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

Added: 


Modified: 
clang/lib/CodeGen/CGExprScalar.cpp
clang/test/CodeGen/PowerPC/ppc64-inline-asm.c
clang/test/CodeGen/address-space.c
clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index d76ce15b41ac570..93ab064bdf3915d 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -3723,10 +3723,12 @@ static Value *emitPointerArithmetic(CodeGenFunction 
&CGF,
   // Explicitly handle GNU void* and function pointer arithmetic extensions. 
The
   // GNU void* casts amount to no-ops since our void* type is i8*, but this is
   // future proof.
+  llvm::Type *elemTy;
   if (elementType->isVoidType() || elementType->isFunctionType())
-return CGF.Builder.CreateGEP(CGF.Int8Ty, pointer, index, "add.ptr");
+elemTy = CGF.Int8Ty;
+  else
+elemTy = CGF.ConvertTypeForMem(elementType);
 
-  llvm::Type *elemTy = CGF.ConvertTypeForMem(elementType);
   if (CGF.getLangOpts().isSignedOverflowDefined())
 return CGF.Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
 

diff  --git a/clang/test/CodeGen/PowerPC/ppc64-inline-asm.c 
b/clang/test/CodeGen/PowerPC/ppc64-inline-asm.c
index e3f2c2ff5507ce5..005bf5c7fa14407 100644
--- a/clang/test/CodeGen/PowerPC/ppc64-inline-asm.c
+++ b/clang/test/CodeGen/PowerPC/ppc64-inline-asm.c
@@ -47,6 +47,6 @@ void testZ(void *addr) {
 void testZwOff(void *addr, long long off) {
   asm volatile ("dcbz %y0\n" :: "Z"(*(unsigned char *)(addr + off)) : 
"memory");
 // CHECK-LABEL: void @testZwOff(ptr noundef %addr, i64 noundef %off)
-// CHECK: %[[VAL:[^ ]+]] = getelementptr i8, ptr %addr, i64 %off
+// CHECK: %[[VAL:[^ ]+]] = getelementptr inbounds i8, ptr %addr, i64 %off
 // CHECK: call void asm sideeffect "dcbz ${0:y}\0A", "*Z,~{memory}"(ptr 
elementtype(i8) %[[VAL]])
 }

diff  --git a/clang/test/CodeGen/address-space.c 
b/clang/test/CodeGen/address-space.c
index 83a434d88b8e8b0..c92fc0dd9687068 100644
--- a/clang/test/CodeGen/address-space.c
+++ b/clang/test/CodeGen/address-space.c
@@ -53,7 +53,7 @@ void test4(MyStruct __attribute__((address_space(2))) *pPtr) {
 // X86: [[ALLOCA:%.*]] = alloca ptr addrspace(1)
 // X86-NEXT: store ptr addrspace(1) %arg, ptr [[ALLOCA]]
 // X86-NEXT: load ptr addrspace(1), ptr [[ALLOCA]]
-// X86-NEXT: getelementptr i8, ptr addrspace(1)
+// X86-NEXT: getelementptr inbounds i8, ptr addrspace(1)
 // X86-NEXT: ret ptr addrspace(1)
 void __attribute__((address_space(1)))*
 void_ptr_arithmetic_test(void __attribute__((address_space(1))) *arg) {

diff  --git a/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c 
b/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
index 0e0a9b157464a64..015102940890a52 100644
--- a/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
+++ b/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
@@ -35,6 +35,7 @@
 // CHECK-SANITIZE-ANYRECOVER-C-DAG: @[[LINE_1400:.*]] = {{.*}}, i32 1400, i32 
15 } }
 // CHECK-SANITIZE-ANYRECOVER-DAG: @[[LINE_1500:.*]] = {{.*}}, i32 1500, i32 15 
} }
 // CHECK-SANITIZE-ANYRECOVER-DAG: @[[LINE_1600:.*]] = {{.*}}, i32 1600, i32 15 
} }
+// CHECK-SANITIZE-ANYRECOVER-DAG: @[[LINE_1700:.*]] = {{.*}}, i32 1700, i32 15 
} }
 
 #ifdef __cplusplus
 extern "C" {
@@ -427,6 +428,48 @@ char *allones_allones_OK(void) {
   return base + offset;
 }
 
+// C++ does not allow void* arithmetic even as a GNU extension. Replace void*
+// with char* in that case to keep test expectations the same.
+#ifdef __cplusplus
+char *void_ptr(char *base, unsigned long offset) {
+#else
+char *void_ptr(void *base, unsigned long offset) {
+#endif
+  // CHECK: define{{.*}} ptr @void_ptr(ptr noundef %[[BASE:.*]], i64 noundef 
%[[OFFSET:.*]])
+  // CHECK-NEXT:  [[ENTRY:.*]]:
+  // CHECK-NEXT:%[[BASE_ADDR:.*]] = alloca ptr, align 8
+  // CHECK-NEXT:%[[OFFSET_ADDR:.*]] = alloca i64, 
align 8
+  // CHECK-NEXT:store ptr %[[BASE]], ptr 
%[[BASE_ADDR]], align 8
+  // CHECK-NEXT:store i64 %[[OFFSET]], ptr 
%[[OFFSET_ADDR]], align 8
+  // CHECK-NEXT:%[[BASE_RELOADED:.*]] = load ptr, ptr 
%[[BASE_ADDR]], align 8
+  // CHECK-NEXT:%[[OFFSET_RELOADED:.*]] = load i64, 
ptr %[

[clang] [clang-repl] Disable InterpreterExceptionTest on RISC-V (PR #68216)

2023-10-04 Thread Job Noorman via cfe-commits

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


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


[clang] [LinkerWrapper] Fix resolution of weak symbols during LTO (PR #68215)

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

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

>From f2e29b6136d245e0712bfb87de1f4253d12dd6f5 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Wed, 4 Oct 2023 07:34:01 -0500
Subject: [PATCH] [LinkerWrapper] Fix resolution of weak symbols during LTO

Summary:
Weak symbols are supposed to have the semantics that they can be
overriden by a strong (i.e. global) definition. This wasn't being
respected by the LTO pass because we simply used the first definition
that was available. This patch fixes that logic by doing a first pass
over the symbols to check for strong resolutions that could override a
weak one.

A lot of fake linker logic is ending up in the linker wrapper. If there
were an option to handle this in `lld` it would be a lot cleaner, but
unfortunately supporting NVPTX is a big restriction as their binaries
require the `nvlink` tool.
---
 .../ClangLinkerWrapper.cpp| 14 
 openmp/libomptarget/test/offloading/weak.c| 33 +++
 2 files changed, 47 insertions(+)
 create mode 100644 openmp/libomptarget/test/offloading/weak.c

diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 632e37e3cac8fec..f95b0f8cb317c75 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,6 +595,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
 
   SmallVector BitcodeInputFiles;
+  DenseSet StrongResolutions;
   DenseSet UsedInRegularObj;
   DenseSet UsedInSharedLib;
   BumpPtrAllocator Alloc;
@@ -608,6 +609,18 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
 file_magic Type = identify_magic(Buffer.getBuffer());
 switch (Type) {
 case file_magic::bitcode: {
+  Expected IRSymtabOrErr = readIRSymtab(Buffer);
+  if (!IRSymtabOrErr)
+return IRSymtabOrErr.takeError();
+
+  // Check for any strong resolutions we need to preserve.
+  for (unsigned I = 0; I != IRSymtabOrErr->Mods.size(); ++I) {
+for (const auto &Sym : IRSymtabOrErr->TheReader.module_symbols(I)) {
+  if (!Sym.isFormatSpecific() && Sym.isGlobal() && !Sym.isWeak() &&
+  !Sym.isUndefined())
+StrongResolutions.insert(Saver.save(Sym.Name));
+}
+  }
   BitcodeInputFiles.emplace_back(std::move(File));
   continue;
 }
@@ -696,6 +709,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   // it is undefined or another definition has already been used.
   Res.Prevailing =
   !Sym.isUndefined() &&
+  !(Sym.isWeak() && StrongResolutions.contains(Sym.getName())) &&
   PrevailingSymbols.insert(Saver.save(Sym.getName())).second;
 
   // We need LTO to preseve the following global symbols:
diff --git a/openmp/libomptarget/test/offloading/weak.c 
b/openmp/libomptarget/test/offloading/weak.c
new file mode 100644
index 000..ca81db958356b2e
--- /dev/null
+++ b/openmp/libomptarget/test/offloading/weak.c
@@ -0,0 +1,33 @@
+// RUN: %libomptarget-compile-generic -DA -c -o %t-a.o
+// RUN: %libomptarget-compile-generic -DB -c -o %t-b.o
+// RUN: %libomptarget-compile-generic %t-a.o %t-b.o && \
+// RUN:   %libomptarget-run-generic | %fcheck-generic
+
+#if defined(A)
+__attribute__((weak)) int x = 999;
+#pragma omp declare target to(x)
+#elif defined(B)
+int x = 42;
+#pragma omp declare target to(x)
+__attribute__((weak)) int y = 42;
+#pragma omp declare target to(y)
+#else
+
+#include 
+
+extern int x;
+#pragma omp declare target to(x)
+extern int y;
+#pragma omp declare target to(y)
+
+int main() {
+  x = 0;
+
+#pragma omp target update from(x)
+#pragma omp target update from(y)
+
+  // CHECK: PASS
+  if (x == 42 && y == 42)
+printf("PASS\n");
+}
+#endif

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


[clang] [clang-repl] Disable InterpreterExceptionTest on RISC-V (PR #68216)

2023-10-04 Thread Vassil Vassilev via cfe-commits

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

LGTM!

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


[clang] a1e81d2 - [HIP] Support compressing device binary (#67162)

2023-10-04 Thread via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2023-10-04T09:32:56-04:00
New Revision: a1e81d2ead02e041471ec2299d7382f80c4dbba6

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

LOG: [HIP] Support compressing device binary (#67162)

Add option -f[no-]offload-compress to clang to enable/disable
compression of device binary for HIP. By default it is disabled.

Add option -compress to clang-offload-bundler to enable compression of
offload bundle. By default it is disabled.

When enabled, zstd or zlib is used for compression when available.

When disabled, it is NFC compared to previous behavior. The same offload
bundle format is used as before.

Clang-offload-bundler automatically detects whether the input file to be
unbundled is compressed and the compression method and decompress if
necessary.

Added: 
clang/test/Driver/clang-offload-bundler-zlib.c
clang/test/Driver/clang-offload-bundler-zstd.c
clang/test/Driver/hip-offload-compress-zlib.hip
clang/test/Driver/hip-offload-compress-zstd.hip

Modified: 
clang/docs/ClangOffloadBundler.rst
clang/include/clang/Driver/OffloadBundler.h
clang/include/clang/Driver/Options.td
clang/lib/Driver/OffloadBundler.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/HIPUtility.cpp
clang/tools/clang-offload-bundler/CMakeLists.txt
clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
llvm/include/llvm/BinaryFormat/Magic.h
llvm/lib/BinaryFormat/Magic.cpp
llvm/lib/Object/Binary.cpp
llvm/lib/Object/ObjectFile.cpp

Removed: 




diff  --git a/clang/docs/ClangOffloadBundler.rst 
b/clang/docs/ClangOffloadBundler.rst
index d08bf4b97781fa4..1e21d3e7264d5c3 100644
--- a/clang/docs/ClangOffloadBundler.rst
+++ b/clang/docs/ClangOffloadBundler.rst
@@ -309,3 +309,30 @@ target by comparing bundle ID's. Two bundle ID's are 
considered compatible if:
   * Their offload kind are the same
   * Their target triple are the same
   * Their GPUArch are the same
+
+Compression and Decompression
+=
+
+``clang-offload-bundler`` provides features to compress and decompress the full
+bundle, leveraging inherent redundancies within the bundle entries. Use the
+`-compress` command-line option to enable this compression capability.
+
+The compressed offload bundle begins with a header followed by the compressed 
binary data:
+
+- **Magic Number (4 bytes)**:
+This is a unique identifier to distinguish compressed offload bundles. The 
value is the string 'CCOB' (Compressed Clang Offload Bundle).
+
+- **Version Number (16-bit unsigned int)**:
+This denotes the version of the compressed offload bundle format. The 
current version is `1`.
+
+- **Compression Method (16-bit unsigned int)**:
+This field indicates the compression method used. The value corresponds to 
either `zlib` or `zstd`, represented as a 16-bit unsigned integer cast from the 
LLVM compression enumeration.
+
+- **Uncompressed Binary Size (32-bit unsigned int)**:
+This is the size (in bytes) of the binary data before it was compressed.
+
+- **Hash (64-bit unsigned int)**:
+This is a 64-bit truncated MD5 hash of the uncompressed binary data. It 
serves for verification and caching purposes.
+
+- **Compressed Data**:
+The actual compressed binary data follows the header. Its size can be 
inferred from the total size of the file minus the header size.

diff  --git a/clang/include/clang/Driver/OffloadBundler.h 
b/clang/include/clang/Driver/OffloadBundler.h
index 28473c53662de2c..17df31d31071d99 100644
--- a/clang/include/clang/Driver/OffloadBundler.h
+++ b/clang/include/clang/Driver/OffloadBundler.h
@@ -19,6 +19,7 @@
 
 #include "llvm/Support/Error.h"
 #include "llvm/TargetParser/Triple.h"
+#include 
 #include 
 #include 
 
@@ -26,11 +27,15 @@ namespace clang {
 
 class OffloadBundlerConfig {
 public:
+  OffloadBundlerConfig();
+
   bool AllowNoHost = false;
   bool AllowMissingBundles = false;
   bool CheckInputArchive = false;
   bool PrintExternalCommands = false;
   bool HipOpenmpCompatible = false;
+  bool Compress = false;
+  bool Verbose = false;
 
   unsigned BundleAlignment = 1;
   unsigned HostInputIndex = ~0u;
@@ -84,6 +89,38 @@ struct OffloadTargetInfo {
   std::string str() const;
 };
 
+// CompressedOffloadBundle represents the format for the compressed offload
+// bundles.
+//
+// The format is as follows:
+// - Magic Number (4 bytes) - A constant "CCOB".
+// - Version (2 bytes)
+// - Compression Method (2 bytes) - Uses the values from
+// llvm::compression::Format.
+// - Uncompressed Size (4 bytes).
+// - Truncated MD5 Hash (8 bytes).
+// - Compressed Data (variable length).
+
+class CompressedOffloadBundle {
+private:
+  static inline const size_t MagicSize = 4;
+  static inline const size_t Ve

[clang] [HIP] Support compressing device binary (PR #67162)

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

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


[clang] ca003ee - [clang-repl] Disable InterpreterExceptionTest on RISC-V (#68216)

2023-10-04 Thread via cfe-commits

Author: Alex Bradbury
Date: 2023-10-04T14:33:31+01:00
New Revision: ca003ee06d0eac7e8facc179181298a05e4d03ed

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

LOG: [clang-repl] Disable InterpreterExceptionTest on RISC-V (#68216)

This test fails as .eh_frame handling is not yet implemented for RISC-V
in JITLink. #66067 is proposed to address this.

Skip the test until the issue is resolved. It seems that D159167 enabled
this test for more than just ppc64. As the test always failed, it just
wasn't run until now, I think skipping is the correct interim approach
(as is already done for Arm, Darwin, and others).

Added: 


Modified: 
clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp

Removed: 




diff  --git 
a/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp 
b/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
index 2f1c4efb381f00b..7b47d93446192ba 100644
--- a/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
+++ b/clang/unittests/Interpreter/ExceptionTests/InterpreterExceptionTest.cpp
@@ -122,6 +122,11 @@ extern "C" int throw_exception() {
   Triple.getArch() == llvm::Triple::aarch64_32))
 GTEST_SKIP();
 
+  // FIXME: RISC-V fails as .eh_frame handling is not yet implemented in
+  // JITLink for RISC-V. See PR #66067.
+  if (Triple.isRISCV())
+GTEST_SKIP();
+
   llvm::cantFail(Interp->ParseAndExecute(ExceptionCode));
   testing::internal::CaptureStdout();
   auto ThrowException =



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


[clang] [clang-repl] Disable InterpreterExceptionTest on RISC-V (PR #68216)

2023-10-04 Thread Alex Bradbury via cfe-commits

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


[PATCH] D155688: [PATCH] [llvm] [InstCombine] Canonicalise ADD+GEP

2023-10-04 Thread Nikita Popov via Phabricator via cfe-commits
nikic accepted this revision.
nikic added a comment.
This revision is now accepted and ready to land.

LGTM

We should give this a try, but I think there is a fairly large chance that this 
will cause regressions somewhere and a more targeted change may be necessary 
(e.g. only do this for loop-invariants in LICM).




Comment at: llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:2334-2335
+  Value *Ptr = GEP.getPointerOperand();
+  auto *NewPtr = GetElementPtrInst::Create(GEP.getResultElementType(), Ptr,
+   Idx1, "", &GEP);
+  return GetElementPtrInst::Create(GEP.getResultElementType(), NewPtr,

IRBuilder needs to be used for all but the last instruction.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155688

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


[clang] [CUDA][HIP] Fix host/device context in concept (PR #67721)

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

yxsamliu wrote:

ping

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


[PATCH] D133361: [BPF] Attribute preserve_static_offset for structs

2023-10-04 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:3701
+  QualType PointeeType = E->getType()->getPointeeType();
+  if (PointeeType.isNull())
+return false;

eddyz87 wrote:
> erichkeane wrote:
> > We override `operator bool` to make this work.
> Sorry, just to clarify, currently such modification fails with the following 
> error:
> 
> ```
> lang=c++
> clang/lib/CodeGen/CGExpr.cpp:3710:7: error: invalid argument type 'QualType' 
> to unary expression
>   if (!PointeeType)
>   ^~~~
> 1 error generated.
> ```
> 
> And you want me to modify `QualType` as follows:
> 
> ```
> --- a/clang/include/clang/AST/Type.h
> +++ b/clang/include/clang/AST/Type.h
> @@ -796,6 +796,8 @@ public:
>  return getTypePtr();
>}
>  
> +  explicit operator bool() const { return isNull(); }
> +
>bool isCanonical() const;
>bool isCanonicalAsParam() const;
> ```
> 
> Right?
No, don't do that, you can leave it just checking isNull.  I could have sworn 
we already had that operator, but perhaps it was removed at one point.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133361

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


[clang] AddDefaultRTL (PR #68220)

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

https://github.com/jhuber6 created 
https://github.com/llvm/llvm-project/pull/68220

- [LinkerWrapper] Fix resolution of weak symbols during LTO
- [Libomptarget] Make the DeviceRTL configuration globals weak


>From f2e29b6136d245e0712bfb87de1f4253d12dd6f5 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Wed, 4 Oct 2023 07:34:01 -0500
Subject: [PATCH 1/2] [LinkerWrapper] Fix resolution of weak symbols during LTO

Summary:
Weak symbols are supposed to have the semantics that they can be
overriden by a strong (i.e. global) definition. This wasn't being
respected by the LTO pass because we simply used the first definition
that was available. This patch fixes that logic by doing a first pass
over the symbols to check for strong resolutions that could override a
weak one.

A lot of fake linker logic is ending up in the linker wrapper. If there
were an option to handle this in `lld` it would be a lot cleaner, but
unfortunately supporting NVPTX is a big restriction as their binaries
require the `nvlink` tool.
---
 .../ClangLinkerWrapper.cpp| 14 
 openmp/libomptarget/test/offloading/weak.c| 33 +++
 2 files changed, 47 insertions(+)
 create mode 100644 openmp/libomptarget/test/offloading/weak.c

diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 632e37e3cac8fec..f95b0f8cb317c75 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,6 +595,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
 
   SmallVector BitcodeInputFiles;
+  DenseSet StrongResolutions;
   DenseSet UsedInRegularObj;
   DenseSet UsedInSharedLib;
   BumpPtrAllocator Alloc;
@@ -608,6 +609,18 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
 file_magic Type = identify_magic(Buffer.getBuffer());
 switch (Type) {
 case file_magic::bitcode: {
+  Expected IRSymtabOrErr = readIRSymtab(Buffer);
+  if (!IRSymtabOrErr)
+return IRSymtabOrErr.takeError();
+
+  // Check for any strong resolutions we need to preserve.
+  for (unsigned I = 0; I != IRSymtabOrErr->Mods.size(); ++I) {
+for (const auto &Sym : IRSymtabOrErr->TheReader.module_symbols(I)) {
+  if (!Sym.isFormatSpecific() && Sym.isGlobal() && !Sym.isWeak() &&
+  !Sym.isUndefined())
+StrongResolutions.insert(Saver.save(Sym.Name));
+}
+  }
   BitcodeInputFiles.emplace_back(std::move(File));
   continue;
 }
@@ -696,6 +709,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   // it is undefined or another definition has already been used.
   Res.Prevailing =
   !Sym.isUndefined() &&
+  !(Sym.isWeak() && StrongResolutions.contains(Sym.getName())) &&
   PrevailingSymbols.insert(Saver.save(Sym.getName())).second;
 
   // We need LTO to preseve the following global symbols:
diff --git a/openmp/libomptarget/test/offloading/weak.c 
b/openmp/libomptarget/test/offloading/weak.c
new file mode 100644
index 000..ca81db958356b2e
--- /dev/null
+++ b/openmp/libomptarget/test/offloading/weak.c
@@ -0,0 +1,33 @@
+// RUN: %libomptarget-compile-generic -DA -c -o %t-a.o
+// RUN: %libomptarget-compile-generic -DB -c -o %t-b.o
+// RUN: %libomptarget-compile-generic %t-a.o %t-b.o && \
+// RUN:   %libomptarget-run-generic | %fcheck-generic
+
+#if defined(A)
+__attribute__((weak)) int x = 999;
+#pragma omp declare target to(x)
+#elif defined(B)
+int x = 42;
+#pragma omp declare target to(x)
+__attribute__((weak)) int y = 42;
+#pragma omp declare target to(y)
+#else
+
+#include 
+
+extern int x;
+#pragma omp declare target to(x)
+extern int y;
+#pragma omp declare target to(y)
+
+int main() {
+  x = 0;
+
+#pragma omp target update from(x)
+#pragma omp target update from(y)
+
+  // CHECK: PASS
+  if (x == 42 && y == 42)
+printf("PASS\n");
+}
+#endif

>From ed9cb56c91b3ed6e51fd9f2cb5381cd5b4101fb2 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Wed, 4 Oct 2023 08:47:43 -0500
Subject: [PATCH 2/2] [Libomptarget] Make the DeviceRTL configuration globals
 weak

Summary:
This patch applies weak linkage to the config globals by the name
`__omp_rtl...`. This is because when passing `-nogpulib` we will not
link in or create these globals. This allows the OpenMP device RTL to be
self contained without requiring the additional definitions from the
`clang` compiler. In the standard case, this should not affect the
current behavior, this is because the strong defintiion coming from the
compiler should always override the weak definition we default to here.
In the case that these are not defined by the compiler, these will
remain weak. This will impact optimizations somewhat, but the previous
behaviour was that it would not link so that is an improvement.

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

[clang] AddDefaultRTL (PR #68220)

2023-10-04 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

- [LinkerWrapper] Fix resolution of weak symbols during LTO
- [Libomptarget] Make the DeviceRTL configuration globals weak


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


4 Files Affected:

- (modified) clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp (+14) 
- (modified) openmp/libomptarget/DeviceRTL/src/Configuration.cpp (+4-4) 
- (modified) openmp/libomptarget/DeviceRTL/src/exports (+4) 
- (added) openmp/libomptarget/test/offloading/weak.c (+33) 


``diff
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 632e37e3cac8fec..f95b0f8cb317c75 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,6 +595,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
 
   SmallVector BitcodeInputFiles;
+  DenseSet StrongResolutions;
   DenseSet UsedInRegularObj;
   DenseSet UsedInSharedLib;
   BumpPtrAllocator Alloc;
@@ -608,6 +609,18 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
 file_magic Type = identify_magic(Buffer.getBuffer());
 switch (Type) {
 case file_magic::bitcode: {
+  Expected IRSymtabOrErr = readIRSymtab(Buffer);
+  if (!IRSymtabOrErr)
+return IRSymtabOrErr.takeError();
+
+  // Check for any strong resolutions we need to preserve.
+  for (unsigned I = 0; I != IRSymtabOrErr->Mods.size(); ++I) {
+for (const auto &Sym : IRSymtabOrErr->TheReader.module_symbols(I)) {
+  if (!Sym.isFormatSpecific() && Sym.isGlobal() && !Sym.isWeak() &&
+  !Sym.isUndefined())
+StrongResolutions.insert(Saver.save(Sym.Name));
+}
+  }
   BitcodeInputFiles.emplace_back(std::move(File));
   continue;
 }
@@ -696,6 +709,7 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
   // it is undefined or another definition has already been used.
   Res.Prevailing =
   !Sym.isUndefined() &&
+  !(Sym.isWeak() && StrongResolutions.contains(Sym.getName())) &&
   PrevailingSymbols.insert(Saver.save(Sym.getName())).second;
 
   // We need LTO to preseve the following global symbols:
diff --git a/openmp/libomptarget/DeviceRTL/src/Configuration.cpp 
b/openmp/libomptarget/DeviceRTL/src/Configuration.cpp
index 5deee9c53926e77..809c5f03886b048 100644
--- a/openmp/libomptarget/DeviceRTL/src/Configuration.cpp
+++ b/openmp/libomptarget/DeviceRTL/src/Configuration.cpp
@@ -20,10 +20,10 @@ using namespace ompx;
 
 #pragma omp begin declare target device_type(nohost)
 
-// defined by CGOpenMPRuntimeGPU
-extern uint32_t __omp_rtl_debug_kind;
-extern uint32_t __omp_rtl_assume_no_thread_state;
-extern uint32_t __omp_rtl_assume_no_nested_parallelism;
+// Weak definitions will be overridden by CGOpenmpRuntimeGPU if enabled.
+[[gnu::weak]] extern const uint32_t __omp_rtl_debug_kind = 0;
+[[gnu::weak]] extern const uint32_t __omp_rtl_assume_no_thread_state = 0;
+[[gnu::weak]] extern const uint32_t __omp_rtl_assume_no_nested_parallelism = 0;
 
 // This variable should be visibile to the plugin so we override the default
 // hidden visibility.
diff --git a/openmp/libomptarget/DeviceRTL/src/exports 
b/openmp/libomptarget/DeviceRTL/src/exports
index 2d13195aa7dc87c..fbcda3ce8f555ca 100644
--- a/openmp/libomptarget/DeviceRTL/src/exports
+++ b/openmp/libomptarget/DeviceRTL/src/exports
@@ -3,6 +3,10 @@ ompx_*
 *llvm_*
 __kmpc_*
 
+__omp_rtl_debug_kind
+__omp_rtl_assume_no_thread_state
+__omp_rtl_assume_no_nested_parallelism
+
 _ZN4ompx*
 
 IsSPMDMode
diff --git a/openmp/libomptarget/test/offloading/weak.c 
b/openmp/libomptarget/test/offloading/weak.c
new file mode 100644
index 000..ca81db958356b2e
--- /dev/null
+++ b/openmp/libomptarget/test/offloading/weak.c
@@ -0,0 +1,33 @@
+// RUN: %libomptarget-compile-generic -DA -c -o %t-a.o
+// RUN: %libomptarget-compile-generic -DB -c -o %t-b.o
+// RUN: %libomptarget-compile-generic %t-a.o %t-b.o && \
+// RUN:   %libomptarget-run-generic | %fcheck-generic
+
+#if defined(A)
+__attribute__((weak)) int x = 999;
+#pragma omp declare target to(x)
+#elif defined(B)
+int x = 42;
+#pragma omp declare target to(x)
+__attribute__((weak)) int y = 42;
+#pragma omp declare target to(y)
+#else
+
+#include 
+
+extern int x;
+#pragma omp declare target to(x)
+extern int y;
+#pragma omp declare target to(y)
+
+int main() {
+  x = 0;
+
+#pragma omp target update from(x)
+#pragma omp target update from(y)
+
+  // CHECK: PASS
+  if (x == 42 && y == 42)
+printf("PASS\n");
+}
+#endif

``




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


[PATCH] D133361: [BPF] Attribute preserve_static_offset for structs

2023-10-04 Thread Eduard Zingerman via Phabricator via cfe-commits
eddyz87 marked 3 inline comments as done.
eddyz87 added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:3701
+  QualType PointeeType = E->getType()->getPointeeType();
+  if (PointeeType.isNull())
+return false;

erichkeane wrote:
> eddyz87 wrote:
> > erichkeane wrote:
> > > We override `operator bool` to make this work.
> > Sorry, just to clarify, currently such modification fails with the 
> > following error:
> > 
> > ```
> > lang=c++
> > clang/lib/CodeGen/CGExpr.cpp:3710:7: error: invalid argument type 
> > 'QualType' to unary expression
> >   if (!PointeeType)
> >   ^~~~
> > 1 error generated.
> > ```
> > 
> > And you want me to modify `QualType` as follows:
> > 
> > ```
> > --- a/clang/include/clang/AST/Type.h
> > +++ b/clang/include/clang/AST/Type.h
> > @@ -796,6 +796,8 @@ public:
> >  return getTypePtr();
> >}
> >  
> > +  explicit operator bool() const { return isNull(); }
> > +
> >bool isCanonical() const;
> >bool isCanonicalAsParam() const;
> > ```
> > 
> > Right?
> No, don't do that, you can leave it just checking isNull.  I could have sworn 
> we already had that operator, but perhaps it was removed at one point.
Understood.
Thank you for the review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133361

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


[PATCH] D157331: [clang] Implement C23

2023-10-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Precommit CI is still finding some issues that boil down to:

  # .---command stderr
  # | C:\ws\src\clang\test\Modules/Inputs/System/usr/include\module.map:19:12: 
error: header 'stdckdint.h' not found
  # |19 | header "stdckdint.h"
  # |   |^
  # | 
C:\ws\src\clang\test\Modules/Inputs/System/usr/include\uses_other_constants.h:2:10:
 note: submodule of top-level module 'cstd' implicitly imported here
  # | 2 | #include 
  # |   |  ^
  # | C:\ws\src\clang\test\Modules\cstd.m:4:9: fatal error: could not build 
module 'uses_other_constants'
  # | 4 | @import uses_other_constants;
  # |   |  ~~~^~~~
  # | C:\ws\src\clang\test\Modules/Inputs/System/usr/include\module.map:19:12: 
error: header 'stdckdint.h' not found
  # |19 | header "stdckdint.h"
  # |   |^
  # | 3 errors generated.
  # `-
  # error: command failed with exit status: 1

I commented on what I think needs to change to fix the issues.




Comment at: clang/test/Modules/Inputs/System/usr/include/module.map:17-21
+  // In both directories (compiler support version wins, does not forward)
+  module stdckdint {
+header "stdckdint.h"
+  }
+

I think these changes should be removed, there is no `stdckdint.h` file in 
`test/Modules/Inputs/System/usr/include`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157331

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


[PATCH] D158413: [Lex] Introduce Preprocessor::LexTokensUntilEOF()

2023-10-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM aside from a minor naming nit. I think finding a way to unify with 
`SkipUntil` would be good follow-up work, though.




Comment at: clang/lib/Lex/Preprocessor.cpp:1000
+  while (1) {
+Token tok;
+Lex(tok);

Minor naming convention nit.


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

https://reviews.llvm.org/D158413

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


[PATCH] D158069: [clang][Interp] Fix getIndex() for composite array elements

2023-10-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/AST/Interp/Pointer.h:81-88
+  /// Equality operators are just for tests.
+  bool operator==(const Pointer &P) const {
+return Pointee == P.Pointee && Base == P.Base && Offset == P.Offset;
+  }
+
+  bool operator!=(const Pointer &P) const {
+return Pointee != P.Pointee || Base != P.Base || Offset != P.Offset;

tbaeder wrote:
> aaron.ballman wrote:
> > tbaeder wrote:
> > > aaron.ballman wrote:
> > > > Same here -- can these be private and friended?
> > > Don't you need a class to friend something? I only have the `TEST(...)` 
> > > function in the unit test, so I can't do that, right?
> > `FRIEND_TEST` does this, I believe: 
> > https://google.github.io/googletest/reference/testing.html#FRIEND_TEST
> Is this something we should be doing? There's nothing else in clang using 
> `FRIEND_TEST` and only stuff in `Testing/` includes gtest.h.
It's a tradeoff as to whether we want to expose private implementation details 
as part of a public interface just to enable unit testing, or whether we want 
to sprinkle unit testing annotations around the private implementation details 
just to enable unit testing. Personally, I prefer having cleaner public 
interfaces; otherwise we end up with people using the implementation details of 
a class and it's harder to refactor in the future. I'm not certain how others 
feel, though.


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

https://reviews.llvm.org/D158069

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


[PATCH] D158516: [clang][Interp] Only lazily visit constant globals

2023-10-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM, I suspect this may have to change for `constexpr` support in C23, but we 
can burn that bridge when we get to it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158516

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


[clang] [clang][Index] Use canonical function parameter types in USRs (PR #68222)

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

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

This is necessary to ensure that functions declared in different translation 
units whose parameter types only differ in top-level cv-qualification generate 
the same USR. 

For example:
```cpp
// A.cpp
void f(const int x); // c:@F@f#1I#

// B.cpp
void f(int x);   // c:@F@f#I#
``` 
With the proposed changes, the USR for both functions will be `c:@F@f#I#`.

>From 0dc45b8b3303acff3703565af6d98c37988c7d66 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Wed, 4 Oct 2023 10:06:28 -0400
Subject: [PATCH] [clang][Index] Use canonical function parameter types in USRs

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

diff --git a/clang/lib/Index/USRGeneration.cpp 
b/clang/lib/Index/USRGeneration.cpp
index f778a6208d5122d..fa0fd094c223f7f 100644
--- a/clang/lib/Index/USRGeneration.cpp
+++ b/clang/lib/Index/USRGeneration.cpp
@@ -265,10 +265,13 @@ void USRGenerator::VisitFunctionDecl(const FunctionDecl 
*D) {
 Out << '>';
   }
 
+  QualType CanonicalType = D->getType().getCanonicalType();
   // Mangle in type information for the arguments.
-  for (auto *PD : D->parameters()) {
-Out << '#';
-VisitType(PD->getType());
+  if (auto *FPT = CanonicalType->getAs()) {
+for (QualType PT : FPT->param_types()) {
+  Out << '#';
+  VisitType(PT);
+}
   }
   if (D->isVariadic())
 Out << '.';

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


[clang-tools-extra] Bugfix for chosing the correct deduction guide (PR #66487)

2023-10-04 Thread Botond István Hprváth via cfe-commits

HoBoIs wrote:

@erichkeane @shafik I don't have write access. Could you merge if there is 
nothing to be done?

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


[clang-tools-extra] [MLIR][NVGPU] Introduce `nvgpu.wargroup.mma.store` Op for Hopper GPUs (PR #65441)

2023-10-04 Thread via cfe-commits


@@ -53,6 +55,16 @@ static Value truncToI32(ConversionPatternRewriter &rewriter, 
Location loc,
   return rewriter.create(loc, rewriter.getI32Type(), value);
 }
 
+/// Returns warp-size as a value.
+static Value getWarpSizeValue(ImplicitLocOpBuilder &b) {

qcolombet wrote:

Second thing, the implementation of the singleton is going to break whenever we 
run the code on more than one function, since the builder will change and we'll 
still return the value of the very first one. (Which at this point could have 
been destroyed, reassigned, etc.)

Long story short, drop the singleton construct :).

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


[clang] [MLIR][NVGPU] Introduce `nvgpu.wargroup.mma.store` Op for Hopper GPUs (PR #65441)

2023-10-04 Thread via cfe-commits


@@ -727,4 +727,24 @@ def NVGPU_WarpgroupMmaOp : NVGPU_Op<"warpgroup.mma"> {
   let hasVerifier = 1;
 }
 
+def NVGPU_WarpgroupMmaStoreOp : NVGPU_Op<"warpgroup.mma.store"> {
+  let description = [{
+The `nvgpu.warpgroup.mma.store` op performs the store of fragmented result 
+in $matrixD to give memref. 

qcolombet wrote:

Maybe I missed something, but I don't see the nit fixed here: "to the given 
memref"

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


[clang-tools-extra] [MLIR][NVGPU] Introduce `nvgpu.wargroup.mma.store` Op for Hopper GPUs (PR #65441)

2023-10-04 Thread via cfe-commits

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


[clang] [MLIR][NVGPU] Introduce `nvgpu.wargroup.mma.store` Op for Hopper GPUs (PR #65441)

2023-10-04 Thread via cfe-commits


@@ -53,6 +55,16 @@ static Value truncToI32(ConversionPatternRewriter &rewriter, 
Location loc,
   return rewriter.create(loc, rewriter.getI32Type(), value);
 }
 
+/// Returns warp-size as a value.
+static Value getWarpSizeValue(ImplicitLocOpBuilder &b) {

qcolombet wrote:

Is there an interest in having a singleton here as opposed to just storing the 
result in a variable in the related place?

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


  1   2   3   4   >