[clang] [clang] Fix --entry command line option (PR #69114)

2023-10-16 Thread Tuur Martens via cfe-commits

https://github.com/JohnyTheCarrot updated 
https://github.com/llvm/llvm-project/pull/69114

>From 111d19a7e03e2c59afc8d40c8210a901378594ee Mon Sep 17 00:00:00 2001
From: Tuur Martens 
Date: Sun, 15 Oct 2023 18:08:35 +0200
Subject: [PATCH 1/2] [clang] Fix --entry command line option

---
 clang/include/clang/Driver/Options.td | 3 ++-
 clang/test/Driver/entry.c | 5 +
 2 files changed, 7 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Driver/entry.c

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 3f2058a5d4650ca..6737af0a8b68728 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5474,7 +5474,8 @@ def _dyld_prefix_EQ : Joined<["--"], "dyld-prefix=">;
 def _dyld_prefix : Separate<["--"], "dyld-prefix">, Alias<_dyld_prefix_EQ>;
 def _encoding_EQ : Joined<["--"], "encoding=">, Alias;
 def _encoding : Separate<["--"], "encoding">, Alias;
-def _entry : Flag<["--"], "entry">, Alias;
+def _entry_EQ : Joined<["--"], "entry=">, Flags<[LinkerInput]>, 
Group, Alias;
+def _entry : Separate<["--"], "entry">, Flags<[LinkerInput]>, 
Group, Alias;
 def _extdirs_EQ : Joined<["--"], "extdirs=">, Alias;
 def _extdirs : Separate<["--"], "extdirs">, Alias;
 def _extra_warnings : Flag<["--"], "extra-warnings">, Alias;
diff --git a/clang/test/Driver/entry.c b/clang/test/Driver/entry.c
new file mode 100644
index 000..773e9676332e517
--- /dev/null
+++ b/clang/test/Driver/entry.c
@@ -0,0 +1,5 @@
+// RUN: %clang -### --entry test %s 2>&1 | FileCheck %s
+// RUN: %clang -### --entry=test %s 2>&1 | FileCheck %s
+// RUN: %clang -### -etest %s 2>&1 | FileCheck %s
+
+// CHECK: "-e" "test"

>From 3bd714bd17d12d24d014362056374e0838a271c0 Mon Sep 17 00:00:00 2001
From: Tuur Martens 
Date: Mon, 16 Oct 2023 08:58:47 +0200
Subject: [PATCH 2/2] make requested changes

---
 clang/include/clang/Driver/Options.td | 2 +-
 clang/test/Driver/entry.c | 5 -
 clang/test/Driver/linker-opts.c   | 7 +++
 3 files changed, 8 insertions(+), 6 deletions(-)
 delete mode 100644 clang/test/Driver/entry.c

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 6737af0a8b68728..084907a2a1696d2 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5474,7 +5474,7 @@ def _dyld_prefix_EQ : Joined<["--"], "dyld-prefix=">;
 def _dyld_prefix : Separate<["--"], "dyld-prefix">, Alias<_dyld_prefix_EQ>;
 def _encoding_EQ : Joined<["--"], "encoding=">, Alias;
 def _encoding : Separate<["--"], "encoding">, Alias;
-def _entry_EQ : Joined<["--"], "entry=">, Flags<[LinkerInput]>, 
Group, Alias;
+def : Joined<["--"], "entry=">, Flags<[LinkerInput]>, Group, 
Alias;
 def _entry : Separate<["--"], "entry">, Flags<[LinkerInput]>, 
Group, Alias;
 def _extdirs_EQ : Joined<["--"], "extdirs=">, Alias;
 def _extdirs : Separate<["--"], "extdirs">, Alias;
diff --git a/clang/test/Driver/entry.c b/clang/test/Driver/entry.c
deleted file mode 100644
index 773e9676332e517..000
--- a/clang/test/Driver/entry.c
+++ /dev/null
@@ -1,5 +0,0 @@
-// RUN: %clang -### --entry test %s 2>&1 | FileCheck %s
-// RUN: %clang -### --entry=test %s 2>&1 | FileCheck %s
-// RUN: %clang -### -etest %s 2>&1 | FileCheck %s
-
-// CHECK: "-e" "test"
diff --git a/clang/test/Driver/linker-opts.c b/clang/test/Driver/linker-opts.c
index 181aeadb8dc97db..72b33916ec79cbe 100644
--- a/clang/test/Driver/linker-opts.c
+++ b/clang/test/Driver/linker-opts.c
@@ -20,3 +20,10 @@
 // Make sure that we do warn in other cases.
 // RUN: %clang %s -lfoo -c -o %t/tmp2.o -### 2>&1 | FileCheck %s 
--check-prefix=UNUSED
 // UNUSED: warning:{{.*}}unused
+
+// Make sure -e and its aliases --entry and --entry= are properly passed on.
+// RUN: %clang -### -target x86_64-unknown-linux-gnu --entry test %s 2>&1 | 
FileCheck --check-prefix=ENTRY %s
+// RUN: %clang -### -target x86_64-unknown-linux-gnu --entry=test %s 2>&1 | 
FileCheck --check-prefix=ENTRY %s
+// RUN: %clang -### -target x86_64-unknown-linux-gnu -etest %s 2>&1 | 
FileCheck --check-prefix=ENTRY %s
+
+// ENTRY: "-e" "test"

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


[clang] [clang] Additional FP classification functions (PR #69041)

2023-10-16 Thread Serge Pavlov via cfe-commits

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

>From 1374e323198d7188e688845eb951df4148a1dfd8 Mon Sep 17 00:00:00 2001
From: Serge Pavlov 
Date: Wed, 11 Oct 2023 14:27:26 +0700
Subject: [PATCH 1/5] [clang] Additional FP classification functions

C language standard defined library functions `iszero`, `issignaling`
and `issubnormal`, which did not have counterparts among clang
builtin functions. This change adds new functions:

__builtin_iszero
__builtin_issubnormal
__builtin_issignaling

They provide builtin implementation for the missing standard functions.
---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/include/clang/Basic/Builtins.def |  3 +++
 clang/lib/CodeGen/CGBuiltin.cpp| 24 
 clang/test/CodeGen/builtins.c  | 15 +++
 4 files changed, 44 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..2453804cd7735be 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -621,6 +621,8 @@ Floating Point Support in Clang
 - Add ``__builtin_exp10``, ``__builtin_exp10f``,
   ``__builtin_exp10f16``, ``__builtin_exp10l`` and
   ``__builtin_exp10f128`` builtins.
+- Add ``__builtin_iszero``, ``__builtin_issignaling`` and
+  ``__builtin_issubnormal``.
 
 AST Matchers
 
diff --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index 6ea8484606cfd5d..ebcb5b45e5bdc23 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -494,6 +494,9 @@ BUILTIN(__builtin_isinf,  "i.", "FnctE")
 BUILTIN(__builtin_isinf_sign, "i.", "FnctE")
 BUILTIN(__builtin_isnan,  "i.", "FnctE")
 BUILTIN(__builtin_isnormal,   "i.", "FnctE")
+BUILTIN(__builtin_issubnormal,"i.", "FnctE")
+BUILTIN(__builtin_iszero, "i.", "FnctE")
+BUILTIN(__builtin_issignaling,"i.", "FnctE")
 BUILTIN(__builtin_isfpclass,  "i.", "nctE")
 
 // FP signbit builtins
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 8cb7943df9a7822..5d3946a84b6c34a 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3287,6 +3287,14 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
ConvertType(E->getType(;
   }
 
+  case Builtin::BI__builtin_issignaling: {
+CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
+Value *V = EmitScalarExpr(E->getArg(0));
+return RValue::get(
+Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcSNan),
+   ConvertType(E->getType(;
+  }
+
   case Builtin::BI__builtin_isinf: {
 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
 Value *V = EmitScalarExpr(E->getArg(0));
@@ -3321,6 +3329,22 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
ConvertType(E->getType(;
   }
 
+  case Builtin::BI__builtin_issubnormal: {
+CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
+Value *V = EmitScalarExpr(E->getArg(0));
+return RValue::get(
+Builder.CreateZExt(Builder.createIsFPClass(V, 
FPClassTest::fcSubnormal),
+   ConvertType(E->getType(;
+  }
+
+  case Builtin::BI__builtin_iszero: {
+CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
+Value *V = EmitScalarExpr(E->getArg(0));
+return RValue::get(
+Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcZero),
+   ConvertType(E->getType(;
+  }
+
   case Builtin::BI__builtin_isfpclass: {
 Expr::EvalResult Result;
 if (!E->getArg(1)->EvaluateAsInt(Result, CGM.getContext()))
diff --git a/clang/test/CodeGen/builtins.c b/clang/test/CodeGen/builtins.c
index 1b1b2cd6413a344..ce1182b724dcc21 100644
--- a/clang/test/CodeGen/builtins.c
+++ b/clang/test/CodeGen/builtins.c
@@ -64,6 +64,9 @@ int main(void) {
   P(isinf_sign, (1.));
   P(isnan, (1.));
   P(isfinite, (1.));
+  P(iszero, (1.));
+  P(issubnormal, (1.));
+  P(issignaling, (1.));
   P(isfpclass, (1., 1));
 
   // Bitwise & Numeric Functions
@@ -270,6 +273,18 @@ void test_float_builtins(__fp16 *H, float F, double D, 
long double LD) {
   // CHECK: [[TMP:%.*]] = call i1 @llvm.is.fpclass.f32(float {{.*}}, i32 264)
   // CHECK: zext i1 [[TMP]] to i32
 
+  res = __builtin_issubnormal(F);
+  // CHECK: [[TMP:%.*]] = call i1 @llvm.is.fpclass.f32(float {{.*}}, i32 144)
+  // CHECK: zext i1 [[TMP]] to i32
+
+  res = __builtin_iszero(F);
+  // CHECK: [[TMP:%.*]] = call i1 @llvm.is.fpclass.f32(float {{.*}}, i32 96)
+  // CHECK: zext i1 [[TMP]] to i32
+
+  res = __builtin_issignaling(F);
+  // CHECK: [[TMP:%.*]] = call i1 @llvm.is.fpclass.f32(float {{.*}}, i32 1)
+  // CHECK: zext i1 [[TMP]] to i32
+
   res = __builtin_flt_rounds();
   // CHECK: call i32 @llvm.get.rounding(
 }

>From ec574ef66538047d58bc0b1bf93c7231adc198

[clang-tools-extra] [clangd] Correctly identify the next token after the completion point (PR #69153)

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

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

The code was previously using Lexer::findNextToken() which does not handle 
being passed the completion point as input.

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

>From e1ae800faed2fe3f612686edf6fe61f5b16e090d Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Mon, 16 Oct 2023 03:51:48 -0400
Subject: [PATCH] [clangd] Correctly identify the next token after the
 completion point

The code was previously using Lexer::findNextToken() which does not
handle being passed the completion point as input.

Fixes https://github.com/clangd/clangd/issues/1785
---
 clang-tools-extra/clangd/CodeComplete.cpp | 42 ++-
 .../clangd/unittests/CodeCompleteTests.cpp| 23 ++
 2 files changed, 64 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 70c4d7e65b76db3..fba93d8e50fc973 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -1491,6 +1491,46 @@ FuzzyFindRequest 
speculativeFuzzyFindRequestForCompletion(
   return CachedReq;
 }
 
+// This function is similar to Lexer::findNextToken(), but assumes
+// that the input SourceLocation is the completion point (which is
+// a case findNextToken() does not handle).
+std::optional
+findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
+  const SourceManager &SM,
+  const LangOptions &LangOpts) {
+  SourceLocation Loc = CompletionPoint;
+  if (Loc.isMacroID()) {
+if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
+  return std::nullopt;
+  }
+
+  // Advance to the next SourceLocation after the completion point.
+  // Lexer::findNextToken() would call MeasureTokenLength() here,
+  // which does not handle the completion point (and can't, because
+  // the Lexer instance it constructs internally doesn't have a
+  // Preprocessor and so doesn't know about the completion point).
+  Loc = Loc.getLocWithOffset(1);
+
+  // Break down the source location.
+  std::pair LocInfo = SM.getDecomposedLoc(Loc);
+
+  // Try to load the file buffer.
+  bool InvalidTemp = false;
+  StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
+  if (InvalidTemp)
+return std::nullopt;
+
+  const char *TokenBegin = File.data() + LocInfo.second;
+
+  // Lex from the start of the given location.
+  Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, 
File.begin(),
+ TokenBegin, File.end());
+  // Find the token.
+  Token Tok;
+  TheLexer.LexFromRawLexer(Tok);
+  return Tok;
+}
+
 // Runs Sema-based (AST) and Index-based completion, returns merged results.
 //
 // There are a few tricky considerations:
@@ -1589,7 +1629,7 @@ class CodeCompleteFlow {
   auto Style = getFormatStyleForFile(SemaCCInput.FileName,
  SemaCCInput.ParseInput.Contents,
  *SemaCCInput.ParseInput.TFS);
-  const auto NextToken = Lexer::findNextToken(
+  const auto NextToken = findTokenAfterCompletionPoint(
   Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
   Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
   if (NextToken)
diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 671c0b7da97c6cf..883aa85f5438acb 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -3854,6 +3854,29 @@ TEST(CompletionTest, FunctionArgsExist) {
  kind(CompletionItemKind::Function;
 }
 
+TEST(CompletionTest, FunctionArgsExist_Issue1785) {
+  // This is a scenario where the implementation of our check for
+  // "is there a function argument list right after the cursor"
+  // gave a bogus result.
+  clangd::CodeCompleteOptions Opts;
+  Opts.EnableSnippets = true;
+  // The whitespace in this testcase is important!
+  std::string Code = R"cpp(
+void waldo(int);
+
+int main()
+{
+  wal^
+
+
+  // ()
+}
+  )cpp";
+  EXPECT_THAT(
+  completions(Code, {}, Opts).Completions,
+  Contains(AllOf(labeled("waldo(int)"), snippetSuffix("(${1:int})";
+}
+
 TEST(CompletionTest, NoCrashDueToMacroOrdering) {
   EXPECT_THAT(completions(R"cpp(
 #define ECHO(X) X

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


[clang-tools-extra] [clangd] Correctly identify the next token after the completion point (PR #69153)

2023-10-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Nathan Ridge (HighCommander4)


Changes

The code was previously using Lexer::findNextToken() which does not handle 
being passed the completion point as input.

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

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


2 Files Affected:

- (modified) clang-tools-extra/clangd/CodeComplete.cpp (+41-1) 
- (modified) clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp (+23) 


``diff
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 70c4d7e65b76db3..fba93d8e50fc973 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -1491,6 +1491,46 @@ FuzzyFindRequest 
speculativeFuzzyFindRequestForCompletion(
   return CachedReq;
 }
 
+// This function is similar to Lexer::findNextToken(), but assumes
+// that the input SourceLocation is the completion point (which is
+// a case findNextToken() does not handle).
+std::optional
+findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
+  const SourceManager &SM,
+  const LangOptions &LangOpts) {
+  SourceLocation Loc = CompletionPoint;
+  if (Loc.isMacroID()) {
+if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
+  return std::nullopt;
+  }
+
+  // Advance to the next SourceLocation after the completion point.
+  // Lexer::findNextToken() would call MeasureTokenLength() here,
+  // which does not handle the completion point (and can't, because
+  // the Lexer instance it constructs internally doesn't have a
+  // Preprocessor and so doesn't know about the completion point).
+  Loc = Loc.getLocWithOffset(1);
+
+  // Break down the source location.
+  std::pair LocInfo = SM.getDecomposedLoc(Loc);
+
+  // Try to load the file buffer.
+  bool InvalidTemp = false;
+  StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
+  if (InvalidTemp)
+return std::nullopt;
+
+  const char *TokenBegin = File.data() + LocInfo.second;
+
+  // Lex from the start of the given location.
+  Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, 
File.begin(),
+ TokenBegin, File.end());
+  // Find the token.
+  Token Tok;
+  TheLexer.LexFromRawLexer(Tok);
+  return Tok;
+}
+
 // Runs Sema-based (AST) and Index-based completion, returns merged results.
 //
 // There are a few tricky considerations:
@@ -1589,7 +1629,7 @@ class CodeCompleteFlow {
   auto Style = getFormatStyleForFile(SemaCCInput.FileName,
  SemaCCInput.ParseInput.Contents,
  *SemaCCInput.ParseInput.TFS);
-  const auto NextToken = Lexer::findNextToken(
+  const auto NextToken = findTokenAfterCompletionPoint(
   Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
   Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
   if (NextToken)
diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 671c0b7da97c6cf..883aa85f5438acb 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -3854,6 +3854,29 @@ TEST(CompletionTest, FunctionArgsExist) {
  kind(CompletionItemKind::Function;
 }
 
+TEST(CompletionTest, FunctionArgsExist_Issue1785) {
+  // This is a scenario where the implementation of our check for
+  // "is there a function argument list right after the cursor"
+  // gave a bogus result.
+  clangd::CodeCompleteOptions Opts;
+  Opts.EnableSnippets = true;
+  // The whitespace in this testcase is important!
+  std::string Code = R"cpp(
+void waldo(int);
+
+int main()
+{
+  wal^
+
+
+  // ()
+}
+  )cpp";
+  EXPECT_THAT(
+  completions(Code, {}, Opts).Completions,
+  Contains(AllOf(labeled("waldo(int)"), snippetSuffix("(${1:int})";
+}
+
 TEST(CompletionTest, NoCrashDueToMacroOrdering) {
   EXPECT_THAT(completions(R"cpp(
 #define ECHO(X) X

``




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


[clang] 5857fec - [clang][ASTImporter] Fix of possible crash "Did not find base!". (#67680)

2023-10-16 Thread via cfe-commits

Author: Balázs Kéri
Date: 2023-10-16T10:31:01+02:00
New Revision: 5857fec27fe8ee5a48a2ee48a4d79a9e39b0332b

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

LOG: [clang][ASTImporter] Fix of possible crash "Did not find base!". (#67680)

A problem with AST import could lead to multiple instances of the same
template class specialization, with different template arguments. The
difference was caused by pointers to different declarations of the same
function.
Problem is fixed by using the canonical declaration at import.

Co-authored-by: Balázs Kéri 

Added: 


Modified: 
clang/lib/AST/ASTImporter.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 3adbabdb7fb878a..628a2b2bbca3986 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -811,7 +811,8 @@ ASTNodeImporter::import(const TemplateArgument &From) {
 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
 if (!ToTypeOrErr)
   return ToTypeOrErr.takeError();
-return TemplateArgument(*ToOrErr, *ToTypeOrErr, From.getIsDefaulted());
+return 
TemplateArgument(dyn_cast((*ToOrErr)->getCanonicalDecl()),
+*ToTypeOrErr, From.getIsDefaulted());
   }
 
   case TemplateArgument::NullPtr: {

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 1dc314eafc4eff4..f1f09a0be2b8d0c 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -9175,6 +9175,64 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   EXPECT_TRUE(ToXType->typeMatchesDecl());
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTemplateArgumentWithPointerToDifferentInstantiation) {
+  const char *CodeTo =
+  R"(
+  template
+  A f1() {
+   return A();
+  }
+  template
+  class X {};
+
+  X> x;
+  )";
+  const char *CodeFrom =
+  R"(
+  template
+  A f1();
+  template
+  class X {};
+
+  X> x;
+  )";
+  Decl *ToTU = getToTuDecl(CodeTo, Lang_CXX11);
+  Decl *FromTU = getTuDecl(CodeFrom, Lang_CXX11);
+
+  auto *ToF1 = FirstDeclMatcher().match(
+  ToTU, functionDecl(hasName("f1"), isInstantiated()));
+  auto *FromF1 = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("f1"), isInstantiated()));
+  EXPECT_TRUE(ToF1->isThisDeclarationADefinition());
+  EXPECT_FALSE(FromF1->isThisDeclarationADefinition());
+
+  auto *ToX = FirstDeclMatcher().match(
+  ToTU, classTemplateSpecializationDecl(hasName("X")));
+  auto *FromX = FirstDeclMatcher().match(
+  FromTU, classTemplateSpecializationDecl(hasName("X")));
+
+  Decl *ToTArgF = ToX->getTemplateArgs().get(1).getAsDecl();
+  Decl *FromTArgF = FromX->getTemplateArgs().get(1).getAsDecl();
+  EXPECT_EQ(ToTArgF, ToF1);
+  EXPECT_EQ(FromTArgF, FromF1);
+
+  auto *ToXImported = Import(FromX, Lang_CXX11);
+  // The template argument 1 of 'X' in the "From" code points to a function
+  // that has no definition. The import must ensure that this template argument
+  // is imported in a way that it will point to the existing 'f1' function, not
+  // to the 'f1' that is imported. In this way when specialization of 'X' is
+  // imported it will have the same template arguments as the existing one.
+  EXPECT_EQ(ToXImported, ToX);
+  // FIXME: This matcher causes a crash "Tried to match orphan node".
+  // The code is removed until the problem is fixed.
+  // auto *ToF1Imported =
+  //LastDeclMatcher().match(ToTU,
+  //functionDecl(hasName("f1"),isInstantiated()));
+  // EXPECT_NE(ToF1Imported, ToF1);
+  // EXPECT_EQ(ToF1Imported->getPreviousDecl(), ToF1);
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 



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


[clang] [clang][ASTImporter] Fix of possible crash "Did not find base!". (PR #67680)

2023-10-16 Thread Balázs Kéri via cfe-commits

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


[clang] [flang][driver] Mark -fcommon and -mtune as visible in Flang (PR #68657)

2023-10-16 Thread Fangcao Wang via cfe-commits


@@ -10,6 +10,9 @@
 ! Make sure that `-L' is "visible" to Flang's driver
 ! RUN: %flang -L/ -### %s
 
+! Make sure that `-fcommon' is "visible" to Flang's driver

LittleMeepo wrote:

So should I put the test for this option somewhere else, or should I still put 
it in this file?

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


[clang] [clang]Avoid to check created local variable multiple time when evaluating (PR #69106)

2023-10-16 Thread via cfe-commits

mzyKi wrote:

I test example in branch llvmorg-16.0.6,ExprConstant.cpp also has this 
assertion but it will not result in crash.So I think should not  remove this 
assertion and try to find the reason ```!Result.isAbsent()```  Maybe somewhere 
change its valueKind.

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


[clang] [flang][driver] Mark -fcommon and -mtune as visible in Flang (PR #68657)

2023-10-16 Thread Andrzej Warzyński via cfe-commits


@@ -10,6 +10,9 @@
 ! Make sure that `-L' is "visible" to Flang's driver
 ! RUN: %flang -L/ -### %s
 
+! Make sure that `-fcommon' is "visible" to Flang's driver

banach-space wrote:

Separate file, please.

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


[clang] [clang][Interp] Check pointer inc/dec ops for null (PR #69168)

2023-10-16 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/69168

None

>From b20da36444adfbdbddd6d0dddf06535815ffe0c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sun, 3 Sep 2023 07:03:04 +0200
Subject: [PATCH] [clang][Interp] Check pointer inc/dec ops for null

---
 clang/lib/AST/Interp/Interp.h|  7 +--
 clang/test/AST/Interp/arrays.cpp | 20 
 2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index e3e6a4cec63b194..3d226a40f9cf608 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1488,11 +1488,14 @@ static inline bool IncDecPtrHelper(InterpState &S, 
CodePtr OpPC,
const Pointer &Ptr) {
   using OneT = Integral<8, false>;
 
+  const Pointer &P = Ptr.deref();
+  if (!CheckNull(S, OpPC, P, CSK_ArrayIndex))
+return false;
+
   // Get the current value on the stack.
-  S.Stk.push(Ptr.deref());
+  S.Stk.push(P);
 
   // Now the current Ptr again and a constant 1.
-  Pointer P = Ptr.deref();
   OneT One = OneT::from(1);
   if (!OffsetHelper(S, OpPC, One, P))
 return false;
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..18c4ae4354f54a0 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -333,6 +333,26 @@ namespace IncDec {
// expected-note {{in call to}} \
// ref-error {{not an integral constant 
expression}} \
   // ref-note {{in call to}}
+
+  constexpr int nullptr1(bool Pre) {
+int *a = nullptr;
+if (Pre)
+  ++a; // ref-note {{arithmetic on null pointer}} \
+   // expected-note {{arithmetic on null pointer}}
+else
+  a++; // ref-note {{arithmetic on null pointer}} \
+   // expected-note {{arithmetic on null pointer}}
+return 1;
+  }
+  static_assert(nullptr1(true) == 1, ""); // ref-error {{not an integral 
constant expression}} \
+  // ref-note {{in call to}} \
+  // expected-error {{not an integral 
constant expression}} \
+  // expected-note {{in call to}}
+
+  static_assert(nullptr1(false) == 1, ""); // ref-error {{not an integral 
constant expression}} \
+   // ref-note {{in call to}} \
+   // expected-error {{not an integral 
constant expression}} \
+   // expected-note {{in call to}}
 };
 
 namespace ZeroInit {

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


[clang] [Driver] Hook up Haiku PowerPC support (PR #69134)

2023-10-16 Thread Qiu Chaofan via cfe-commits

ecnelises wrote:

Does backend have any recognition of Haiku-PPC target?

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


[clang] [Driver] Link Flang runtime on Solaris (PR #65644)

2023-10-16 Thread Andrzej Warzyński via cfe-commits

banach-space wrote:

> > Agreed: AFAICS the only open issue is whether the Solaris test should use 
> > the `GNU` label as I have done, introduce an new common one (like `UNIX`; 
> > there's nothing GNU-specific in that test), or really introduce a separate 
> > copy of the check under a different label per target (my least preference 
> > because it makes the test hard to read for no gain).
> 
> I think having additional tests makes sense if there is some variation on 
> what is being checked but not when it's just copying and pasting the same 
> thing with a different label.

I feel that we are bike-shedding here a bit. Please prioritise correctness - 
using `GNU` as a label for Solaris would not be correct. The following would be:
* duplicating tests with a different label (e.g. `SOLARIS`) would be correct,
* renaming the current label from `GNU` to e.g. `UNIX` would be correct.

Unless I am missing something?

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


[clang] c68bc17 - [analyzer] Fix note for member reference (#68691)

2023-10-16 Thread via cfe-commits

Author: Gábor Spaits
Date: 2023-10-16T10:55:31+02:00
New Revision: c68bc1726c1c14a297c75cae597dab00e9e7e905

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

LOG: [analyzer] Fix note for member reference (#68691)

In the following code:
```cpp
int main() {
struct Wrapper {char c; int &ref; };
Wrapper w = {.c = 'a', .ref = *(int *)0 };
w.ref = 1;
}
```

The clang static analyzer will produce the following warnings and notes:
```
test.cpp:12:11: warning: Dereference of null pointer [core.NullDereference]
   12 | w.ref = 1;
  | ~~^~~
test.cpp:11:5: note: 'w' initialized here
   11 | Wrapper w = {.c = 'a', .ref = *(int *)0 };
  | ^
test.cpp:12:11: note: Dereference of null pointer
   12 | w.ref = 1;
  | ~~^~~
1 warning generated.
```
In the line where `w` is created, the note gives information about the
initialization of `w` instead of `w.ref`. Let's compare it to a similar
case where a null pointer dereference happens to a pointer member:

```cpp
int main() {
 struct Wrapper {char c; int *ptr; };
 Wrapper w = {.c = 'a', .ptr = nullptr };
 *w.ptr = 1;
}
```

Here the following error and notes are seen:
```
test.cpp:18:12: warning: Dereference of null pointer (loaded from field 'ptr') 
[core.NullDereference]
   18 | *w.ptr = 1;
  |~~~ ^
test.cpp:17:5: note: 'w.ptr' initialized to a null pointer value
   17 | Wrapper w = {.c = 'a', .ptr = nullptr };
  | ^
test.cpp:18:12: note: Dereference of null pointer (loaded from field 'ptr')
   18 | *w.ptr = 1;
  |~~~ ^
1 warning generated.
```
Here the note that shows the initialization the initialization of
`w.ptr` in shown instead of `w`.

This commit is here to achieve similar notes for member reference as the
notes of member pointers, so the report looks like the following:

```
test.cpp:12:11: warning: Dereference of null pointer [core.NullDereference]
   12 | w.ref = 1;
  | ~~^~~
test.cpp:11:5: note: 'w.ref' initialized to a null pointer value
   11 | Wrapper w = {.c = 'a', .ref = *(int *)0 };
  | ^
test.cpp:12:11: note: Dereference of null pointer
   12 | w.ref = 1;
  | ~~^~~
1 warning generated.
```
Here the initialization of `w.ref` is shown instead of `w`.

-

Authored-by: Gábor Spaits 
Reviewed-by: Donát Nagy 

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 42d03f67510cf88..2d184d529513253 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -132,6 +132,16 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the AST for dereferencing a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // Without this special case the notes would refer to the whole object
+  // (struct, class or union variable) instead of just the relevant member.
+
+  if (ME->getMemberDecl()->getType()->isReferenceType())
+break;
   E = ME->getBase();
 } else if (const auto *IvarRef = dyn_cast(E)) {
   E = IvarRef->getBase();
@@ -157,26 +167,42 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles null references from FieldRegions, for example:
+//   struct Wrapper { int &ref; };
+//   Wrapper w = { *(int *)0 };
+//   w.ref = 1;
+const Expr *Base = ME->getBase();
+const VarDecl *VD = getVarDeclForExpression(Base);
+if (!VD)
+  return nullptr;
+
+const auto *FD = dyn_cast(ME->getMemberDecl());
+if (!FD)
+  return nullptr;
+
+

[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-16 Thread via cfe-commits
=?utf-8?q?Gábor?= Spaits,=?utf-8?q?Gábor?= Spaits,
=?utf-8?q?Gábor?= Spaits
Message-ID:
In-Reply-To: 


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


[clang] [Clang] Support target attr specifying CPU (PR #68678)

2023-10-16 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/68678

>From 78f22a8a57f5b67660763b8c7731b9d3cddede72 Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Tue, 10 Oct 2023 17:20:00 +0800
Subject: [PATCH 1/3] [Clang] Support target attr specifying CPU

Currently targets except AArch64 cannot recognize function attribute
specifying target CPU. Make it equivalent to arch directive.
---
 clang/lib/Basic/TargetInfo.cpp | 7 ---
 clang/test/Sema/attr-target.c  | 4 
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp
index 6cd5d618a4acaa5..474f4173eb5257d 100644
--- a/clang/lib/Basic/TargetInfo.cpp
+++ b/clang/lib/Basic/TargetInfo.cpp
@@ -560,11 +560,12 @@ ParsedTargetAttr TargetInfo::parseTargetAttr(StringRef 
Features) const {
 }
 
 // While we're here iterating check for a different target cpu.
-if (Feature.startswith("arch=")) {
+if (Feature.startswith("arch=") || Feature.startswith("cpu=")) {
+  auto [Key, CPU] = Feature.split("=");
   if (!Ret.CPU.empty())
-Ret.Duplicate = "arch=";
+Ret.Duplicate = StringRef(Key.data(), Key.size() + 1);
   else
-Ret.CPU = Feature.split("=").second.trim();
+Ret.CPU = CPU.trim();
 } else if (Feature.startswith("tune=")) {
   if (!Ret.Tune.empty())
 Ret.Duplicate = "tune=";
diff --git a/clang/test/Sema/attr-target.c b/clang/test/Sema/attr-target.c
index 3416a3d0a6ba134..631e40b947ed69b 100644
--- a/clang/test/Sema/attr-target.c
+++ b/clang/test/Sema/attr-target.c
@@ -17,10 +17,14 @@ int __attribute__((target("avx,sse4.2,arch=hiss"))) 
meow(void) {  return 4; }
 int __attribute__((target("woof"))) bark(void) {  return 4; }
 // no warning, same as saying 'nothing'.
 int __attribute__((target("arch="))) turtle(void) { return 4; }
+// no warning, same as saying 'nothing'.
+int __attribute__((target("cpu="))) equus(void) { return 4; }
 //expected-warning@+1 {{unknown CPU 'hiss' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=hiss,arch=woof"))) pine_tree(void) { return 4; 
}
 //expected-warning@+1 {{duplicate 'arch=' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=ivybridge,arch=haswell"))) oak_tree(void) { 
return 4; }
+//expected-warning@+1 {{duplicate 'cpu=' in the 'target' attribute string; 
'target' attribute ignored}}
+int __attribute__((target("arch=ivybridge,cpu=haswell"))) cypress_tree(void) { 
return 4; }
 //expected-warning@+1 {{unsupported 'branch-protection' in the 'target' 
attribute string; 'target' attribute ignored}}
 int __attribute__((target("branch-protection=none"))) birch_tree(void) { 
return 5; }
 //expected-warning@+1 {{unknown tune CPU 'hiss' in the 'target' attribute 
string; 'target' attribute ignored}}

>From 69db1b10f119026c857781ee559b4e3e1b0de8af Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Wed, 11 Oct 2023 11:17:36 +0800
Subject: [PATCH 2/3] Rebase for PowerPC tests

---
 clang/test/Sema/attr-target.c | 4 
 1 file changed, 4 insertions(+)

diff --git a/clang/test/Sema/attr-target.c b/clang/test/Sema/attr-target.c
index 72ca9887b21b016..3939f4d02744e4a 100644
--- a/clang/test/Sema/attr-target.c
+++ b/clang/test/Sema/attr-target.c
@@ -80,10 +80,14 @@ int __attribute__((target("fpmath=387"))) walrus(void) { 
return 4; }
 int __attribute__((target("float128,arch=hiss"))) meow(void) {  return 4; }
 // no warning, same as saying 'nothing'.
 int __attribute__((target("arch="))) turtle(void) { return 4; }
+// no warning, same as saying 'nothing'.
+int __attribute__((target("cpu="))) equus(void) { return 4; }
 //expected-warning@+1 {{unknown CPU 'hiss' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=hiss,arch=woof"))) pine_tree(void) { return 4; 
}
 //expected-warning@+1 {{duplicate 'arch=' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=pwr9,arch=pwr10"))) oak_tree(void) { return 4; 
}
+//expected-warning@+1 {{duplicate 'cpu=' in the 'target' attribute string; 
'target' attribute ignored}}
+int __attribute__((target("arch=pwr8,cpu=pwr9"))) cypress_tree(void) { return 
4; }
 //expected-warning@+1 {{unsupported 'branch-protection' in the 'target' 
attribute string; 'target' attribute ignored}}
 int __attribute__((target("branch-protection=none"))) birch_tree(void) { 
return 5; }
 //expected-warning@+1 {{unknown tune CPU 'hiss' in the 'target' attribute 
string; 'target' attribute ignored}}

>From 4e984e123b1a71b80d4d134059371cf1a6ad2a94 Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Mon, 16 Oct 2023 16:53:33 +0800
Subject: [PATCH 3/3] Update attribute docs

---
 clang/include/clang/Basic/AttrDocs.td | 8 
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index cbbf69faeb308a

[clang] [Clang] Support target attr specifying CPU (PR #68678)

2023-10-16 Thread Qiu Chaofan via cfe-commits


@@ -76,10 +80,14 @@ int __attribute__((target("fpmath=387"))) walrus(void) { 
return 4; }
 int __attribute__((target("float128,arch=hiss"))) meow(void) {  return 4; }
 // no warning, same as saying 'nothing'.
 int __attribute__((target("arch="))) turtle(void) { return 4; }
+// no warning, same as saying 'nothing'.
+int __attribute__((target("cpu="))) equus(void) { return 4; }
 //expected-warning@+1 {{unknown CPU 'hiss' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=hiss,arch=woof"))) pine_tree(void) { return 4; 
}
 //expected-warning@+1 {{duplicate 'arch=' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=pwr9,arch=pwr10"))) oak_tree(void) { return 4; 
}
+//expected-warning@+1 {{duplicate 'cpu=' in the 'target' attribute string; 
'target' attribute ignored}}

ecnelises wrote:

AArch64 has its own implementation, this behavior is consistent with it. Maybe 
another patch to unify the warning message of AArch64 and other to `duplicate 
'arch=/cpu=' in ...` helps.

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


[clang-tools-extra] [libc++] Add assertions for potential OOB reads in std::nth_element (PR #67023)

2023-10-16 Thread Daniel Kutenin via cfe-commits

https://github.com/danlark1 updated 
https://github.com/llvm/llvm-project/pull/67023

>From 059bbfab50592026ce2785c5f7d98eaf5c9f8bd6 Mon Sep 17 00:00:00 2001
From: Daniel Kutenin 
Date: Thu, 21 Sep 2023 14:55:11 +0100
Subject: [PATCH 1/6] Add bound checking in nth_element

---
 libcxx/include/__algorithm/nth_element.h | 28 +++-
 1 file changed, 22 insertions(+), 6 deletions(-)

diff --git a/libcxx/include/__algorithm/nth_element.h 
b/libcxx/include/__algorithm/nth_element.h
index dbacf58f9ecdbc4..37e43ab0db8ca4f 100644
--- a/libcxx/include/__algorithm/nth_element.h
+++ b/libcxx/include/__algorithm/nth_element.h
@@ -116,10 +116,18 @@ __nth_element(_RandomAccessIterator __first, 
_RandomAccessIterator __nth, _Rando
 return;
 }
 while (true) {
-while (!__comp(*__first, *__i))
+while (!__comp(*__first, *__i)) {
 ++__i;
-while (__comp(*__first, *--__j))
-;
+_LIBCPP_ASSERT_UNCATEGORIZED(
+__i != __last,
+"Would read out of bounds, does your comparator 
satisfy the strict-weak ordering requirement?");
+}
+do {
+_LIBCPP_ASSERT_UNCATEGORIZED(
+__j != __first,
+"Would read out of bounds, does your comparator 
satisfy the strict-weak ordering requirement?");
+--__j;
+} while (__comp(*__first, *__j));
 if (__i >= __j)
 break;
 _Ops::iter_swap(__i, __j);
@@ -146,11 +154,19 @@ __nth_element(_RandomAccessIterator __first, 
_RandomAccessIterator __nth, _Rando
 while (true)
 {
 // __m still guards upward moving __i
-while (__comp(*__i, *__m))
+while (__comp(*__i, *__m)) {
 ++__i;
+_LIBCPP_ASSERT_UNCATEGORIZED(
+__i != __last,
+"Would read out of bounds, does your comparator 
satisfy the strict-weak ordering requirement?");
+}
 // It is now known that a guard exists for downward moving __j
-while (!__comp(*--__j, *__m))
-;
+do {
+_LIBCPP_ASSERT_UNCATEGORIZED(
+__j != __first,
+"Would read out of bounds, does your comparator 
satisfy the strict-weak ordering requirement?");
+--__j;
+} while (!__comp(*__j, *__m));
 if (__i >= __j)
 break;
 _Ops::iter_swap(__i, __j);

>From 8e128c3ce6d8dc8afb94ba2465a2585fe3b8525a Mon Sep 17 00:00:00 2001
From: Daniel Kutenin 
Date: Thu, 21 Sep 2023 15:22:18 +0100
Subject: [PATCH 2/6] Update nth_element out of bound test

---
 .../assert.sort.invalid_comparator.pass.cpp   | 77 +++
 1 file changed, 61 insertions(+), 16 deletions(-)

diff --git 
a/libcxx/test/libcxx/algorithms/alg.sorting/assert.sort.invalid_comparator.pass.cpp
 
b/libcxx/test/libcxx/algorithms/alg.sorting/assert.sort.invalid_comparator.pass.cpp
index e5e417fe7bda2d4..b02ae2118ec5f47 100644
--- 
a/libcxx/test/libcxx/algorithms/alg.sorting/assert.sort.invalid_comparator.pass.cpp
+++ 
b/libcxx/test/libcxx/algorithms/alg.sorting/assert.sort.invalid_comparator.pass.cpp
@@ -50,27 +50,37 @@
 #include "bad_comparator_values.h"
 #include "check_assertion.h"
 
-void check_oob_sort_read() {
-std::map> comparison_results; // 
terrible for performance, but really convenient
-for (auto line : std::views::split(DATA, '\n') | 
std::views::filter([](auto const& line) { return !line.empty(); })) {
-auto values = std::views::split(line, ' ');
-auto it = values.begin();
-std::size_t left = std::stol(std::string((*it).data(), (*it).size()));
-it = std::next(it);
-std::size_t right = std::stol(std::string((*it).data(), (*it).size()));
-it = std::next(it);
-bool result = static_cast(std::stol(std::string((*it).data(), 
(*it).size(;
-comparison_results[left][right] = result;
-}
-auto predicate = [&](std::size_t* left, std::size_t* right) {
+class ComparisonResults {
+public:
+ComparisonResults(std::string_view data) {
+for (auto line : std::views::split(data, '\n') | 
std::views::filter([](auto const& line) { return !line.empty(); })) {
+auto values = std::views::split(line, ' ');
+auto it = values.begin();
+std::size_t left = std::stol(std::string((*it).data(), 
(*it).size()));
+it = std::next(it);
+std::size_t right = std::stol(std::string((*it).data(), 
(*it).size()));
+it = std::next(it);
+ 

[clang] [PowerPC] Fix use of FPSCR builtins in smmintrin.h (PR #67299)

2023-10-16 Thread Qiu Chaofan via cfe-commits


@@ -11595,6 +11595,50 @@ SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, 
SelectionDAG &DAG) const {
   llvm_unreachable("ERROR:Should return for all cases within swtich.");
 }
 
+// Lower mffsl intrinsic with mffs in targets without ISA 3.0
+static SDValue lowerMFFSL(SDValue Op, SelectionDAG &DAG,

ecnelises wrote:

> The reason mffsl exists is because it is a lightweight version of mffs.

Thanks, according to the 'lightweight' meaning, this sounds reasonable. I don't 
have strong preference to align with GCC behavior. We have builtins only for P9 
which can't be or haven't been emulated.

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


[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits

DonatNagyE wrote:

After some delays (I had a short vacation, then forgot about this patch) I 
finally got some test results... and they revealed that it was causing lots of 
segfaults. @steakhal thanks for asking for the experimental confirmation, it 
was useful!

After fixing the buggy line and pushing the update, I re-analyzed the open 
source projects, and this produced the intended results: the analysis did not 
crash and the set of the reports did not change. Based on this I think that 
this commit is ready to be merged now.

For reference, I insert the table of the test results, but it contains no 
differences:
| CodeChecker results | | |
| --- | --- | --- |
| bitcoin_v0.20.1_baseline_vs_bitcoin_v0.20.1_new | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=bitcoin_v0.20.1_baseline&newcheck=bitcoin_v0.20.1_new&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=bitcoin_v0.20.1_baseline&newcheck=bitcoin_v0.20.1_new&is-unique=on&diff-mode=Resolved)
 |
| redis_6.2.6_baseline_vs_redis_6.2.6_new | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=redis_6.2.6_baseline&newcheck=redis_6.2.6_new&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=redis_6.2.6_baseline&newcheck=redis_6.2.6_new&is-unique=on&diff-mode=Resolved)
 |
| protobuf_v3.13.0_baseline_vs_protobuf_v3.13.0_new | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=protobuf_v3.13.0_baseline&newcheck=protobuf_v3.13.0_new&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=protobuf_v3.13.0_baseline&newcheck=protobuf_v3.13.0_new&is-unique=on&diff-mode=Resolved)
 |
| ffmpeg_n4.3.1_baseline_vs_ffmpeg_n4.3.1_new | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=ffmpeg_n4.3.1_baseline&newcheck=ffmpeg_n4.3.1_new&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=ffmpeg_n4.3.1_baseline&newcheck=ffmpeg_n4.3.1_new&is-unique=on&diff-mode=Resolved)
 |
| postgres_REL_13_0_baseline_vs_postgres_REL_13_0_new | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_baseline&newcheck=postgres_REL_13_0_new&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_baseline&newcheck=postgres_REL_13_0_new&is-unique=on&diff-mode=Resolved)
 |
| sqlite_version-3.33.0_baseline_vs_sqlite_version-3.33.0_new | [New 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=sqlite_version-3.33.0_baseline&newcheck=sqlite_version-3.33.0_new&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=sqlite_version-3.33.0_baseline&newcheck=sqlite_version-3.33.0_new&is-unique=on&diff-mode=Resolved)
 |

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


[clang] [PowerPC] Fix use of FPSCR builtins in smmintrin.h (PR #67299)

2023-10-16 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/67299

>From 2d628587b9cede36e7a93ecb1414cc0c16596934 Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Mon, 25 Sep 2023 17:06:26 +0800
Subject: [PATCH 1/3] [PowerPC] Fix use of FPSCR builtins in smmintrin.h

smmintrin.h uses __builtin_mffs, __builtin_mffsl, __builtin_mtfsf and
__builtin_set_fpscr_rn. This patch replaces the uses with ppc prefix and
implement the missing ones.

This fixes issue #64664.
---
 clang/include/clang/Basic/BuiltinsPPC.def |  2 +
 clang/lib/Basic/Targets/PPC.cpp   |  4 ++
 clang/lib/CodeGen/CGBuiltin.cpp   |  5 ++
 clang/lib/Headers/ppc_wrappers/smmintrin.h| 50 +--
 clang/test/CodeGen/PowerPC/builtins-ppc.c | 13 -
 clang/test/CodeGen/PowerPC/ppc-emmintrin.c|  5 ++
 clang/test/CodeGen/PowerPC/ppc-mmintrin.c |  5 ++
 clang/test/CodeGen/PowerPC/ppc-pmmintrin.c|  3 ++
 clang/test/CodeGen/PowerPC/ppc-smmintrin.c| 37 --
 clang/test/CodeGen/PowerPC/ppc-tmmintrin.c|  3 ++
 clang/test/CodeGen/PowerPC/ppc-x86gprintrin.c |  3 ++
 11 files changed, 99 insertions(+), 31 deletions(-)

diff --git a/clang/include/clang/Basic/BuiltinsPPC.def 
b/clang/include/clang/Basic/BuiltinsPPC.def
index 18a1186053481ed..a35488ed3dfa565 100644
--- a/clang/include/clang/Basic/BuiltinsPPC.def
+++ b/clang/include/clang/Basic/BuiltinsPPC.def
@@ -151,9 +151,11 @@ TARGET_BUILTIN(__builtin_ppc_extract_exp, "Uid", "", 
"power9-vector")
 TARGET_BUILTIN(__builtin_ppc_extract_sig, "ULLid", "", "power9-vector")
 BUILTIN(__builtin_ppc_mtfsb0, "vUIi", "")
 BUILTIN(__builtin_ppc_mtfsb1, "vUIi", "")
+BUILTIN(__builtin_ppc_mffs, "d", "")
 TARGET_BUILTIN(__builtin_ppc_mffsl, "d", "", "isa-v30-instructions")
 BUILTIN(__builtin_ppc_mtfsf, "vUIiUi", "")
 BUILTIN(__builtin_ppc_mtfsfi, "vUIiUIi", "")
+BUILTIN(__builtin_ppc_set_fpscr_rn, "di", "")
 TARGET_BUILTIN(__builtin_ppc_insert_exp, "ddULLi", "", "power9-vector")
 BUILTIN(__builtin_ppc_fmsub, "", "")
 BUILTIN(__builtin_ppc_fmsubs, "", "")
diff --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp
index 4e895cc7310c00e..b8bc920c45f40a2 100644
--- a/clang/lib/Basic/Targets/PPC.cpp
+++ b/clang/lib/Basic/Targets/PPC.cpp
@@ -264,6 +264,10 @@ static void defineXLCompatMacros(MacroBuilder &Builder) {
   Builder.defineMacro("__builtin_minfe", "__builtin_ppc_minfe");
   Builder.defineMacro("__builtin_minfl", "__builtin_ppc_minfl");
   Builder.defineMacro("__builtin_minfs", "__builtin_ppc_minfs");
+  Builder.defineMacro("__builtin_mffs", "__builtin_ppc_mffs");
+  Builder.defineMacro("__builtin_mffsl", "__builtin_ppc_mffsl");
+  Builder.defineMacro("__builtin_mtfsf", "__builtin_ppc_mtfsf");
+  Builder.defineMacro("__builtin_set_fpscr_rn", "__builtin_ppc_set_fpscr_rn");
 }
 
 /// PPCTargetInfo::getTargetDefines - Return a set of the PowerPC-specific
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index bf984861bccb5cc..b80c5d9e7c01dc0 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -17258,6 +17258,11 @@ Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned 
BuiltinID,
 Value *Op1 = EmitScalarExpr(E->getArg(1));
 return Builder.CreateFDiv(Op0, Op1, "swdiv");
   }
+  case PPC::BI__builtin_ppc_set_fpscr_rn:
+return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::ppc_setrnd),
+  {EmitScalarExpr(E->getArg(0))});
+  case PPC::BI__builtin_ppc_mffs:
+return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::ppc_readflm));
   }
 }
 
diff --git a/clang/lib/Headers/ppc_wrappers/smmintrin.h 
b/clang/lib/Headers/ppc_wrappers/smmintrin.h
index 349b395c4f00b92..19cdecb18d2b83f 100644
--- a/clang/lib/Headers/ppc_wrappers/smmintrin.h
+++ b/clang/lib/Headers/ppc_wrappers/smmintrin.h
@@ -14,7 +14,7 @@
 
 #ifndef NO_WARN_X86_INTRINSICS
 /* This header is distributed to simplify porting x86_64 code that
-   makes explicit use of Intel intrinsics to powerp64/powerpc64le.
+   makes explicit use of Intel intrinsics to powerpc64/powerpc64le.
 
It is the user's responsibility to determine if the results are
acceptable and make additional changes as necessary.
@@ -68,10 +68,10 @@ extern __inline __m128d
 __asm__("mffsce %0" : "=f"(__fpscr_save.__fr));
 __enables_save.__fpscr = __fpscr_save.__fpscr & 0xf8;
 #else
-__fpscr_save.__fr = __builtin_mffs();
+__fpscr_save.__fr = __builtin_ppc_mffs();
 __enables_save.__fpscr = __fpscr_save.__fpscr & 0xf8;
 __fpscr_save.__fpscr &= ~0xf8;
-__builtin_mtfsf(0b0011, __fpscr_save.__fr);
+__builtin_ppc_mtfsf(0b0011, __fpscr_save.__fr);
 #endif
 /* Insert an artificial "read/write" reference to the variable
read below, to ensure the compiler does not schedule
@@ -83,10 +83,15 @@ extern __inline __m128d
 
   switch (__rounding) {
   case _MM_FROUND_TO_NEAREST_INT:
-__fpscr_save.__fr = __builtin_mffsl();
+#ifdef _ARCH_PWR9
+

[clang] [clang]Avoid to check created local variable multiple time when evaluating (PR #69106)

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


@@ -393,6 +393,9 @@ Bug Fixes in This Version
   operator in C. No longer issuing a confusing diagnostic along the lines of
   "incompatible operand types ('foo' and 'foo')" with extensions such as matrix
   types. Fixes (`#69008 `_)
+- Fix a crash when evaluating comparasion between the field from the same 
variable

Fznamznon wrote:

a typo
```suggestion
- Fix a crash when evaluating comparison between the field from the same 
variable
```

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


[clang] [clang] [Gnu] Improve GCCVersion parsing to match versions such as "10-win32" (PR #69079)

2023-10-16 Thread Martin Storsjö via cfe-commits

https://github.com/mstorsjo updated 
https://github.com/llvm/llvm-project/pull/69079

From 2b127200dc7b7b7c60e3001c7acf49a33a22e2a5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Martin=20Storsj=C3=B6?= 
Date: Sat, 14 Oct 2023 00:06:05 +0300
Subject: [PATCH 1/2] [clang] [unittest] Add a test for
 Generic_GCC::GCCVersion::Parse

This adds actual test cases for all the cases that are listed in
a code comment in the implementation of this function; having such
test coverage eases doing further modifications to the function.
---
 clang/unittests/Driver/CMakeLists.txt |  1 +
 clang/unittests/Driver/GCCVersionTest.cpp | 48 +++
 2 files changed, 49 insertions(+)
 create mode 100644 clang/unittests/Driver/GCCVersionTest.cpp

diff --git a/clang/unittests/Driver/CMakeLists.txt 
b/clang/unittests/Driver/CMakeLists.txt
index e37c158d7137a88..752037f78fb147d 100644
--- a/clang/unittests/Driver/CMakeLists.txt
+++ b/clang/unittests/Driver/CMakeLists.txt
@@ -9,6 +9,7 @@ set(LLVM_LINK_COMPONENTS
 add_clang_unittest(ClangDriverTests
   DistroTest.cpp
   DXCModeTest.cpp
+  GCCVersionTest.cpp
   ToolChainTest.cpp
   ModuleCacheTest.cpp
   MultilibBuilderTest.cpp
diff --git a/clang/unittests/Driver/GCCVersionTest.cpp 
b/clang/unittests/Driver/GCCVersionTest.cpp
new file mode 100644
index 000..ef05a0b4fe734e5
--- /dev/null
+++ b/clang/unittests/Driver/GCCVersionTest.cpp
@@ -0,0 +1,48 @@
+//===- unittests/Driver/GCCVersionTest.cpp --- GCCVersion parser tests 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Unit tests for Generic_GCC::GCCVersion
+//
+//===--===//
+
+#include "../../lib/Driver/ToolChains/Gnu.h"
+#include "gtest/gtest.h"
+
+using namespace clang::driver;
+using namespace clang;
+
+struct VersionParseTest {
+  std::string Text;
+
+  int Major, Minor, Patch;
+  std::string MajorStr, MinorStr, PatchSuffix;
+};
+
+const VersionParseTest TestCases[] = {
+{"5", 5, -1, -1, "5", "", ""},
+{"4.4", 4, 4, -1, "4", "4", ""},
+{"4.4-patched", 4, 4, -1, "4", "4", "-patched"},
+{"4.4.0", 4, 4, 0, "4", "4", ""},
+{"4.4.x", 4, 4, -1, "4", "4", ""},
+{"4.4.2-rc4", 4, 4, 2, "4", "4", "-rc4"},
+{"4.4.x-patched", 4, 4, -1, "4", "4", ""},
+{"not-a-version", -1, -1, -1, "", "", ""},
+};
+
+TEST(GCCVersionTest, Parse) {
+  for (const auto &TC : TestCases) {
+auto V = toolchains::Generic_GCC::GCCVersion::Parse(TC.Text);
+ASSERT_EQ(V.Text, TC.Text);
+ASSERT_EQ(V.Major, TC.Major);
+ASSERT_EQ(V.Minor, TC.Minor);
+ASSERT_EQ(V.Patch, TC.Patch);
+ASSERT_EQ(V.MajorStr, TC.MajorStr);
+ASSERT_EQ(V.MinorStr, TC.MinorStr);
+ASSERT_EQ(V.PatchSuffix, TC.PatchSuffix);
+  }
+}

From 322d9e0626b3185533e1f7f83ab0ec2b64453ca8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Martin=20Storsj=C3=B6?= 
Date: Sat, 14 Oct 2023 00:55:18 +0300
Subject: [PATCH 2/2] [clang] [Gnu] Improve GCCVersion parsing to match
 versions such as "10-win32"

In earlier GCC versions, the Debian/Ubuntu provided mingw toolchains
were packaged in /usr/lib/gcc/ with version strings such
as "5.3-win32", which were matched and found since
6afcd64eb65fca233a7b173f88cffb2c2c9c114c. However in recent versions,
they have stopped including the minor version number and only
have version strings such as "10-win32" and "10-posix".

Generalize the parsing code to tolerate the patch suffix to be
present on a version number with only a major number.

Refactor the string parsing code to highlight the overall structure
of the parsing. This implementation should yield the same result
as before, except for when there's only one segment and it has
trailing, non-number contents.

This allows Clang to find the GCC libraries and headers in
Debian/Ubuntu provided MinGW cross compilers.
---
 clang/lib/Driver/ToolChains/Gnu.cpp   | 82 +++
 clang/unittests/Driver/GCCVersionTest.cpp |  1 +
 2 files changed, 55 insertions(+), 28 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index cdd911af9a73361..e6f94836c4110a1 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2007,45 +2007,71 @@ Generic_GCC::GCCVersion 
Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
   std::pair First = VersionText.split('.');
   std::pair Second = First.second.split('.');
 
-  GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
-  if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
-return BadVersion;
-  GoodVersion.MajorStr = First.first.str();
-  if (First.second.empty())
-return GoodVersion;
+  StringRef MajorStr = First.first;
   StringRef Mino

[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits


@@ -32,42 +32,72 @@ using namespace taint;
 namespace {
 class ArrayBoundCheckerV2 :
 public Checker {
-  mutable std::unique_ptr BT;
-  mutable std::unique_ptr TaintBT;
+  BugType BT{this, "Out-of-bound access"};
+  BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
 
-  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
- OOB_Kind kind) const;
-  void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
-  SVal TaintedSVal) const;
+  void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
+ SVal TaintedSVal = UnknownVal()) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
 public:
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
 };
+} // anonymous namespace
 
-// FIXME: Eventually replace RegionRawOffset with this class.
-class RegionRawOffsetV2 {
-private:
-  const SubRegion *baseRegion;
-  NonLoc byteOffset;
+/// For a given Location that can be represented as a symbolic expression
+/// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
+/// Arr and the distance of Location from the beginning of Arr (expressed in a
+/// NonLoc that specifies the number of CharUnits). Returns nullopt when these
+/// cannot be determined.
+std::optional>
+computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
+  QualType T = SVB.getArrayIndexType();
+  auto Calc = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc RHS) {
+// We will use this utility to add and multiply values.
+return SVB.evalBinOpNN(State, Op, LHS, RHS, T).getAs();
+  };
 
-public:
-  RegionRawOffsetV2(const SubRegion *base, NonLoc offset)
-  : baseRegion(base), byteOffset(offset) { assert(base); }
+  const auto *Region = dyn_cast_or_null(Location.getAsRegion());
+  std::optional Offset = std::nullopt;

DonatNagyE wrote:

It's intentionally set to `std::nullopt` instead of zero because this way we 
won't perform the bounds checks on Location checks involving regions that don't 
have any `ElementRegion` layers.

I think that this might provide a significant performance advantage, as it may 
be costly to perform simplification steps and evaluate comparisons each time a 
"plain" variable is accessed.

I'd like to keep this solution, but I'll add a comment to explain the 
motivations.

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


[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits


@@ -32,42 +32,72 @@ using namespace taint;
 namespace {
 class ArrayBoundCheckerV2 :
 public Checker {
-  mutable std::unique_ptr BT;
-  mutable std::unique_ptr TaintBT;
+  BugType BT{this, "Out-of-bound access"};
+  BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
 
-  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
- OOB_Kind kind) const;
-  void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
-  SVal TaintedSVal) const;
+  void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
+ SVal TaintedSVal = UnknownVal()) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
 public:
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
 };
+} // anonymous namespace
 
-// FIXME: Eventually replace RegionRawOffset with this class.
-class RegionRawOffsetV2 {
-private:
-  const SubRegion *baseRegion;
-  NonLoc byteOffset;
+/// For a given Location that can be represented as a symbolic expression
+/// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
+/// Arr and the distance of Location from the beginning of Arr (expressed in a
+/// NonLoc that specifies the number of CharUnits). Returns nullopt when these
+/// cannot be determined.
+std::optional>
+computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
+  QualType T = SVB.getArrayIndexType();
+  auto Calc = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc RHS) {
+// We will use this utility to add and multiply values.
+return SVB.evalBinOpNN(State, Op, LHS, RHS, T).getAs();
+  };
 
-public:
-  RegionRawOffsetV2(const SubRegion *base, NonLoc offset)
-  : baseRegion(base), byteOffset(offset) { assert(base); }
+  const auto *Region = dyn_cast_or_null(Location.getAsRegion());
+  std::optional Offset = std::nullopt;
+
+  while (const auto *ERegion = dyn_cast_or_null(Region)) {
+const auto Index = ERegion->getIndex().getAs();
+if (!Index)
+  return std::nullopt;
+
+QualType ElemType = ERegion->getElementType();
+// If the element is an incomplete type, go no further.
+if (ElemType->isIncompleteType())
+  return std::nullopt;
+
+// Calculate Delta = Index * sizeof(ElemType).
+NonLoc Size = SVB.makeArrayIndex(
+SVB.getContext().getTypeSizeInChars(ElemType).getQuantity());
+auto Delta = Calc(BO_Mul, *Index, Size);
+if (!Delta)
+  return std::nullopt;
+
+// Perform Offset += Delta, handling the initial nullopt as 0.
+if (!Offset) {
+  Offset = Delta;
+} else {
+  Offset = Calc(BO_Add, *Offset, *Delta);
+  if (!Offset)
+return std::nullopt;
+}

DonatNagyE wrote:

The `!Offset` case is just for handling the initial value of the variable 
`Offset`; which is an intentional special case to detect situations where the 
`while` loop wasn't entered at all. 

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-16 Thread Jerin Philip via cfe-commits

https://github.com/jerinphilip updated 
https://github.com/llvm/llvm-project/pull/65638

>From 941af68ab8dad68ed8df65f6e0559476f137bfe2 Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:43:53 +0530
Subject: [PATCH 1/7] Fix `Form` to recognize `_Alignas` in addition to
 `alignas`

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

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index e57adc4bf5b99a2..36f4eb885cf12f8 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -94,7 +94,7 @@ class AttributeCommonInfo {
   IsRegularKeywordAttribute(IsRegularKeywordAttribute) {}
 constexpr Form(tok::TokenKind Tok)
 : SyntaxUsed(AS_Keyword), SpellingIndex(SpellingNotCalculated),
-  IsAlignas(Tok == tok::kw_alignas),
+  IsAlignas(Tok == tok::kw_alignas || Tok == tok::kw__Alignas),
   IsRegularKeywordAttribute(tok::isRegularKeywordAttribute(Tok)) {}
 
 Syntax getSyntax() const { return Syntax(SyntaxUsed); }

>From 8c0bfe350dfa2d4d24988eb544f5c1a9eb1aec6d Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Thu, 7 Sep 2023 18:53:57 +0530
Subject: [PATCH 2/7] Avoid mixing `isCXX11Attribute` with `isAlignAs`

---
 clang/include/clang/Basic/AttributeCommonInfo.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 36f4eb885cf12f8..669227589dfacd5 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -186,14 +186,14 @@ class AttributeCommonInfo {
   bool isGNUScope() const;
   bool isClangScope() const;
 
-  bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11 || IsAlignas; }
+  bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11; }
 
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
   /// attributes spelled with a keyword, like alignas.
   bool isStandardAttributeSyntax() const {
-return isCXX11Attribute() || isC23Attribute();
+return isCXX11Attribute() || isC23Attribute() || IsAlignas;
   }
 
   bool isGNUAttribute() const { return SyntaxUsed == AS_GNU; }

>From 8f699d5dfe62b2a1eb1f67f37ffa3d4ba1f2bfce Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Thu, 7 Sep 2023 19:15:03 +0530
Subject: [PATCH 3/7] Fix diagnostic warning post `isAlignAs` decoupling

---
 clang/include/clang/Basic/AttributeCommonInfo.h | 2 +-
 clang/lib/Parse/ParseDecl.cpp   | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/AttributeCommonInfo.h 
b/clang/include/clang/Basic/AttributeCommonInfo.h
index 669227589dfacd5..f1e3325d44f0e1a 100644
--- a/clang/include/clang/Basic/AttributeCommonInfo.h
+++ b/clang/include/clang/Basic/AttributeCommonInfo.h
@@ -186,8 +186,8 @@ class AttributeCommonInfo {
   bool isGNUScope() const;
   bool isClangScope() const;
 
+  bool isAlignas() const { return IsAlignas; }
   bool isCXX11Attribute() const { return SyntaxUsed == AS_CXX11; }
-
   bool isC23Attribute() const { return SyntaxUsed == AS_C23; }
 
   /// The attribute is spelled [[]] in either C or C++ mode, including standard
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 4a9f2caf654713e..f91141f7cd39cbf 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3405,8 +3405,8 @@ void Parser::ParseDeclarationSpecifiers(
   else {
 // Reject C++11 / C23 attributes that aren't type attributes.
 for (const ParsedAttr &PA : attrs) {
-  if (!PA.isCXX11Attribute() && !PA.isC23Attribute() &&
-  !PA.isRegularKeywordAttribute())
+  if (!PA.isAlignas() && !PA.isCXX11Attribute() &&
+  !PA.isC23Attribute() && !PA.isRegularKeywordAttribute())
 continue;
   if (PA.getKind() == ParsedAttr::UnknownAttribute)
 // We will warn about the unknown attribute elsewhere (in

>From e7ddd755f1a873421809a05a4d5d999b7a15f62e Mon Sep 17 00:00:00 2001
From: Jerin Philip 
Date: Sat, 19 Aug 2023 16:44:51 +0530
Subject: [PATCH 4/7] Add attribute-ignored diagnostic warning variant

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0ac4df8edb242f6..f76f872a98288f7 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3491,10 +3491,14 @@ def err_attribute_invalid_on_decl : Error<
 def warn_type_attribute_deprecated_on_decl : Warning<
   "applying attribute %0 to a declaration is deprecated

[clang] [clang]Avoid to check created local variable multiple time when evaluating (PR #69106)

2023-10-16 Thread Congcong Cai via cfe-commits

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

>From 8e599770d1dc3a5cd3edc011e7d830bc5b428410 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sun, 15 Oct 2023 19:48:09 +0800
Subject: [PATCH 1/2] [clang]Avoid to check created local variable multiple
 time when constant evaluating

When evaluting variable initialized from compound literal multiple times, it 
will be
converted to evaluting the compound literal itself multiple times, which causes 
clang
crash in assertions.

And the further evaluting is not rely on this assertion.

Fixes: #69065
---
 clang/docs/ReleaseNotes.rst|  3 +++
 clang/lib/AST/ExprConstant.cpp |  1 -
 clang/test/AST/issue69065.c| 17 +
 3 files changed, 20 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/AST/issue69065.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index be7c8bf247f7af5..5578663a90f104a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -393,6 +393,9 @@ Bug Fixes in This Version
   operator in C. No longer issuing a confusing diagnostic along the lines of
   "incompatible operand types ('foo' and 'foo')" with extensions such as matrix
   types. Fixes (`#69008 `_)
+- Fix a crash when evaluating comparasion between the field from the same 
variable
+  which initialized from compound literals in C. Fixes
+  (`#69065 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index e5539dedec02a4b..9948b516745a30b 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -1912,7 +1912,6 @@ APValue &CallStackFrame::createLocal(APValue::LValueBase 
Base, const void *Key,
   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
   unsigned Version = Base.getVersion();
   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
-  assert(Result.isAbsent() && "local created multiple times");
 
   // If we're creating a local immediately in the operand of a speculative
   // evaluation, don't register a cleanup to be run outside the speculative
diff --git a/clang/test/AST/issue69065.c b/clang/test/AST/issue69065.c
new file mode 100644
index 000..11428932019418d
--- /dev/null
+++ b/clang/test/AST/issue69065.c
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -fsyntax-only %s -verify
+// expected-no-diagnostics
+
+struct A {
+  int i;
+};
+struct B {
+  struct A *a;
+};
+const struct B c = {&(struct A){1}};
+
+int main(void) {
+  if ((c.a->i != 1) || (c.a->i)) {
+return 1;
+  }
+  return 0;
+}

>From a3085aa7a927206a464335c07ebbbf17d4c96180 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Mon, 16 Oct 2023 17:40:10 +0800
Subject: [PATCH 2/2] Update clang/docs/ReleaseNotes.rst

Co-authored-by: Mariya Podchishchaeva 
---
 clang/docs/ReleaseNotes.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5578663a90f104a..50c34de51f254ce 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -393,7 +393,7 @@ Bug Fixes in This Version
   operator in C. No longer issuing a confusing diagnostic along the lines of
   "incompatible operand types ('foo' and 'foo')" with extensions such as matrix
   types. Fixes (`#69008 `_)
-- Fix a crash when evaluating comparasion between the field from the same 
variable
+- Fix a crash when evaluating comparison between the field from the same 
variable
   which initialized from compound literals in C. Fixes
   (`#69065 `_)
 

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


[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits


@@ -32,42 +32,72 @@ using namespace taint;
 namespace {
 class ArrayBoundCheckerV2 :
 public Checker {
-  mutable std::unique_ptr BT;
-  mutable std::unique_ptr TaintBT;
+  BugType BT{this, "Out-of-bound access"};
+  BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
 
-  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
- OOB_Kind kind) const;
-  void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
-  SVal TaintedSVal) const;
+  void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
+ SVal TaintedSVal = UnknownVal()) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
 public:
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
 };
+} // anonymous namespace
 
-// FIXME: Eventually replace RegionRawOffset with this class.
-class RegionRawOffsetV2 {
-private:
-  const SubRegion *baseRegion;
-  NonLoc byteOffset;
+/// For a given Location that can be represented as a symbolic expression
+/// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
+/// Arr and the distance of Location from the beginning of Arr (expressed in a
+/// NonLoc that specifies the number of CharUnits). Returns nullopt when these
+/// cannot be determined.
+std::optional>
+computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
+  QualType T = SVB.getArrayIndexType();
+  auto Calc = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc RHS) {
+// We will use this utility to add and multiply values.
+return SVB.evalBinOpNN(State, Op, LHS, RHS, T).getAs();
+  };
 
-public:
-  RegionRawOffsetV2(const SubRegion *base, NonLoc offset)
-  : baseRegion(base), byteOffset(offset) { assert(base); }
+  const auto *Region = dyn_cast_or_null(Location.getAsRegion());
+  std::optional Offset = std::nullopt;
+
+  while (const auto *ERegion = dyn_cast_or_null(Region)) {
+const auto Index = ERegion->getIndex().getAs();
+if (!Index)
+  return std::nullopt;
+
+QualType ElemType = ERegion->getElementType();
+// If the element is an incomplete type, go no further.
+if (ElemType->isIncompleteType())

DonatNagyE wrote:

Good question, I "inherited" this check from the older variants of the code and 
I can easily imagine that it's never triggered. I'd prefer to avoid this 
question by just adding a "Paranoia: " prefix to this comment -- but I can 
investigate the situation if you think that it's important.

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


[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits


@@ -32,42 +32,72 @@ using namespace taint;
 namespace {
 class ArrayBoundCheckerV2 :
 public Checker {
-  mutable std::unique_ptr BT;
-  mutable std::unique_ptr TaintBT;
+  BugType BT{this, "Out-of-bound access"};
+  BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
 
-  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
- OOB_Kind kind) const;
-  void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
-  SVal TaintedSVal) const;
+  void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
+ SVal TaintedSVal = UnknownVal()) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
 public:
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
 };
+} // anonymous namespace
 
-// FIXME: Eventually replace RegionRawOffset with this class.
-class RegionRawOffsetV2 {
-private:
-  const SubRegion *baseRegion;
-  NonLoc byteOffset;
+/// For a given Location that can be represented as a symbolic expression
+/// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
+/// Arr and the distance of Location from the beginning of Arr (expressed in a
+/// NonLoc that specifies the number of CharUnits). Returns nullopt when these
+/// cannot be determined.
+std::optional>
+computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
+  QualType T = SVB.getArrayIndexType();
+  auto Calc = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc RHS) {

DonatNagyE wrote:

Good suggestion, I'll change it. Previously the four-character name was needed 
because I was using this in very deeply indented code, but now I can switch to 
this more descriptive name.

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


[clang] [clang][NFC] Replace TypeAlignment with alignof(T) (PR #69185)

2023-10-16 Thread Vlad Serebrennikov via cfe-commits

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

This patch replaces usages of `TypeAlignment` with `alignof(T)`, where `T` is 
type that will be created in allocated storage with placement-new. This is now 
possible, because `alignof` reports the correct alignment for `Type` and 
classes derived from it after #68377 was merged.

While preparing #68377 I verified via `static_assert` that there are no 
mismatches of alignment between `TypeAlignment` and alignment of types derived 
from `Type`, so no changes are expected to codegen.

>From a2a05516a0a828f96881eed4e4d89b5934202b2f Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Mon, 16 Oct 2023 12:25:36 +0300
Subject: [PATCH 1/2] [clang][NFC] Replace TypeAlignment with alignof(T)

---
 clang/lib/AST/ASTContext.cpp | 146 +--
 clang/lib/Sema/SemaType.cpp  |   4 +-
 2 files changed, 75 insertions(+), 75 deletions(-)

diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 4c4bcbf8a68f7ff..217cf7bf9a03225 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -1234,7 +1234,7 @@ TypedefDecl *ASTContext::getUInt128Decl() const {
 }
 
 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
-  auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
+  auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
   Types.push_back(Ty);
 }
@@ -3066,7 +3066,7 @@ ASTContext::getExtQualType(const Type *baseType, 
Qualifiers quals) const {
 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
   }
 
-  auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
+  auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
   ExtQualNodes.InsertNode(eq, insertPos);
   return QualType(eq, fastQuals);
 }
@@ -3310,7 +3310,7 @@ QualType ASTContext::getComplexType(QualType T) const {
 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
-  auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
+  auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
   Types.push_back(New);
   ComplexTypes.InsertNode(New, InsertPos);
   return QualType(New, 0);
@@ -3338,7 +3338,7 @@ QualType ASTContext::getPointerType(QualType T) const {
 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
-  auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
+  auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
   Types.push_back(New);
   PointerTypes.InsertNode(New, InsertPos);
   return QualType(New, 0);
@@ -3358,7 +3358,7 @@ QualType ASTContext::getAdjustedType(QualType Orig, 
QualType New) const {
   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
   assert(!AT && "Shouldn't be in the map!");
 
-  AT = new (*this, TypeAlignment)
+  AT = new (*this, alignof(AdjustedType))
   AdjustedType(Type::Adjusted, Orig, New, Canonical);
   Types.push_back(AT);
   AdjustedTypes.InsertNode(AT, InsertPos);
@@ -3379,7 +3379,7 @@ QualType ASTContext::getDecayedType(QualType Orig, 
QualType Decayed) const {
   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
   assert(!AT && "Shouldn't be in the map!");
 
-  AT = new (*this, TypeAlignment) DecayedType(Orig, Decayed, Canonical);
+  AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
   Types.push_back(AT);
   AdjustedTypes.InsertNode(AT, InsertPos);
   return QualType(AT, 0);
@@ -3433,7 +3433,7 @@ QualType ASTContext::getBlockPointerType(QualType T) 
const {
   BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
-  auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
+  auto *New = new (*this, alignof(BlockPointerType)) BlockPointerType(T, 
Canonical);
   Types.push_back(New);
   BlockPointerTypes.InsertNode(New, InsertPos);
   return QualType(New, 0);
@@ -3472,7 +3472,7 @@ ASTContext::getLValueReferenceType(QualType T, bool 
SpelledAsLValue) const {
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
-  auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
+  auto *New = new (*this, alignof(LValueReferenceType)) LValueReferenceType(T, 
Canonical,
  SpelledAsLValue);
   Types.push_back(New);
   LValueReferenceTypes.InsertNode(New, InsertPos);
@@ -3512,7 +3512,7 @@ QualType ASTContext::getRValueReferenceType(QualType T) 
const {
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
-  auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
+  auto *New = new (*this, alignof(RValueReferenceType)) RValueReferenceType(T, 
Canonical);
   Types.push_b

[clang] [clang][NFC] Replace TypeAlignment with alignof(T) (PR #69185)

2023-10-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

This patch replaces usages of `TypeAlignment` with `alignof(T)`, where `T` is 
type that will be created in allocated storage with placement-new. This is now 
possible, because `alignof` reports the correct alignment for `Type` and 
classes derived from it after #68377 was merged.

While preparing #68377 I verified via `static_assert` that there are no 
mismatches of alignment between `TypeAlignment` and alignment of types derived 
from `Type`, so no changes are expected to codegen.

---

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


2 Files Affected:

- (modified) clang/lib/AST/ASTContext.cpp (+115-99) 
- (modified) clang/lib/Sema/SemaType.cpp (+2-2) 


``diff
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 4c4bcbf8a68f7ff..27a675b83211775 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -1234,7 +1234,7 @@ TypedefDecl *ASTContext::getUInt128Decl() const {
 }
 
 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
-  auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
+  auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
   Types.push_back(Ty);
 }
@@ -3066,7 +3066,7 @@ ASTContext::getExtQualType(const Type *baseType, 
Qualifiers quals) const {
 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
   }
 
-  auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
+  auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
   ExtQualNodes.InsertNode(eq, insertPos);
   return QualType(eq, fastQuals);
 }
@@ -3310,7 +3310,7 @@ QualType ASTContext::getComplexType(QualType T) const {
 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
-  auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
+  auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
   Types.push_back(New);
   ComplexTypes.InsertNode(New, InsertPos);
   return QualType(New, 0);
@@ -3338,7 +3338,7 @@ QualType ASTContext::getPointerType(QualType T) const {
 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
-  auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
+  auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
   Types.push_back(New);
   PointerTypes.InsertNode(New, InsertPos);
   return QualType(New, 0);
@@ -3358,7 +3358,7 @@ QualType ASTContext::getAdjustedType(QualType Orig, 
QualType New) const {
   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
   assert(!AT && "Shouldn't be in the map!");
 
-  AT = new (*this, TypeAlignment)
+  AT = new (*this, alignof(AdjustedType))
   AdjustedType(Type::Adjusted, Orig, New, Canonical);
   Types.push_back(AT);
   AdjustedTypes.InsertNode(AT, InsertPos);
@@ -3379,7 +3379,7 @@ QualType ASTContext::getDecayedType(QualType Orig, 
QualType Decayed) const {
   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
   assert(!AT && "Shouldn't be in the map!");
 
-  AT = new (*this, TypeAlignment) DecayedType(Orig, Decayed, Canonical);
+  AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
   Types.push_back(AT);
   AdjustedTypes.InsertNode(AT, InsertPos);
   return QualType(AT, 0);
@@ -3433,7 +3433,8 @@ QualType ASTContext::getBlockPointerType(QualType T) 
const {
   BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
-  auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
+  auto *New =
+  new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
   Types.push_back(New);
   BlockPointerTypes.InsertNode(New, InsertPos);
   return QualType(New, 0);
@@ -3472,8 +3473,8 @@ ASTContext::getLValueReferenceType(QualType T, bool 
SpelledAsLValue) const {
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
-  auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
- SpelledAsLValue);
+  auto *New = new (*this, alignof(LValueReferenceType))
+  LValueReferenceType(T, Canonical, SpelledAsLValue);
   Types.push_back(New);
   LValueReferenceTypes.InsertNode(New, InsertPos);
 
@@ -3512,7 +3513,8 @@ QualType ASTContext::getRValueReferenceType(QualType T) 
const {
 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
   }
 
-  auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
+  auto *New = new (*this, alignof(RValueReferenceType))
+  RValueReferenceType(T, Canonical);
   Types.push_back(New);
   RValueReferenceTypes.InsertNode(New, InsertPos);
   r

[clang] [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha. (PR #66207)

2023-10-16 Thread Balázs Kéri via cfe-commits

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


[clang] [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha. (PR #66207)

2023-10-16 Thread Balázs Kéri via cfe-commits

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2023-10-16 Thread Bret Brown via cfe-commits

bretbrownjr wrote:

I highly recommend talking to @mathstuf of the CMake project about a way for 
the build system can emit a next generation set of build graph metadata (think 
modules appropriate compile commands, including dependencies).

I expect it will be more efficient for the build system, compiler, and LSP to 
all work together compared to implementing large subsets of a build system in 
the clangd LSP.

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


[clang] [clang] Add information about lld presence in RISCVToolchain. (PR #68904)

2023-10-16 Thread Bushev Dmitry via cfe-commits

https://github.com/dybv-sc updated 
https://github.com/llvm/llvm-project/pull/68904

>From d66ffe242716560408bd314a9725bb49556992e0 Mon Sep 17 00:00:00 2001
From: Dmitry Bushev 
Date: Mon, 9 Oct 2023 19:49:09 +0300
Subject: [PATCH] [clang] Add information about lld presence in RISCVToolchain.

---
 .../lib/Driver/ToolChains/RISCVToolchain.cpp  |  4 ++-
 clang/lib/Driver/ToolChains/RISCVToolchain.h  |  3 +++
 clang/test/Driver/riscv64-toolchain.c | 25 +++
 3 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index 7e6abd144428783..d87af6b4cb89170 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -49,7 +49,9 @@ bool RISCVToolChain::hasGCCToolchain(const Driver &D,
 /// RISC-V Toolchain
 RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
-: Generic_ELF(D, Triple, Args) {
+: Generic_ELF(D, Triple, Args), UseLLD{Args.getLastArgValue(
+   options::OPT_fuse_ld_EQ)
+   .equals_insensitive("lld")} {
   GCCInstallation.init(Triple, Args);
   if (GCCInstallation.isValid()) {
 Multilibs = GCCInstallation.getMultilibs();
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index de6960726f1cd77..afe98968ecd8616 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -35,11 +35,14 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const override;
 
+  bool HasNativeLLVMSupport() const override { return UseLLD; }
+
 protected:
   Tool *buildLinker() const override;
 
 private:
   std::string computeSysRoot() const override;
+  bool UseLLD;
 };
 
 } // end namespace toolchains
diff --git a/clang/test/Driver/riscv64-toolchain.c 
b/clang/test/Driver/riscv64-toolchain.c
index f177bff33dd4d72..c5f142cc876642c 100644
--- a/clang/test/Driver/riscv64-toolchain.c
+++ b/clang/test/Driver/riscv64-toolchain.c
@@ -121,6 +121,31 @@
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
 
+// Check that lto works in riscv-toolchain when explicitly specified lld as 
linker.
+// RUN: env "PATH=" %clang -### %s -fuse-ld=lld -flto \
+// RUN:   -B%S/Inputs/lld --target=riscv64-unknown-elf --rtlib=platform 
--sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "{{.*}}lld"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "-m" "elf64lriscv"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../../../riscv64-unknown-elf/lib/rv64imac/lp64/crt0.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtbegin.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../../../riscv64-unknown-elf/lib"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
+
+// Check driver error when lto is used without specified lld linker.
+// RUN: env "PATH=" %clang -### %s -flto \
+// RUN:   --target=riscv64-unknown-elf --rtlib=platform --sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64: clang-16: error: 
'riscv64-unknown-unknown-elf': unable to pass LLVM bit-code files to linker
+
 // RUN: env "PATH=" %clang -### %s -fuse-ld=ld \
 // RUN:   --target=riscv64-unknown-elf --rtlib=platform --unwindlib=platform 
--sysroot= \
 // RUN:   -march=rv64imafdc -mabi=lp64d \

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


[clang] Use the correct namespace for looking up matching operator!= (PR #68922)

2023-10-16 Thread Utkarsh Saxena via cfe-commits

usx95 wrote:

Thanks @zygoloid.
This case was failing with my change. Corrected and added tests.

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


[clang] Use the correct namespace for looking up matching operator!= (PR #68922)

2023-10-16 Thread Utkarsh Saxena via cfe-commits

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

>From 0c71b6bdd557ff4b9ad9a4ec4f0919e3460596b0 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 12 Oct 2023 21:35:52 +0200
Subject: [PATCH 1/4] Find opertor!= in the correct namespace

---
 clang/lib/Sema/SemaOverload.cpp   |  7 +-
 .../over.match.oper/p3-2a.cpp | 24 +++
 2 files changed, 25 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index ce78994e6553814..e1e0b4a888e49fa 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -960,12 +960,7 @@ static bool shouldAddReversedEqEq(Sema &S, SourceLocation 
OpLoc,
 return true;
   }
   // Otherwise the search scope is the namespace scope of which F is a member.
-  LookupResult NonMembers(S, NotEqOp, OpLoc,
-  Sema::LookupNameKind::LookupOperatorName);
-  S.LookupName(NonMembers,
-   S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
-  NonMembers.suppressAccessDiagnostics();
-  for (NamedDecl *Op : NonMembers) {
+  for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
 auto *FD = Op->getAsFunction();
 if(auto* UD = dyn_cast(Op))
   FD = UD->getUnderlyingDecl()->getAsFunction();
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
index 5c6804eb7726b5f..7142ed22ddb22ca 100644
--- a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
+++ b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
@@ -324,6 +324,30 @@ bool x = X() == X(); // expected-warning {{ambiguous}}
 }
 } // namespace P2468R2
 
+namespace ADL_GH68901{
+namespace A {
+struct S {};
+bool operator==(S, int); // expected-note {{no known conversion from 'int' to 
'S' for 1st argument}}
+bool operator!=(S, int);
+} // namespace A
+bool a = 0 == A::S(); // expected-error {{invalid operands to binary 
expression ('int' and 'A::S')}}
+
+namespace B {
+struct Derived {};
+struct Base : Derived {};
+
+bool operator==(Derived& a, Base& b);
+bool operator!=(Derived& a, Base& b);
+}  // namespace B
+
+void foo() {
+  // B::Base{} == B::Base{};
+  B::Base a,b;
+  bool v = a == b;
+}
+} //namespace ADL_GH68901
+
+
 #else // NO_ERRORS
 
 namespace problem_cases {

>From eb7ac047b269d71e4fc7afbbb8b8f65e857ff3a3 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 12 Oct 2023 21:48:20 +0200
Subject: [PATCH 2/4] Add release notes

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..c5b5f665ce9834c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -64,6 +64,10 @@ C/C++ Language Potentially Breaking Changes
 ``__has_c_attribute(warn_unused_result)``,  202003, 0
 ``__has_c_attribute(gnu::warn_unused_result)``, 202003, 1
 
+- Fixed a bug in finding matching `operator!=` while adding reveresed 
`operator==` as
+  outlined in "The Equality Operator You Are Looking For" (`P2468 
`_).
+  Fixes (`#68901: `_).
+
 C++ Specific Potentially Breaking Changes
 -
 - The name mangling rules for function templates has been changed to take into

>From 73d48e546775290196c5a5fbe2922d26df29f013 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 13 Oct 2023 12:28:29 +0200
Subject: [PATCH 3/4] fix a typo

---
 clang/docs/ReleaseNotes.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c5b5f665ce9834c..88cbf1d864da400 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -64,7 +64,7 @@ C/C++ Language Potentially Breaking Changes
 ``__has_c_attribute(warn_unused_result)``,  202003, 0
 ``__has_c_attribute(gnu::warn_unused_result)``, 202003, 1
 
-- Fixed a bug in finding matching `operator!=` while adding reveresed 
`operator==` as
+- Fixed a bug in finding matching `operator!=` while adding reversed 
`operator==` as
   outlined in "The Equality Operator You Are Looking For" (`P2468 
`_).
   Fixes (`#68901: `_).
 

>From 8e26dd5732e4cef11a3f3c6e278147b11ae01ac8 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Mon, 16 Oct 2023 12:15:05 +0200
Subject: [PATCH 4/4] Add tests for function scope operators

---
 clang/lib/Sema/SemaOverload.cpp   | 12 +++
 .../over.match.oper/p3-2a.cpp | 32 +++
 2 files changed, 38 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index e1e0b4a888e4

[clang] [clang-format] Don't align comments over scopes (PR #68743)

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


@@ -1118,16 +1121,40 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+const bool DontAlignThisComment = [&] {
+  if (I == 0)
+return false;
+  if (C.NewlinesBefore != 0)
+return false;
+  const auto &PrevChange = Changes[I - 1];
+  if (PrevChange.Tok->is(tok::r_brace))
+return true;
+  if (PrevChange.Tok->is(tok::semi)) {
+if (auto PrevNonComment = PrevChange.Tok->getPreviousNonComment()) {
+  if (PrevNonComment->is(tok::r_paren) &&
+  PrevNonComment->MatchingParen &&
+  PrevNonComment->MatchingParen->endsSequence(
+  tok::l_paren, tok::kw_while, TT_ControlStatementRBrace)) {
+return true;
+  }
+  return PrevNonComment->isOneOf(
+  TT_ClassRBrace, TT_ControlStatementRBrace, TT_ElseRBrace,
+  TT_EnumRBrace, TT_NamespaceRBrace, TT_RecordRBrace,
+  TT_StructRBrace, TT_UnionRBrace);
+}
+  }
+  return false;

owenca wrote:

We can skip do-while loops (or handle them in another patch) because we would 
also need to handle those without braces or with the closing brace on its own 
line.

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

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


@@ -1118,16 +1121,40 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+const bool DontAlignThisComment = [&] {
+  if (I == 0)
+return false;
+  if (C.NewlinesBefore != 0)
+return false;
+  const auto &PrevChange = Changes[I - 1];
+  if (PrevChange.Tok->is(tok::r_brace))
+return true;
+  if (PrevChange.Tok->is(tok::semi)) {
+if (auto PrevNonComment = PrevChange.Tok->getPreviousNonComment()) {
+  if (PrevNonComment->is(tok::r_paren) &&
+  PrevNonComment->MatchingParen &&
+  PrevNonComment->MatchingParen->endsSequence(
+  tok::l_paren, tok::kw_while, TT_ControlStatementRBrace)) {
+return true;
+  }
+  return PrevNonComment->isOneOf(
+  TT_ClassRBrace, TT_ControlStatementRBrace, TT_ElseRBrace,
+  TT_EnumRBrace, TT_NamespaceRBrace, TT_RecordRBrace,
+  TT_StructRBrace, TT_UnionRBrace);
+}
+  }
+  return false;

owenca wrote:

```suggestion
  if (I == 0 || C.NewlinesBefore > 0)
return false;
  const auto *Tok = Changes[I - 1].Tok;
  if (Tok->is(tok::semi)) {
Tok = Tok->Previous;
if (!Tok)
  return false;
  }
  if (Tok->isNot(tok::r_brace))
return false;
  while (Tok->Previous && Tok->Previous->is(tok::r_brace))
Tok = Tok->Previous;
  return Tok->NewlinesBefore > 0;
```

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


[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 


https://github.com/DonatNagyE updated 
https://github.com/llvm/llvm-project/pull/67572

>From 7bd280e2da3f2ee8fe5fd7086a4704331f21b435 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Wed, 6 Sep 2023 13:39:27 +0200
Subject: [PATCH 1/2] [analyzer][NFC] Simplifications in ArrayBoundV2

I'm planning to improve diagnostics generation in `ArrayBoundCheckerV2`
but before that I'm refactoring the source code to clean up some
over-complicated code and an inaccurate comment.

Changes in this commit:
- Remove the `mutable std::unique_ptr` boilerplate, because
  it's no longer needed.
- Remove the code duplication between the methods `reportOOB()` and
  `reportTaintedOOB()`.
- Eliminate the class `RegionRawOffsetV2` because it's just a "reinvent
  the wheel" version of `std::pair` and it was used only once, as a
  temporary object that was immediately decomposed. (I suspect that
  `RegionRawOffset` in MemRegion.cpp could also be eliminated.)
- Flatten the code of `computeOffset()` which had contained six nested
  indentation levels before this commit.
- Ensure that `computeOffset()` returns `std::nullopt` instead of a
  `{Region, }` pair in the case when it encounters a
  `Location` that is not an `ElementRegion`. This ensures that the
  `checkLocation` callback returns early when it handles a memory access
  where it has "nothing to do" (no subscript operation or equivalent
  pointer arithmetic). (Note that this is still NFC because zero is a
  valid index everywhere, so the old logic without this shortcut
  eventually reached the same conclusion.)
- Correct a wrong explanation comment in `getSimplifiedOffsets()`.
---
 .../Checkers/ArrayBoundCheckerV2.cpp  | 221 +++---
 1 file changed, 86 insertions(+), 135 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
index db4a2fcea9b2cdd..c2ffcdf5e306d1f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -32,15 +32,13 @@ using namespace taint;
 namespace {
 class ArrayBoundCheckerV2 :
 public Checker {
-  mutable std::unique_ptr BT;
-  mutable std::unique_ptr TaintBT;
+  BugType BT{this, "Out-of-bound access"};
+  BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
 
-  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
- OOB_Kind kind) const;
-  void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
-  SVal TaintedSVal) const;
+  void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
+ SVal TaintedSVal = UnknownVal()) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
@@ -48,26 +46,58 @@ class ArrayBoundCheckerV2 :
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
 };
+} // anonymous namespace
 
-// FIXME: Eventually replace RegionRawOffset with this class.
-class RegionRawOffsetV2 {
-private:
-  const SubRegion *baseRegion;
-  NonLoc byteOffset;
+/// For a given Location that can be represented as a symbolic expression
+/// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
+/// Arr and the distance of Location from the beginning of Arr (expressed in a
+/// NonLoc that specifies the number of CharUnits). Returns nullopt when these
+/// cannot be determined.
+std::optional>
+computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
+  QualType T = SVB.getArrayIndexType();
+  auto Calc = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc RHS) {
+// We will use this utility to add and multiply values.
+return SVB.evalBinOpNN(State, Op, LHS, RHS, T).getAs();
+  };
 
-public:
-  RegionRawOffsetV2(const SubRegion *base, NonLoc offset)
-  : baseRegion(base), byteOffset(offset) { assert(base); }
+  const auto *Region = dyn_cast_or_null(Location.getAsRegion());
+  std::optional Offset = std::nullopt;
+
+  while (const auto *ERegion = dyn_cast_or_null(Region)) {
+const auto Index = ERegion->getIndex().getAs();
+if (!Index)
+  return std::nullopt;
+
+QualType ElemType = ERegion->getElementType();
+// If the element is an incomplete type, go no further.
+if (ElemType->isIncompleteType())
+  return std::nullopt;
+
+// Calculate Delta = Index * sizeof(ElemType).
+NonLoc Size = SVB.makeArrayIndex(
+SVB.getContext().getTypeSizeInChars(ElemType).getQuantity());
+auto Delta = Calc(BO_Mul, *Index, Size);
+if (!Delta)
+  return std::nullopt;
+
+// Perform Offset += Delta, handling the initial nullopt as 0.
+if (!Offset) {
+  Offset = Delta;
+} else {
+  Offset = Calc(BO_Add, *Offset, *Delta

[clang] [clang-format] Don't align comments over scopes (PR #68743)

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


@@ -20794,7 +20794,7 @@ TEST_F(FormatTest, 
CatchAlignArrayOfStructuresRightAlignment) {
   verifyFormat("int a[][] = {\n"
"{\n"
" {0, 2}, //\n"
-   " {1, 2}  //\n"
+   " {1, 2} //\n"

owenca wrote:

We don't need to change the test case with 
https://github.com/llvm/llvm-project/pull/68743#discussion_r1360437969.

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


[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 



@@ -32,42 +32,72 @@ using namespace taint;
 namespace {
 class ArrayBoundCheckerV2 :
 public Checker {
-  mutable std::unique_ptr BT;
-  mutable std::unique_ptr TaintBT;
+  BugType BT{this, "Out-of-bound access"};
+  BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
 
-  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
- OOB_Kind kind) const;
-  void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
-  SVal TaintedSVal) const;
+  void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
+ SVal TaintedSVal = UnknownVal()) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
 public:
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
 };
+} // anonymous namespace
 
-// FIXME: Eventually replace RegionRawOffset with this class.
-class RegionRawOffsetV2 {
-private:
-  const SubRegion *baseRegion;
-  NonLoc byteOffset;
+/// For a given Location that can be represented as a symbolic expression
+/// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
+/// Arr and the distance of Location from the beginning of Arr (expressed in a
+/// NonLoc that specifies the number of CharUnits). Returns nullopt when these
+/// cannot be determined.
+std::optional>
+computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
+  QualType T = SVB.getArrayIndexType();
+  auto Calc = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc RHS) {
+// We will use this utility to add and multiply values.
+return SVB.evalBinOpNN(State, Op, LHS, RHS, T).getAs();
+  };
 
-public:
-  RegionRawOffsetV2(const SubRegion *base, NonLoc offset)
-  : baseRegion(base), byteOffset(offset) { assert(base); }
+  const auto *Region = dyn_cast_or_null(Location.getAsRegion());
+  std::optional Offset = std::nullopt;

DonatNagyE wrote:

Also note that creating zero-valued `NonLoc` (with the appropriate type...) is 
approximately two lines of code, so overall this solution is less verbose than 
using a separate early return to filter out the situations when the initial 
value of `Region` is not an `ElementRegion`. 

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

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


@@ -1118,16 +1121,40 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+const bool DontAlignThisComment = [&] {
+  if (I == 0)
+return false;
+  if (C.NewlinesBefore != 0)
+return false;
+  const auto &PrevChange = Changes[I - 1];
+  if (PrevChange.Tok->is(tok::r_brace))
+return true;
+  if (PrevChange.Tok->is(tok::semi)) {
+if (auto PrevNonComment = PrevChange.Tok->getPreviousNonComment()) {
+  if (PrevNonComment->is(tok::r_paren) &&
+  PrevNonComment->MatchingParen &&
+  PrevNonComment->MatchingParen->endsSequence(
+  tok::l_paren, tok::kw_while, TT_ControlStatementRBrace)) {
+return true;
+  }
+  return PrevNonComment->isOneOf(
+  TT_ClassRBrace, TT_ControlStatementRBrace, TT_ElseRBrace,
+  TT_EnumRBrace, TT_NamespaceRBrace, TT_RecordRBrace,
+  TT_StructRBrace, TT_UnionRBrace);
+}
+  }
+  return false;

owenca wrote:

This would also fix a couple of test cases in 
FormatTestComments.DontAlignNamespaceComments.

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

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


@@ -1118,16 +1121,40 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+const bool DontAlignThisComment = [&] {
+  if (I == 0)
+return false;
+  if (C.NewlinesBefore != 0)
+return false;
+  const auto &PrevChange = Changes[I - 1];
+  if (PrevChange.Tok->is(tok::r_brace))
+return true;
+  if (PrevChange.Tok->is(tok::semi)) {
+if (auto PrevNonComment = PrevChange.Tok->getPreviousNonComment()) {
+  if (PrevNonComment->is(tok::r_paren) &&
+  PrevNonComment->MatchingParen &&
+  PrevNonComment->MatchingParen->endsSequence(
+  tok::l_paren, tok::kw_while, TT_ControlStatementRBrace)) {
+return true;
+  }
+  return PrevNonComment->isOneOf(
+  TT_ClassRBrace, TT_ControlStatementRBrace, TT_ElseRBrace,
+  TT_EnumRBrace, TT_NamespaceRBrace, TT_RecordRBrace,
+  TT_StructRBrace, TT_UnionRBrace);
+}
+  }
+  return false;

owenca wrote:

See https://github.com/llvm/llvm-project/issues/67906#issuecomment-1764110372.

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

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


@@ -3191,20 +3191,120 @@ TEST_F(FormatTestComments, DontAlignNamespaceComments) 
{
   "}\n"
   "// Comment";
 
-#if 0
-  // FIXME: The following comment is aligned with the namespace comment.
   verifyFormat("namespace A {\n"
"  int Foo;\n"
"  int Bar;\n"
"} // namespace A\n"
-   " // Comment",
+   "// Comment",
Input, Style);
-#endif
 
   Style.FixNamespaceComments = false;
   verifyFormat(Input, Style);
 }
 
+TEST_F(FormatTestComments, DontAlignOverScope) {
+  verifyFormat("if (foo) {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("if (foo) {\n"
+   "  // something\n"
+   "} else {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("if (foo) {\n"
+   "  // something\n"
+   "} else if (foo) {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("while (foo) {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("for (;;) {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("do {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} while (foo); // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("switch (foo) {\n"
+   "case 7: {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // case not aligned\n"
+   "} // switch also not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("switch (foo) {\n"
+   "default: {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "} // case not aligned\n"
+   "} // switch also not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("class C {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "}; // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("struct S {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "}; // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("union U {\n"
+   "  int aLongVariable; // with comment\n"
+   "  int f; // aligned\n"
+   "}; // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("enum E {\n"
+   "  aLongVariable, // with comment\n"
+   "  f  // aligned\n"
+   "}; // not aligned\n"
+   "int bar;// new align\n"
+   "int foobar; // group");
+
+  verifyFormat("void foo() {\n"
+   "  {\n"
+   "int aLongVariable; // with comment\n"
+   "int f; // aligned\n"
+   "  } // not aligned\n"
+   "  int bar;// new align\n"
+   "  int foobar; // group\n"
+   "}");
+}
+

owenca wrote:

We can (and should) handle lambdas with 
https://github.com/llvm/llvm-project/pull/68743#discussion_r1360437969.

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


[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 


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 b22917e6e2a0aec05474f58e64b7e87d1ea0a054 
59bccd98022f61e6a656dca6ac3fc5622f994226 -- 
clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
index 0b53aa9b2051..6819cd6a6b90 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -56,7 +56,8 @@ public:
 std::optional>
 computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
   QualType T = SVB.getArrayIndexType();
-  auto EvalBinOp = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc 
RHS) {
+  auto EvalBinOp = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS,
+NonLoc RHS) {
 // We will use this utility to add and multiply values.
 return SVB.evalBinOpNN(State, Op, LHS, RHS, T).getAs();
   };

``




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


[clang] [clang-format] Allow default values for template parameters in lambda (PR #69052)

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

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


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


[clang] [clang-format] Allow default values for template parameters in lambda (PR #69052)

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

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


[clang] [clang-format] Allow default values for template parameters in lambda (PR #69052)

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


@@ -2268,6 +2265,12 @@ bool UnwrappedLineParser::tryToParseLambda() {
   parseRequiresClause(RequiresToken);
   break;
 }
+case tok::equal:
+  if (InTemplateParameterList) {
+nextToken();
+break;
+  }
+  return true;

owenca wrote:

```suggestion
  if (!InTemplateParameterList)
return true;
  nextToken();
  break;
```

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


[clang] [clang-format] Allow default values for template parameters in lambda (PR #69052)

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


@@ -2268,6 +2265,12 @@ bool UnwrappedLineParser::tryToParseLambda() {
   parseRequiresClause(RequiresToken);
   break;
 }
+case tok::equal:
+  if (InTemplateParameterList) {
+nextToken();
+break;
+  }
+  return true;

owenca wrote:

Nit.

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


[clang] [Driver] Link Flang runtime on Solaris (PR #65644)

2023-10-16 Thread Rainer Orth via cfe-commits

rorth wrote:

> I feel that we are bike-shedding here a bit. Please prioritise correctness - 
> using `GNU` as a label for Solaris would not be correct. The following would 
> be:
> 
> * duplicating tests with a different label (e.g. `SOLARIS`) would be 
> correct,
> 
> * renaming the current label from `GNU` to e.g. `UNIX` would be correct.
> 
> 
> Unless I am missing something?

I'd go for renaming the label to `UNIX` then: it avoids unnecessary duplication 
and better describes what those cases are about.

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


[clang] [clang][Interp] Handle delegating constructors (PR #67823)

2023-10-16 Thread via cfe-commits

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

LGTM

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


[clang] [clang-format] Allow default values for template parameters in lambda (PR #69052)

2023-10-16 Thread Emilia Kond via cfe-commits

https://github.com/rymiel updated 
https://github.com/llvm/llvm-project/pull/69052

>From 4f532ab0ae47bce011043f41cfac3ad3e601dd41 Mon Sep 17 00:00:00 2001
From: Emilia Kond 
Date: Sat, 14 Oct 2023 16:52:31 +0300
Subject: [PATCH 1/2] [clang-format] Allow default values for template
 parameters in lambda

Previously, upon encountering an equals sign while parsing a lambda in
the UnwrappedLineParser, it would fall through and fail. This caused any
lambda template with a default argument for a template parameter to be
annotated as an ArraySubscriptLSquare.

This patch allows equals signs in the UnwrappedLineParser if we're
currently in a template parameter list. This resolved a FIXME that was
in the lambda parsing function.

This patch seems deceptively easy, it's likely it doesn't solve the
FIXME entirely, or causes other issues (the FIXME itself mentions
something about Objective-C, which I cannot comment about). However this
patch is sufficient to fix the below issue.

Fixes https://github.com/llvm/llvm-project/issues/68913
---
 clang/lib/Format/UnwrappedLineParser.cpp  |  9 +++--
 clang/unittests/Format/TokenAnnotatorTest.cpp | 38 +++
 2 files changed, 44 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 82a812fc8bcc610..45a3fdbb5ba12e0 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2226,9 +2226,6 @@ bool UnwrappedLineParser::tryToParseLambda() {
 // followed by an `a->b` expression, such as:
 // ([obj func:arg] + a->b)
 // Otherwise the code below would parse as a lambda.
-//
-// FIXME: This heuristic is incorrect for C++20 generic lambdas with
-// explicit template lists: [](U &&u){}
 case tok::plus:
 case tok::minus:
 case tok::exclaim:
@@ -2268,6 +2265,12 @@ bool UnwrappedLineParser::tryToParseLambda() {
   parseRequiresClause(RequiresToken);
   break;
 }
+case tok::equal:
+  if (InTemplateParameterList) {
+nextToken();
+break;
+  }
+  return true;
 default:
   return true;
 }
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index b6d4cf166de0281..f4f382cfe8f2494 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1620,6 +1620,44 @@ TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   EXPECT_TOKEN(Tokens[15], tok::kw_requires, TT_RequiresClause);
   EXPECT_TRUE(Tokens[19]->ClosesRequiresClause);
   EXPECT_TOKEN(Tokens[20], tok::l_brace, TT_LambdaLBrace);
+
+  Tokens = annotate("[]  (T t) {}");
+  ASSERT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[2], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[7], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[12], tok::l_brace, TT_LambdaLBrace);
+
+  Tokens = annotate("[]  (T t) {}");
+  ASSERT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[2], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[7], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[12], tok::l_brace, TT_LambdaLBrace);
+
+  Tokens = annotate("[]  (T t) {}");
+  ASSERT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[2], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[7], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[12], tok::l_brace, TT_LambdaLBrace);
+
+  Tokens = annotate("[]  (T&& t) {}");
+  ASSERT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[2], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[7], tok::ampamp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[9], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[12], tok::ampamp, TT_PointerOrReference);
+  EXPECT_TOKEN(Tokens[15], tok::l_brace, TT_LambdaLBrace);
+
+  Tokens = annotate("[]  requires Foo (T t) {}");
+  ASSERT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[2], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[7], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[8], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TOKEN(Tokens[17], tok::l_brace, TT_LambdaLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsFunctionAnnotations) {

>From 819938fb70e3d6ff7558dfa565c94416ac203140 Mon Sep 17 00:00:00 2001
From: Emilia Kond 
Date: Mon, 16 Oct 2023 13:51:22 +0300
Subject: [PATCH 2/2] Suggestion from code review

Co-authored-by: Owen Pan 
---
 clang/lib/Format/UnwrappedLineParser.cpp | 9 -
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 45a3fdbb5b

[clang] [analyzer] Trust base to derived casts for dynamic types (PR #69057)

2023-10-16 Thread via cfe-commits

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


[clang] [analyzer] Trust base to derived casts for dynamic types (PR #69057)

2023-10-16 Thread via cfe-commits

https://github.com/DonatNagyE commented:

The only thing that I know about the dynamic type handling is that it's not too 
reliable; it would be great if you could improve it.

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


[clang] [analyzer] Trust base to derived casts for dynamic types (PR #69057)

2023-10-16 Thread via cfe-commits


@@ -0,0 +1,105 @@
+// RUN: %clang_analyze_cc1 %s -verify \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.security.taint.TaintPropagation \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+// See issue https://github.com/llvm/llvm-project/issues/62663
+
+template  void clang_analyzer_dump(T);
+void clang_analyzer_warnIfReached();
+void clang_analyzer_numTimesReached();
+void clang_analyzer_isTainted(int);
+
+extern int scanf(const char *format, ...);
+
+class ActionHandler {
+public:
+  virtual ~ActionHandler() = default;
+  virtual void onAction(int x, int &) {
+clang_analyzer_dump(x + 1); // expected-warning {{101}}
+  }
+};
+
+class MyHandler final : public ActionHandler {
+public:
+  void onAction(int x, int &) override {
+clang_analyzer_dump(x + 2); // expected-warning {{202}}
+  }
+};
+
+void trust_static_types(ActionHandler *p) {
+  // This variable will help to see if conservative call evaluation happened 
or not.
+  int invalidation_detector;
+
+  // At this point we don't know anything about the dynamic type of `*p`, thus 
the `onAction` call might be resolved to the default implementation, matching 
the static type.
+  invalidation_detector = 1000;
+  p->onAction(100, invalidation_detector);
+  clang_analyzer_dump(invalidation_detector);
+  // expected-warning@-1 {{1000}} on this path we trusted the type, and 
resolved the call to `ActionHandler::onAction(int, int&)`
+  // expected-warning@-2 {{conj}} on this path we conservatively evaluated the 
previous call
+
+  clang_analyzer_numTimesReached(); // expected-warning {{2}} we only have 
that 2 paths here
+  // 1) inlined `ActionHandler::onAction(int, int&)`
+  // 2) conservatively eval called
+
+  // Trust that the `*p` refers to an object with `MyHandler` static type (or 
to some other sub-class).
+  auto *q = static_cast(p);
+  (void)q; // Discard the result of the cast. We already learned the type `p` 
might refer to.
+
+  invalidation_detector = 2000;
+  p->onAction(200, invalidation_detector);
+  clang_analyzer_dump(invalidation_detector);
+  // expected-warning@-1 {{2000}} on this path we trusted the type, and 
resolved the call to `MyHandler::onAction(int, int&)`
+  // expected-warning@-2 {{conj}} on this path we conservatively evaluated the 
previous call
+
+  clang_analyzer_numTimesReached(); // expected-warning {{3}} we only have 3 
paths here, not 4
+  // 1) inlined 2 different callees
+  // 2) inlined only 1st
+  // 3) non were inlined

DonatNagyE wrote:

This line seems to be garbled.

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


[clang] [analyzer] Trust base to derived casts for dynamic types (PR #69057)

2023-10-16 Thread via cfe-commits


@@ -392,19 +393,26 @@ void DynamicTypePropagation::checkPostCall(const 
CallEvent &Call,
   }
 }
 
-/// TODO: Handle explicit casts.
-///   Handle C++ casts.
-///
-/// Precondition: the cast is between ObjCObjectPointers.
 ExplodedNode *DynamicTypePropagation::dynamicTypePropagationOnCasts(
 const CastExpr *CE, ProgramStateRef &State, CheckerContext &C) const {
   // We only track type info for regions.
   const MemRegion *ToR = C.getSVal(CE).getAsRegion();
   if (!ToR)
 return C.getPredecessor();
 
-  if (isa(CE))
+  if (CE->getCastKind() == CK_BaseToDerived) {
+bool CastSucceeds = true;

DonatNagyE wrote:

Based on a rough intuition I feel that it's suspicious that here the code 
blindly assumes that the cast succeeds instead of checking the previously 
collected knowledge and somehow reporting an error if the cast contradicts it.

However I don't understand the exact details, so this might be the correct 
heuristic depending on other factors.

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


[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 


https://github.com/DonatNagyE updated 
https://github.com/llvm/llvm-project/pull/67572

>From 7bd280e2da3f2ee8fe5fd7086a4704331f21b435 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Wed, 6 Sep 2023 13:39:27 +0200
Subject: [PATCH 1/3] [analyzer][NFC] Simplifications in ArrayBoundV2

I'm planning to improve diagnostics generation in `ArrayBoundCheckerV2`
but before that I'm refactoring the source code to clean up some
over-complicated code and an inaccurate comment.

Changes in this commit:
- Remove the `mutable std::unique_ptr` boilerplate, because
  it's no longer needed.
- Remove the code duplication between the methods `reportOOB()` and
  `reportTaintedOOB()`.
- Eliminate the class `RegionRawOffsetV2` because it's just a "reinvent
  the wheel" version of `std::pair` and it was used only once, as a
  temporary object that was immediately decomposed. (I suspect that
  `RegionRawOffset` in MemRegion.cpp could also be eliminated.)
- Flatten the code of `computeOffset()` which had contained six nested
  indentation levels before this commit.
- Ensure that `computeOffset()` returns `std::nullopt` instead of a
  `{Region, }` pair in the case when it encounters a
  `Location` that is not an `ElementRegion`. This ensures that the
  `checkLocation` callback returns early when it handles a memory access
  where it has "nothing to do" (no subscript operation or equivalent
  pointer arithmetic). (Note that this is still NFC because zero is a
  valid index everywhere, so the old logic without this shortcut
  eventually reached the same conclusion.)
- Correct a wrong explanation comment in `getSimplifiedOffsets()`.
---
 .../Checkers/ArrayBoundCheckerV2.cpp  | 221 +++---
 1 file changed, 86 insertions(+), 135 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
index db4a2fcea9b2cdd..c2ffcdf5e306d1f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -32,15 +32,13 @@ using namespace taint;
 namespace {
 class ArrayBoundCheckerV2 :
 public Checker {
-  mutable std::unique_ptr BT;
-  mutable std::unique_ptr TaintBT;
+  BugType BT{this, "Out-of-bound access"};
+  BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
 
-  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
- OOB_Kind kind) const;
-  void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
-  SVal TaintedSVal) const;
+  void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
+ SVal TaintedSVal = UnknownVal()) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
@@ -48,26 +46,58 @@ class ArrayBoundCheckerV2 :
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
 };
+} // anonymous namespace
 
-// FIXME: Eventually replace RegionRawOffset with this class.
-class RegionRawOffsetV2 {
-private:
-  const SubRegion *baseRegion;
-  NonLoc byteOffset;
+/// For a given Location that can be represented as a symbolic expression
+/// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
+/// Arr and the distance of Location from the beginning of Arr (expressed in a
+/// NonLoc that specifies the number of CharUnits). Returns nullopt when these
+/// cannot be determined.
+std::optional>
+computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
+  QualType T = SVB.getArrayIndexType();
+  auto Calc = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc RHS) {
+// We will use this utility to add and multiply values.
+return SVB.evalBinOpNN(State, Op, LHS, RHS, T).getAs();
+  };
 
-public:
-  RegionRawOffsetV2(const SubRegion *base, NonLoc offset)
-  : baseRegion(base), byteOffset(offset) { assert(base); }
+  const auto *Region = dyn_cast_or_null(Location.getAsRegion());
+  std::optional Offset = std::nullopt;
+
+  while (const auto *ERegion = dyn_cast_or_null(Region)) {
+const auto Index = ERegion->getIndex().getAs();
+if (!Index)
+  return std::nullopt;
+
+QualType ElemType = ERegion->getElementType();
+// If the element is an incomplete type, go no further.
+if (ElemType->isIncompleteType())
+  return std::nullopt;
+
+// Calculate Delta = Index * sizeof(ElemType).
+NonLoc Size = SVB.makeArrayIndex(
+SVB.getContext().getTypeSizeInChars(ElemType).getQuantity());
+auto Delta = Calc(BO_Mul, *Index, Size);
+if (!Delta)
+  return std::nullopt;
+
+// Perform Offset += Delta, handling the initial nullopt as 0.
+if (!Offset) {
+  Offset = Delta;
+} else {
+  Offset = Cal

[clang] [analyzer][NFC] Simplifications in ArrayBoundV2 (PR #67572)

2023-10-16 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy ,
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 



@@ -32,42 +32,72 @@ using namespace taint;
 namespace {
 class ArrayBoundCheckerV2 :
 public Checker {
-  mutable std::unique_ptr BT;
-  mutable std::unique_ptr TaintBT;
+  BugType BT{this, "Out-of-bound access"};
+  BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
 
-  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
- OOB_Kind kind) const;
-  void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
-  SVal TaintedSVal) const;
+  void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
+ SVal TaintedSVal = UnknownVal()) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
 public:
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
 };
+} // anonymous namespace
 
-// FIXME: Eventually replace RegionRawOffset with this class.
-class RegionRawOffsetV2 {
-private:
-  const SubRegion *baseRegion;
-  NonLoc byteOffset;
+/// For a given Location that can be represented as a symbolic expression
+/// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
+/// Arr and the distance of Location from the beginning of Arr (expressed in a
+/// NonLoc that specifies the number of CharUnits). Returns nullopt when these
+/// cannot be determined.
+std::optional>
+computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
+  QualType T = SVB.getArrayIndexType();
+  auto Calc = [&SVB, State, T](BinaryOperatorKind Op, NonLoc LHS, NonLoc RHS) {

DonatNagyE wrote:

Now I recall why I picked the short name -- it's the definition of the lambda 
where a longer name doesn't fit. However, I was just able to squeeze 
`EvalBinOp` in by reducing `LHS` and `RHS` to `L` and `R` (which seems to be 
enough in a single-line lambda). 

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2023-10-16 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> I highly recommend talking to @mathstuf of the CMake project about a way for 
> the build system can emit a next generation set of build graph metadata 
> (think modules appropriate compile commands, including dependencies).
> 
> I expect it will be more efficient for the build system, compiler, and LSP to 
> all work together compared to implementing large subsets of a build system in 
> the clangd LSP.

Yeah, yeah, of course. This is listed as the second step of `What we need to do 
next` section. And for the patch itself, it is just an initial move in the 
clangd for C++20 modules. Since it is complex so that we decide to split the 
works into several patches to make sure every one could be in the same page. 
I've already left the space to extend how we find the map from module name to 
source files later. But now I prefer to not change the design even if it looks 
unefficient clearly.

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


[clang] [analyzer] Trust base to derived casts for dynamic types (PR #69057)

2023-10-16 Thread Balazs Benics via cfe-commits


@@ -0,0 +1,105 @@
+// RUN: %clang_analyze_cc1 %s -verify \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.security.taint.TaintPropagation \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+// See issue https://github.com/llvm/llvm-project/issues/62663
+
+template  void clang_analyzer_dump(T);
+void clang_analyzer_warnIfReached();
+void clang_analyzer_numTimesReached();
+void clang_analyzer_isTainted(int);
+
+extern int scanf(const char *format, ...);
+
+class ActionHandler {
+public:
+  virtual ~ActionHandler() = default;
+  virtual void onAction(int x, int &) {
+clang_analyzer_dump(x + 1); // expected-warning {{101}}
+  }
+};
+
+class MyHandler final : public ActionHandler {
+public:
+  void onAction(int x, int &) override {
+clang_analyzer_dump(x + 2); // expected-warning {{202}}
+  }
+};
+
+void trust_static_types(ActionHandler *p) {
+  // This variable will help to see if conservative call evaluation happened 
or not.
+  int invalidation_detector;
+
+  // At this point we don't know anything about the dynamic type of `*p`, thus 
the `onAction` call might be resolved to the default implementation, matching 
the static type.
+  invalidation_detector = 1000;
+  p->onAction(100, invalidation_detector);
+  clang_analyzer_dump(invalidation_detector);
+  // expected-warning@-1 {{1000}} on this path we trusted the type, and 
resolved the call to `ActionHandler::onAction(int, int&)`
+  // expected-warning@-2 {{conj}} on this path we conservatively evaluated the 
previous call
+
+  clang_analyzer_numTimesReached(); // expected-warning {{2}} we only have 
that 2 paths here
+  // 1) inlined `ActionHandler::onAction(int, int&)`
+  // 2) conservatively eval called
+
+  // Trust that the `*p` refers to an object with `MyHandler` static type (or 
to some other sub-class).
+  auto *q = static_cast(p);
+  (void)q; // Discard the result of the cast. We already learned the type `p` 
might refer to.
+
+  invalidation_detector = 2000;
+  p->onAction(200, invalidation_detector);
+  clang_analyzer_dump(invalidation_detector);
+  // expected-warning@-1 {{2000}} on this path we trusted the type, and 
resolved the call to `MyHandler::onAction(int, int&)`
+  // expected-warning@-2 {{conj}} on this path we conservatively evaluated the 
previous call
+
+  clang_analyzer_numTimesReached(); // expected-warning {{3}} we only have 3 
paths here, not 4
+  // 1) inlined 2 different callees
+  // 2) inlined only 1st
+  // 3) non were inlined

steakhal wrote:

Looks as I intended.

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


[clang] [analyzer] Trust base to derived casts for dynamic types (PR #69057)

2023-10-16 Thread via cfe-commits


@@ -0,0 +1,105 @@
+// RUN: %clang_analyze_cc1 %s -verify \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.security.taint.TaintPropagation \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+// See issue https://github.com/llvm/llvm-project/issues/62663
+
+template  void clang_analyzer_dump(T);
+void clang_analyzer_warnIfReached();
+void clang_analyzer_numTimesReached();
+void clang_analyzer_isTainted(int);
+
+extern int scanf(const char *format, ...);
+
+class ActionHandler {
+public:
+  virtual ~ActionHandler() = default;
+  virtual void onAction(int x, int &) {
+clang_analyzer_dump(x + 1); // expected-warning {{101}}
+  }
+};
+
+class MyHandler final : public ActionHandler {
+public:
+  void onAction(int x, int &) override {
+clang_analyzer_dump(x + 2); // expected-warning {{202}}
+  }
+};
+
+void trust_static_types(ActionHandler *p) {
+  // This variable will help to see if conservative call evaluation happened 
or not.
+  int invalidation_detector;
+
+  // At this point we don't know anything about the dynamic type of `*p`, thus 
the `onAction` call might be resolved to the default implementation, matching 
the static type.
+  invalidation_detector = 1000;
+  p->onAction(100, invalidation_detector);
+  clang_analyzer_dump(invalidation_detector);
+  // expected-warning@-1 {{1000}} on this path we trusted the type, and 
resolved the call to `ActionHandler::onAction(int, int&)`
+  // expected-warning@-2 {{conj}} on this path we conservatively evaluated the 
previous call
+
+  clang_analyzer_numTimesReached(); // expected-warning {{2}} we only have 
that 2 paths here
+  // 1) inlined `ActionHandler::onAction(int, int&)`
+  // 2) conservatively eval called
+
+  // Trust that the `*p` refers to an object with `MyHandler` static type (or 
to some other sub-class).
+  auto *q = static_cast(p);
+  (void)q; // Discard the result of the cast. We already learned the type `p` 
might refer to.
+
+  invalidation_detector = 2000;
+  p->onAction(200, invalidation_detector);
+  clang_analyzer_dump(invalidation_detector);
+  // expected-warning@-1 {{2000}} on this path we trusted the type, and 
resolved the call to `MyHandler::onAction(int, int&)`
+  // expected-warning@-2 {{conj}} on this path we conservatively evaluated the 
previous call
+
+  clang_analyzer_numTimesReached(); // expected-warning {{3}} we only have 3 
paths here, not 4
+  // 1) inlined 2 different callees
+  // 2) inlined only 1st
+  // 3) non were inlined

DonatNagyE wrote:

I don't think that "non" alone can be used as the subject of a phrase; did  you 
mean to write "none"?

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


[clang] [clang-format] Allow default values for template parameters in lambda (PR #69052)

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

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


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


[clang] de9b3c5 - [clang][Interp] Handle delegating constructors (#67823)

2023-10-16 Thread via cfe-commits

Author: Timm Baeder
Date: 2023-10-16T14:11:25+02:00
New Revision: de9b3c5eba41fd024aef6dfa4dab0c8feae29b18

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

LOG: [clang][Interp] Handle delegating constructors (#67823)

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeStmtGen.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp 
b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
index 6193a8d55a14685..509abe3ae867f93 100644
--- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -198,6 +198,14 @@ bool ByteCodeStmtGen::visitFunc(const 
FunctionDecl *F) {
   return false;
 if (!this->emitInitPtrPop(InitExpr))
   return false;
+  } else {
+assert(Init->isDelegatingInitializer());
+if (!this->emitThis(InitExpr))
+  return false;
+if (!this->visitInitializer(Init->getInit()))
+  return false;
+if (!this->emitPopPtr(InitExpr))
+  return false;
   }
 }
   }

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index bcc84087fc54020..3c866825d1f077c 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -1066,3 +1066,26 @@ namespace ParenInit {
   constexpr B b(A(1),2);
 }
 #endif
+
+namespace DelegatingConstructors {
+  struct S {
+int a;
+constexpr S() : S(10) {}
+constexpr S(int a) : a(a) {}
+  };
+  constexpr S s = {};
+  static_assert(s.a == 10, "");
+
+  struct B {
+int a;
+int b;
+
+constexpr B(int a) : a(a), b(a + 2) {}
+  };
+  struct A : B {
+constexpr A() : B(10) {};
+  };
+  constexpr A d4 = {};
+  static_assert(d4.a == 10, "");
+  static_assert(d4.b == 12, "");
+}



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


[clang] [clang][Interp] Handle delegating constructors (PR #67823)

2023-10-16 Thread Timm Baeder via cfe-commits

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


[clang] [clang] Add information about lld presence in RISCVToolchain. (PR #68904)

2023-10-16 Thread Bushev Dmitry via cfe-commits

https://github.com/dybv-sc updated 
https://github.com/llvm/llvm-project/pull/68904

>From 51a150e7abd2ff88261f82fc4a4c799f2a1fb11d Mon Sep 17 00:00:00 2001
From: Dmitry Bushev 
Date: Mon, 9 Oct 2023 19:49:09 +0300
Subject: [PATCH] [clang] Add information about lld presence in RISCVToolchain.

---
 .../lib/Driver/ToolChains/RISCVToolchain.cpp  |  4 ++-
 clang/lib/Driver/ToolChains/RISCVToolchain.h  |  3 +++
 clang/test/Driver/riscv64-toolchain.c | 25 +++
 3 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index 7e6abd144428783..d87af6b4cb89170 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -49,7 +49,9 @@ bool RISCVToolChain::hasGCCToolchain(const Driver &D,
 /// RISC-V Toolchain
 RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
-: Generic_ELF(D, Triple, Args) {
+: Generic_ELF(D, Triple, Args), UseLLD{Args.getLastArgValue(
+   options::OPT_fuse_ld_EQ)
+   .equals_insensitive("lld")} {
   GCCInstallation.init(Triple, Args);
   if (GCCInstallation.isValid()) {
 Multilibs = GCCInstallation.getMultilibs();
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index de6960726f1cd77..afe98968ecd8616 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -35,11 +35,14 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const override;
 
+  bool HasNativeLLVMSupport() const override { return UseLLD; }
+
 protected:
   Tool *buildLinker() const override;
 
 private:
   std::string computeSysRoot() const override;
+  bool UseLLD;
 };
 
 } // end namespace toolchains
diff --git a/clang/test/Driver/riscv64-toolchain.c 
b/clang/test/Driver/riscv64-toolchain.c
index f177bff33dd4d72..663296e7432ea40 100644
--- a/clang/test/Driver/riscv64-toolchain.c
+++ b/clang/test/Driver/riscv64-toolchain.c
@@ -121,6 +121,31 @@
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
 
+// Check that lto works in riscv-toolchain when explicitly specified lld as 
linker.
+// RUN: env "PATH=" %clang -### %s -fuse-ld=lld -flto \
+// RUN:   -B%S/Inputs/lld --target=riscv64-unknown-elf --rtlib=platform 
--sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "{{.*}}lld"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "-m" "elf64lriscv"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../../../riscv64-unknown-elf/lib/rv64imac/lp64/crt0.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtbegin.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../../../riscv64-unknown-elf/lib"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
+
+// Check driver error when lto is used without specified lld linker.
+// RUN: env "PATH=" %clang -### %s -flto \
+// RUN:   --target=riscv64-unknown-elf --rtlib=platform --sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64: error: 'riscv64-unknown-unknown-elf': 
unable to pass LLVM bit-code files to linker
+
 // RUN: env "PATH=" %clang -### %s -fuse-ld=ld \
 // RUN:   --target=riscv64-unknown-elf --rtlib=platform --unwindlib=platform 
--sysroot= \
 // RUN:   -march=rv64imafdc -mabi=lp64d \

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


[clang-tools-extra] [clang-tidy] Add check to diagnose coroutine-hostile RAII objects (PR #68738)

2023-10-16 Thread Utkarsh Saxena via cfe-commits


@@ -0,0 +1,82 @@
+//===--- CoroutineSuspensionHostileCheck.cpp - clang-tidy --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CoroutineHostileRAIICheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/Attrs.inc"
+#include "clang/AST/Decl.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::misc {
+CoroutineHostileRAIICheck::CoroutineHostileRAIICheck(StringRef Name,
+ ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context) {
+  for (StringRef Denied :
+   utils::options::parseStringList(Options.get("RAIIDenyList", ""))) {

usx95 wrote:

> 1. Maybe all it RAIITypesList

Done.
> 2. Consider puting things like std::mutex by default here.

`std::mutex` is not a RAII type. `std::lock_guard`, `std::scoped_lock` are RAII 
and are already annotated with `scoped_lockable`

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


[clang] [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha. (PR #66207)

2023-10-16 Thread Balázs Kéri via cfe-commits

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


[clang] c202a17 - [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha. (#66207)

2023-10-16 Thread via cfe-commits

Author: Balázs Kéri
Date: 2023-10-16T14:51:05+02:00
New Revision: c202a17d024068c70364116f2d06535d79535b30

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

LOG: [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of 
alpha. (#66207)

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/docs/analyzer/checkers.rst
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/test/Analysis/PR49642.c
clang/test/Analysis/analyzer-config.c
clang/test/Analysis/analyzer-enabled-checkers.c
clang/test/Analysis/conversion.c
clang/test/Analysis/errno-stdlibraryfunctions-notes.c
clang/test/Analysis/errno-stdlibraryfunctions.c
clang/test/Analysis/std-c-library-functions-POSIX-lookup.c
clang/test/Analysis/std-c-library-functions-POSIX-socket-sockaddr.cpp
clang/test/Analysis/std-c-library-functions-POSIX.c
clang/test/Analysis/std-c-library-functions-arg-constraints-note-tags.cpp
clang/test/Analysis/std-c-library-functions-arg-constraints-notes.cpp
clang/test/Analysis/std-c-library-functions-arg-constraints-tracking-notes.c
clang/test/Analysis/std-c-library-functions-arg-constraints.c
clang/test/Analysis/std-c-library-functions-arg-constraints.cpp
clang/test/Analysis/std-c-library-functions-arg-cstring-dependency.c
clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
clang/test/Analysis/std-c-library-functions-arg-weakdeps.c
clang/test/Analysis/std-c-library-functions-eof.c
clang/test/Analysis/std-c-library-functions-inlined.c
clang/test/Analysis/std-c-library-functions-lookup.c
clang/test/Analysis/std-c-library-functions-lookup.cpp
clang/test/Analysis/std-c-library-functions-path-notes.c
clang/test/Analysis/std-c-library-functions-restrict.c
clang/test/Analysis/std-c-library-functions-restrict.cpp
clang/test/Analysis/std-c-library-functions-vs-stream-checker.c
clang/test/Analysis/std-c-library-functions.c
clang/test/Analysis/std-c-library-functions.cpp
clang/test/Analysis/std-c-library-posix-crash.c
clang/test/Analysis/stream-errno-note.c
clang/test/Analysis/stream-errno.c
clang/test/Analysis/stream-noopen.c
clang/test/Analysis/stream-note.c
clang/test/Analysis/stream-stdlibraryfunctionargs.c
clang/test/Analysis/weak-dependencies.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 52d5b9a3f66d155..9782c123f4c9372 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -662,6 +662,8 @@ Static Analyzer
 - Added a new checker ``core.BitwiseShift`` which reports situations where
   bitwise shift operators produce undefined behavior (because some operand is
   negative or too large).
+- Move checker ``alpha.unix.StdCLibraryFunctions`` out of the ``alpha`` package
+  to ``unix.StdCLibraryFunctions``.
 
 - Fix false positive in mutation check when using pointer to member function.
   (`#66204: `_).

diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index 81f333e644f31c9..597ffcc4a10a25b 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1016,7 +1016,7 @@ Check the size argument passed into C string functions 
for common erroneous patt
 .. _unix-cstring-NullArg:
 
 unix.cstring.NullArg (C)
-"
+
 Check for null pointers being passed as arguments to C string functions:
 ``strlen, strnlen, strcpy, strncpy, strcat, strncat, strcmp, strncmp, 
strcasecmp, strncasecmp, wcslen, wcsnlen``.
 
@@ -1026,6 +1026,99 @@ Check for null pointers being passed as arguments to C 
string functions:
return strlen(0); // warn
  }
 
+.. _unix-StdCLibraryFunctions:
+
+unix.StdCLibraryFunctions (C)
+"
+Check for calls of standard library functions that violate predefined argument
+constraints. For example, according to the C standard the behavior of function
+``int isalnum(int ch)`` is undefined if the value of ``ch`` is not 
representable
+as ``unsigned char`` and is not equal to ``EOF``.
+
+You can think of this checker as defining restrictions (pre- and 
postconditions)
+on standard library functions. Preconditions are checked, and when they are
+violated, a warning is emitted. Postconditions are added to the analysis, e.g.
+that the return value of a function is not greater than 255. Preconditions are
+added to the analysis too, in the case when the affected values are not known
+before the call.
+
+For example, if an argument to a function must be in between 0 and 255, but the
+value of the argument is unknown, the analyzer will assume that it is in this
+interval. Similarly, if a functi

[clang] [libc++] Add assertions for potential OOB reads in std::nth_element (PR #67023)

2023-10-16 Thread Daniel Kutenin via cfe-commits

danlark1 wrote:

>Also @danlark1 if you rebase onto main the issues with macOS in the CI should 
>be fixed now.

@ldionne, Done

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


[clang-tools-extra] [libc++] Add assertions for potential OOB reads in std::nth_element (PR #67023)

2023-10-16 Thread Daniel Kutenin via cfe-commits

danlark1 wrote:

>Also @danlark1 if you rebase onto main the issues with macOS in the CI should 
>be fixed now.

@ldionne, Done

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


[clang-tools-extra] [clang-tidy] Add check to diagnose coroutine-hostile RAII objects (PR #68738)

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


@@ -0,0 +1,82 @@
+//===--- CoroutineSuspensionHostileCheck.cpp - clang-tidy --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CoroutineHostileRAIICheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/Attrs.inc"
+#include "clang/AST/Decl.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::misc {
+CoroutineHostileRAIICheck::CoroutineHostileRAIICheck(StringRef Name,
+ ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context) {
+  for (StringRef Denied :
+   utils::options::parseStringList(Options.get("RAIIDenyList", ""))) {

PiotrZSL wrote:

scoped_lockable is an Clang language extension 
(https://releases.llvm.org/3.1/tools/clang/docs/LanguageExtensions.html), gcc 
std::lock_guard, std::scoped_lock are not mark with this attribute. So please 
put all those RAII objects on this list by default.

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


[clang-tools-extra] [clang-tidy] Add check to diagnose coroutine-hostile RAII objects (PR #68738)

2023-10-16 Thread Utkarsh Saxena via cfe-commits


@@ -0,0 +1,82 @@
+//===--- CoroutineSuspensionHostileCheck.cpp - clang-tidy --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CoroutineHostileRAIICheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/Attrs.inc"
+#include "clang/AST/Decl.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::misc {
+CoroutineHostileRAIICheck::CoroutineHostileRAIICheck(StringRef Name,
+ ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context) {
+  for (StringRef Denied :
+   utils::options::parseStringList(Options.get("RAIIDenyList", ""))) {
+Denied.consume_front("::");
+RAIIDenyList.push_back(Denied);
+  }
+}
+
+void CoroutineHostileRAIICheck::registerMatchers(MatchFinder *Finder) {
+  // A suspension happens with co_await or co_yield.
+  Finder->addMatcher(coawaitExpr().bind("suspension"), this);
+  Finder->addMatcher(coyieldExpr().bind("suspension"), this);
+}
+
+void CoroutineHostileRAIICheck::checkVarDecl(VarDecl *VD) {

usx95 wrote:

I think it should be fine to ignore static RAII variables as they are pretty 
much contradictory to RAII pattern specially in the context of holding locks.

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


[clang] [clang][ASTMatcher] fix hasAnyBase not binding submatchers (PR #67939)

2023-10-16 Thread via cfe-commits

5chmidti wrote:

I think this can be merged, but I don't have write access.

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


[clang] [clang] Add information about lld presence in RISCVToolchain. (PR #68904)

2023-10-16 Thread Bushev Dmitry via cfe-commits

https://github.com/dybv-sc updated 
https://github.com/llvm/llvm-project/pull/68904

>From d61eacc29e0b70dc50ee7eeb96446b7b66dc2e1d Mon Sep 17 00:00:00 2001
From: Dmitry Bushev 
Date: Mon, 9 Oct 2023 19:49:09 +0300
Subject: [PATCH] [clang] Add information about lld presence in RISCVToolchain.

---
 .../lib/Driver/ToolChains/RISCVToolchain.cpp  |  4 ++-
 clang/lib/Driver/ToolChains/RISCVToolchain.h  |  3 +++
 clang/test/Driver/riscv64-toolchain.c | 25 +++
 3 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index 7e6abd144428783..d87af6b4cb89170 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -49,7 +49,9 @@ bool RISCVToolChain::hasGCCToolchain(const Driver &D,
 /// RISC-V Toolchain
 RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
-: Generic_ELF(D, Triple, Args) {
+: Generic_ELF(D, Triple, Args), UseLLD{Args.getLastArgValue(
+   options::OPT_fuse_ld_EQ)
+   .equals_insensitive("lld")} {
   GCCInstallation.init(Triple, Args);
   if (GCCInstallation.isValid()) {
 Multilibs = GCCInstallation.getMultilibs();
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index de6960726f1cd77..afe98968ecd8616 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -35,11 +35,14 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const override;
 
+  bool HasNativeLLVMSupport() const override { return UseLLD; }
+
 protected:
   Tool *buildLinker() const override;
 
 private:
   std::string computeSysRoot() const override;
+  bool UseLLD;
 };
 
 } // end namespace toolchains
diff --git a/clang/test/Driver/riscv64-toolchain.c 
b/clang/test/Driver/riscv64-toolchain.c
index f177bff33dd4d72..8715dff2171b5ef 100644
--- a/clang/test/Driver/riscv64-toolchain.c
+++ b/clang/test/Driver/riscv64-toolchain.c
@@ -121,6 +121,31 @@
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
 
+// Check that lto works in riscv-toolchain when explicitly specified lld as 
linker.
+// RUN: env "PATH=" %clang -### %s -fuse-ld=lld -flto \
+// RUN:   -B%S/Inputs/lld --target=riscv64-unknown-elf --rtlib=platform 
--sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "{{.*}}lld"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "-m" "elf64lriscv"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../../../riscv64-unknown-elf/lib/rv64imac/lp64/crt0.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtbegin.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../../../riscv64-unknown-elf/lib"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
+
+// Check driver error when lto is used without specified lld linker.
+// RUN: env "PATH=" not %clang -### %s -flto \
+// RUN:   --target=riscv64-unknown-elf --rtlib=platform --sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64: error: 'riscv64-unknown-unknown-elf': 
unable to pass LLVM bit-code files to linker
+
 // RUN: env "PATH=" %clang -### %s -fuse-ld=ld \
 // RUN:   --target=riscv64-unknown-elf --rtlib=platform --unwindlib=platform 
--sysroot= \
 // RUN:   -march=rv64imafdc -mabi=lp64d \

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


[PATCH] D143813: [ClangFE] Check that __sync builtins are naturally aligned.

2023-10-16 Thread Tom Stellard via Phabricator via cfe-commits
tstellar added a comment.

This introduced a build failure on s390x: 
https://github.com/llvm/llvm-project/issues/69146


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

https://reviews.llvm.org/D143813

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


[clang] [Driver] Ignore non-clang pch files when -include a.h probes a.h.gch (PR #69204)

2023-10-16 Thread via cfe-commits

https://github.com/zmodem created 
https://github.com/llvm/llvm-project/pull/69204

Instead of deprecating the "gch probe" as in
f726da1193baf51e0a66453cc32dcffb8a9121d4, this makes clang ignore files which 
are not clang pch files (See discussion on PR #67084).

This fixes the issues mentioned in the former patch, with GCC-generated .gch 
files getting in the way when using clang, while maintaining the probing 
behavior for builds which rely on that.

>From 3b9e3ba2f26df496fe077ae08488d840522e1b37 Mon Sep 17 00:00:00 2001
From: Hans Wennborg 
Date: Mon, 16 Oct 2023 13:18:01 +0200
Subject: [PATCH] [Driver] Ignore non-clang pch files when -include a.h probes
 a.h.gch

Instead of deprecating the "gch probe" as in
f726da1193baf51e0a66453cc32dcffb8a9121d4, this makes clang ignore files
which are not clang pch files (See discussion on PR #67084).

This fixes the issues mentioned in the former patch, with GCC-generated
.gch files getting in the way when using clang, while maintaining
the probing behavior for builds which rely on that.
---
 clang/docs/ReleaseNotes.rst   |  4 +--
 .../clang/Basic/DiagnosticDriverKinds.td  |  9 +++--
 clang/include/clang/Basic/DiagnosticGroups.td |  5 ++-
 clang/lib/Driver/ToolChains/Clang.cpp | 35 ---
 clang/test/PCH/Inputs/gch-probe.h |  1 +
 clang/test/PCH/Inputs/gch-probe.h.gch |  1 +
 clang/test/PCH/gch-probe.c|  9 +
 clang/test/PCH/pch-dir.c  | 10 --
 8 files changed, 60 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/PCH/Inputs/gch-probe.h
 create mode 100644 clang/test/PCH/Inputs/gch-probe.h.gch
 create mode 100644 clang/test/PCH/gch-probe.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9782c123f4c9372..95a671617d72504 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -43,8 +43,8 @@ C/C++ Language Potentially Breaking Changes
 
 - The default extension name for PCH generation (``-c -xc-header`` and ``-c
   -xc++-header``) is now ``.pch`` instead of ``.gch``.
-- ``-include a.h`` probing ``a.h.gch`` is deprecated. Change the extension name
-  to ``.pch`` or use ``-include-pch a.h.gch``.
+- ``-include a.h`` probing ``a.h.gch`` will now ignore ``a.h.gch`` if it is not
+  a clang pch file or a directory containing any clang pch file.
 - Fixed a bug that caused ``__has_cpp_attribute`` and ``__has_c_attribute``
   return incorrect values for some C++-11-style attributes. Below is a complete
   list of behavior changes.
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 9c00fa50bb95580..370eb4d0fe71e9c 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -441,11 +441,14 @@ def warn_drv_overriding_option : Warning<
 def warn_drv_treating_input_as_cxx : Warning<
   "treating '%0' input as '%1' when in C++ mode, this behavior is deprecated">,
   InGroup;
-def warn_drv_include_probe_gch : Warning<
-  "'%0' probing .gch is deprecated. Use '-include-pch %1' or switch to .pch 
instead">,
-  InGroup;
 def warn_drv_pch_not_first_include : Warning<
   "precompiled header '%0' was ignored because '%1' is not first '-include'">;
+def warn_drv_pch_ignoring_gch_file : Warning<
+  "precompiled header '%0' was ignored because it is not a clang PCH file">,
+  InGroup;
+def warn_drv_pch_ignoring_gch_dir : Warning<
+  "precompiled header directory '%0' was ignored because it contains no clang 
PCH files">,
+  InGroup;
 def warn_missing_sysroot : Warning<"no such sysroot directory: '%0'">,
   InGroup>;
 def warn_incompatible_sysroot : Warning<"using sysroot for '%0' but targeting 
'%1'">,
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 0b09c002191848a..3d82d2955d17896 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -209,7 +209,6 @@ def DeprecatedWritableStr : 
DiagGroup<"deprecated-writable-strings",
   [CXX11CompatDeprecatedWritableStr]>;
 def DeprecatedPragma : DiagGroup<"deprecated-pragma">;
 def DeprecatedType : DiagGroup<"deprecated-type">;
-def DeprecatedIncludeGch : DiagGroup<"deprecated-include-gch">;
 // FIXME: Why is DeprecatedImplementations not in this group?
 def Deprecated : DiagGroup<"deprecated", [DeprecatedAnonEnumEnumConversion,
   DeprecatedArrayCompare,
@@ -232,8 +231,7 @@ def Deprecated : DiagGroup<"deprecated", 
[DeprecatedAnonEnumEnumConversion,
   DeprecatedType,
   DeprecatedVolatile,
   DeprecatedWritableStr,
-  
DeprecatedRedundantConstexprStaticDef,
-  

[clang] [Driver] Ignore non-clang pch files when -include a.h probes a.h.gch (PR #69204)

2023-10-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Hans (zmodem)


Changes

Instead of deprecating the "gch probe" as in
f726da1193baf51e0a66453cc32dcffb8a9121d4, this makes clang ignore files which 
are not clang pch files (See discussion on PR #67084).

This fixes the issues mentioned in the former patch, with GCC-generated .gch 
files getting in the way when using clang, while maintaining the probing 
behavior for builds which rely on that.

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


8 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2-2) 
- (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+6-3) 
- (modified) clang/include/clang/Basic/DiagnosticGroups.td (+2-3) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+31-4) 
- (added) clang/test/PCH/Inputs/gch-probe.h (+1) 
- (added) clang/test/PCH/Inputs/gch-probe.h.gch (+1) 
- (added) clang/test/PCH/gch-probe.c (+9) 
- (modified) clang/test/PCH/pch-dir.c (+8-2) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9782c123f4c9372..95a671617d72504 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -43,8 +43,8 @@ C/C++ Language Potentially Breaking Changes
 
 - The default extension name for PCH generation (``-c -xc-header`` and ``-c
   -xc++-header``) is now ``.pch`` instead of ``.gch``.
-- ``-include a.h`` probing ``a.h.gch`` is deprecated. Change the extension name
-  to ``.pch`` or use ``-include-pch a.h.gch``.
+- ``-include a.h`` probing ``a.h.gch`` will now ignore ``a.h.gch`` if it is not
+  a clang pch file or a directory containing any clang pch file.
 - Fixed a bug that caused ``__has_cpp_attribute`` and ``__has_c_attribute``
   return incorrect values for some C++-11-style attributes. Below is a complete
   list of behavior changes.
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 9c00fa50bb95580..370eb4d0fe71e9c 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -441,11 +441,14 @@ def warn_drv_overriding_option : Warning<
 def warn_drv_treating_input_as_cxx : Warning<
   "treating '%0' input as '%1' when in C++ mode, this behavior is deprecated">,
   InGroup;
-def warn_drv_include_probe_gch : Warning<
-  "'%0' probing .gch is deprecated. Use '-include-pch %1' or switch to .pch 
instead">,
-  InGroup;
 def warn_drv_pch_not_first_include : Warning<
   "precompiled header '%0' was ignored because '%1' is not first '-include'">;
+def warn_drv_pch_ignoring_gch_file : Warning<
+  "precompiled header '%0' was ignored because it is not a clang PCH file">,
+  InGroup;
+def warn_drv_pch_ignoring_gch_dir : Warning<
+  "precompiled header directory '%0' was ignored because it contains no clang 
PCH files">,
+  InGroup;
 def warn_missing_sysroot : Warning<"no such sysroot directory: '%0'">,
   InGroup>;
 def warn_incompatible_sysroot : Warning<"using sysroot for '%0' but targeting 
'%1'">,
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 0b09c002191848a..3d82d2955d17896 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -209,7 +209,6 @@ def DeprecatedWritableStr : 
DiagGroup<"deprecated-writable-strings",
   [CXX11CompatDeprecatedWritableStr]>;
 def DeprecatedPragma : DiagGroup<"deprecated-pragma">;
 def DeprecatedType : DiagGroup<"deprecated-type">;
-def DeprecatedIncludeGch : DiagGroup<"deprecated-include-gch">;
 // FIXME: Why is DeprecatedImplementations not in this group?
 def Deprecated : DiagGroup<"deprecated", [DeprecatedAnonEnumEnumConversion,
   DeprecatedArrayCompare,
@@ -232,8 +231,7 @@ def Deprecated : DiagGroup<"deprecated", 
[DeprecatedAnonEnumEnumConversion,
   DeprecatedType,
   DeprecatedVolatile,
   DeprecatedWritableStr,
-  
DeprecatedRedundantConstexprStaticDef,
-  DeprecatedIncludeGch
+  DeprecatedRedundantConstexprStaticDef
   ]>,
  DiagCategory<"Deprecations">;
 
@@ -443,6 +441,7 @@ def IncrementBool : DiagGroup<"increment-bool", 
[DeprecatedIncrementBool]>;
 def InfiniteRecursion : DiagGroup<"infinite-recursion">;
 def PureVirtualCallFromCtorDtor: 
DiagGroup<"call-to-pure-virtual-from-ctor-dtor">;
 def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
+def IgnoredGCH : DiagGroup<"ignored-gch">;
 def IgnoredReferenceQualifiers : DiagGroup<"ignored-reference-qualifiers">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers", 
[IgnoredReferenceQualifiers]>;
 def : Dia

[clang] [Driver] Ignore non-clang pch files when -include a.h probes a.h.gch (PR #69204)

2023-10-16 Thread via cfe-commits

zmodem wrote:

Please take a look.

This has the benefit of fixing users broken by gcc-generated .gch files without 
having to wait a release cycle for deprecation, while at the same time not 
breaking users relying clang performing these probes at all.

cc folks from the previous pr:
@MaskRay @jansvoboda11 @nico @tahonermann @dwblaikie 

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


[clang] [Driver] -include: deprecate probing .gch (PR #67084)

2023-10-16 Thread via cfe-commits

zmodem wrote:

I've posted an alternative patch in 
https://github.com/llvm/llvm-project/pull/69204 which I believe is fixing the 
issues mentioned in this pr better (users don't have to wait another release), 
while not breaking builds relying on gch probing.

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


[clang] [clang] Add information about lld presence in RISCVToolchain. (PR #68904)

2023-10-16 Thread Bushev Dmitry via cfe-commits

https://github.com/dybv-sc updated 
https://github.com/llvm/llvm-project/pull/68904

>From d1ceb3258b0ade810ebdcb3bf2c5727026bef17f Mon Sep 17 00:00:00 2001
From: Dmitry Bushev 
Date: Mon, 9 Oct 2023 19:49:09 +0300
Subject: [PATCH] [clang] Add information about lld presence in RISCVToolchain.

---
 .../lib/Driver/ToolChains/RISCVToolchain.cpp  |  4 ++-
 clang/lib/Driver/ToolChains/RISCVToolchain.h  |  3 +++
 clang/test/Driver/riscv64-toolchain.c | 25 +++
 3 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index 7e6abd144428783..d87af6b4cb89170 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -49,7 +49,9 @@ bool RISCVToolChain::hasGCCToolchain(const Driver &D,
 /// RISC-V Toolchain
 RISCVToolChain::RISCVToolChain(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args)
-: Generic_ELF(D, Triple, Args) {
+: Generic_ELF(D, Triple, Args), UseLLD{Args.getLastArgValue(
+   options::OPT_fuse_ld_EQ)
+   .equals_insensitive("lld")} {
   GCCInstallation.init(Triple, Args);
   if (GCCInstallation.isValid()) {
 Multilibs = GCCInstallation.getMultilibs();
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index de6960726f1cd77..afe98968ecd8616 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -35,11 +35,14 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const override;
 
+  bool HasNativeLLVMSupport() const override { return UseLLD; }
+
 protected:
   Tool *buildLinker() const override;
 
 private:
   std::string computeSysRoot() const override;
+  bool UseLLD;
 };
 
 } // end namespace toolchains
diff --git a/clang/test/Driver/riscv64-toolchain.c 
b/clang/test/Driver/riscv64-toolchain.c
index f177bff33dd4d72..cd7d7624c1c5539 100644
--- a/clang/test/Driver/riscv64-toolchain.c
+++ b/clang/test/Driver/riscv64-toolchain.c
@@ -121,6 +121,31 @@
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV64IMAC-BAREMETAL-MULTI-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
 
+// Check that lto works in riscv-toolchain when explicitly specified lld as 
linker.
+// RUN: env "PATH=" %clang -### %s -fuse-ld=lld -flto \
+// RUN:   -B%S/Inputs/lld --target=riscv64-unknown-elf --rtlib=platform 
--sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "{{.*}}lld"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "-m" "elf64lriscv"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../../../riscv64-unknown-elf/lib/rv64imac/lp64/crt0.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtbegin.o"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"-L{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/../../../../riscv64-unknown-elf/lib"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
+// C-RV64IMAC-BAREMETAL-LTO-LP64: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o"
+
+// Check driver error when lto is used without specified lld linker.
+// RUN: not env "PATH=" %clang -### %s -flto \
+// RUN:   --target=riscv64-unknown-elf --rtlib=platform --sysroot= \
+// RUN:   -march=rv64imac -mabi=lp64\
+// RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
+// RUN:   | FileCheck -check-prefix=C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64 %s
+
+// C-RV64IMAC-BAREMETAL-LTO-FAIL-LP64: error: 'riscv64-unknown-unknown-elf': 
unable to pass LLVM bit-code files to linker
+
 // RUN: env "PATH=" %clang -### %s -fuse-ld=ld \
 // RUN:   --target=riscv64-unknown-elf --rtlib=platform --unwindlib=platform 
--sysroot= \
 // RUN:   -march=rv64imafdc -mabi=lp64d \

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


[clang-tools-extra] [clang-tidy] modernize-avoid-bind only return for non-void function (PR #69207)

2023-10-16 Thread via cfe-commits

https://github.com/5chmidti created 
https://github.com/llvm/llvm-project/pull/69207

- only return when the return type is non-void
- fix missing return on member functions


>From 7771acd00ace1362e580531f1a3ed63f81cfa5a3 Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Mon, 14 Aug 2023 03:04:36 +0200
Subject: [PATCH] [clang-tidy] modernize-avoid-bind only return for non-void
 function

- only return when the return type is non-void
- fix missing return on member functions
---
 .../clang-tidy/modernize/AvoidBindCheck.cpp   | 13 --
 .../checkers/modernize/avoid-bind.cpp | 43 +--
 2 files changed, 41 insertions(+), 15 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
index 4628c09f196996b..bcdf6f98055486e 100644
--- a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
@@ -96,6 +96,7 @@ struct CallableInfo {
   std::string UsageIdentifier;
   StringRef CaptureInitializer;
   const FunctionDecl *Decl = nullptr;
+  bool DoesReturn = false;
 };
 
 struct LambdaProperties {
@@ -554,6 +555,8 @@ getLambdaProperties(const MatchFinder::MatchResult &Result) 
{
   LP.Callable.Materialization = getCallableMaterialization(Result);
   LP.Callable.Decl =
   getCallMethodDecl(Result, LP.Callable.Type, LP.Callable.Materialization);
+  if (LP.Callable.Decl)
+LP.Callable.DoesReturn = !LP.Callable.Decl->getReturnType()->isVoidType();
   LP.Callable.SourceTokens = getSourceTextForExpr(Result, CalleeExpr);
   if (LP.Callable.Materialization == CMK_VariableRef) {
 LP.Callable.CE = CE_Var;
@@ -672,15 +675,20 @@ void AvoidBindCheck::check(const MatchFinder::MatchResult 
&Result) {
 
   addPlaceholderArgs(LP, Stream, PermissiveParameterList);
 
+  Stream << " { ";
+
+  if (LP.Callable.DoesReturn) {
+Stream << "return ";
+  }
+
   if (LP.Callable.Type == CT_Function) {
 StringRef SourceTokens = LP.Callable.SourceTokens;
 SourceTokens.consume_front("&");
-Stream << " { return " << SourceTokens;
+Stream << SourceTokens;
   } else if (LP.Callable.Type == CT_MemberFunction) {
 const auto *MethodDecl = dyn_cast(LP.Callable.Decl);
 const BindArgument &ObjPtr = FunctionCallArgs.front();
 
-Stream << " { ";
 if (!isa(ignoreTemporariesAndPointers(ObjPtr.E))) {
   Stream << ObjPtr.UsageIdentifier;
   Stream << "->";
@@ -688,7 +696,6 @@ void AvoidBindCheck::check(const MatchFinder::MatchResult 
&Result) {
 
 Stream << MethodDecl->getName();
   } else {
-Stream << " { return ";
 switch (LP.Callable.CE) {
 case CE_Var:
   if (LP.Callable.UsageIdentifier != LP.Callable.CaptureIdentifier) {
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
index 3334eab2d407e49..336b3cb4ee08f94 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
@@ -45,6 +45,7 @@ struct D {
   void operator()(int x, int y) const {}
 
   void MemberFunction(int x) {}
+  int MemberFunctionWithReturn(int x) {}
 
   static D *create();
 };
@@ -162,11 +163,11 @@ struct TestCaptureByValueStruct {
 // those here.
 auto FFF = boost::bind(UseF, f);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to 
boost::bind [modernize-avoid-bind]
-// CHECK-FIXES: auto FFF = [f] { return UseF(f); };
+// CHECK-FIXES: auto FFF = [f] { UseF(f); };
 
 auto GGG = boost::bind(UseF, MemberStruct);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to 
boost::bind [modernize-avoid-bind]
-// CHECK-FIXES: auto GGG = [this] { return UseF(MemberStruct); };
+// CHECK-FIXES: auto GGG = [this] { UseF(MemberStruct); };
 
 auto HHH = std::bind(add, MemberStructWithData._member, 1);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to std::bind
@@ -227,34 +228,34 @@ void testFunctionObjects() {
   D *e = nullptr;
   auto AAA = std::bind(d, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto AAA = [d] { return d(1, 2); }
+  // CHECK-FIXES: auto AAA = [d] { d(1, 2); }
 
   auto BBB = std::bind(*e, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto BBB = [e] { return (*e)(1, 2); }
+  // CHECK-FIXES: auto BBB = [e] { (*e)(1, 2); }
 
   auto CCC = std::bind(D{}, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto CCC = [] { return D{}(1, 2); }
+  // CHECK-FIXES: auto CCC = [] { D{}(1, 2); }
 
   auto DDD = std::bind(D(), 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto DDD = [] { return D()(1, 2); }
+  // CH

[clang-tools-extra] [clang-tidy] modernize-avoid-bind only return for non-void function (PR #69207)

2023-10-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: None (5chmidti)


Changes

- only return when the return type is non-void
- fix missing return on member functions


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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp (+10-3) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp (+31-12) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
index 4628c09f196996b..bcdf6f98055486e 100644
--- a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
@@ -96,6 +96,7 @@ struct CallableInfo {
   std::string UsageIdentifier;
   StringRef CaptureInitializer;
   const FunctionDecl *Decl = nullptr;
+  bool DoesReturn = false;
 };
 
 struct LambdaProperties {
@@ -554,6 +555,8 @@ getLambdaProperties(const MatchFinder::MatchResult &Result) 
{
   LP.Callable.Materialization = getCallableMaterialization(Result);
   LP.Callable.Decl =
   getCallMethodDecl(Result, LP.Callable.Type, LP.Callable.Materialization);
+  if (LP.Callable.Decl)
+LP.Callable.DoesReturn = !LP.Callable.Decl->getReturnType()->isVoidType();
   LP.Callable.SourceTokens = getSourceTextForExpr(Result, CalleeExpr);
   if (LP.Callable.Materialization == CMK_VariableRef) {
 LP.Callable.CE = CE_Var;
@@ -672,15 +675,20 @@ void AvoidBindCheck::check(const MatchFinder::MatchResult 
&Result) {
 
   addPlaceholderArgs(LP, Stream, PermissiveParameterList);
 
+  Stream << " { ";
+
+  if (LP.Callable.DoesReturn) {
+Stream << "return ";
+  }
+
   if (LP.Callable.Type == CT_Function) {
 StringRef SourceTokens = LP.Callable.SourceTokens;
 SourceTokens.consume_front("&");
-Stream << " { return " << SourceTokens;
+Stream << SourceTokens;
   } else if (LP.Callable.Type == CT_MemberFunction) {
 const auto *MethodDecl = dyn_cast(LP.Callable.Decl);
 const BindArgument &ObjPtr = FunctionCallArgs.front();
 
-Stream << " { ";
 if (!isa(ignoreTemporariesAndPointers(ObjPtr.E))) {
   Stream << ObjPtr.UsageIdentifier;
   Stream << "->";
@@ -688,7 +696,6 @@ void AvoidBindCheck::check(const MatchFinder::MatchResult 
&Result) {
 
 Stream << MethodDecl->getName();
   } else {
-Stream << " { return ";
 switch (LP.Callable.CE) {
 case CE_Var:
   if (LP.Callable.UsageIdentifier != LP.Callable.CaptureIdentifier) {
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
index 3334eab2d407e49..336b3cb4ee08f94 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
@@ -45,6 +45,7 @@ struct D {
   void operator()(int x, int y) const {}
 
   void MemberFunction(int x) {}
+  int MemberFunctionWithReturn(int x) {}
 
   static D *create();
 };
@@ -162,11 +163,11 @@ struct TestCaptureByValueStruct {
 // those here.
 auto FFF = boost::bind(UseF, f);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to 
boost::bind [modernize-avoid-bind]
-// CHECK-FIXES: auto FFF = [f] { return UseF(f); };
+// CHECK-FIXES: auto FFF = [f] { UseF(f); };
 
 auto GGG = boost::bind(UseF, MemberStruct);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to 
boost::bind [modernize-avoid-bind]
-// CHECK-FIXES: auto GGG = [this] { return UseF(MemberStruct); };
+// CHECK-FIXES: auto GGG = [this] { UseF(MemberStruct); };
 
 auto HHH = std::bind(add, MemberStructWithData._member, 1);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to std::bind
@@ -227,34 +228,34 @@ void testFunctionObjects() {
   D *e = nullptr;
   auto AAA = std::bind(d, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto AAA = [d] { return d(1, 2); }
+  // CHECK-FIXES: auto AAA = [d] { d(1, 2); }
 
   auto BBB = std::bind(*e, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto BBB = [e] { return (*e)(1, 2); }
+  // CHECK-FIXES: auto BBB = [e] { (*e)(1, 2); }
 
   auto CCC = std::bind(D{}, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto CCC = [] { return D{}(1, 2); }
+  // CHECK-FIXES: auto CCC = [] { D{}(1, 2); }
 
   auto DDD = std::bind(D(), 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto DDD = [] { return D()(1, 2); }
+  // CHECK-FIXES: auto DDD = [] { D()(1, 2); }
 
   auto EEE = std::bind(*D::create(), 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto EEE = [Func = *D::create()] { return Func(1, 2); };
+  // CHECK-FIXES: a

[clang] [Clang] Fix dependence handling of nttp for variable templates (PR #69075)

2023-10-16 Thread Erich Keane via cfe-commits

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


[clang] [Clang] Fix dependence handling of nttp for variable templates (PR #69075)

2023-10-16 Thread Erich Keane via cfe-commits


@@ -1299,8 +1299,9 @@ static bool checkTupleLikeDecomposition(Sema &S,
   //   in the associated namespaces.
   Expr *Get = UnresolvedLookupExpr::Create(
   S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
-  DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
-  UnresolvedSetIterator(), UnresolvedSetIterator());
+  DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/ true, &Args,
+  UnresolvedSetIterator(), UnresolvedSetIterator(),
+  /*KnownDependent*/ false);

erichkeane wrote:

```suggestion
  /*KnownDependent=*/ false);
```

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


[clang] [Clang] Fix dependence handling of nttp for variable templates (PR #69075)

2023-10-16 Thread Erich Keane via cfe-commits


@@ -165,3 +165,18 @@ namespace BindingInStmtExpr {
   using U = decltype(num_bindings()); // expected-note {{previous}}
   using U = N<3>; // expected-error-re {{type alias redefinition with 
different types ('N<3>' vs {{.*}}N<2>}}
 }
+
+namespace PR65153 {
+struct A{};
+
+template 
+const A JoinStringViews = T;
+
+template 
+class Builder {
+public:
+static constexpr A Equal{};
+// no crash here
+static constexpr auto Val = JoinStringViews;
+};
+} // namespace PR65153

erichkeane wrote:

needs newline at end.

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


[clang] [Clang] Fix dependence handling of nttp for variable templates (PR #69075)

2023-10-16 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

This needs a release note, else I think it is OK.

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


[clang] [clang] use relative paths for builtin headers during module compilation (PR #68023)

2023-10-16 Thread Richard Howell via cfe-commits

rmaz wrote:

@jansvoboda11 still good with this change, or is there a less invasive way to 
get this done?

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


[clang-tools-extra] [clang-tidy] modernize-avoid-bind only return for non-void function (PR #69207)

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


@@ -554,6 +555,8 @@ getLambdaProperties(const MatchFinder::MatchResult &Result) 
{
   LP.Callable.Materialization = getCallableMaterialization(Result);
   LP.Callable.Decl =
   getCallMethodDecl(Result, LP.Callable.Type, LP.Callable.Materialization);
+  if (LP.Callable.Decl)
+LP.Callable.DoesReturn = !LP.Callable.Decl->getReturnType()->isVoidType();

PiotrZSL wrote:

check here also that return type is not null, just in case..., you may also try 
to check a canonical type, in case that void would be somehow hidden behind 
some typedefs/templates or something

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


[clang-tools-extra] [clang-tidy] modernize-avoid-bind only return for non-void function (PR #69207)

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

https://github.com/PiotrZSL commented:

Release notes Except that looks +- fine for me.

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


[PATCH] D151197: [Clang][SVE2p1] Add svpsel builtins

2023-10-16 Thread Caroline via Phabricator via cfe-commits
CarolineConcatto added inline comments.
Herald added a subscriber: wangpc.



Comment at: clang/include/clang/Basic/arm_sve.td:2123
+
+def SVPSEL_COUNT_ALIAS_B : SInst<"svpsel_lane_c8",  "}}Pmi", "Pc", MergeNone, 
"", [], [ImmCheck<3, ImmCheck0_15>]>;
+def SVPSEL_COUNT_ALIAS_H : SInst<"svpsel_lane_c16", "}}Pmi", "Ps", MergeNone, 
"", [], [ImmCheck<3, ImmCheck0_7>]>;

hassnaa-arm wrote:
> In the section of prototype modifiers: "}}Pmi"
> According to the used modifiers, I see that they refer to 4 parameters, while 
> in the testing file I see the function takes 3 parameters only.
> Isn't that 'i' modifier extra ?
> The same case for all the builtins.
> Am I correct ?
It looks we have a change in the way we use slice. Now the base and offset are 
only 1 parameter.
So this prototype has changed.
I will update this patch
See https://github.com/ARM-software/acle/pull/217/files


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151197

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


[PATCH] D151307: [Clang][SVE2.1] Add svwhile (predicate-as-counter) builtins

2023-10-16 Thread Caroline via Phabricator via cfe-commits
CarolineConcatto added inline comments.



Comment at: clang/include/clang/Basic/arm_sve.td:2129
 
+def SVWHILEGE_COUNT  : SInst<"svwhilege_{d}",  "}lli", "QcQsQiQl", MergeNone, 
"aarch64_sve_whilege_{d}", [IsOverloadNone], [ImmCheck<2, ImmCheck2_4_Mul2>]>;
+def SVWHILEGT_COUNT  : SInst<"svwhilegt_{d}",  "}lli", "QcQsQiQl", MergeNone, 
"aarch64_sve_whilegt_{d}", [IsOverloadNone], [ImmCheck<2, ImmCheck2_4_Mul2>]>;

dtemirbulatov wrote:
> I could not find where ImmCheck2_4_Mul2 is defined?
Hi @dtemirbulatov ,

This check was created in this patch:
https://reviews.llvm.org/D150961, which is in the stack.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151307

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


[clang-tools-extra] [clang-tidy] modernize-avoid-bind only return for non-void function (PR #69207)

2023-10-16 Thread via cfe-commits

https://github.com/5chmidti updated 
https://github.com/llvm/llvm-project/pull/69207

>From 7771acd00ace1362e580531f1a3ed63f81cfa5a3 Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Mon, 14 Aug 2023 03:04:36 +0200
Subject: [PATCH 1/2] [clang-tidy] modernize-avoid-bind only return for
 non-void function

- only return when the return type is non-void
- fix missing return on member functions
---
 .../clang-tidy/modernize/AvoidBindCheck.cpp   | 13 --
 .../checkers/modernize/avoid-bind.cpp | 43 +--
 2 files changed, 41 insertions(+), 15 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
index 4628c09f196996b..bcdf6f98055486e 100644
--- a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
@@ -96,6 +96,7 @@ struct CallableInfo {
   std::string UsageIdentifier;
   StringRef CaptureInitializer;
   const FunctionDecl *Decl = nullptr;
+  bool DoesReturn = false;
 };
 
 struct LambdaProperties {
@@ -554,6 +555,8 @@ getLambdaProperties(const MatchFinder::MatchResult &Result) 
{
   LP.Callable.Materialization = getCallableMaterialization(Result);
   LP.Callable.Decl =
   getCallMethodDecl(Result, LP.Callable.Type, LP.Callable.Materialization);
+  if (LP.Callable.Decl)
+LP.Callable.DoesReturn = !LP.Callable.Decl->getReturnType()->isVoidType();
   LP.Callable.SourceTokens = getSourceTextForExpr(Result, CalleeExpr);
   if (LP.Callable.Materialization == CMK_VariableRef) {
 LP.Callable.CE = CE_Var;
@@ -672,15 +675,20 @@ void AvoidBindCheck::check(const MatchFinder::MatchResult 
&Result) {
 
   addPlaceholderArgs(LP, Stream, PermissiveParameterList);
 
+  Stream << " { ";
+
+  if (LP.Callable.DoesReturn) {
+Stream << "return ";
+  }
+
   if (LP.Callable.Type == CT_Function) {
 StringRef SourceTokens = LP.Callable.SourceTokens;
 SourceTokens.consume_front("&");
-Stream << " { return " << SourceTokens;
+Stream << SourceTokens;
   } else if (LP.Callable.Type == CT_MemberFunction) {
 const auto *MethodDecl = dyn_cast(LP.Callable.Decl);
 const BindArgument &ObjPtr = FunctionCallArgs.front();
 
-Stream << " { ";
 if (!isa(ignoreTemporariesAndPointers(ObjPtr.E))) {
   Stream << ObjPtr.UsageIdentifier;
   Stream << "->";
@@ -688,7 +696,6 @@ void AvoidBindCheck::check(const MatchFinder::MatchResult 
&Result) {
 
 Stream << MethodDecl->getName();
   } else {
-Stream << " { return ";
 switch (LP.Callable.CE) {
 case CE_Var:
   if (LP.Callable.UsageIdentifier != LP.Callable.CaptureIdentifier) {
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
index 3334eab2d407e49..336b3cb4ee08f94 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/avoid-bind.cpp
@@ -45,6 +45,7 @@ struct D {
   void operator()(int x, int y) const {}
 
   void MemberFunction(int x) {}
+  int MemberFunctionWithReturn(int x) {}
 
   static D *create();
 };
@@ -162,11 +163,11 @@ struct TestCaptureByValueStruct {
 // those here.
 auto FFF = boost::bind(UseF, f);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to 
boost::bind [modernize-avoid-bind]
-// CHECK-FIXES: auto FFF = [f] { return UseF(f); };
+// CHECK-FIXES: auto FFF = [f] { UseF(f); };
 
 auto GGG = boost::bind(UseF, MemberStruct);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to 
boost::bind [modernize-avoid-bind]
-// CHECK-FIXES: auto GGG = [this] { return UseF(MemberStruct); };
+// CHECK-FIXES: auto GGG = [this] { UseF(MemberStruct); };
 
 auto HHH = std::bind(add, MemberStructWithData._member, 1);
 // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: prefer a lambda to std::bind
@@ -227,34 +228,34 @@ void testFunctionObjects() {
   D *e = nullptr;
   auto AAA = std::bind(d, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto AAA = [d] { return d(1, 2); }
+  // CHECK-FIXES: auto AAA = [d] { d(1, 2); }
 
   auto BBB = std::bind(*e, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto BBB = [e] { return (*e)(1, 2); }
+  // CHECK-FIXES: auto BBB = [e] { (*e)(1, 2); }
 
   auto CCC = std::bind(D{}, 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto CCC = [] { return D{}(1, 2); }
+  // CHECK-FIXES: auto CCC = [] { D{}(1, 2); }
 
   auto DDD = std::bind(D(), 1, 2);
   // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto DDD = [] { return D()(1, 2); }
+  // CHECK-FIXES: auto DDD = [] { D()(1, 2); }
 
   auto EEE = std::bind(*D::create(), 1, 2);

[clang-tools-extra] [clang-tidy] modernize-avoid-bind only return for non-void function (PR #69207)

2023-10-16 Thread via cfe-commits


@@ -554,6 +555,8 @@ getLambdaProperties(const MatchFinder::MatchResult &Result) 
{
   LP.Callable.Materialization = getCallableMaterialization(Result);
   LP.Callable.Decl =
   getCallMethodDecl(Result, LP.Callable.Type, LP.Callable.Materialization);
+  if (LP.Callable.Decl)
+LP.Callable.DoesReturn = !LP.Callable.Decl->getReturnType()->isVoidType();

5chmidti wrote:

This should be fixed now(?)

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


[clang-tools-extra] [clang-tidy] modernize-avoid-bind only return for non-void function (PR #69207)

2023-10-16 Thread via cfe-commits

5chmidti wrote:

Any particular reason for the `+-`? Maybe it can be resolved?

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


[clang] [OpenMP][libomptarget] Add map checks when running under unified shared memory (PR #69005)

2023-10-16 Thread Gheorghe-Teodor Bercea via cfe-commits


@@ -444,6 +486,29 @@ DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size, 
bool UpdateRefCount,
  LR.TPR.getEntry()->dynRefCountToStr().c_str(), DynRefCountAction,
  LR.TPR.getEntry()->holdRefCountToStr().c_str(), HoldRefCountAction);
 LR.TPR.TargetPointer = (void *)TP;
+
+// If this entry is not marked as being host pointer (the way the
+// implementation works today this is never true, mistake?) then we
+// have to check if this is a host pointer or not. This is a host pointer
+// if the host address matches the target address.
+if ((PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) &&
+!LR.TPR.Flags.IsHostPointer) {

doru1004 wrote:

There are several tests which exercise the call to the getTgtPtrBegin. The 
reason this change is needed is because the first condition, if true, and it 
can be true even when USM is enabled, then the USM branch will not be taken at 
all and the IsHostPointer and IsPresent will not be correctly set.

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


[clang] [OpenMP][libomptarget] Add map checks when running under unified shared memory (PR #69005)

2023-10-16 Thread Gheorghe-Teodor Bercea via cfe-commits

https://github.com/doru1004 updated 
https://github.com/llvm/llvm-project/pull/69005

>From cb4121c466a0fc357d6ca129bfdd4e7c5e2d11ee Mon Sep 17 00:00:00 2001
From: Doru Bercea 
Date: Wed, 16 Nov 2022 17:23:48 -0600
Subject: [PATCH 1/2] Fix declare target implementation to support enter.

---
 clang/include/clang/Basic/Attr.td |  4 +-
 .../clang/Basic/DiagnosticParseKinds.td   | 12 -
 clang/lib/AST/AttrImpl.cpp|  2 +-
 clang/lib/CodeGen/CGExpr.cpp  | 12 +++--
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 24 ++---
 clang/lib/CodeGen/CodeGenModule.cpp   |  6 ++-
 clang/lib/Parse/ParseOpenMP.cpp   | 39 ++
 clang/lib/Sema/SemaOpenMP.cpp | 10 ++--
 .../test/OpenMP/declare_target_ast_print.cpp  | 53 +++
 9 files changed, 130 insertions(+), 32 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 16cf932c3760bd3..eaf4a6db3600e07 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3749,8 +3749,8 @@ def OMPDeclareTargetDecl : InheritableAttr {
   let Documentation = [OMPDeclareTargetDocs];
   let Args = [
 EnumArgument<"MapType", "MapTypeTy",
- [ "to", "link" ],
- [ "MT_To", "MT_Link" ]>,
+ [ "to", "enter", "link" ],
+ [ "MT_To", "MT_Enter", "MT_Link" ]>,
 EnumArgument<"DevType", "DevTypeTy",
  [ "host", "nohost", "any" ],
  [ "DT_Host", "DT_NoHost", "DT_Any" ]>,
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 674d6bd34fc544f..27cd3da1f191c3d 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1383,12 +1383,22 @@ def note_omp_assumption_clause_continue_here
 : Note<"the ignored tokens spans until here">;
 def err_omp_declare_target_unexpected_clause: Error<
   "unexpected '%0' clause, only %select{'device_type'|'to' or 'link'|'to', 
'link' or 'device_type'|'device_type', 'indirect'|'to', 'link', 'device_type' 
or 'indirect'}1 clauses expected">;
+def err_omp_declare_target_unexpected_clause_52: Error<
+  "unexpected '%0' clause, only %select{'device_type'|'enter' or 
'link'|'enter', 'link' or 'device_type'|'device_type', 'indirect'|'enter', 
'link', 'device_type' or 'indirect'}1 clauses expected">;
 def err_omp_begin_declare_target_unexpected_implicit_to_clause: Error<
   "unexpected '(', only 'to', 'link' or 'device_type' clauses expected for 
'begin declare target' directive">;
-def err_omp_declare_target_unexpected_clause_after_implicit_to: Error<
+def err_omp_declare_target_wrong_clause_after_implicit_to: Error<
   "unexpected clause after an implicit 'to' clause">;
+def err_omp_declare_target_wrong_clause_after_implicit_enter: Error<
+  "unexpected clause after an implicit 'enter' clause">;
 def err_omp_declare_target_missing_to_or_link_clause: Error<
   "expected at least one %select{'to' or 'link'|'to', 'link' or 'indirect'}0 
clause">;
+def err_omp_declare_target_missing_enter_or_link_clause: Error<
+  "expected at least one %select{'enter' or 'link'|'enter', 'link' or 
'indirect'}0 clause">;
+def err_omp_declare_target_unexpected_to_clause: Error<
+  "unexpected 'to' clause, use 'enter' instead">;
+def err_omp_declare_target_unexpected_enter_clause: Error<
+  "unexpected 'enter' clause, use 'to' instead">;
 def err_omp_declare_target_multiple : Error<
   "%0 appears multiple times in clauses on the same declare target directive">;
 def err_omp_declare_target_indirect_device_type: Error<
diff --git a/clang/lib/AST/AttrImpl.cpp b/clang/lib/AST/AttrImpl.cpp
index cecbd703ac61e8c..da842f6b190e74d 100644
--- a/clang/lib/AST/AttrImpl.cpp
+++ b/clang/lib/AST/AttrImpl.cpp
@@ -137,7 +137,7 @@ void OMPDeclareTargetDeclAttr::printPrettyPragma(
   // Use fake syntax because it is for testing and debugging purpose only.
   if (getDevType() != DT_Any)
 OS << " device_type(" << ConvertDevTypeTyToStr(getDevType()) << ")";
-  if (getMapType() != MT_To)
+  if (getMapType() != MT_To && getMapType() != MT_Enter)
 OS << ' ' << ConvertMapTypeTyToStr(getMapType());
   if (Expr *E = getIndirectExpr()) {
 OS << " indirect(";
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ee09a8566c3719e..77085ff34fca233 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -2495,14 +2495,16 @@ static Address 
emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
const VarDecl *VD, QualType T) {
   llvm::Optional Res =
   OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
-  // Return an invalid address if variable is MT_To and unified
-  // memory is not enabled. For all other cases: MT_Link and
-  // MT_To with unified memory, return a valid address.
-  if (!Res || (*

[clang] [OpenMP][libomptarget] Add map checks when running under unified shared memory (PR #69005)

2023-10-16 Thread Gheorghe-Teodor Bercea via cfe-commits

https://github.com/doru1004 updated 
https://github.com/llvm/llvm-project/pull/69005

>From cb4121c466a0fc357d6ca129bfdd4e7c5e2d11ee Mon Sep 17 00:00:00 2001
From: Doru Bercea 
Date: Wed, 16 Nov 2022 17:23:48 -0600
Subject: [PATCH 1/2] Fix declare target implementation to support enter.

---
 clang/include/clang/Basic/Attr.td |  4 +-
 .../clang/Basic/DiagnosticParseKinds.td   | 12 -
 clang/lib/AST/AttrImpl.cpp|  2 +-
 clang/lib/CodeGen/CGExpr.cpp  | 12 +++--
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 24 ++---
 clang/lib/CodeGen/CodeGenModule.cpp   |  6 ++-
 clang/lib/Parse/ParseOpenMP.cpp   | 39 ++
 clang/lib/Sema/SemaOpenMP.cpp | 10 ++--
 .../test/OpenMP/declare_target_ast_print.cpp  | 53 +++
 9 files changed, 130 insertions(+), 32 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 16cf932c3760bd3..eaf4a6db3600e07 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3749,8 +3749,8 @@ def OMPDeclareTargetDecl : InheritableAttr {
   let Documentation = [OMPDeclareTargetDocs];
   let Args = [
 EnumArgument<"MapType", "MapTypeTy",
- [ "to", "link" ],
- [ "MT_To", "MT_Link" ]>,
+ [ "to", "enter", "link" ],
+ [ "MT_To", "MT_Enter", "MT_Link" ]>,
 EnumArgument<"DevType", "DevTypeTy",
  [ "host", "nohost", "any" ],
  [ "DT_Host", "DT_NoHost", "DT_Any" ]>,
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 674d6bd34fc544f..27cd3da1f191c3d 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1383,12 +1383,22 @@ def note_omp_assumption_clause_continue_here
 : Note<"the ignored tokens spans until here">;
 def err_omp_declare_target_unexpected_clause: Error<
   "unexpected '%0' clause, only %select{'device_type'|'to' or 'link'|'to', 
'link' or 'device_type'|'device_type', 'indirect'|'to', 'link', 'device_type' 
or 'indirect'}1 clauses expected">;
+def err_omp_declare_target_unexpected_clause_52: Error<
+  "unexpected '%0' clause, only %select{'device_type'|'enter' or 
'link'|'enter', 'link' or 'device_type'|'device_type', 'indirect'|'enter', 
'link', 'device_type' or 'indirect'}1 clauses expected">;
 def err_omp_begin_declare_target_unexpected_implicit_to_clause: Error<
   "unexpected '(', only 'to', 'link' or 'device_type' clauses expected for 
'begin declare target' directive">;
-def err_omp_declare_target_unexpected_clause_after_implicit_to: Error<
+def err_omp_declare_target_wrong_clause_after_implicit_to: Error<
   "unexpected clause after an implicit 'to' clause">;
+def err_omp_declare_target_wrong_clause_after_implicit_enter: Error<
+  "unexpected clause after an implicit 'enter' clause">;
 def err_omp_declare_target_missing_to_or_link_clause: Error<
   "expected at least one %select{'to' or 'link'|'to', 'link' or 'indirect'}0 
clause">;
+def err_omp_declare_target_missing_enter_or_link_clause: Error<
+  "expected at least one %select{'enter' or 'link'|'enter', 'link' or 
'indirect'}0 clause">;
+def err_omp_declare_target_unexpected_to_clause: Error<
+  "unexpected 'to' clause, use 'enter' instead">;
+def err_omp_declare_target_unexpected_enter_clause: Error<
+  "unexpected 'enter' clause, use 'to' instead">;
 def err_omp_declare_target_multiple : Error<
   "%0 appears multiple times in clauses on the same declare target directive">;
 def err_omp_declare_target_indirect_device_type: Error<
diff --git a/clang/lib/AST/AttrImpl.cpp b/clang/lib/AST/AttrImpl.cpp
index cecbd703ac61e8c..da842f6b190e74d 100644
--- a/clang/lib/AST/AttrImpl.cpp
+++ b/clang/lib/AST/AttrImpl.cpp
@@ -137,7 +137,7 @@ void OMPDeclareTargetDeclAttr::printPrettyPragma(
   // Use fake syntax because it is for testing and debugging purpose only.
   if (getDevType() != DT_Any)
 OS << " device_type(" << ConvertDevTypeTyToStr(getDevType()) << ")";
-  if (getMapType() != MT_To)
+  if (getMapType() != MT_To && getMapType() != MT_Enter)
 OS << ' ' << ConvertMapTypeTyToStr(getMapType());
   if (Expr *E = getIndirectExpr()) {
 OS << " indirect(";
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ee09a8566c3719e..77085ff34fca233 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -2495,14 +2495,16 @@ static Address 
emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
const VarDecl *VD, QualType T) {
   llvm::Optional Res =
   OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
-  // Return an invalid address if variable is MT_To and unified
-  // memory is not enabled. For all other cases: MT_Link and
-  // MT_To with unified memory, return a valid address.
-  if (!Res || (*

[clang] [OpenMP][libomptarget] Add map checks when running under unified shared memory (PR #69005)

2023-10-16 Thread Gheorghe-Teodor Bercea via cfe-commits

https://github.com/doru1004 updated 
https://github.com/llvm/llvm-project/pull/69005

>From cb4121c466a0fc357d6ca129bfdd4e7c5e2d11ee Mon Sep 17 00:00:00 2001
From: Doru Bercea 
Date: Wed, 16 Nov 2022 17:23:48 -0600
Subject: [PATCH 1/2] Fix declare target implementation to support enter.

---
 clang/include/clang/Basic/Attr.td |  4 +-
 .../clang/Basic/DiagnosticParseKinds.td   | 12 -
 clang/lib/AST/AttrImpl.cpp|  2 +-
 clang/lib/CodeGen/CGExpr.cpp  | 12 +++--
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 24 ++---
 clang/lib/CodeGen/CodeGenModule.cpp   |  6 ++-
 clang/lib/Parse/ParseOpenMP.cpp   | 39 ++
 clang/lib/Sema/SemaOpenMP.cpp | 10 ++--
 .../test/OpenMP/declare_target_ast_print.cpp  | 53 +++
 9 files changed, 130 insertions(+), 32 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 16cf932c3760bd3..eaf4a6db3600e07 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3749,8 +3749,8 @@ def OMPDeclareTargetDecl : InheritableAttr {
   let Documentation = [OMPDeclareTargetDocs];
   let Args = [
 EnumArgument<"MapType", "MapTypeTy",
- [ "to", "link" ],
- [ "MT_To", "MT_Link" ]>,
+ [ "to", "enter", "link" ],
+ [ "MT_To", "MT_Enter", "MT_Link" ]>,
 EnumArgument<"DevType", "DevTypeTy",
  [ "host", "nohost", "any" ],
  [ "DT_Host", "DT_NoHost", "DT_Any" ]>,
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 674d6bd34fc544f..27cd3da1f191c3d 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1383,12 +1383,22 @@ def note_omp_assumption_clause_continue_here
 : Note<"the ignored tokens spans until here">;
 def err_omp_declare_target_unexpected_clause: Error<
   "unexpected '%0' clause, only %select{'device_type'|'to' or 'link'|'to', 
'link' or 'device_type'|'device_type', 'indirect'|'to', 'link', 'device_type' 
or 'indirect'}1 clauses expected">;
+def err_omp_declare_target_unexpected_clause_52: Error<
+  "unexpected '%0' clause, only %select{'device_type'|'enter' or 
'link'|'enter', 'link' or 'device_type'|'device_type', 'indirect'|'enter', 
'link', 'device_type' or 'indirect'}1 clauses expected">;
 def err_omp_begin_declare_target_unexpected_implicit_to_clause: Error<
   "unexpected '(', only 'to', 'link' or 'device_type' clauses expected for 
'begin declare target' directive">;
-def err_omp_declare_target_unexpected_clause_after_implicit_to: Error<
+def err_omp_declare_target_wrong_clause_after_implicit_to: Error<
   "unexpected clause after an implicit 'to' clause">;
+def err_omp_declare_target_wrong_clause_after_implicit_enter: Error<
+  "unexpected clause after an implicit 'enter' clause">;
 def err_omp_declare_target_missing_to_or_link_clause: Error<
   "expected at least one %select{'to' or 'link'|'to', 'link' or 'indirect'}0 
clause">;
+def err_omp_declare_target_missing_enter_or_link_clause: Error<
+  "expected at least one %select{'enter' or 'link'|'enter', 'link' or 
'indirect'}0 clause">;
+def err_omp_declare_target_unexpected_to_clause: Error<
+  "unexpected 'to' clause, use 'enter' instead">;
+def err_omp_declare_target_unexpected_enter_clause: Error<
+  "unexpected 'enter' clause, use 'to' instead">;
 def err_omp_declare_target_multiple : Error<
   "%0 appears multiple times in clauses on the same declare target directive">;
 def err_omp_declare_target_indirect_device_type: Error<
diff --git a/clang/lib/AST/AttrImpl.cpp b/clang/lib/AST/AttrImpl.cpp
index cecbd703ac61e8c..da842f6b190e74d 100644
--- a/clang/lib/AST/AttrImpl.cpp
+++ b/clang/lib/AST/AttrImpl.cpp
@@ -137,7 +137,7 @@ void OMPDeclareTargetDeclAttr::printPrettyPragma(
   // Use fake syntax because it is for testing and debugging purpose only.
   if (getDevType() != DT_Any)
 OS << " device_type(" << ConvertDevTypeTyToStr(getDevType()) << ")";
-  if (getMapType() != MT_To)
+  if (getMapType() != MT_To && getMapType() != MT_Enter)
 OS << ' ' << ConvertMapTypeTyToStr(getMapType());
   if (Expr *E = getIndirectExpr()) {
 OS << " indirect(";
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ee09a8566c3719e..77085ff34fca233 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -2495,14 +2495,16 @@ static Address 
emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
const VarDecl *VD, QualType T) {
   llvm::Optional Res =
   OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
-  // Return an invalid address if variable is MT_To and unified
-  // memory is not enabled. For all other cases: MT_Link and
-  // MT_To with unified memory, return a valid address.
-  if (!Res || (*

[libunwind] [OpenMP][libomptarget] Add map checks when running under unified shared memory (PR #69005)

2023-10-16 Thread Gheorghe-Teodor Bercea via cfe-commits

https://github.com/doru1004 updated 
https://github.com/llvm/llvm-project/pull/69005

>From cb4121c466a0fc357d6ca129bfdd4e7c5e2d11ee Mon Sep 17 00:00:00 2001
From: Doru Bercea 
Date: Wed, 16 Nov 2022 17:23:48 -0600
Subject: [PATCH 1/2] Fix declare target implementation to support enter.

---
 clang/include/clang/Basic/Attr.td |  4 +-
 .../clang/Basic/DiagnosticParseKinds.td   | 12 -
 clang/lib/AST/AttrImpl.cpp|  2 +-
 clang/lib/CodeGen/CGExpr.cpp  | 12 +++--
 clang/lib/CodeGen/CGOpenMPRuntime.cpp | 24 ++---
 clang/lib/CodeGen/CodeGenModule.cpp   |  6 ++-
 clang/lib/Parse/ParseOpenMP.cpp   | 39 ++
 clang/lib/Sema/SemaOpenMP.cpp | 10 ++--
 .../test/OpenMP/declare_target_ast_print.cpp  | 53 +++
 9 files changed, 130 insertions(+), 32 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 16cf932c3760bd3..eaf4a6db3600e07 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3749,8 +3749,8 @@ def OMPDeclareTargetDecl : InheritableAttr {
   let Documentation = [OMPDeclareTargetDocs];
   let Args = [
 EnumArgument<"MapType", "MapTypeTy",
- [ "to", "link" ],
- [ "MT_To", "MT_Link" ]>,
+ [ "to", "enter", "link" ],
+ [ "MT_To", "MT_Enter", "MT_Link" ]>,
 EnumArgument<"DevType", "DevTypeTy",
  [ "host", "nohost", "any" ],
  [ "DT_Host", "DT_NoHost", "DT_Any" ]>,
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 674d6bd34fc544f..27cd3da1f191c3d 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1383,12 +1383,22 @@ def note_omp_assumption_clause_continue_here
 : Note<"the ignored tokens spans until here">;
 def err_omp_declare_target_unexpected_clause: Error<
   "unexpected '%0' clause, only %select{'device_type'|'to' or 'link'|'to', 
'link' or 'device_type'|'device_type', 'indirect'|'to', 'link', 'device_type' 
or 'indirect'}1 clauses expected">;
+def err_omp_declare_target_unexpected_clause_52: Error<
+  "unexpected '%0' clause, only %select{'device_type'|'enter' or 
'link'|'enter', 'link' or 'device_type'|'device_type', 'indirect'|'enter', 
'link', 'device_type' or 'indirect'}1 clauses expected">;
 def err_omp_begin_declare_target_unexpected_implicit_to_clause: Error<
   "unexpected '(', only 'to', 'link' or 'device_type' clauses expected for 
'begin declare target' directive">;
-def err_omp_declare_target_unexpected_clause_after_implicit_to: Error<
+def err_omp_declare_target_wrong_clause_after_implicit_to: Error<
   "unexpected clause after an implicit 'to' clause">;
+def err_omp_declare_target_wrong_clause_after_implicit_enter: Error<
+  "unexpected clause after an implicit 'enter' clause">;
 def err_omp_declare_target_missing_to_or_link_clause: Error<
   "expected at least one %select{'to' or 'link'|'to', 'link' or 'indirect'}0 
clause">;
+def err_omp_declare_target_missing_enter_or_link_clause: Error<
+  "expected at least one %select{'enter' or 'link'|'enter', 'link' or 
'indirect'}0 clause">;
+def err_omp_declare_target_unexpected_to_clause: Error<
+  "unexpected 'to' clause, use 'enter' instead">;
+def err_omp_declare_target_unexpected_enter_clause: Error<
+  "unexpected 'enter' clause, use 'to' instead">;
 def err_omp_declare_target_multiple : Error<
   "%0 appears multiple times in clauses on the same declare target directive">;
 def err_omp_declare_target_indirect_device_type: Error<
diff --git a/clang/lib/AST/AttrImpl.cpp b/clang/lib/AST/AttrImpl.cpp
index cecbd703ac61e8c..da842f6b190e74d 100644
--- a/clang/lib/AST/AttrImpl.cpp
+++ b/clang/lib/AST/AttrImpl.cpp
@@ -137,7 +137,7 @@ void OMPDeclareTargetDeclAttr::printPrettyPragma(
   // Use fake syntax because it is for testing and debugging purpose only.
   if (getDevType() != DT_Any)
 OS << " device_type(" << ConvertDevTypeTyToStr(getDevType()) << ")";
-  if (getMapType() != MT_To)
+  if (getMapType() != MT_To && getMapType() != MT_Enter)
 OS << ' ' << ConvertMapTypeTyToStr(getMapType());
   if (Expr *E = getIndirectExpr()) {
 OS << " indirect(";
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ee09a8566c3719e..77085ff34fca233 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -2495,14 +2495,16 @@ static Address 
emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
const VarDecl *VD, QualType T) {
   llvm::Optional Res =
   OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
-  // Return an invalid address if variable is MT_To and unified
-  // memory is not enabled. For all other cases: MT_Link and
-  // MT_To with unified memory, return a valid address.
-  if (!Res || (*

[clang] Null field access (PR #69223)

2023-10-16 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= 
Message-ID: 
In-Reply-To:


https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/69223

Looks like this should work as long as we don't dereference the value.


Note: This is a change from my local branch where I introduce integral 
pointers. One thing I changed is that null pointers are integral pointers and 
not block pointers, but in this version they are still block pointers so we 
have to be careful about `Pointee` being null.

>From b20da36444adfbdbddd6d0dddf06535815ffe0c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sun, 3 Sep 2023 07:03:04 +0200
Subject: [PATCH 1/2] [clang][Interp] Check pointer inc/dec ops for null

---
 clang/lib/AST/Interp/Interp.h|  7 +--
 clang/test/AST/Interp/arrays.cpp | 20 
 2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index e3e6a4cec63b194..3d226a40f9cf608 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1488,11 +1488,14 @@ static inline bool IncDecPtrHelper(InterpState &S, 
CodePtr OpPC,
const Pointer &Ptr) {
   using OneT = Integral<8, false>;
 
+  const Pointer &P = Ptr.deref();
+  if (!CheckNull(S, OpPC, P, CSK_ArrayIndex))
+return false;
+
   // Get the current value on the stack.
-  S.Stk.push(Ptr.deref());
+  S.Stk.push(P);
 
   // Now the current Ptr again and a constant 1.
-  Pointer P = Ptr.deref();
   OneT One = OneT::from(1);
   if (!OffsetHelper(S, OpPC, One, P))
 return false;
diff --git a/clang/test/AST/Interp/arrays.cpp b/clang/test/AST/Interp/arrays.cpp
index 281835f828bbd7c..18c4ae4354f54a0 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -333,6 +333,26 @@ namespace IncDec {
// expected-note {{in call to}} \
// ref-error {{not an integral constant 
expression}} \
   // ref-note {{in call to}}
+
+  constexpr int nullptr1(bool Pre) {
+int *a = nullptr;
+if (Pre)
+  ++a; // ref-note {{arithmetic on null pointer}} \
+   // expected-note {{arithmetic on null pointer}}
+else
+  a++; // ref-note {{arithmetic on null pointer}} \
+   // expected-note {{arithmetic on null pointer}}
+return 1;
+  }
+  static_assert(nullptr1(true) == 1, ""); // ref-error {{not an integral 
constant expression}} \
+  // ref-note {{in call to}} \
+  // expected-error {{not an integral 
constant expression}} \
+  // expected-note {{in call to}}
+
+  static_assert(nullptr1(false) == 1, ""); // ref-error {{not an integral 
constant expression}} \
+   // ref-note {{in call to}} \
+   // expected-error {{not an integral 
constant expression}} \
+   // expected-note {{in call to}}
 };
 
 namespace ZeroInit {

>From a1d79cbe5c3ad257b44beb0ba3b8cb3e0dcbe84a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Mon, 16 Oct 2023 17:51:44 +0200
Subject: [PATCH 2/2] [clang][Interp] Only diagnose null field access in
 constant contexts

---
 clang/lib/AST/Interp/Interp.h |  2 +-
 clang/lib/AST/Interp/Pointer.h|  4 +++-
 clang/test/AST/Interp/c.c | 12 +++
 clang/test/AST/Interp/records.cpp | 33 +++
 4 files changed, 49 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 3d226a40f9cf608..92584421d4d 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1159,7 +1159,7 @@ inline bool GetPtrGlobal(InterpState &S, CodePtr OpPC, 
uint32_t I) {
 /// 2) Pushes Pointer.atField(Off) on the stack
 inline bool GetPtrField(InterpState &S, CodePtr OpPC, uint32_t Off) {
   const Pointer &Ptr = S.Stk.pop();
-  if (!CheckNull(S, OpPC, Ptr, CSK_Field))
+  if (S.inConstantContext() && !CheckNull(S, OpPC, Ptr, CSK_Field))
 return false;
   if (!CheckExtern(S, OpPC, Ptr))
 return false;
diff --git a/clang/lib/AST/Interp/Pointer.h b/clang/lib/AST/Interp/Pointer.h
index d5279e757f04764..c6a2f371764d02f 100644
--- a/clang/lib/AST/Interp/Pointer.h
+++ b/clang/lib/AST/Interp/Pointer.h
@@ -295,7 +295,7 @@ class Pointer {
   bool isUnion() const;
 
   /// Checks if the storage is extern.
-  bool isExtern() const { return Pointee->isExtern(); }
+  bool isExtern() const { return Pointee && Pointee->isExtern(); }
   /// Checks if the storage is static.
   bool isStatic() const { return Pointee->isStatic(); }
   /// Checks if the storage is temporary.
@@ -348,6 +348,8 @@ class Pointer {
 
   /// Checks if the index is one past end.
   bool isOnePastEnd() const {
+if (!Pointee)
+  return fa

  1   2   3   4   >