[clang] [llvm] [Sema] Implement support for -Wformat-signedness (PR #74440)

2023-12-05 Thread Takuya Shimizu via cfe-commits


@@ -918,6 +918,9 @@ def Wdeprecated : Flag<["-"], "Wdeprecated">, 
Group,
   HelpText<"Enable warnings for deprecated constructs and define 
__DEPRECATED">;
 def Wno_deprecated : Flag<["-"], "Wno-deprecated">, Group,
   Visibility<[ClangOption, CC1Option]>;
+def Wformat_signedness : Flag<["-"], "Wformat-signedness">,

hazohelet wrote:

I think the warning option config should go to 
`clang/include/clang/Basic/DiagnosticSemaKinds.td` instead of the toplevel 
driver setting. For example,  you wouldn't have `-Wno-format-signedness` atm.

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


[llvm] [clang] [Sema] Implement support for -Wformat-signedness (PR #74440)

2023-12-11 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

> I need to extend the tablegen backend ClangDiagnosticsEmitter with some kind 
> of new option to handle this, right?

Alternatively, you could probably use `DiagnosticsEngine::isIgnored` to check 
if the `-Wformat-signedness` is enabled or not, and control whether 
`MatchSignedNess` is `NoMatch` or `Match`, as your first implementation did.
This way we can achieve GCC compatibility for 1, 2, 3, 4, 6, 7, while 
benefitting from a real warning flag.
However, in this implementation `-Wformat-signedness` would be an _dummy 
warning_ which never gets emitted. As far as I know, there isn't anything 
similar in the codebase, so it might not be the ideal way.

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


[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-26 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/67817

>From 7f4db6d81f24adb72416e79bde65a1a13d9a82b8 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Fri, 29 Sep 2023 23:49:11 +0900
Subject: [PATCH 1/4] [clang][ExprConst] Fix crash on uninitialized array
 subobject

https://reviews.llvm.org/D146358 was assuming that all subobjects have
their own name (`SubobjectDecl`), but it was not true for array
elements.

Fixes https://github.com/llvm/llvm-project/issues/67317
---
 clang/include/clang/Basic/DiagnosticASTKinds.td |  2 +-
 clang/lib/AST/ExprConstant.cpp  | 13 +
 clang/lib/AST/Interp/Interp.cpp |  2 +-
 clang/test/SemaCXX/eval-crashes.cpp |  7 +++
 4 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index b70cf1071d865da..492f6b270ca5201 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -69,7 +69,7 @@ def note_consteval_address_accessible : Note<
   "%select{pointer|reference}0 to a consteval declaration "
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
-  "subobject %0 is not initialized">;
+  "subobject %select{of type |}0%1 is not initialized">;
 def note_constexpr_uninitialized_base : Note<
   "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 320e2ef12c38db3..131624e4e82db6e 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2411,10 +2411,15 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-assert(SubobjectDecl && "SubobjectDecl shall be non-null");
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
-Info.Note(SubobjectDecl->getLocation(),
-  diag::note_constexpr_subobject_declared_here);
+if (SubobjectDecl) {
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
+  << true << SubobjectDecl;
+  Info.Note(SubobjectDecl->getLocation(),
+diag::note_constexpr_subobject_declared_here);
+} else {
+  // FIXME: We should add a test to check the output of this case.
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << false << 
Type;
+}
 return false;
   }
 
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 1ebbadc375f38c8..50ee4192712fcbe 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -439,7 +439,7 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
const FieldDecl *SubObjDecl) {
   assert(SubObjDecl && "Subobject declaration does not exist");
-  S.FFDiag(SI, diag::note_constexpr_uninitialized) << SubObjDecl;
+  S.FFDiag(SI, diag::note_constexpr_uninitialized) << true << SubObjDecl;
   S.Note(SubObjDecl->getLocation(),
  diag::note_constexpr_subobject_declared_here);
 }
diff --git a/clang/test/SemaCXX/eval-crashes.cpp 
b/clang/test/SemaCXX/eval-crashes.cpp
index 3e59ad31c559da8..ac04b113f99b7aa 100644
--- a/clang/test/SemaCXX/eval-crashes.cpp
+++ b/clang/test/SemaCXX/eval-crashes.cpp
@@ -54,3 +54,10 @@ namespace pr33140_10 {
   int a(const int &n = 0);
   bool b() { return a() == a(); }
 }
+
+namespace GH67317 {
+struct array {
+  int (&data)[2];
+  array() : data(*new int[1][2]) {}
+};
+}

>From fe009c3eeac2283df7b4b966d91b2a2bfb824f56 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Sat, 30 Sep 2023 00:03:29 +0900
Subject: [PATCH 2/4] Add release note

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 82550232947f743..8eca67677f1d82c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -529,6 +529,8 @@ Bug Fixes in This Version
   ``thread_local`` instead of ``_Thread_local``.
   Fixes (`#70068 `_) and
   (`#69167 `_)
+- Fix crash from constexpr evaluator evaluating uninitialized arrays as rvalue.
+  Fixes (`#67317 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

>From 9fb5dd6c3b3f0e456e6a8deb99caa97fbb2f8cc0 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 16 Oct 2023 13:43:02 +0900
Subject: [PATCH 3/4] Add test to test the fallbacked output

---
 clang/lib/AST/ExprConstant.cpp   | 1 -
 clang/test/S

[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-26 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-26 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

Thanks for the heads up. I'll request backporting in a few hours when buildbots 
finish running tests.

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


[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-15 Thread Takuya Shimizu via cfe-commits


@@ -2411,10 +2411,15 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-assert(SubobjectDecl && "SubobjectDecl shall be non-null");
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
-Info.Note(SubobjectDecl->getLocation(),
-  diag::note_constexpr_subobject_declared_here);
+if (SubobjectDecl) {
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
+  << true << SubobjectDecl;
+  Info.Note(SubobjectDecl->getLocation(),
+diag::note_constexpr_subobject_declared_here);
+} else {
+  // FIXME: We should add a test to check the output of this case.
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << false << 
Type;

hazohelet wrote:

Finally I found a test case that can check the fallback diagnostic message: 
https://godbolt.org/z/Mc3nPq15n
Clang 16's output is a little weird in that it does not mention `new 
*char[3][1]` part, and this patch's fallback approach inherits this behavior.

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


[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-15 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/67817

>From acb5d8286335f85732ede8d33ac2529e13a3f61b Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Fri, 29 Sep 2023 23:49:11 +0900
Subject: [PATCH 1/3] [clang][ExprConst] Fix crash on uninitialized array
 subobject

https://reviews.llvm.org/D146358 was assuming that all subobjects have
their own name (`SubobjectDecl`), but it was not true for array
elements.

Fixes https://github.com/llvm/llvm-project/issues/67317
---
 clang/include/clang/Basic/DiagnosticASTKinds.td |  2 +-
 clang/lib/AST/ExprConstant.cpp  | 13 +
 clang/lib/AST/Interp/Interp.cpp |  2 +-
 clang/test/SemaCXX/eval-crashes.cpp |  7 +++
 4 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index 0019553233fdef6..cebcefff53d18ae 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -69,7 +69,7 @@ def note_consteval_address_accessible : Note<
   "%select{pointer|reference}0 to a consteval declaration "
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
-  "subobject %0 is not initialized">;
+  "subobject %select{of type |}0%1 is not initialized">;
 def note_constexpr_uninitialized_base : Note<
   "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index e5539dedec02a4b..bfa2837fe746da3 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2411,10 +2411,15 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-assert(SubobjectDecl && "SubobjectDecl shall be non-null");
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
-Info.Note(SubobjectDecl->getLocation(),
-  diag::note_constexpr_subobject_declared_here);
+if (SubobjectDecl) {
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
+  << true << SubobjectDecl;
+  Info.Note(SubobjectDecl->getLocation(),
+diag::note_constexpr_subobject_declared_here);
+} else {
+  // FIXME: We should add a test to check the output of this case.
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << false << 
Type;
+}
 return false;
   }
 
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index a4d6844ebe61722..51bf8f9197ae134 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -404,7 +404,7 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
const FieldDecl *SubObjDecl) {
   assert(SubObjDecl && "Subobject declaration does not exist");
-  S.FFDiag(SI, diag::note_constexpr_uninitialized) << SubObjDecl;
+  S.FFDiag(SI, diag::note_constexpr_uninitialized) << true << SubObjDecl;
   S.Note(SubObjDecl->getLocation(),
  diag::note_constexpr_subobject_declared_here);
 }
diff --git a/clang/test/SemaCXX/eval-crashes.cpp 
b/clang/test/SemaCXX/eval-crashes.cpp
index 3e59ad31c559da8..ac04b113f99b7aa 100644
--- a/clang/test/SemaCXX/eval-crashes.cpp
+++ b/clang/test/SemaCXX/eval-crashes.cpp
@@ -54,3 +54,10 @@ namespace pr33140_10 {
   int a(const int &n = 0);
   bool b() { return a() == a(); }
 }
+
+namespace GH67317 {
+struct array {
+  int (&data)[2];
+  array() : data(*new int[1][2]) {}
+};
+}

>From cd6fd87b28ffc94a5e45bcc763beec73d6d13e20 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Sat, 30 Sep 2023 00:03:29 +0900
Subject: [PATCH 2/3] Add release note

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 52d5b9a3f66d155..12204d0cdc0bc45 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -397,6 +397,8 @@ 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 crash from constexpr evaluator evaluating uninitialized arrays as rvalue.
+  Fixes (`#67317 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

>From d49fbc1cb7e596f0c8210739410c24950d46b99e Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 16 Oct 2023 13:43:02 +0900
Subject: [PATCH 3/3] Add test to test the fallbacked output

---
 clang/lib/AST/ExprConst

[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-15 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/67817

>From acb5d8286335f85732ede8d33ac2529e13a3f61b Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Fri, 29 Sep 2023 23:49:11 +0900
Subject: [PATCH 1/4] [clang][ExprConst] Fix crash on uninitialized array
 subobject

https://reviews.llvm.org/D146358 was assuming that all subobjects have
their own name (`SubobjectDecl`), but it was not true for array
elements.

Fixes https://github.com/llvm/llvm-project/issues/67317
---
 clang/include/clang/Basic/DiagnosticASTKinds.td |  2 +-
 clang/lib/AST/ExprConstant.cpp  | 13 +
 clang/lib/AST/Interp/Interp.cpp |  2 +-
 clang/test/SemaCXX/eval-crashes.cpp |  7 +++
 4 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index 0019553233fdef6..cebcefff53d18ae 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -69,7 +69,7 @@ def note_consteval_address_accessible : Note<
   "%select{pointer|reference}0 to a consteval declaration "
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
-  "subobject %0 is not initialized">;
+  "subobject %select{of type |}0%1 is not initialized">;
 def note_constexpr_uninitialized_base : Note<
   "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index e5539dedec02a4b..bfa2837fe746da3 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2411,10 +2411,15 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-assert(SubobjectDecl && "SubobjectDecl shall be non-null");
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
-Info.Note(SubobjectDecl->getLocation(),
-  diag::note_constexpr_subobject_declared_here);
+if (SubobjectDecl) {
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
+  << true << SubobjectDecl;
+  Info.Note(SubobjectDecl->getLocation(),
+diag::note_constexpr_subobject_declared_here);
+} else {
+  // FIXME: We should add a test to check the output of this case.
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << false << 
Type;
+}
 return false;
   }
 
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index a4d6844ebe61722..51bf8f9197ae134 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -404,7 +404,7 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
const FieldDecl *SubObjDecl) {
   assert(SubObjDecl && "Subobject declaration does not exist");
-  S.FFDiag(SI, diag::note_constexpr_uninitialized) << SubObjDecl;
+  S.FFDiag(SI, diag::note_constexpr_uninitialized) << true << SubObjDecl;
   S.Note(SubObjDecl->getLocation(),
  diag::note_constexpr_subobject_declared_here);
 }
diff --git a/clang/test/SemaCXX/eval-crashes.cpp 
b/clang/test/SemaCXX/eval-crashes.cpp
index 3e59ad31c559da8..ac04b113f99b7aa 100644
--- a/clang/test/SemaCXX/eval-crashes.cpp
+++ b/clang/test/SemaCXX/eval-crashes.cpp
@@ -54,3 +54,10 @@ namespace pr33140_10 {
   int a(const int &n = 0);
   bool b() { return a() == a(); }
 }
+
+namespace GH67317 {
+struct array {
+  int (&data)[2];
+  array() : data(*new int[1][2]) {}
+};
+}

>From cd6fd87b28ffc94a5e45bcc763beec73d6d13e20 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Sat, 30 Sep 2023 00:03:29 +0900
Subject: [PATCH 2/4] Add release note

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 52d5b9a3f66d155..12204d0cdc0bc45 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -397,6 +397,8 @@ 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 crash from constexpr evaluator evaluating uninitialized arrays as rvalue.
+  Fixes (`#67317 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

>From d49fbc1cb7e596f0c8210739410c24950d46b99e Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 16 Oct 2023 13:43:02 +0900
Subject: [PATCH 3/4] Add test to test the fallbacked output

---
 clang/lib/AST/ExprConst

[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-22 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

Ping

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


[clang] [clang][Sema] Refine unused-member-function diagnostic message for constructors (PR #84515)

2024-03-20 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

Please add a release note line to `clang/docs/ReleaseNotes.rst` because this 
patch changes the diagnostic behavior of clang

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


[clang] [clang][Sema] Fix crash on atomic builtins with incomplete type args (PR #96374)

2024-06-29 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Fix crash on atomic builtins with incomplete type args (PR #96374)

2024-06-21 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet created 
https://github.com/llvm/llvm-project/pull/96374

This patch fixes the crash when pointers to incomplete type are passed to 
atomic builtins such as `__atomic_load`.
`ASTContext::getTypeInfoInChars` assumes that the argument type is a complete 
type, so I added a check to eliminate cases where incomplete types gets passed 
to this function

Relevant PR: https://github.com/llvm/llvm-project/pull/91057
Fixes https://github.com/llvm/llvm-project/issues/96289

>From 7a76e4fe198eb2b9751ccd40f8e3850e7bae119c Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Sat, 22 Jun 2024 12:05:50 +0900
Subject: [PATCH] [clang][Sema] Fix crash on atomic with incomplete type args

---
 clang/lib/Sema/SemaChecking.cpp |  3 ++-
 clang/test/Sema/atomic-ops.c| 30 ++
 2 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 7a2076d139c69..1872bdb5767f0 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4570,7 +4570,8 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, 
SourceRange ExprRange,
   }
 
   // Pointer to object of size zero is not allowed.
-  if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
+  if (!AtomTy->isIncompleteType() &&
+  Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
 << Ptr->getType() << 1 << Ptr->getSourceRange();
 return ExprError();
diff --git a/clang/test/Sema/atomic-ops.c b/clang/test/Sema/atomic-ops.c
index 2024b81ce6aec..d957461b6cb75 100644
--- a/clang/test/Sema/atomic-ops.c
+++ b/clang/test/Sema/atomic-ops.c
@@ -671,6 +671,36 @@ void zeroSizeArgError(struct Z *a, struct Z *b, struct Z 
*c) {
 
 }
 
+struct IncompleteTy IncA, IncB, IncC; // expected-error 3{{tentative 
definition has type 'struct IncompleteTy' that is never completed}} \
+  // expected-note 3{{forward declaration 
of 'struct IncompleteTy'}}
+void incompleteTypeArgError() {
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_relaxed); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_acq_rel); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_acquire); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_consume); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_release); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_seq_cst); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_relaxed); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_acq_rel); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_acquire); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_consume); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_release); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_seq_cst); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_relaxed); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_acq_rel); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_acquire); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_consume); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_release); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_seq_cst); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_relaxed, 
memory_order_relaxed); // expected-error {{must be a pointer to a 
trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_acq_rel, 
memory_order_acq_rel); // expected-error {{must be a pointer to a 
trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_acquire, 
memory_order_acquire); // expected-error {{must be a pointer to a 
trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_consume, 
memor

[clang] [clang][Sema] Fix crash on atomic builtins with incomplete type args (PR #96374)

2024-06-24 Thread Takuya Shimizu via cfe-commits


@@ -4570,7 +4570,8 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, 
SourceRange ExprRange,
   }
 
   // Pointer to object of size zero is not allowed.
-  if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
+  if (!AtomTy->isIncompleteType() &&

hazohelet wrote:

The current diagnostic message only says we need trivially-copyable type here, 
and the `RequireCompleteType` version would say we need complete type here and 
it sounds more understandable to me.

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


[clang] [clang][Sema] Fix crash on atomic builtins with incomplete type args (PR #96374)

2024-06-24 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

Thanks for the feedback. `RequireCompleteType` seems like the right direction.
I'm not writing about the crash fix to the release note because this crash was 
introduced AFTER clang 18 was released.


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


[clang] [clang][Sema] Fix crash on atomic builtins with incomplete type args (PR #96374)

2024-06-24 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/96374

>From a655e6beb048aa0d6bde730f586d3261e43f69a6 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Sat, 22 Jun 2024 12:05:50 +0900
Subject: [PATCH 1/2] [clang][Sema] Fix crash on atomic with incomplete type
 args

---
 clang/lib/Sema/SemaChecking.cpp |  3 ++-
 clang/test/Sema/atomic-ops.c| 30 ++
 2 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 87988519e7691..6d746481ccbb9 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4582,7 +4582,8 @@ ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, 
SourceRange ExprRange,
   }
 
   // Pointer to object of size zero is not allowed.
-  if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
+  if (!AtomTy->isIncompleteType() &&
+  Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
 << Ptr->getType() << 1 << Ptr->getSourceRange();
 return ExprError();
diff --git a/clang/test/Sema/atomic-ops.c b/clang/test/Sema/atomic-ops.c
index 2024b81ce6aec..d957461b6cb75 100644
--- a/clang/test/Sema/atomic-ops.c
+++ b/clang/test/Sema/atomic-ops.c
@@ -671,6 +671,36 @@ void zeroSizeArgError(struct Z *a, struct Z *b, struct Z 
*c) {
 
 }
 
+struct IncompleteTy IncA, IncB, IncC; // expected-error 3{{tentative 
definition has type 'struct IncompleteTy' that is never completed}} \
+  // expected-note 3{{forward declaration 
of 'struct IncompleteTy'}}
+void incompleteTypeArgError() {
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_relaxed); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_acq_rel); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_acquire); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_consume); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_release); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_exchange(&IncB, &IncB, &IncC, memory_order_seq_cst); // 
expected-error {{must be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_relaxed); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_acq_rel); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_acquire); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_consume); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_release); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_load(&IncA, &IncB, memory_order_seq_cst); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_relaxed); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_acq_rel); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_acquire); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_consume); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_release); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_store(&IncA, &IncB, memory_order_seq_cst); // expected-error {{must 
be a pointer to a trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_relaxed, 
memory_order_relaxed); // expected-error {{must be a pointer to a 
trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_acq_rel, 
memory_order_acq_rel); // expected-error {{must be a pointer to a 
trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_acquire, 
memory_order_acquire); // expected-error {{must be a pointer to a 
trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_consume, 
memory_order_consume); // expected-error {{must be a pointer to a 
trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_release, 
memory_order_release); // expected-error {{must be a pointer to a 
trivially-copyable type}}
+  __atomic_compare_exchange(&IncA, &IncB, &IncC, 0, memory_order_seq_cst, 
memory_order_seq_cst); // expected-error {{must be a pointer to a 
trivia

[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-24 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

> ping @hazohelet . This should be good to land and should help clear some red 
> in our CI for Linux kernel builds.

Thanks for the ping. I was away for a while. I'm merging this after updating 
the PR descriptions.

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


[clang] [clang][Sema] Make format size estimator aware of %p's existence in format string (PR #65969)

2023-09-24 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Make format size estimator aware of %p's existence in format string (PR #65969)

2023-09-24 Thread Takuya Shimizu via cfe-commits

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


[clang] 491b281 - [clang][SemaCXX] Diagnose tautological uses of consteval if and is_constant_evaluated

2023-09-26 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-09-27T09:26:06+09:00
New Revision: 491b2810fb7fe5f080fa9c4f5945ed0a6909dc92

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

LOG: [clang][SemaCXX] Diagnose tautological uses of consteval if and 
is_constant_evaluated

This patch makes clang diagnose extensive cases of consteval if and 
is_constant_evaluated usage that are tautologically true or false.
This introduces a new IsRuntimeEvaluated boolean flag to 
Sema::ExpressionEvaluationContextRecord that means the immediate appearance of 
if consteval or is_constant_evaluated are tautologically false(e.g. inside if 
!consteval {} block or non-constexpr-qualified function definition body)
This patch also pushes new expression evaluation context when parsing the 
condition of if constexpr and initializer of constexpr variables so that Sema 
can be aware that the use of consteval if and is_consteval are tautologically 
true in if constexpr condition and constexpr variable initializers.
BEFORE this patch, the warning for is_constant_evaluated was emitted from 
constant evaluator. This patch moves the warning logic to Sema in order to 
diagnose tautological use of is_constant_evaluated in the same way as consteval 
if.

This patch separates initializer evaluation context from InitializerScopeRAII.
This fixes a bug that was happening when user takes address of function address 
in initializers of non-local variables.

Fixes https://github.com/llvm/llvm-project/issues/43760
Fixes https://github.com/llvm/llvm-project/issues/51567

Reviewed By: cor3ntin, ldionne
Differential Revision: https://reviews.llvm.org/D155064

Added: 
clang/test/SemaCXX/fixit-tautological-meta-constant.cpp
clang/test/SemaCXX/warn-tautological-meta-constant.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticASTKinds.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/ExprConstant.cpp
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/ParseExpr.cpp
clang/lib/Parse/ParseExprCXX.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaLambda.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/AST/Interp/builtins.cpp
clang/test/AST/Interp/if.cpp
clang/test/AST/Interp/literals.cpp
clang/test/CXX/expr/expr.const/p2-0x.cpp
clang/test/CXX/expr/expr.const/p6-2a.cpp
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp
clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p4.cpp
clang/test/Parser/pragma-fenv_access.c
clang/test/SemaCXX/constant-conversion.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/cxx2a-consteval.cpp
clang/test/SemaCXX/cxx2b-consteval-if.cpp
clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
clang/test/SemaCXX/vartemplate-lambda.cpp
clang/test/SemaCXX/warn-constant-evaluated-constexpr.cpp
clang/test/SemaTemplate/concepts.cpp
clang/unittests/Support/TimeProfilerTest.cpp
libcxx/include/__type_traits/is_constant_evaluated.h

libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp

libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8a136aae5489a8c..a17efab57bcdfa3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -206,6 +206,12 @@ Improvements to Clang's diagnostics
 - Clang no longer emits irrelevant notes about unsatisfied constraint 
expressions
   on the left-hand side of ``||`` when the right-hand side constraint is 
satisfied.
   (`#54678: `_).
+- Clang now diagnoses wider cases of tautological use of consteval if or
+  ``std::is_constant_evaluated``. This also suppresses some false positives.
+  (`#43760: `_)
+  (`#51567: `_)
+- Clang now diagnoses narrowing implicit conversions on variable initializers 
in immediate
+  function context and on constexpr variable template initializers.
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index d2656310e79c9b8..1abb0b89af9f1c1 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -413,10 +413,6 @@ def warn_cons

[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-09-29 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet created 
https://github.com/llvm/llvm-project/pull/67817

https://reviews.llvm.org/D146358 was assuming that all subobjects have
their own name (`SubobjectDecl`), but it was not true for array
elements.

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


>From e331f12dd6f8976df44855619ab740aee86ddd2e Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Fri, 29 Sep 2023 23:49:11 +0900
Subject: [PATCH] [clang][ExprConst] Fix crash on uninitialized array subobject

https://reviews.llvm.org/D146358 was assuming that all subobjects have
their own name (`SubobjectDecl`), but it was not true for array
elements.

Fixes https://github.com/llvm/llvm-project/issues/67317
---
 clang/include/clang/Basic/DiagnosticASTKinds.td |  2 +-
 clang/lib/AST/ExprConstant.cpp  | 13 +
 clang/lib/AST/Interp/Interp.cpp |  2 +-
 clang/test/SemaCXX/eval-crashes.cpp |  7 +++
 4 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index d2656310e79c9b8..71dabac2d32402a 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -69,7 +69,7 @@ def note_consteval_address_accessible : Note<
   "%select{pointer|reference}0 to a consteval declaration "
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
-  "subobject %0 is not initialized">;
+  "subobject %select{of type |}0%1 is not initialized">;
 def note_constexpr_uninitialized_base : Note<
   "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index f0d53d6ae18e804..acf4b33242c4a27 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2411,10 +2411,15 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-assert(SubobjectDecl && "SubobjectDecl shall be non-null");
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
-Info.Note(SubobjectDecl->getLocation(),
-  diag::note_constexpr_subobject_declared_here);
+if (SubobjectDecl) {
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
+  << true << SubobjectDecl;
+  Info.Note(SubobjectDecl->getLocation(),
+diag::note_constexpr_subobject_declared_here);
+} else {
+  // FIXME: We should add a test to check the output of this case.
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << false << 
Type;
+}
 return false;
   }
 
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index e1951574edb6288..0e7e9bac1c8079a 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -404,7 +404,7 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
const FieldDecl *SubObjDecl) {
   assert(SubObjDecl && "Subobject declaration does not exist");
-  S.FFDiag(SI, diag::note_constexpr_uninitialized) << SubObjDecl;
+  S.FFDiag(SI, diag::note_constexpr_uninitialized) << true << SubObjDecl;
   S.Note(SubObjDecl->getLocation(),
  diag::note_constexpr_subobject_declared_here);
 }
diff --git a/clang/test/SemaCXX/eval-crashes.cpp 
b/clang/test/SemaCXX/eval-crashes.cpp
index 3e59ad31c559da8..ac04b113f99b7aa 100644
--- a/clang/test/SemaCXX/eval-crashes.cpp
+++ b/clang/test/SemaCXX/eval-crashes.cpp
@@ -54,3 +54,10 @@ namespace pr33140_10 {
   int a(const int &n = 0);
   bool b() { return a() == a(); }
 }
+
+namespace GH67317 {
+struct array {
+  int (&data)[2];
+  array() : data(*new int[1][2]) {}
+};
+}

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


[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-09-29 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/67817

>From e331f12dd6f8976df44855619ab740aee86ddd2e Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Fri, 29 Sep 2023 23:49:11 +0900
Subject: [PATCH 1/2] [clang][ExprConst] Fix crash on uninitialized array
 subobject

https://reviews.llvm.org/D146358 was assuming that all subobjects have
their own name (`SubobjectDecl`), but it was not true for array
elements.

Fixes https://github.com/llvm/llvm-project/issues/67317
---
 clang/include/clang/Basic/DiagnosticASTKinds.td |  2 +-
 clang/lib/AST/ExprConstant.cpp  | 13 +
 clang/lib/AST/Interp/Interp.cpp |  2 +-
 clang/test/SemaCXX/eval-crashes.cpp |  7 +++
 4 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index d2656310e79c9b8..71dabac2d32402a 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -69,7 +69,7 @@ def note_consteval_address_accessible : Note<
   "%select{pointer|reference}0 to a consteval declaration "
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
-  "subobject %0 is not initialized">;
+  "subobject %select{of type |}0%1 is not initialized">;
 def note_constexpr_uninitialized_base : Note<
   "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index f0d53d6ae18e804..acf4b33242c4a27 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2411,10 +2411,15 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-assert(SubobjectDecl && "SubobjectDecl shall be non-null");
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
-Info.Note(SubobjectDecl->getLocation(),
-  diag::note_constexpr_subobject_declared_here);
+if (SubobjectDecl) {
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
+  << true << SubobjectDecl;
+  Info.Note(SubobjectDecl->getLocation(),
+diag::note_constexpr_subobject_declared_here);
+} else {
+  // FIXME: We should add a test to check the output of this case.
+  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << false << 
Type;
+}
 return false;
   }
 
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index e1951574edb6288..0e7e9bac1c8079a 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -404,7 +404,7 @@ bool CheckPure(InterpState &S, CodePtr OpPC, const 
CXXMethodDecl *MD) {
 static void DiagnoseUninitializedSubobject(InterpState &S, const SourceInfo 
&SI,
const FieldDecl *SubObjDecl) {
   assert(SubObjDecl && "Subobject declaration does not exist");
-  S.FFDiag(SI, diag::note_constexpr_uninitialized) << SubObjDecl;
+  S.FFDiag(SI, diag::note_constexpr_uninitialized) << true << SubObjDecl;
   S.Note(SubObjDecl->getLocation(),
  diag::note_constexpr_subobject_declared_here);
 }
diff --git a/clang/test/SemaCXX/eval-crashes.cpp 
b/clang/test/SemaCXX/eval-crashes.cpp
index 3e59ad31c559da8..ac04b113f99b7aa 100644
--- a/clang/test/SemaCXX/eval-crashes.cpp
+++ b/clang/test/SemaCXX/eval-crashes.cpp
@@ -54,3 +54,10 @@ namespace pr33140_10 {
   int a(const int &n = 0);
   bool b() { return a() == a(); }
 }
+
+namespace GH67317 {
+struct array {
+  int (&data)[2];
+  array() : data(*new int[1][2]) {}
+};
+}

>From fb69c5ab54087f86111c7eb7600a4d8015f7d092 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Sat, 30 Sep 2023 00:03:29 +0900
Subject: [PATCH 2/2] Add release note

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 09302040a3510b6..195896ae089ba7f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -269,6 +269,8 @@ Bug Fixes in This Version
 - Fixes crash when trying to obtain the common sugared type of
   `decltype(instantiation-dependent-expr)`.
   Fixes (`#67603 `_)
+- Fix crash from constexpr evaluator evaluating uninitialized arrays as rvalue.
+  Fixes (`#67317 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-11 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet created 
https://github.com/llvm/llvm-project/pull/65969:

GCC stops counting format string's size when it sees %p format in order to 
avoid `Wformat-truncation` false positive against Linux kernel's format 
extension (%pOF, for example).
This change makes clang's behavior align with GCC's.
As requested in https://github.com/llvm/llvm-project/issues/64871


>From 80d8743441ce1e25f19dbc48bce480b5becfa208 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Tue, 12 Sep 2023 00:39:44 +0900
Subject: [PATCH] [clang][Sema] Stop format size estimator upon %p to adapt to
 linux kernel's extension

GCC stops counting format string's size when it sees %p format in order to 
avoid `Wformat-truncation` false positive against Linux kernel's format 
extension (%pOF, for example).
This change makes clang's behavior align with GCC's.
As requested in https://github.com/llvm/llvm-project/issues/64871
---
 clang/include/clang/AST/FormatString.h |  6 ++
 clang/lib/AST/PrintfFormatString.cpp   |  8 +++-
 clang/lib/Sema/SemaChecking.cpp| 10 ++
 clang/test/Sema/warn-fortify-source.c  | 16 +---
 4 files changed, 36 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index 5c4ad9baaef608c..97ce3cfe0b25c68 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -742,6 +742,12 @@ class FormatStringHandler {
 return true;
   }
 
+  virtual bool
+  ShouldStopOnFormatSpecifier(const analyze_printf::PrintfSpecifier &FS,
+  unsigned RemainLen) {
+return false;
+  }
+
   /// Handle mask types whose sizes are not between one and eight bytes.
   virtual void handleInvalidMaskType(StringRef MaskType) {}
 
diff --git a/clang/lib/AST/PrintfFormatString.cpp 
b/clang/lib/AST/PrintfFormatString.cpp
index f0b9d0ecaf23461..750f584d8d37a76 100644
--- a/clang/lib/AST/PrintfFormatString.cpp
+++ b/clang/lib/AST/PrintfFormatString.cpp
@@ -429,7 +429,13 @@ bool 
clang::analyze_format_string::ParsePrintfString(FormatStringHandler &H,
 // we can recover from?
 if (!FSR.hasValue())
   continue;
-// We have a format specifier.  Pass it to the callback.
+// We have a format specifier.
+// In case the handler needs to abort parsing upon specific specifiers
+if (H.ShouldStopOnFormatSpecifier(
+FSR.getValue(), static_cast(E - FSR.getStart( {
+  return false;
+}
+// Pass the format specifier to the callback.
 if (!H.HandlePrintfSpecifier(FSR.getValue(), FSR.getStart(),
  I - FSR.getStart(), Target))
   return true;
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 3b4ac613da76aa8..1a6ff6cfa19b661 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -860,6 +860,16 @@ class EstimateSizeFormatHandler
   : Size(std::min(Format.find(0), Format.size()) +
  1 /* null byte always written by sprintf */) {}
 
+  bool ShouldStopOnFormatSpecifier(const analyze_printf::PrintfSpecifier &FS,
+   unsigned RemainLen) override {
+if (FS.getConversionSpecifier().getKind() ==
+analyze_printf::PrintfConversionSpecifier::pArg) {
+  assert(Size >= RemainLen && "no underflow");
+  Size -= RemainLen;
+  return true;
+}
+return false;
+  }
   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  const char *, unsigned SpecifierLen,
  const TargetInfo &) override {
diff --git a/clang/test/Sema/warn-fortify-source.c 
b/clang/test/Sema/warn-fortify-source.c
index 5ed9782b26fb788..fba6c718be4a33a 100644
--- a/clang/test/Sema/warn-fortify-source.c
+++ b/clang/test/Sema/warn-fortify-source.c
@@ -85,7 +85,7 @@ void call_memset(void) {
   __builtin_memset(buf, 0xff, 11); // expected-warning {{'memset' will always 
overflow; destination buffer has size 10, but size argument is 11}}
 }
 
-void call_snprintf(double d) {
+void call_snprintf(double d, int *ptr) {
   char buf[10];
   __builtin_snprintf(buf, 10, "merp");
   __builtin_snprintf(buf, 11, "merp"); // expected-warning {{'snprintf' size 
argument is too large; destination buffer has size 10, but size argument is 11}}
@@ -96,6 +96,11 @@ void call_snprintf(double d) {
   __builtin_snprintf(buf, 1, "%.1000g", d); // expected-warning {{'snprintf' 
will always be truncated; specified size is 1, but format string expands to at 
least 2}}
   __builtin_snprintf(buf, 5, "%.1000g", d);
   __builtin_snprintf(buf, 5, "%.1000G", d);
+  char node_name[6];
+  __builtin_snprintf(node_name, sizeof(node_name), "%pOFn", ptr);
+  __builtin_snprintf(node_name, sizeof(node_name), "12345%pOFn", ptr);
+  __builtin_snprintf(node_name, sizeof(node_name), "123456%pOFn", ptr); // 
expected-warning {{'snprintf' will always be truncated; specifi

[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-11 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-11 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-11 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-11 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-11 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-11 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-11 Thread Takuya Shimizu via cfe-commits


@@ -96,6 +96,11 @@ void call_snprintf(double d) {
   __builtin_snprintf(buf, 1, "%.1000g", d); // expected-warning {{'snprintf' 
will always be truncated; specified size is 1, but format string expands to at 
least 2}}
   __builtin_snprintf(buf, 5, "%.1000g", d);
   __builtin_snprintf(buf, 5, "%.1000G", d);
+  char node_name[6];
+  __builtin_snprintf(node_name, sizeof(node_name), "%pOFn", ptr);
+  __builtin_snprintf(node_name, sizeof(node_name), "12345%pOFn", ptr);
+  __builtin_snprintf(node_name, sizeof(node_name), "123456%pOFn", ptr); // 
expected-warning {{'snprintf' will always be truncated; specified size is 6, 
but format string expands to at least 7}}

hazohelet wrote:

GCC doesn't warn on this ([live demo](https://godbolt.org/z/bEbYx5Gar)). It's 
probably because GCC even ignores the terminating null char, but I think it 
makes sense to consider the null char and add 1 (Probably it doesn't matter 
much, though).

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


[clang] 72f6abb - [clang][Sema] Fix format size estimator's handling of %o, %x, %X with alternative form

2023-09-11 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-09-12T12:22:26+09:00
New Revision: 72f6abb9bca68bf1398b321a73ebe3158bca67e5

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

LOG: [clang][Sema] Fix format size estimator's handling of %o, %x, %X with 
alternative form

The wrong handling of %x specifier with alternative form causes a false 
positive in linux kernel 
(https://github.com/ClangBuiltLinux/linux/issues/1923#issuecomment-1696075886)

The kernel code: 
https://github.com/torvalds/linux/blob/651a00bc56403161351090a9d7ddbd7095975324/drivers/media/pci/cx18/cx18-mailbox.c#L99

This patch fixes this handling, and also adds some standard wordings as 
comments to clarify the reason.

Reviewed By: nickdesaulniers
Differential Revision: https://reviews.llvm.org/D159138

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/warn-fortify-source.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fc0972c20476d09..c7b4432380120cb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -164,7 +164,7 @@ Improvements to Clang's diagnostics
   result in string truncation.
   (`#64871: `_).
   Also clang no longer emits false positive warnings about the output length of
-  ``%g`` format specifier.
+  ``%g`` format specifier and about ``%o, %x, %X`` with ``#`` flag.
 - Clang now emits ``-Wcast-qual`` for functional-style cast expressions.
 
 Bug Fixes in This Version

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 3b4ac613da76aa8..fad70223362eddd 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -890,6 +890,8 @@ class EstimateSizeFormatHandler
 // %g style conversion switches between %f or %e style dynamically.
 // %g removes trailing zeros, and does not print decimal point if there are
 // no digits that follow it. Thus %g can print a single digit.
+// FIXME: If it is alternative form:
+// For g and G conversions, trailing zeros are not removed from the result.
 case analyze_format_string::ConversionSpecifier::gArg:
 case analyze_format_string::ConversionSpecifier::GArg:
   Size += 1;
@@ -947,18 +949,26 @@ class EstimateSizeFormatHandler
 
 if (FS.hasAlternativeForm()) {
   switch (FS.getConversionSpecifier().getKind()) {
-  default:
-break;
-  // Force a leading '0'.
+  // For o conversion, it increases the precision, if and only if 
necessary,
+  // to force the first digit of the result to be a zero
+  // (if the value and precision are both 0, a single 0 is printed)
   case analyze_format_string::ConversionSpecifier::oArg:
-Size += 1;
-break;
-  // Force a leading '0x'.
+  // For b conversion, a nonzero result has 0b prefixed to it.
+  case analyze_format_string::ConversionSpecifier::bArg:
+  // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
+  // it.
   case analyze_format_string::ConversionSpecifier::xArg:
   case analyze_format_string::ConversionSpecifier::XArg:
-Size += 2;
+// Note: even when the prefix is added, if
+// (prefix_width <= FieldWidth - formatted_length) holds,
+// the prefix does not increase the format
+// size. e.g.(("%#3x", 0xf) is "0xf")
+
+// If the result is zero, o, b, x, X adds nothing.
 break;
-  // Force a period '.' before decimal, even if precision is 0.
+  // For a, A, e, E, f, F, g, and G conversions,
+  // the result of converting a floating-point number always contains a
+  // decimal-point
   case analyze_format_string::ConversionSpecifier::aArg:
   case analyze_format_string::ConversionSpecifier::AArg:
   case analyze_format_string::ConversionSpecifier::eArg:
@@ -969,6 +979,9 @@ class EstimateSizeFormatHandler
   case analyze_format_string::ConversionSpecifier::GArg:
 Size += (Precision ? 0 : 1);
 break;
+  // For other conversions, the behavior is undefined.
+  default:
+break;
   }
 }
 assert(SpecifierLen <= Size && "no underflow");

diff  --git a/clang/test/Sema/warn-fortify-source.c 
b/clang/test/Sema/warn-fortify-source.c
index 5ed9782b26fb788..de6171af8c14524 100644
--- a/clang/test/Sema/warn-fortify-source.c
+++ b/clang/test/Sema/warn-fortify-source.c
@@ -85,7 +85,7 @@ void call_memset(void) {
   __builtin_memset(buf, 0xff, 11); // expected-warning {{'memset' will always 
overflow; destination buffer has size 10, but size argument is 11}}
 }
 
-void call_snprintf(double d) {
+void call_snprintf(double d, int n) {
   char buf[10];
   __builtin_snprintf(b

[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-12 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65969:

>From 80d8743441ce1e25f19dbc48bce480b5becfa208 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Tue, 12 Sep 2023 00:39:44 +0900
Subject: [PATCH 1/3] [clang][Sema] Stop format size estimator upon %p to adapt
 to linux kernel's extension

GCC stops counting format string's size when it sees %p format in order to 
avoid `Wformat-truncation` false positive against Linux kernel's format 
extension (%pOF, for example).
This change makes clang's behavior align with GCC's.
As requested in https://github.com/llvm/llvm-project/issues/64871
---
 clang/include/clang/AST/FormatString.h |  6 ++
 clang/lib/AST/PrintfFormatString.cpp   |  8 +++-
 clang/lib/Sema/SemaChecking.cpp| 10 ++
 clang/test/Sema/warn-fortify-source.c  | 16 +---
 4 files changed, 36 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index 5c4ad9baaef608c..97ce3cfe0b25c68 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -742,6 +742,12 @@ class FormatStringHandler {
 return true;
   }
 
+  virtual bool
+  ShouldStopOnFormatSpecifier(const analyze_printf::PrintfSpecifier &FS,
+  unsigned RemainLen) {
+return false;
+  }
+
   /// Handle mask types whose sizes are not between one and eight bytes.
   virtual void handleInvalidMaskType(StringRef MaskType) {}
 
diff --git a/clang/lib/AST/PrintfFormatString.cpp 
b/clang/lib/AST/PrintfFormatString.cpp
index f0b9d0ecaf23461..750f584d8d37a76 100644
--- a/clang/lib/AST/PrintfFormatString.cpp
+++ b/clang/lib/AST/PrintfFormatString.cpp
@@ -429,7 +429,13 @@ bool 
clang::analyze_format_string::ParsePrintfString(FormatStringHandler &H,
 // we can recover from?
 if (!FSR.hasValue())
   continue;
-// We have a format specifier.  Pass it to the callback.
+// We have a format specifier.
+// In case the handler needs to abort parsing upon specific specifiers
+if (H.ShouldStopOnFormatSpecifier(
+FSR.getValue(), static_cast(E - FSR.getStart( {
+  return false;
+}
+// Pass the format specifier to the callback.
 if (!H.HandlePrintfSpecifier(FSR.getValue(), FSR.getStart(),
  I - FSR.getStart(), Target))
   return true;
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 3b4ac613da76aa8..1a6ff6cfa19b661 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -860,6 +860,16 @@ class EstimateSizeFormatHandler
   : Size(std::min(Format.find(0), Format.size()) +
  1 /* null byte always written by sprintf */) {}
 
+  bool ShouldStopOnFormatSpecifier(const analyze_printf::PrintfSpecifier &FS,
+   unsigned RemainLen) override {
+if (FS.getConversionSpecifier().getKind() ==
+analyze_printf::PrintfConversionSpecifier::pArg) {
+  assert(Size >= RemainLen && "no underflow");
+  Size -= RemainLen;
+  return true;
+}
+return false;
+  }
   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  const char *, unsigned SpecifierLen,
  const TargetInfo &) override {
diff --git a/clang/test/Sema/warn-fortify-source.c 
b/clang/test/Sema/warn-fortify-source.c
index 5ed9782b26fb788..fba6c718be4a33a 100644
--- a/clang/test/Sema/warn-fortify-source.c
+++ b/clang/test/Sema/warn-fortify-source.c
@@ -85,7 +85,7 @@ void call_memset(void) {
   __builtin_memset(buf, 0xff, 11); // expected-warning {{'memset' will always 
overflow; destination buffer has size 10, but size argument is 11}}
 }
 
-void call_snprintf(double d) {
+void call_snprintf(double d, int *ptr) {
   char buf[10];
   __builtin_snprintf(buf, 10, "merp");
   __builtin_snprintf(buf, 11, "merp"); // expected-warning {{'snprintf' size 
argument is too large; destination buffer has size 10, but size argument is 11}}
@@ -96,6 +96,11 @@ void call_snprintf(double d) {
   __builtin_snprintf(buf, 1, "%.1000g", d); // expected-warning {{'snprintf' 
will always be truncated; specified size is 1, but format string expands to at 
least 2}}
   __builtin_snprintf(buf, 5, "%.1000g", d);
   __builtin_snprintf(buf, 5, "%.1000G", d);
+  char node_name[6];
+  __builtin_snprintf(node_name, sizeof(node_name), "%pOFn", ptr);
+  __builtin_snprintf(node_name, sizeof(node_name), "12345%pOFn", ptr);
+  __builtin_snprintf(node_name, sizeof(node_name), "123456%pOFn", ptr); // 
expected-warning {{'snprintf' will always be truncated; specified size is 6, 
but format string expands to at least 7}}
+  __builtin_snprintf(node_name, sizeof(node_name), "1234567%pOFn", ptr); // 
expected-warning {{'snprintf' will always be truncated; specified size is 6, 
but format string expands to at least 8}}
 }
 
 void call_vsnprintf(void) {
@@ -110,

[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-12 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

> Is there some way we can narrow the scope of this patch so we don't lose 
> warnings for normal `snprintf`s, only for the kernel one? If we really can't 
> tell the difference from the source code, we could move the affected warnings 
> to a different warning group instead, so the kernel can turn them off.

Thanks for the feedback. I narrowed the scope by checking whether the next 
character of `%p` can be part of the kernel extended format specifier.
If people write `%pM` or a similar outside kernel, it still aborts the format 
size estimator and could lead to false negative. But I think it would hurt 
people much less because people usually put non-alphanumeric character after 
`%p`.

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-12 Thread Takuya Shimizu via cfe-commits


@@ -851,6 +851,50 @@ class ScanfDiagnosticFormatHandler
   }
 };
 
+/// `I` points to the next character of `%p` format.
+/// This functon checks if the subsequent character can be linux kernel's
+/// extnded format specifier
+static inline constexpr bool canBeLinuxFormatExtension(const char *I,
+   const char *E) {
+  assert(I < E && "format string not yet exhausted");
+  // Kernel Document: https://docs.kernel.org/core-api/printk-formats.html
+  switch (*I) {

hazohelet wrote:

These switch cases correspond to 
https://github.com/torvalds/linux/blob/0bb80ecc33a8fb5a682236443c1e740d5c917d1d/lib/vsprintf.c#L2406-L2412
Note that kernel extension `%pA` is for Rust and thus excluded here.
ref: https://docs.kernel.org/core-api/printk-formats.html

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-13 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

Thanks for the detailed suggestion! I agree it's the appropriate approach.

I was planning to separate `Wformat-truncation` from `Wfortify-source` sometime 
after this PR (as was requested in the same issue), but now that we are going 
to introduce a new warning group, we should finish the separation before 
proceeding further on this.
Sadly we don't have any way to make stacked patches as of now, so I'll merge 
the separation change to this PR. If reviewers think it's unreasonable, let's 
make another PR for the separation then.

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-13 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65969:

>From 5ee1a4f83c69b5e2910ea883dca7f0fa2c1a4bd3 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Wed, 13 Sep 2023 17:43:11 +0900
Subject: [PATCH 1/2] [clang][Diagnostics] Separate Wformat-overflow and
 Wformat-truncation from Wfortify-source

Newly introduces `Wformat-overflow` and `Wformat-truncation` and imports the 
existing warning from `Wfortify-source` that correspond to GCC's counterpart so 
that they can be disabled separately from `Wfortify-source`.
---
 clang/docs/ReleaseNotes.rst   |   5 +-
 .../clang/Basic/DiagnosticSemaKinds.td|   4 +-
 clang/lib/Sema/SemaChecking.cpp   |  12 +-
 .../Sema/warn-format-overflow-truncation.c| 153 ++
 clang/test/Sema/warn-fortify-source.c |  14 +-
 5 files changed, 171 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/Sema/warn-format-overflow-truncation.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3cdad2f7b9f0e5a..628253c730cd1e0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -160,9 +160,12 @@ Improvements to Clang's diagnostics
 - Clang constexpr evaluator now diagnoses compound assignment operators against
   uninitialized variables as a read of uninitialized object.
   (`#51536 `_)
-- Clang's ``-Wfortify-source`` now diagnoses ``snprintf`` call that is known to
+- Clang's ``-Wformat-truncation`` now diagnoses ``snprintf`` call that is 
known to
   result in string truncation.
   (`#64871: `_).
+  Existing warnings that similarly warn about the overflow in ``sprintf``
+  now falls under its own warning group ```-Wformat-overflow`` so that it can
+  be disabled separately from ``Wfortify-source``.
   Also clang no longer emits false positive warnings about the output length of
   ``%g`` format specifier and about ``%o, %x, %X`` with ``#`` flag.
 - Clang now emits ``-Wcast-qual`` for functional-style cast expressions.
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0ac4df8edb242f6..7f708a5267e0052 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -857,12 +857,12 @@ def warn_fortify_strlen_overflow: Warning<
 def warn_fortify_source_format_overflow : Warning<
   "'%0' will always overflow; destination buffer has size %1,"
   " but format string expands to at least %2">,
-  InGroup;
+  InGroup>;
 
 def warn_fortify_source_format_truncation: Warning<
   "'%0' will always be truncated; specified size is %1,"
   " but format string expands to at least %2">,
-  InGroup;
+  InGroup>;
 
 def warn_fortify_scanf_overflow : Warning<
   "'%0' may overflow; destination buffer in argument %1 has size "
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index fad70223362eddd..8260e72bd99e839 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -1350,10 +1350,14 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
 .extOrTrunc(SizeTypeWidth);
 if (FormatSize > *SourceSize && *SourceSize != 0) {
-  DiagID = diag::warn_fortify_source_format_truncation;
-  DestinationSize = SourceSize;
-  SourceSize = FormatSize;
-  break;
+  SmallString<16> SpecifiedSizeStr;
+  SmallString<16> FormatSizeStr;
+  SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
+  FormatSize.toString(FormatSizeStr, /*Radix=*/10);
+  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
+  
PDiag(diag::warn_fortify_source_format_truncation)
+  << GetFunctionName() << SpecifiedSizeStr
+  << FormatSizeStr);
 }
   }
 }
diff --git a/clang/test/Sema/warn-format-overflow-truncation.c 
b/clang/test/Sema/warn-format-overflow-truncation.c
new file mode 100644
index 000..dada1f9355afe07
--- /dev/null
+++ b/clang/test/Sema/warn-format-overflow-truncation.c
@@ -0,0 +1,153 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify 
-DUSE_BUILTINS
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -Wno-format-truncation 
-Wno-format-overflow %s -verify=off
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 
-Wno-format-truncation -Wno-format-overflow %s -verify=off
+
+typedef unsigned long size_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int sprintf(cha

[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-13 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-13 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-13 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-13 Thread Takuya Shimizu via cfe-commits

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


[clang] [Clang] Handle consteval expression in array bounds expressions (PR #66222)

2023-09-14 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

> @hazohelet Does this collide or intersect with the work wrt. (un)evaluated 
> contexts in https://reviews.llvm.org/D155064 ?

I wasn't aware of VLA cases in that patch.
My patch needs modification so that use of `is_constant_evaluated` and 
consteval-if NOT considered tautologically-true when they happen 
`InConditionallyConstantEvaluateContext`, which is a few lines of change.

@cor3ntin
Is it alright to set `InConditionallyConstantEvaluateContext` true only when 
the outer evaluation context `isAlwaysConstantEvaluatedContext()` so that we 
can say the array bound expr is always constant-evaluated if it happens in 
always-constant-evaluated context?
Something like this:
```diff
 ExprResult Parser::ParseArrayBoundExpression() {
+  bool IsAlwaysConstantEvaluated = Actions.isAlwaysConstantEvaluatedContext();
   EnterExpressionEvaluationContext ConstantEvaluated(
   Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   // If we parse the bound of a VLA... we parse a non-constant
   // constant-expression!
-  Actions.ExprEvalContexts.back().InConditionallyConstantEvaluateContext = 
true;
+  Actions.ExprEvalContexts.back().InConditionallyConstantEvaluateContext = 
!IsAlwaysConstantEvaluated;
   return ParseConstantExpressionInExprEvalContext(NotTypeCast);
 }
```

Also, does this change suggest that we let some diagnostic mechanisms consider 
VLA cases? (e.g. `DiagRuntimeBehavior` should not early-return if the context 
is `InConditionallyConstantEvaluateContext` to diagnose div-by-zero in 
https://godbolt.org/z/556rKnMTG)

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-14 Thread Takuya Shimizu via cfe-commits


@@ -961,10 +961,16 @@ def FormatNonStandard : DiagGroup<"format-non-iso">;
 def FormatY2K : DiagGroup<"format-y2k">;
 def FormatPedantic : DiagGroup<"format-pedantic">;
 def FormatTypeConfusion : DiagGroup<"format-type-confusion">;
+
+def FormatOverflowNonKprintf: DiagGroup<"format-overflow-non-kprintf">;
+def FormatOverflow: DiagGroup<"format-overflow", [FormatOverflowNonKprintf]>;
+def FormatTruncationNonKprintf: DiagGroup<"format-truncation-non-kprintf">;
+def FormatTruncation: DiagGroup<"format-truncation", 
[FormatTruncationNonKprintf]>;

hazohelet wrote:

Thanks. It makes sense to add this to `FortifySource` for backward 
compatibility.

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-14 Thread Takuya Shimizu via cfe-commits


@@ -1350,10 +1360,17 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
 .extOrTrunc(SizeTypeWidth);
 if (FormatSize > *SourceSize && *SourceSize != 0) {
-  DiagID = diag::warn_fortify_source_format_truncation;
-  DestinationSize = SourceSize;
-  SourceSize = FormatSize;
-  break;

hazohelet wrote:

This is intentional.
When the truncation warning was grouped under `Wfortify-source`, I thought it 
made sense to override the warning because there was no way to disable only one 
of `warn_fortify_source_size_mismatch` and the truncation warning.
Now that `Wformat-truncation` is made, I no longer think this warning should 
hide the `Wfortify-source` warning.

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-14 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65969:

>From 5ee1a4f83c69b5e2910ea883dca7f0fa2c1a4bd3 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Wed, 13 Sep 2023 17:43:11 +0900
Subject: [PATCH 1/3] [clang][Diagnostics] Separate Wformat-overflow and
 Wformat-truncation from Wfortify-source

Newly introduces `Wformat-overflow` and `Wformat-truncation` and imports the 
existing warning from `Wfortify-source` that correspond to GCC's counterpart so 
that they can be disabled separately from `Wfortify-source`.
---
 clang/docs/ReleaseNotes.rst   |   5 +-
 .../clang/Basic/DiagnosticSemaKinds.td|   4 +-
 clang/lib/Sema/SemaChecking.cpp   |  12 +-
 .../Sema/warn-format-overflow-truncation.c| 153 ++
 clang/test/Sema/warn-fortify-source.c |  14 +-
 5 files changed, 171 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/Sema/warn-format-overflow-truncation.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3cdad2f7b9f0e5a..628253c730cd1e0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -160,9 +160,12 @@ Improvements to Clang's diagnostics
 - Clang constexpr evaluator now diagnoses compound assignment operators against
   uninitialized variables as a read of uninitialized object.
   (`#51536 `_)
-- Clang's ``-Wfortify-source`` now diagnoses ``snprintf`` call that is known to
+- Clang's ``-Wformat-truncation`` now diagnoses ``snprintf`` call that is 
known to
   result in string truncation.
   (`#64871: `_).
+  Existing warnings that similarly warn about the overflow in ``sprintf``
+  now falls under its own warning group ```-Wformat-overflow`` so that it can
+  be disabled separately from ``Wfortify-source``.
   Also clang no longer emits false positive warnings about the output length of
   ``%g`` format specifier and about ``%o, %x, %X`` with ``#`` flag.
 - Clang now emits ``-Wcast-qual`` for functional-style cast expressions.
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0ac4df8edb242f6..7f708a5267e0052 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -857,12 +857,12 @@ def warn_fortify_strlen_overflow: Warning<
 def warn_fortify_source_format_overflow : Warning<
   "'%0' will always overflow; destination buffer has size %1,"
   " but format string expands to at least %2">,
-  InGroup;
+  InGroup>;
 
 def warn_fortify_source_format_truncation: Warning<
   "'%0' will always be truncated; specified size is %1,"
   " but format string expands to at least %2">,
-  InGroup;
+  InGroup>;
 
 def warn_fortify_scanf_overflow : Warning<
   "'%0' may overflow; destination buffer in argument %1 has size "
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index fad70223362eddd..8260e72bd99e839 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -1350,10 +1350,14 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
 .extOrTrunc(SizeTypeWidth);
 if (FormatSize > *SourceSize && *SourceSize != 0) {
-  DiagID = diag::warn_fortify_source_format_truncation;
-  DestinationSize = SourceSize;
-  SourceSize = FormatSize;
-  break;
+  SmallString<16> SpecifiedSizeStr;
+  SmallString<16> FormatSizeStr;
+  SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
+  FormatSize.toString(FormatSizeStr, /*Radix=*/10);
+  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
+  
PDiag(diag::warn_fortify_source_format_truncation)
+  << GetFunctionName() << SpecifiedSizeStr
+  << FormatSizeStr);
 }
   }
 }
diff --git a/clang/test/Sema/warn-format-overflow-truncation.c 
b/clang/test/Sema/warn-format-overflow-truncation.c
new file mode 100644
index 000..dada1f9355afe07
--- /dev/null
+++ b/clang/test/Sema/warn-format-overflow-truncation.c
@@ -0,0 +1,153 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify 
-DUSE_BUILTINS
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -Wno-format-truncation 
-Wno-format-overflow %s -verify=off
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 
-Wno-format-truncation -Wno-format-overflow %s -verify=off
+
+typedef unsigned long size_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int sprintf(cha

[clang] [Clang] Handle consteval expression in array bounds expressions (PR #66222)

2023-09-14 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

> Where do you think it matters? I can't this of cases where ConstantEvaluated 
> context are nested in one another without some intertwined potentially 
> evaluated context

I was mostly thinking about cases where the array-bound expression appears 
inside immediate function context.
The current checks for "Is this always constant-evaluated?" only see the 
innermost evaluation context (e.g. `Sema::isConstantEvaluated`, and 
`Sema::DiagRuntimeBehavior`), so I hope the newly pushed evaluation contexts on 
`ExprEvalContexts` be strict about whether it's always-constant-evaluated or 
not.
Although this PR is not relevant, for the same reason, I don't think it's ideal 
that potentially-evaluated-contexts appear inside constant-evaluated context.

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


[clang] [Clang] Handle consteval expression in array bounds expressions (PR #66222)

2023-09-15 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

> I'll add a test. immediate contexts are recursive, constant evaluated 
> contexts are not, i don't think there is a case where you would get an 
> additional evaluation context that is not for a full expression, and if you 
> have a full expression you do expect the immediate invocation to be called 
> anyway - eg, lambda case.

It turns out I was misunderstanding the standard about the recursiveness of 
constant-evaluated-context. I found a flaw in my patch that comes from it 
(pushing constant-evaluated context upon lambda body if it happens in 
constant-evaluated context). Thanks!

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


[clang] [clang][Sema] Stop format size estimator upon %p to adapt to linux kernel's extension (PR #65969)

2023-09-18 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65969

>From 5ee1a4f83c69b5e2910ea883dca7f0fa2c1a4bd3 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Wed, 13 Sep 2023 17:43:11 +0900
Subject: [PATCH 1/4] [clang][Diagnostics] Separate Wformat-overflow and
 Wformat-truncation from Wfortify-source

Newly introduces `Wformat-overflow` and `Wformat-truncation` and imports the 
existing warning from `Wfortify-source` that correspond to GCC's counterpart so 
that they can be disabled separately from `Wfortify-source`.
---
 clang/docs/ReleaseNotes.rst   |   5 +-
 .../clang/Basic/DiagnosticSemaKinds.td|   4 +-
 clang/lib/Sema/SemaChecking.cpp   |  12 +-
 .../Sema/warn-format-overflow-truncation.c| 153 ++
 clang/test/Sema/warn-fortify-source.c |  14 +-
 5 files changed, 171 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/Sema/warn-format-overflow-truncation.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3cdad2f7b9f0e5a..628253c730cd1e0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -160,9 +160,12 @@ Improvements to Clang's diagnostics
 - Clang constexpr evaluator now diagnoses compound assignment operators against
   uninitialized variables as a read of uninitialized object.
   (`#51536 `_)
-- Clang's ``-Wfortify-source`` now diagnoses ``snprintf`` call that is known to
+- Clang's ``-Wformat-truncation`` now diagnoses ``snprintf`` call that is 
known to
   result in string truncation.
   (`#64871: `_).
+  Existing warnings that similarly warn about the overflow in ``sprintf``
+  now falls under its own warning group ```-Wformat-overflow`` so that it can
+  be disabled separately from ``Wfortify-source``.
   Also clang no longer emits false positive warnings about the output length of
   ``%g`` format specifier and about ``%o, %x, %X`` with ``#`` flag.
 - Clang now emits ``-Wcast-qual`` for functional-style cast expressions.
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0ac4df8edb242f6..7f708a5267e0052 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -857,12 +857,12 @@ def warn_fortify_strlen_overflow: Warning<
 def warn_fortify_source_format_overflow : Warning<
   "'%0' will always overflow; destination buffer has size %1,"
   " but format string expands to at least %2">,
-  InGroup;
+  InGroup>;
 
 def warn_fortify_source_format_truncation: Warning<
   "'%0' will always be truncated; specified size is %1,"
   " but format string expands to at least %2">,
-  InGroup;
+  InGroup>;
 
 def warn_fortify_scanf_overflow : Warning<
   "'%0' may overflow; destination buffer in argument %1 has size "
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index fad70223362eddd..8260e72bd99e839 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -1350,10 +1350,14 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
 .extOrTrunc(SizeTypeWidth);
 if (FormatSize > *SourceSize && *SourceSize != 0) {
-  DiagID = diag::warn_fortify_source_format_truncation;
-  DestinationSize = SourceSize;
-  SourceSize = FormatSize;
-  break;
+  SmallString<16> SpecifiedSizeStr;
+  SmallString<16> FormatSizeStr;
+  SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
+  FormatSize.toString(FormatSizeStr, /*Radix=*/10);
+  DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
+  
PDiag(diag::warn_fortify_source_format_truncation)
+  << GetFunctionName() << SpecifiedSizeStr
+  << FormatSizeStr);
 }
   }
 }
diff --git a/clang/test/Sema/warn-format-overflow-truncation.c 
b/clang/test/Sema/warn-format-overflow-truncation.c
new file mode 100644
index 000..dada1f9355afe07
--- /dev/null
+++ b/clang/test/Sema/warn-format-overflow-truncation.c
@@ -0,0 +1,153 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify 
-DUSE_BUILTINS
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -Wno-format-truncation 
-Wno-format-overflow %s -verify=off
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 
-Wno-format-truncation -Wno-format-overflow %s -verify=off
+
+typedef unsigned long size_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int sprintf(char

[clang] b2cd9db - [clang][Sema] Remove irrelevant diagnostics from constraint satisfaction failure

2023-09-18 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-09-18T18:14:44+09:00
New Revision: b2cd9db589335d5885c04df83003a623cf2f05ff

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

LOG: [clang][Sema] Remove irrelevant diagnostics from constraint satisfaction 
failure

BEFORE this patch, when clang handles constraints like C1 || C2 where C1 
evaluates to false and C2 evaluates to true, it emitted irrelevant diagnostics 
about the falsity of C1.
This patch removes the irrelevant diagnostic information generated during the 
evaluation of C1 if C2 evaluates to true.

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

Reviewed By: erichkeane
Differential Revision: https://reviews.llvm.org/D157526

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaConcept.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d47d664c062c204..500f9c9a0cda741 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -169,6 +169,9 @@ Improvements to Clang's diagnostics
   Also clang no longer emits false positive warnings about the output length of
   ``%g`` format specifier and about ``%o, %x, %X`` with ``#`` flag.
 - Clang now emits ``-Wcast-qual`` for functional-style cast expressions.
+- Clang no longer emits irrelevant notes about unsatisfied constraint 
expressions
+  on the left-hand side of ``||`` when the right-hand side constraint is 
satisfied.
+  (`#54678: `_).
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d1fa8e7831225b7..dacdd07c8069950 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -185,6 +185,7 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
 
   if (LogicalBinOp BO = ConstraintExpr) {
+auto EffectiveDetailEnd = Satisfaction.Details.end();
 ExprResult LHSRes = calculateConstraintSatisfaction(
 S, BO.getLHS(), Satisfaction, Evaluator);
 
@@ -218,6 +219,19 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 if (RHSRes.isInvalid())
   return ExprError();
 
+bool IsRHSSatisfied = Satisfaction.IsSatisfied;
+// Current implementation adds diagnostic information about the falsity
+// of each false atomic constraint expression when it evaluates them.
+// When the evaluation results to `false || true`, the information
+// generated during the evaluation of left-hand side is meaningless
+// because the whole expression evaluates to true.
+// The following code removes the irrelevant diagnostic information.
+// FIXME: We should probably delay the addition of diagnostic information
+// until we know the entire expression is false.
+if (BO.isOr() && IsRHSSatisfied)
+  Satisfaction.Details.erase(EffectiveDetailEnd,
+ Satisfaction.Details.end());
+
 return BO.recreateBinOp(S, LHSRes, RHSRes);
   }
 

diff  --git a/clang/test/SemaTemplate/concepts.cpp 
b/clang/test/SemaTemplate/concepts.cpp
index 9776ddbb372991e..891b45aa5789296 100644
--- a/clang/test/SemaTemplate/concepts.cpp
+++ b/clang/test/SemaTemplate/concepts.cpp
@@ -994,3 +994,40 @@ void test_params() {
 }
 
 }
+
+namespace GH54678 {
+template
+concept True = true;
+
+template
+concept False = false; // expected-note 9 {{'false' evaluated to false}}
+
+template
+concept Irrelevant = false;
+
+template 
+concept ErrorRequires = requires(ErrorRequires auto x) { x; }; // 
expected-error {{unknown type name 'ErrorRequires'}}
+
+template void aaa(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (False || False) || False {} // expected-note 3 {{'int' does 
not satisfy 'False'}}
+template void bbb(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (False || False) && True {} // expected-note 2 {{'long' does 
not satisfy 'False'}}
+template void ccc(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (True || Irrelevant) && False {} // expected-note 
{{'unsigned long' does not satisfy 'False'}}
+template void ddd(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (Irrelevant || True) && False {} // expected-note {{'int' 
does not satisfy 'False'}}
+template void eee(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (Irrelevant || Irrelevant || True) && False {} // 
expected-note {{'long' does not satisfy 'False'}}
+
+template void fff(T t) // expected-note {{ca

[clang] [clang][Sema] Fix crash introduced in b2cd9db589335d5885c04df83003a623cf2f05ff (PR #66954)

2023-09-20 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet created 
https://github.com/llvm/llvm-project/pull/66954

Old iterator is invalidated upon SmallVector elements additions. Stores index 
instead of iterator to avoid this.

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

>From 74b06739e7309798e53110307bfe0abb9bd5b649 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Thu, 21 Sep 2023 06:27:55 +0900
Subject: [PATCH] [clang][Sema] Fix crash introduced in b2cd9db

Old iterator is invalidaed upon SmallVector elements additions.
Stores index instead of iterator to avoid this.

Fixes https://github.com/llvm/llvm-project/issues/66938
---
 clang/lib/Sema/SemaConcept.cpp   |  7 +--
 clang/test/SemaTemplate/concepts.cpp | 16 
 2 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index dacdd07c8069950..80788f04e2241c5 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -185,7 +185,7 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
 
   if (LogicalBinOp BO = ConstraintExpr) {
-auto EffectiveDetailEnd = Satisfaction.Details.end();
+size_t EffectiveDetailEndIndex = Satisfaction.Details.size();
 ExprResult LHSRes = calculateConstraintSatisfaction(
 S, BO.getLHS(), Satisfaction, Evaluator);
 
@@ -228,9 +228,12 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 // The following code removes the irrelevant diagnostic information.
 // FIXME: We should probably delay the addition of diagnostic information
 // until we know the entire expression is false.
-if (BO.isOr() && IsRHSSatisfied)
+if (BO.isOr() && IsRHSSatisfied) {
+  auto EffectiveDetailEnd =
+  Satisfaction.Details.begin() + EffectiveDetailEndIndex;
   Satisfaction.Details.erase(EffectiveDetailEnd,
  Satisfaction.Details.end());
+}
 
 return BO.recreateBinOp(S, LHSRes, RHSRes);
   }
diff --git a/clang/test/SemaTemplate/concepts.cpp 
b/clang/test/SemaTemplate/concepts.cpp
index 68050e0f09e248a..e98ebcc9203a430 100644
--- a/clang/test/SemaTemplate/concepts.cpp
+++ b/clang/test/SemaTemplate/concepts.cpp
@@ -1048,3 +1048,19 @@ namespace GH66612 {
   // expected-note@-1{{because 'int' does not satisfy 'Container'}}
   // expected-note@#66612GH_END{{because 'end' would be invalid: reference to 
overloaded function could not be resolved; did you mean to call it?}}
 }
+
+namespace GH66938 {
+template 
+concept True = true;
+
+template 
+concept False = false;
+
+template 
+void cand(T t)
+  requires False || False || False || False || False ||
+   False || False || False || False || True
+{}
+
+void test() { cand(42); }
+}

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


[clang] [clang][Sema] Fix crash introduced in b2cd9db589335d5885c04df83003a623cf2f05ff (PR #66954)

2023-09-20 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/66954

>From 74b06739e7309798e53110307bfe0abb9bd5b649 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Thu, 21 Sep 2023 06:27:55 +0900
Subject: [PATCH 1/2] [clang][Sema] Fix crash introduced in b2cd9db

Old iterator is invalidaed upon SmallVector elements additions.
Stores index instead of iterator to avoid this.

Fixes https://github.com/llvm/llvm-project/issues/66938
---
 clang/lib/Sema/SemaConcept.cpp   |  7 +--
 clang/test/SemaTemplate/concepts.cpp | 16 
 2 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index dacdd07c8069950..80788f04e2241c5 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -185,7 +185,7 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
 
   if (LogicalBinOp BO = ConstraintExpr) {
-auto EffectiveDetailEnd = Satisfaction.Details.end();
+size_t EffectiveDetailEndIndex = Satisfaction.Details.size();
 ExprResult LHSRes = calculateConstraintSatisfaction(
 S, BO.getLHS(), Satisfaction, Evaluator);
 
@@ -228,9 +228,12 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 // The following code removes the irrelevant diagnostic information.
 // FIXME: We should probably delay the addition of diagnostic information
 // until we know the entire expression is false.
-if (BO.isOr() && IsRHSSatisfied)
+if (BO.isOr() && IsRHSSatisfied) {
+  auto EffectiveDetailEnd =
+  Satisfaction.Details.begin() + EffectiveDetailEndIndex;
   Satisfaction.Details.erase(EffectiveDetailEnd,
  Satisfaction.Details.end());
+}
 
 return BO.recreateBinOp(S, LHSRes, RHSRes);
   }
diff --git a/clang/test/SemaTemplate/concepts.cpp 
b/clang/test/SemaTemplate/concepts.cpp
index 68050e0f09e248a..e98ebcc9203a430 100644
--- a/clang/test/SemaTemplate/concepts.cpp
+++ b/clang/test/SemaTemplate/concepts.cpp
@@ -1048,3 +1048,19 @@ namespace GH66612 {
   // expected-note@-1{{because 'int' does not satisfy 'Container'}}
   // expected-note@#66612GH_END{{because 'end' would be invalid: reference to 
overloaded function could not be resolved; did you mean to call it?}}
 }
+
+namespace GH66938 {
+template 
+concept True = true;
+
+template 
+concept False = false;
+
+template 
+void cand(T t)
+  requires False || False || False || False || False ||
+   False || False || False || False || True
+{}
+
+void test() { cand(42); }
+}

>From f60bddd47003aa2c7791ac99e50aa718995e4b37 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Thu, 21 Sep 2023 06:41:06 +0900
Subject: [PATCH 2/2] Address comments from erichkeane

---
 clang/lib/Sema/SemaConcept.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 80788f04e2241c5..036548b68247bfa 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -229,8 +229,8 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 // FIXME: We should probably delay the addition of diagnostic information
 // until we know the entire expression is false.
 if (BO.isOr() && IsRHSSatisfied) {
-  auto EffectiveDetailEnd =
-  Satisfaction.Details.begin() + EffectiveDetailEndIndex;
+  auto EffectiveDetailEnd = Satisfaction.Details.begin();
+  std::advance(EffectiveDetailEnd, EffectiveDetailEndIndex);
   Satisfaction.Details.erase(EffectiveDetailEnd,
  Satisfaction.Details.end());
 }

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


[clang] [clang][Sema] Fix crash introduced in b2cd9db589335d5885c04df83003a623cf2f05ff (PR #66954)

2023-09-21 Thread Takuya Shimizu via cfe-commits

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


[clang] 6408317 - [clang][Sema] Provide source range to several Wunused warnings

2023-06-16 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-06-16T19:26:53+09:00
New Revision: 64083172eea26e50c8b22b85697a825be8bda424

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

LOG: [clang][Sema] Provide source range to several Wunused warnings

When the diagnosed function/variable is a template specialization, the source 
range covers the specialization arguments.
e.g.
```
warning: unused function 'func' [-Wunused-function]
template <> int func () {}
^
```
This comes in line with the printed text in the warning message. In the above 
case, `func`

Reviewed By: aaron.ballman

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

Added: 
clang/test/Misc/Inputs/diag-unused-source-ranges.h
clang/test/Misc/diag-unused-source-ranges.cpp

Modified: 
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 09084176cbf41..694e07b46aaf0 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1347,10 +1347,14 @@ void Sema::ActOnEndOfTranslationUnit() {
   DiagD = FD;
 if (DiagD->isDeleted())
   continue; // Deleted functions are supposed to be unused.
+SourceRange DiagRange = DiagD->getLocation();
+if (const ASTTemplateArgumentListInfo *ASTTAL =
+DiagD->getTemplateSpecializationArgsAsWritten())
+  DiagRange.setEnd(ASTTAL->RAngleLoc);
 if (DiagD->isReferenced()) {
   if (isa(DiagD))
 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
-<< DiagD;
+<< DiagD << DiagRange;
   else {
 if (FD->getStorageClass() == SC_Static &&
 !FD->isInlineSpecified() &&
@@ -1358,39 +1362,46 @@ void Sema::ActOnEndOfTranslationUnit() {
SourceMgr.getExpansionLoc(FD->getLocation(
   Diag(DiagD->getLocation(),
diag::warn_unneeded_static_internal_decl)
-  << DiagD;
+  << DiagD << DiagRange;
 else
   Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
-  << /*function*/ 0 << DiagD;
+  << /*function*/ 0 << DiagD << DiagRange;
   }
 } else {
   if (FD->getDescribedFunctionTemplate())
 Diag(DiagD->getLocation(), diag::warn_unused_template)
-<< /*function*/ 0 << DiagD;
+<< /*function*/ 0 << DiagD << DiagRange;
   else
 Diag(DiagD->getLocation(), isa(DiagD)
? diag::warn_unused_member_function
: diag::warn_unused_function)
-<< DiagD;
+<< DiagD << DiagRange;
 }
   } else {
 const VarDecl *DiagD = cast(*I)->getDefinition();
 if (!DiagD)
   DiagD = cast(*I);
+SourceRange DiagRange = DiagD->getLocation();
+if (const auto *VTSD = dyn_cast(DiagD)) 
{
+  if (const ASTTemplateArgumentListInfo *ASTTAL =
+  VTSD->getTemplateArgsInfo())
+DiagRange.setEnd(ASTTAL->RAngleLoc);
+}
 if (DiagD->isReferenced()) {
   Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
-  << /*variable*/ 1 << DiagD;
+  << /*variable*/ 1 << DiagD << DiagRange;
 } else if (DiagD->getDescribedVarTemplate()) {
   Diag(DiagD->getLocation(), diag::warn_unused_template)
-  << /*variable*/ 1 << DiagD;
+  << /*variable*/ 1 << DiagD << DiagRange;
 } else if (DiagD->getType().isConstQualified()) {
   const SourceManager &SM = SourceMgr;
   if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
   !PP.getLangOpts().IsHeaderFile)
 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
-<< DiagD;
+<< DiagD << DiagRange;
 } else {
-  Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
+  Diag(DiagD->getLocation(), diag::warn_unused_variable)
+  << DiagD << DiagRange;
 }
   }
 }

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 757c4c310be3d..e93f86821d846 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2151,7 +2151,8 @@ void Sema::DiagnoseUnusedDecl(const NamedDecl *D, 
DiagReceiverTy DiagReceiver) {
   else
 DiagID = diag::warn_unused_variable;
 
-  DiagReceiver(D->getLocation(), PDiag(DiagID) << D << Hint);
+  SourceLocation DiagLoc = D->getLocation();
+  DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
 }
 

[clang] dfb85c3 - [Clang][Interp] Diagnose uninitialized ctor of global record arrays

2023-06-21 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-06-21T19:03:01+09:00
New Revision: dfb85c3ce09a7bd1a059a3e821390b5111454f9e

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

LOG: [Clang][Interp] Diagnose uninitialized ctor of global record arrays

This patch adds a check for uninitialized subobjects of global variables that 
are record arrays.
e.g. `constexpr Foo f[2];`

Reviewed By: tbaeder

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/lib/AST/Interp/Interp.cpp
clang/test/AST/Interp/cxx20.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 8708bf99d91e7..83bafeb9aac61 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -166,7 +166,8 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
 if (!visitInitializer(Init))
   return false;
 
-if (Init->getType()->isRecordType() && !this->emitCheckGlobalCtor(Init))
+if ((Init->getType()->isArrayType() || Init->getType()->isRecordType()) &&
+!this->emitCheckGlobalCtor(Init))
   return false;
 
 return this->emitPopPtr(Init);

diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 8d7f191ebaa09..f646e876554ca 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -456,8 +456,11 @@ static bool CheckFieldsInitialized(InterpState &S, CodePtr 
OpPC,
 
 bool CheckCtorCall(InterpState &S, CodePtr OpPC, const Pointer &This) {
   assert(!This.isZero());
-  const Record *R = This.getRecord();
-  return CheckFieldsInitialized(S, OpPC, This, R);
+  if (const Record *R = This.getRecord())
+return CheckFieldsInitialized(S, OpPC, This, R);
+  const auto *CAT =
+  cast(This.getType()->getAsArrayTypeUnsafe());
+  return CheckArrayInitialized(S, OpPC, This, CAT);
 }
 
 bool CheckFloatResult(InterpState &S, CodePtr OpPC, APFloat::opStatus Status) {

diff  --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/AST/Interp/cxx20.cpp
index 5d9fa90b482ea..87c32e42d053e 100644
--- a/clang/test/AST/Interp/cxx20.cpp
+++ b/clang/test/AST/Interp/cxx20.cpp
@@ -138,14 +138,43 @@ static_assert(!b4); // ref-error {{not an integral 
constant expression}} \
 namespace UninitializedFields {
   class A {
   public:
-int a; // expected-note 3{{subobject declared here}} \
-   // ref-note 3{{subobject declared here}}
+int a; // expected-note 4{{subobject declared here}} \
+   // ref-note 4{{subobject declared here}}
 constexpr A() {}
   };
   constexpr A a; // expected-error {{must be initialized by a constant 
expression}} \
  // expected-note {{subobject 'a' is not initialized}} \
  // ref-error {{must be initialized by a constant expression}} 
\
  // ref-note {{subobject 'a' is not initialized}}
+  constexpr A aarr[2]; // expected-error {{must be initialized by a constant 
expression}} \
+   // expected-note {{subobject 'a' is not initialized}} \
+   // ref-error {{must be initialized by a constant 
expression}} \
+   // ref-note {{subobject 'a' is not initialized}}
+  class F {
+public:
+  int f; // expected-note 3{{subobject declared here}} \
+ // ref-note 3{{subobject declared here}}
+
+  constexpr F() {}
+  constexpr F(bool b) {
+if (b)
+  f = 42;
+  }
+  };
+
+  constexpr F foo[2] = {true}; // expected-error {{must be initialized by a 
constant expression}} \
+   // expected-note {{subobject 'f' is not 
initialized}} \
+   // ref-error {{must be initialized by a 
constant expression}} \
+   // ref-note {{subobject 'f' is not initialized}}
+  constexpr F foo2[3] = {true, false, true}; // expected-error {{must be 
initialized by a constant expression}} \
+ // expected-note {{subobject 'f' 
is not initialized}} \
+ // ref-error {{must be 
initialized by a constant expression}} \
+ // ref-note {{subobject 'f' is 
not initialized}}
+  constexpr F foo3[3] = {true, true, F()}; // expected-error {{must be 
initialized by a constant expression}} \
+   // expected-note {{subobject 'f' is 
not initialized}} \
+   // ref-error {{must be initialized 
by a constant expression}} \
+   // ref-note {{subobject 'f' is not 
initialized}}
+
 
 
   class Base {



__

[clang] 940c94e - [clang][Sema] Fix comments to conform to bugprone-argument-comment (NFC)

2023-06-23 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-06-23T22:25:04+09:00
New Revision: 940c94e1c1b99511630b6f61890ac54161b5829c

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

LOG: [clang][Sema] Fix comments to conform to bugprone-argument-comment (NFC)

Makes some comments conform to bugprone-argument-comment 
(https://clang.llvm.org/extra/clang-tidy/checks/bugprone/argument-comment.html)

Added: 


Modified: 
clang/lib/Sema/Sema.cpp

Removed: 




diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 694e07b46aaf0..24363af392ea2 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1365,12 +1365,12 @@ void Sema::ActOnEndOfTranslationUnit() {
   << DiagD << DiagRange;
 else
   Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
-  << /*function*/ 0 << DiagD << DiagRange;
+  << /*function=*/0 << DiagD << DiagRange;
   }
 } else {
   if (FD->getDescribedFunctionTemplate())
 Diag(DiagD->getLocation(), diag::warn_unused_template)
-<< /*function*/ 0 << DiagD << DiagRange;
+<< /*function=*/0 << DiagD << DiagRange;
   else
 Diag(DiagD->getLocation(), isa(DiagD)
? diag::warn_unused_member_function
@@ -1389,10 +1389,10 @@ void Sema::ActOnEndOfTranslationUnit() {
 }
 if (DiagD->isReferenced()) {
   Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
-  << /*variable*/ 1 << DiagD << DiagRange;
+  << /*variable=*/1 << DiagD << DiagRange;
 } else if (DiagD->getDescribedVarTemplate()) {
   Diag(DiagD->getLocation(), diag::warn_unused_template)
-  << /*variable*/ 1 << DiagD << DiagRange;
+  << /*variable=*/1 << DiagD << DiagRange;
 } else if (DiagD->getType().isConstQualified()) {
   const SourceManager &SM = SourceMgr;
   if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||



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


[clang] 409a809 - [clang][Diagnostics] Provide parameter source range to arity-mismatch notes

2023-06-25 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-06-26T00:27:15+09:00
New Revision: 409a8097c5c728607eb6b05efb1744bf5f9096e1

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

LOG: [clang][Diagnostics] Provide parameter source range to arity-mismatch notes

Consider the following piece of code:
```
void func( int aa,
   int bb,
   int cc) {}

void arity_mismatch() {
  func(2, 4);
}
```
BEFORE:
```
source.cpp:6:3: error: no matching function for call to 'func'
6 |   func(2, 4);
  |   ^~~~
source.cpp:1:6: note: candidate function not viable: requires 3 arguments, but 
2 were provided
1 | void func( int aa,
  |  ^
```
AFTER:
```
source.cpp:6:3: error: no matching function for call to 'func'
6 |   func(2, 4);
  |   ^~~~
source.cpp:1:6: note: candidate function not viable: requires 3 arguments, but 
2 were provided
1 | void func( int aa,
  |  ^ ~~~
2 |int bb,
  |~~~
3 |int cc) {}
  |~~
```

Reviewed By: cjdb, aaron.ballman

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

Added: 
clang/test/Misc/diag-func-call-ranges.c
clang/test/Misc/diag-func-call-ranges.cpp

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

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ff9f8da044db5..43f80bddce3ff 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -364,6 +364,8 @@ Improvements to Clang's diagnostics
 - The Fix-It emitted for unused labels used to expand to the next line, which 
caused
   visual oddities now that Clang shows more than one line of code snippet. 
This has
   been fixed and the Fix-It now only spans to the end of the ``:``.
+- Clang now underlines the parameter list of function declaration when emitting
+  a note about the mismatch in the number of arguments.
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 45056f0d56075..528b76518ff3a 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6459,7 +6459,8 @@ Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
 
   // Emit the location of the prototype.
   if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
-Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
+Diag(FDecl->getLocation(), diag::note_callee_decl)
+<< FDecl << FDecl->getParametersSourceRange();
 
   return true;
 }
@@ -6504,7 +6505,8 @@ Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
 
   // Emit the location of the prototype.
   if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
-Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
+Diag(FDecl->getLocation(), diag::note_callee_decl)
+<< FDecl << FDecl->getParametersSourceRange();
 
   // This deletes the extra arguments.
   Call->shrinkNumArgs(NumParams);

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 108e2cf47437a..d4f1c61259c03 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -11037,11 +11037,13 @@ static void DiagnoseArityMismatch(Sema &S, NamedDecl 
*Found, Decl *D,
   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
-<< Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
+<< Description << mode << Fn->getParamDecl(0) << NumFormalArgs
+<< Fn->getParametersSourceRange();
   else
 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
-<< Description << mode << modeCount << NumFormalArgs;
+<< Description << mode << modeCount << NumFormalArgs
+<< Fn->getParametersSourceRange();
 
   MaybeEmitInheritedConstructorNote(S, Found);
 }

diff  --git a/clang/test/Misc/diag-func-call-ranges.c 
b/clang/test/Misc/diag-func-call-ranges.c
new file mode 100644
index 0..c1ad687acb146
--- /dev/null
+++ b/clang/test/Misc/diag-func-call-ranges.c
@@ -0,0 +1,11 @@
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 
2>&1 | FileCheck %s --strict-whitespace
+
+// CHECK:  :{9:3-9:7}: error: too few arguments
+// CHECK:  :{7:12-7:26}: note: 'func' declared here
+// CHECK:  :{10:3-10:7}{10:13-10:17}: error: too many arguments
+// CHECK:  :{7:12-7:26}: note: 'func' declared here
+void func( int aa, int bb) {}
+void arity_mismatch() {
+  func(3

[clang] f6be96a - [clang][ExprConstant] Fix display of syntactically-invalid note for member function calls

2023-06-27 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-06-28T00:19:46+09:00
New Revision: f6be96aa4e5e282ea52041ad6fe5fff13a3df103

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

LOG: [clang][ExprConstant] Fix display of syntactically-invalid note for member 
function calls

This patch makes the display of member function calls more true to the 
user-written code by making use of the syntactical structure of the function 
calls.
This patch also changes the display of conventional value-based printing from 
arrow operator to dot operator.
This avoids the syntactical invalidness in notes previously caused by the 
display of & operator
(lack of parentheses and reference of rvalue)

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

Reviewed By: cjdb
Differential Revision: https://reviews.llvm.org/D151720

Added: 
clang/test/SemaCXX/constexpr-frame-describe.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ExprConstant.cpp
clang/test/AST/Interp/constexpr-nqueens.cpp
clang/test/AST/Interp/lambda.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
clang/test/CXX/temp/temp.param/p8-cxx20.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/cxx2a-consteval.cpp
clang/test/SemaCXX/deduced-return-type-cxx14.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1ecf620f2a768..f00082fad24dd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -371,6 +371,10 @@ Improvements to Clang's diagnostics
   ``#pragma clang|GCC diagnostic push|pop`` directive.
   (`#13920: `_)
 - Clang now does not try to analyze cast validity on variables with dependent 
alignment (`#63007: `_).
+- Clang constexpr evaluator now displays member function calls more precisely
+  by making use of the syntactical structure of function calls. This avoids 
display
+  of syntactically invalid codes in diagnostics.
+  (`#57081: `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 19d8e24fef63c..777245f86bdff 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -531,6 +531,9 @@ namespace {
 /// This - The binding for the this pointer in this call, if any.
 const LValue *This;
 
+/// CallExpr - The syntactical structure of member function calls
+const Expr *CallExpr;
+
 /// Information on how to find the arguments to this call. Our arguments
 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
 /// key and this value as the version.
@@ -584,7 +587,7 @@ namespace {
 
 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
-   CallRef Arguments);
+   const Expr *CallExpr, CallRef Arguments);
 ~CallStackFrame();
 
 // Return the temporary for Key whose version number is Version.
@@ -978,7 +981,9 @@ namespace {
   CallStackDepth(0), NextCallIndex(1),
   StepsLeft(C.getLangOpts().ConstexprStepLimit),
   EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
-  BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
+  BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
+  /*This=*/nullptr,
+  /*CallExpr=*/nullptr, CallRef()),
   EvaluatingDecl((const ValueDecl *)nullptr),
   EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
   HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
@@ -1436,9 +1441,10 @@ void 
SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
 
 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
-   CallRef Call)
+   const Expr *CallExpr, CallRef Call)
 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
-  Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
+  CallExpr(CallExpr), Arguments(Call), CallLoc(CallLoc),
+  Index(Info.NextCallIndex++) {
   Info.CurrentCall = this;
   ++Info.CallStackDepth;
 }
@@ -1918,12 +1924,29 @@ void CallStackFrame::describe(raw_ostream &Out) {
 Out << *Callee << '(';
 
   if (This && IsMemberCall) {
-APValue Val;
-This->moveInto(Val);
-Val.printPretty(Out, Info.Ctx,
-This->Designator.MostDerivedType);
-// FIXME: Add parens around Val if needed.
-Out << "->"

[clang] 8038086 - [clang][Sema] Remove dead diagnostic for loss of __unaligned qualifier

2023-06-29 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-06-29T23:02:09+09:00
New Revision: 8038086aa75a122e5e632ebb1e7da06a2f7eed4b

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

LOG: [clang][Sema] Remove dead diagnostic for loss of __unaligned qualifier

D120936 has made the loss of `__unaligned` qualifier NOT a bad-conversion.
Because of this, the bad-conversion note about the loss of this qualifier does 
not take effect.
e.g.
```
void foo(int *ptr);

void func(const __unaligned int *var) { foo(var); }
```
BEFORE this patch:
```
source.cpp:3:41: error: no matching function for call to 'foo'
3 | void func(const __unaligned int *var) { foo(var); }
  | ^~~
source.cpp:1:6: note: candidate function not viable: 1st argument ('const 
__unaligned int *') would lose __unaligned qualifier
1 | void foo(int *ptr);
  |  ^
2 |
3 | void func(const __unaligned int *var) { foo(var); }
  | ~~~
```
AFTER this patch:
```
source.cpp:3:41: error: no matching function for call to 'foo'
3 | void func(const __unaligned int *var) { foo(var); }
  | ^~~
source.cpp:1:6: note: candidate function not viable: 1st argument ('const 
__unaligned int *') would lose const qualifier
1 | void foo(int *ptr);
  |  ^
2 |
3 | void func(const __unaligned int *var) { foo(var); }
  | ~~~
```
Please note the different mentions of `__unaligned` and `const` in notes.

Reviewed By: cjdb, rnk
Differential Revision: https://reviews.llvm.org/D153690

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaOverload.cpp
clang/test/SemaCXX/MicrosoftExtensions.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f00082fad24ddf..03c27a207d5e1b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -375,6 +375,8 @@ Improvements to Clang's diagnostics
   by making use of the syntactical structure of function calls. This avoids 
display
   of syntactically invalid codes in diagnostics.
   (`#57081: `_)
+- Clang no longer emits inappropriate notes about the loss of ``__unaligned`` 
qualifier
+  on overload resolution, when the actual reason for the failure is loss of 
other qualifiers.
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 507e9f11f46646..c2b8bd4ce9cd96 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4700,9 +4700,6 @@ def note_ovl_candidate_bad_cvr : Note<
 "%select{const|restrict|const and restrict|volatile|const and volatile|"
 "volatile and restrict|const, volatile, and restrict}4 qualifier"
 "%select{||s||s|s|s}4">;
-def note_ovl_candidate_bad_unaligned : Note<
-"candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: "
-"%ordinal5 argument (%3) would lose __unaligned qualifier">;
 def note_ovl_candidate_bad_base_to_derived_conv : Note<
 "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: "
 "cannot %select{convert from|convert from|bind}3 "

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 0d2db9fe88c483..febcbad1f3727a 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10821,15 +10821,6 @@ static void DiagnoseBadConversion(Sema &S, 
OverloadCandidate *Cand,
   return;
 }
 
-if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
-  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
-  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << 
FnDesc
-  << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
-  << FromQs.hasUnaligned() << I + 1;
-  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
-  return;
-}
-
 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
 assert(CVR && "expected qualifiers mismatch");
 

diff  --git a/clang/test/SemaCXX/MicrosoftExtensions.cpp 
b/clang/test/SemaCXX/MicrosoftExtensions.cpp
index effe2e6e6f0866..960030d44f0c15 100644
--- a/clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -68,19 +68,23 @@ __unaligned int aligned_type4::* __unaligned 
p3_aligned_type4 = &aligned_type4::
 void (aligned_type4::*__unaligned p4_aligned_type4)();
 
 // Check that __unaligned qualifier can be used for overloading
-void foo_unaligned(int *arg) {

[clang] 8e329ca - Reland "[Clang][SemaCXX] Add unused warning for variables declared in condition expressions"

2023-08-15 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-15T17:24:13+09:00
New Revision: 8e329caa944c377c51ef567d5aa67cfac9ffd0fa

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

LOG: Reland "[Clang][SemaCXX] Add unused warning for variables declared in 
condition expressions"

This patch marks the declarations with initializations in condition expressions 
such as
if (int var = init) as unreferenced so that -Wunused can warn on them.

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

Reviewed By: cor3ntin
Differential Revision: https://reviews.llvm.org/D152495

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaCXX/warn-unused-variables.cpp
llvm/lib/Support/VirtualFileSystem.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd7beff546c932..96a9ec14112292 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -129,6 +129,9 @@ Improvements to Clang's diagnostics
   of a base class is not called in the constructor of its derived class.
 - Clang no longer emits ``-Wmissing-variable-declarations`` for variables 
declared
   with the ``register`` storage class.
+- Clang now warns on unused variables declared and initialized in condition
+  expressions.
+  (`#61681: `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 0ad807cca36c7b..db1cd28f7b5a93 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1995,7 +1995,7 @@ static bool ShouldDiagnoseUnusedDecl(const LangOptions 
&LangOpts,
   return false;
   } else if (!D->getDeclName()) {
 return false;
-  } else if (D->isReferenced() || D->isUsed()) {
+  } else if (D->isReferenced() || (!isa(D) && D->isUsed())) {
 return false;
   }
 

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index e6eb9508f8e6ff..17fda20c1ca11c 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -4015,6 +4015,10 @@ ExprResult Sema::CheckConditionVariable(VarDecl 
*ConditionVar,
   ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
   ConditionVar->getLocation());
 
+  // Ensure that `-Wunused-variable` will be emitted for condition variables
+  // that are not referenced later. e.g.: if (int var = init());
+  ConditionVar->setReferenced(/*R=*/false);
+
   switch (CK) {
   case ConditionKind::Boolean:
 return CheckBooleanCondition(StmtLoc, Condition.get());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index f78d46f5950360..522ec12de3d368 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5352,7 +5352,7 @@ void Sema::BuildVariableInstantiation(
   // will have been deferred.
   if (!NewVar->isInvalidDecl() &&
   NewVar->getDeclContext()->isFunctionOrMethod() &&
-  OldVar->getType()->isDependentType())
+  OldVar->getType()->isDependentType() && !OldVar->isImplicit())
 DiagnoseUnusedDecl(NewVar);
 }
 

diff  --git a/clang/test/SemaCXX/warn-unused-variables.cpp 
b/clang/test/SemaCXX/warn-unused-variables.cpp
index 4db8bdf12e5de0..db33086436d3af 100644
--- a/clang/test/SemaCXX/warn-unused-variables.cpp
+++ b/clang/test/SemaCXX/warn-unused-variables.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify %s
-// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++14-extensions -Wno-c++17-extensions -verify -std=c++11 %s
 template void f() {
   T t;
   t = 17;
@@ -294,3 +294,115 @@ void RAIIWrapperTest() {
 }
 
 } // namespace gh54489
+
+namespace inside_condition {
+  void ifs() {
+if (int hoge = 0) // expected-warning {{unused variable 'hoge'}}
+  return;
+if (const int const_hoge = 0) // expected-warning {{unused variable 
'const_hoge'}}
+  return;
+else if (int fuga = 0)
+  (void)fuga;
+else if (int used = 1; int catched = used) // expected-warning {{unused 
variable 'catched'}}
+  return;
+else if (int refed = 1; int used = refed)
+  (void)used;
+else if (int unused1 = 2; int unused2 = 3) // expected-warning {{unused 
variable 'unused1'}} \
+   // expected-warning {{unused 
variable 'unused2'}}
+  return;
+else if (int unused = 4; int used = 5) // expected-warning {{unused 
var

[clang] 5aded52 - Revert "Reland "[Clang][SemaCXX] Add unused warning for variables declared in condition expressions""

2023-08-15 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-15T19:54:51+09:00
New Revision: 5aded521ea94810b81369eaa951dcf59ad5ab82d

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

LOG: Revert "Reland "[Clang][SemaCXX] Add unused warning for variables declared 
in condition expressions""

This causes a lot of warning in sanitizer build:
https://lab.llvm.org/buildbot/#/builders/258/builds/5424
https://lab.llvm.org/buildbot/#/builders/36/builds/36560

This reverts commit 8e329caa944c377c51ef567d5aa67cfac9ffd0fa.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaCXX/warn-unused-variables.cpp
llvm/lib/Support/VirtualFileSystem.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 96a9ec14112292..cd7beff546c932 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -129,9 +129,6 @@ Improvements to Clang's diagnostics
   of a base class is not called in the constructor of its derived class.
 - Clang no longer emits ``-Wmissing-variable-declarations`` for variables 
declared
   with the ``register`` storage class.
-- Clang now warns on unused variables declared and initialized in condition
-  expressions.
-  (`#61681: `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index db1cd28f7b5a93..0ad807cca36c7b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1995,7 +1995,7 @@ static bool ShouldDiagnoseUnusedDecl(const LangOptions 
&LangOpts,
   return false;
   } else if (!D->getDeclName()) {
 return false;
-  } else if (D->isReferenced() || (!isa(D) && D->isUsed())) {
+  } else if (D->isReferenced() || D->isUsed()) {
 return false;
   }
 

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 17fda20c1ca11c..e6eb9508f8e6ff 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -4015,10 +4015,6 @@ ExprResult Sema::CheckConditionVariable(VarDecl 
*ConditionVar,
   ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
   ConditionVar->getLocation());
 
-  // Ensure that `-Wunused-variable` will be emitted for condition variables
-  // that are not referenced later. e.g.: if (int var = init());
-  ConditionVar->setReferenced(/*R=*/false);
-
   switch (CK) {
   case ConditionKind::Boolean:
 return CheckBooleanCondition(StmtLoc, Condition.get());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 522ec12de3d368..f78d46f5950360 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5352,7 +5352,7 @@ void Sema::BuildVariableInstantiation(
   // will have been deferred.
   if (!NewVar->isInvalidDecl() &&
   NewVar->getDeclContext()->isFunctionOrMethod() &&
-  OldVar->getType()->isDependentType() && !OldVar->isImplicit())
+  OldVar->getType()->isDependentType())
 DiagnoseUnusedDecl(NewVar);
 }
 

diff  --git a/clang/test/SemaCXX/warn-unused-variables.cpp 
b/clang/test/SemaCXX/warn-unused-variables.cpp
index db33086436d3af..4db8bdf12e5de0 100644
--- a/clang/test/SemaCXX/warn-unused-variables.cpp
+++ b/clang/test/SemaCXX/warn-unused-variables.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify %s
-// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++14-extensions -Wno-c++17-extensions -verify -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=c++11 %s
 template void f() {
   T t;
   t = 17;
@@ -294,115 +294,3 @@ void RAIIWrapperTest() {
 }
 
 } // namespace gh54489
-
-namespace inside_condition {
-  void ifs() {
-if (int hoge = 0) // expected-warning {{unused variable 'hoge'}}
-  return;
-if (const int const_hoge = 0) // expected-warning {{unused variable 
'const_hoge'}}
-  return;
-else if (int fuga = 0)
-  (void)fuga;
-else if (int used = 1; int catched = used) // expected-warning {{unused 
variable 'catched'}}
-  return;
-else if (int refed = 1; int used = refed)
-  (void)used;
-else if (int unused1 = 2; int unused2 = 3) // expected-warning {{unused 
variable 'unused1'}} \
-   // expected-warning {{unused 
variable 'unused2'}}
-  return;
-else if (int unused = 4; int used = 5) // expected-warning {{unused 
variable 'unused'}}
-  (void)used;
-else if (int used = 

[clang] b3469ce - [clang][Analysis] Handle && and || against variable and its negation as tautology

2023-08-17 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-17T17:55:48+09:00
New Revision: b3469ce6f80bce2b0a86026fd6867c4b04853466

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

LOG: [clang][Analysis] Handle && and || against variable and its negation as 
tautology

This patch introduces a new warning flag -Wtautological-negation-compare 
grouped in -Wtautological-compare that warns on the use of && or || operators 
against a variable and its negation.
e.g. x || !x and !x && x
This also makes the -Winfinite-recursion diagnose more cases.

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

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

Added: 
clang/test/SemaCXX/tautological-negation-compare.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Analysis/CFG.h
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Analysis/CFG.cpp
clang/lib/Sema/AnalysisBasedWarnings.cpp
clang/test/Analysis/temp-obj-dtors-cfg-output.cpp
clang/test/Misc/warning-wall.c
clang/test/SemaCXX/warn-infinite-recursion.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 61272838a68b8c..02b897bcd0a68e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -132,6 +132,10 @@ Improvements to Clang's diagnostics
   of a base class is not called in the constructor of its derived class.
 - Clang no longer emits ``-Wmissing-variable-declarations`` for variables 
declared
   with the ``register`` storage class.
+- Clang's ``-Wtautological-negation-compare`` flag now diagnoses logical
+  tautologies like ``x && !x`` and ``!x || x`` in expressions. This also
+  makes ``-Winfinite-recursion`` diagnose more cases.
+  (`#56035: `_).
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Analysis/CFG.h 
b/clang/include/clang/Analysis/CFG.h
index eacebe176dda4c..cf4fa2da2a358e 100644
--- a/clang/include/clang/Analysis/CFG.h
+++ b/clang/include/clang/Analysis/CFG.h
@@ -1162,6 +1162,7 @@ class CFGCallback {
   CFGCallback() = default;
   virtual ~CFGCallback() = default;
 
+  virtual void logicAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {}
   virtual void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {}
   virtual void compareBitwiseEquality(const BinaryOperator *B,
   bool isAlwaysTrue) {}

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 6f8386cd10922f..d1aa51393ef357 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -678,13 +678,15 @@ def TautologicalOverlapCompare : 
DiagGroup<"tautological-overlap-compare">;
 def TautologicalBitwiseCompare : DiagGroup<"tautological-bitwise-compare">;
 def TautologicalUndefinedCompare : DiagGroup<"tautological-undefined-compare">;
 def TautologicalObjCBoolCompare : DiagGroup<"tautological-objc-bool-compare">;
+def TautologicalNegationCompare : DiagGroup<"tautological-negation-compare">;
 def TautologicalCompare : DiagGroup<"tautological-compare",
 [TautologicalConstantCompare,
  TautologicalPointerCompare,
  TautologicalOverlapCompare,
  TautologicalBitwiseCompare,
  TautologicalUndefinedCompare,
- TautologicalObjCBoolCompare]>;
+ TautologicalObjCBoolCompare,
+ TautologicalNegationCompare]>;
 def HeaderHygiene : DiagGroup<"header-hygiene">;
 def DuplicateDeclSpecifier : DiagGroup<"duplicate-decl-specifier">;
 def CompareDistinctPointerType : DiagGroup<"compare-distinct-pointer-types">;

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 632be32cfddd5a..8c629aad89f48a 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9796,6 +9796,12 @@ def warn_comparison_bitwise_always : Warning<
 def warn_comparison_bitwise_or : Warning<
   "bitwise or with non-zero value always evaluates to true">,
   InGroup, DefaultIgnore;
+def warn_tautological_negation_and_compare: Warning<
+  "'&&' of a value and its negation always evaluates to false">,
+  InGroup, DefaultIgnore;
+def warn_tautological_negation_or_compare: Warning<
+  "'||' of a value and its negation always evaluates to true">,
+  InGroup, DefaultIgnore;
 def warn_tautological_overlap_compariso

[clang] 985a72b - [clang][Diagnostics] Provide source range to integer-overflow warnings

2023-08-19 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-19T22:05:12+09:00
New Revision: 985a72b6b3e74f0d29780b2a97b5817473338ffe

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

LOG: [clang][Diagnostics] Provide source range to integer-overflow warnings

BEFORE:

```
overflow.cpp:1:21: warning: overflow in expression; result is -2147483648 with 
type 'int' [-Winteger-overflow]
1 | int x = __INT_MAX__ + 1 + 3;
  | ^
overflow.cpp:2:9: warning: overflow in expression; result is -2147483648 with 
type 'int' [-Winteger-overflow]
2 | int a = -(1 << 31) + 1;
  | ^
```
AFTER:

```
overflow.cpp:1:21: warning: overflow in expression; result is -2147483648 with 
type 'int' [-Winteger-overflow]
1 | int x = __INT_MAX__ + 1 + 3;
  | ^~~
overflow.cpp:2:9: warning: overflow in expression; result is -2147483648 with 
type 'int' [-Winteger-overflow]
2 | int a = -(1 << 31) + 1;
  | ^~
```

Reviewed By: tbaeder
Differential Revision: https://reviews.llvm.org/D157383

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/Interp/Interp.h
clang/test/Misc/constexpr-source-ranges.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 9ee9fccfd461f5..9f4c758b81303c 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2798,7 +2798,7 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const 
Expr *E,
 if (Info.checkingForUndefinedBehavior())
   Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
diag::warn_integer_constant_overflow)
-  << toString(Result, 10) << E->getType();
+  << toString(Result, 10) << E->getType() << E->getSourceRange();
 return HandleOverflow(Info, E, Value, E->getType());
   }
   return true;
@@ -13643,7 +13643,7 @@ bool IntExprEvaluator::VisitUnaryOperator(const 
UnaryOperator *E) {
   if (Info.checkingForUndefinedBehavior())
 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
  diag::warn_integer_constant_overflow)
-<< toString(Value, 10) << E->getType();
+<< toString(Value, 10) << E->getType() << E->getSourceRange();
 
   if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
   E->getType()))

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index aebab9023a3580..79995b5a74897c 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -271,7 +271,8 @@ bool AddSubMulHelper(InterpState &S, CodePtr OpPC, unsigned 
Bits, const T &LHS,
 SmallString<32> Trunc;
 Value.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();
 return true;
   } else {
 S.CCEDiag(E, diag::note_constexpr_overflow) << Value << Type;
@@ -478,7 +479,8 @@ bool Neg(InterpState &S, CodePtr OpPC) {
 SmallString<32> Trunc;
 NegatedValue.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();
 return true;
   }
 
@@ -531,7 +533,8 @@ bool IncDecHelper(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr) {
 SmallString<32> Trunc;
 APResult.trunc(Result.bitWidth()).toString(Trunc, 10);
 auto Loc = E->getExprLoc();
-S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type;
+S.report(Loc, diag::warn_integer_constant_overflow)
+<< Trunc << Type << E->getSourceRange();
 return true;
   }
 

diff  --git a/clang/test/Misc/constexpr-source-ranges.cpp 
b/clang/test/Misc/constexpr-source-ranges.cpp
index 15fd54847f4762..f21373eff3a95c 100644
--- a/clang/test/Misc/constexpr-source-ranges.cpp
+++ b/clang/test/Misc/constexpr-source-ranges.cpp
@@ -34,3 +34,10 @@ constexpr int ints(int a, int b, int c, int d) {
 }
 static_assert(ints(1, div(true, false), 2, div(false, true)) == 1, "");
 // CHECK: constexpr-source-ranges.cpp:35:23:{35:23-35:39}
+
+namespace overflow {
+// CHECK:  :{[[@LINE+1]]:9-[[@LINE+1]]:29}:
+int x = -1 + __INT_MAX__ + 2 + 3;
+// CHECK:  :{[[@LINE+1]]:9-[[@LINE+1]]:19}:
+int a = -(1 << 31) + 1;
+}



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


[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-02 Thread Takuya Shimizu via cfe-commits


@@ -2411,10 +2411,15 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-assert(SubobjectDecl && "SubobjectDecl shall be non-null");
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
-Info.Note(SubobjectDecl->getLocation(),
-  diag::note_constexpr_subobject_declared_here);
+if (SubobjectDecl) {

hazohelet wrote:

I'm not worrying about `SubobjectLoc` that was used for `subobject declared 
here` note. https://reviews.llvm.org/D146358 introduced the explicit `nullptr` 
args, but it only happens on calls where invalid source location was explicitly 
passed before that patch. (There was one exception about base classes but it 
was fixed in https://reviews.llvm.org/D153969. Despite passing null 
`SubobjectDecl` there, the passed `APValue` is known to be `isStruct()`, so its 
subobjects do not inherit the nullness of `SubobjectDecl`)
So, we always had an invalid source location where we now have 
null`SubobjectDecl`; thus no information being lost.

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


[clang] 2176c5e - [Clang][Sema] Fix display of characters on static assertion failure

2023-10-03 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-10-04T14:09:06+09:00
New Revision: 2176c5e510e3bfcbc75afb13e78d287141f239a7

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

LOG: [Clang][Sema] Fix display of characters on static assertion failure

This patch fixes the display of characters appearing in LHS or RHS of == 
expression in notes to static assertion failure.
This applies C-style escape if the printed character is a special character. 
This also adds a numerical value displayed next to the character representation.
This also tries to print multi-byte characters if the user-provided expression 
is multi-byte char type.

Reviewed By: cor3ntin
Differential Revision: https://reviews.llvm.org/D155610

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Diagnostic.h
clang/lib/Basic/Diagnostic.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/Lexer/cxx1z-trigraphs.cpp
clang/test/SemaCXX/static-assert-cxx26.cpp
clang/test/SemaCXX/static-assert.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3dce7f6a8f9d56e..4c8b85fc29755c1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -222,6 +222,41 @@ Improvements to Clang's diagnostics
 - ``-Wfixed-enum-extension`` and ``-Wmicrosoft-fixed-enum`` diagnostics are no 
longer
   emitted when building as C23, since C23 standardizes support for enums with a
   fixed underlying type.
+- When describing the failure of static assertion of `==` expression, clang 
prints the integer
+  representation of the value as well as its character representation when
+  the user-provided expression is of character type. If the character is
+  non-printable, clang now shows the escpaed character.
+  Clang also prints multi-byte characters if the user-provided expression
+  is of multi-byte character type.
+
+  *Example Code*:
+
+  .. code-block:: c++
+
+ static_assert("A\n"[1] == U'🌍');
+
+  *BEFORE*:
+
+  .. code-block:: text
+
+source:1:15: error: static assertion failed due to requirement '"A\n"[1] 
== U'\U0001f30d''
+1 | static_assert("A\n"[1] == U'🌍');
+  |   ^
+source:1:24: note: expression evaluates to ''
+' == 127757'
+1 | static_assert("A\n"[1] == U'🌍');
+  |   ~^~~~
+
+  *AFTER*:
+
+  .. code-block:: text
+
+source:1:15: error: static assertion failed due to requirement '"A\n"[1] 
== U'\U0001f30d''
+1 | static_assert("A\n"[1] == U'🌍');
+  |   ^
+source:1:24: note: expression evaluates to ''\n' (0x0A, 10) == U'🌍' 
(0x1F30D, 127757)'
+1 | static_assert("A\n"[1] == U'🌍');
+  |   ~^~~~
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Basic/Diagnostic.h 
b/clang/include/clang/Basic/Diagnostic.h
index 5606a22fe9d68b4..3df037b793b3946 100644
--- a/clang/include/clang/Basic/Diagnostic.h
+++ b/clang/include/clang/Basic/Diagnostic.h
@@ -1840,7 +1840,7 @@ const char ToggleHighlight = 127;
 void ProcessWarningOptions(DiagnosticsEngine &Diags,
const DiagnosticOptions &Opts,
bool ReportDiags = true);
-
+void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl &OutStr);
 } // namespace clang
 
 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H

diff  --git a/clang/lib/Basic/Diagnostic.cpp b/clang/lib/Basic/Diagnostic.cpp
index 7a54d27ef9d8ee2..0208ccc31bd7fc0 100644
--- a/clang/lib/Basic/Diagnostic.cpp
+++ b/clang/lib/Basic/Diagnostic.cpp
@@ -800,9 +800,10 @@ FormatDiagnostic(SmallVectorImpl &OutStr) const {
   FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
 }
 
-/// pushEscapedString - Append Str to the diagnostic buffer,
+/// EscapeStringForDiagnostic - Append Str to the diagnostic buffer,
 /// escaping non-printable characters and ill-formed code unit sequences.
-static void pushEscapedString(StringRef Str, SmallVectorImpl &OutStr) {
+void clang::EscapeStringForDiagnostic(StringRef Str,
+  SmallVectorImpl &OutStr) {
   OutStr.reserve(OutStr.size() + Str.size());
   auto *Begin = reinterpret_cast(Str.data());
   llvm::raw_svector_ostream OutStream(OutStr);
@@ -854,7 +855,7 @@ FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
   StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
   getArgKind(0) == DiagnosticsEngine::ak_std_string) {
 const std::string &S = getArgStdStr(0);
-pushEscapedString(S, OutStr);
+EscapeStringForDiagnostic(S, OutStr);
 return;
   }
 
@@ -961,7 +962,7 @@ FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
 case DiagnosticsEngine::ak_std_string: {
   const std::string &S = getArgStdStr(ArgNo);

[clang] [clang][ExprConst] Fix crash on uninitialized array subobject (PR #67817)

2023-10-09 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

Ping

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


[clang] e90f4fc - [clang][ExprConstant] Print template arguments when describing stack frame

2023-07-31 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-07-31T17:05:56+09:00
New Revision: e90f4fc6acaffd216e06e47df0aee6a8b5b2d4a9

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

LOG: [clang][ExprConstant] Print template arguments when describing stack frame

This patch adds additional printing of template argument list when the 
described function is a template specialization.
This can be useful when handling complex template functions in constexpr 
evaluator.

Reviewed By: cjdb, dblaikie
Differential Revision: https://reviews.llvm.org/D154366

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ExprConstant.cpp
clang/test/AST/Interp/literals.cpp
clang/test/SemaCXX/builtin-align-cxx.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/constant-expression-cxx14.cpp
clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
clang/test/SemaCXX/constexpr-frame-describe.cpp
clang/test/SemaCXX/cxx2a-constexpr-dynalloc-limits.cpp
clang/test/SemaCXX/cxx2b-consteval-propagate.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4b8a323093ccd5..d369af7944ebeb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -95,6 +95,8 @@ Attribute Changes in Clang
 
 Improvements to Clang's diagnostics
 ---
+- Clang constexpr evaluator now prints template arguments when displaying
+  template-specialization function calls.
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index c06ca3c405370e..c688467a2fef74 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -1950,7 +1950,8 @@ void CallStackFrame::describe(raw_ostream &Out) const {
   cast(Callee)->isInstance();
 
   if (!IsMemberCall)
-Out << *Callee << '(';
+Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
+ /*Qualified=*/false);
 
   if (This && IsMemberCall) {
 if (const auto *MCE = dyn_cast_if_present(CallExpr)) {
@@ -1975,10 +1976,13 @@ void CallStackFrame::describe(raw_ostream &Out) const {
   Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
   Out << ".";
 }
-Out << *Callee << '(';
+Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
+ /*Qualified=*/false);
 IsMemberCall = false;
   }
 
+  Out << '(';
+
   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
 if (ArgIndex > (unsigned)IsMemberCall)

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index d2b5f4a5a1901f..ad0adc23b42e40 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -502,22 +502,22 @@ namespace IncDec {
 return 1;
   }
   static_assert(uninit(), ""); // ref-error {{not an integral 
constant expression}} \
-  // ref-note {{in call to 
'uninit()'}} \
+  // ref-note {{in call to 
'uninit()'}} \
   // expected-error {{not an integral 
constant expression}} \
   // expected-note {{in call to 
'uninit()'}}
 
   static_assert(uninit(), ""); // ref-error {{not an integral 
constant expression}} \
-   // ref-note {{in call to 
'uninit()'}} \
+   // ref-note {{in call to 
'uninit()'}} \
// expected-error {{not an integral 
constant expression}} \
// expected-note {{in call to 
'uninit()'}}
 
   static_assert(uninit(), ""); // ref-error {{not an integral 
constant expression}} \
-// ref-note {{in call to 
'uninit()'}} \
+// ref-note {{in call to 
'uninit()'}} \
 // expected-error {{not an 
integral constant expression}} \
 // expected-note {{in call to 
'uninit()'}}
 
   static_assert(uninit(), ""); // ref-error {{not an integral 
constant expression}} \
- // ref-note {{in call to 
'uninit()'}} \
+ // ref-note {{in call to 
'uninit()'}} \
  // expected-error {{not an 
integral constant expression}} \
  // expected-note {{in call to 
'uninit(

[clang] bd0ed0a - [Clang][SemaCXX] Add unused warning for variables declared in condition expressions

2023-08-06 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-06T16:24:09+09:00
New Revision: bd0ed0abc31fa5a49e87eeca7aa872e7f6e4d1e7

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

LOG: [Clang][SemaCXX] Add unused warning for variables declared in condition 
expressions

This patch marks the declarations with initializations in condition expressions 
such as
if (int var = init) as unreferenced so that -Wunused can warn on them.

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

Reviewed By: cor3ntin
Differential Revision: https://reviews.llvm.org/D152495

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaCXX/warn-unused-variables.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f03e5231215eb2..8ff9a019563447 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -121,6 +121,9 @@ Improvements to Clang's diagnostics
 ---
 - Clang constexpr evaluator now prints template arguments when displaying
   template-specialization function calls.
+- Clang now warns on unused variables declared and initialized in condition
+  expressions.
+  (`#61681: `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index a24856b64ec92b..6ea3b88389735a 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1995,7 +1995,7 @@ static bool ShouldDiagnoseUnusedDecl(const LangOptions 
&LangOpts,
   return false;
   } else if (!D->getDeclName()) {
 return false;
-  } else if (D->isReferenced() || D->isUsed()) {
+  } else if (D->isReferenced() || (!isa(D) && D->isUsed())) {
 return false;
   }
 

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 423d5372a6f65a..ec7c146f08d2ea 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -4015,6 +4015,10 @@ ExprResult Sema::CheckConditionVariable(VarDecl 
*ConditionVar,
   ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
   ConditionVar->getLocation());
 
+  // Ensure that `-Wunused-variable` will be emitted for condition variables
+  // that are not referenced later. e.g.: if (int var = init());
+  ConditionVar->setReferenced(/*R=*/false);
+
   switch (CK) {
   case ConditionKind::Boolean:
 return CheckBooleanCondition(StmtLoc, Condition.get());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index f78d46f5950360..522ec12de3d368 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5352,7 +5352,7 @@ void Sema::BuildVariableInstantiation(
   // will have been deferred.
   if (!NewVar->isInvalidDecl() &&
   NewVar->getDeclContext()->isFunctionOrMethod() &&
-  OldVar->getType()->isDependentType())
+  OldVar->getType()->isDependentType() && !OldVar->isImplicit())
 DiagnoseUnusedDecl(NewVar);
 }
 

diff  --git a/clang/test/SemaCXX/warn-unused-variables.cpp 
b/clang/test/SemaCXX/warn-unused-variables.cpp
index 4db8bdf12e5de0..db33086436d3af 100644
--- a/clang/test/SemaCXX/warn-unused-variables.cpp
+++ b/clang/test/SemaCXX/warn-unused-variables.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify %s
-// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++14-extensions -Wno-c++17-extensions -verify -std=c++11 %s
 template void f() {
   T t;
   t = 17;
@@ -294,3 +294,115 @@ void RAIIWrapperTest() {
 }
 
 } // namespace gh54489
+
+namespace inside_condition {
+  void ifs() {
+if (int hoge = 0) // expected-warning {{unused variable 'hoge'}}
+  return;
+if (const int const_hoge = 0) // expected-warning {{unused variable 
'const_hoge'}}
+  return;
+else if (int fuga = 0)
+  (void)fuga;
+else if (int used = 1; int catched = used) // expected-warning {{unused 
variable 'catched'}}
+  return;
+else if (int refed = 1; int used = refed)
+  (void)used;
+else if (int unused1 = 2; int unused2 = 3) // expected-warning {{unused 
variable 'unused1'}} \
+   // expected-warning {{unused 
variable 'unused2'}}
+  return;
+else if (int unused = 4; int used = 5) // expected-warning {{unused 
variable 'unused'}}
+  (void)used;
+else if (int used = 6; int unused = 7) // expected-warn

[clang] 18b6f6e - Revert "[Clang][SemaCXX] Add unused warning for variables declared in condition expressions"

2023-08-06 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-06T17:02:01+09:00
New Revision: 18b6f6e0c7d0b492e90738d684aeb731754aeaac

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

LOG: Revert "[Clang][SemaCXX] Add unused warning for variables declared in 
condition expressions"

Broke sanitizer buildbot:
https://lab.llvm.org/buildbot/#/builders/240/builds/12947
https://lab.llvm.org/buildbot/#/builders/19/builds/18369

Reverting while I figure out the cause.

This reverts commit bd0ed0abc31fa5a49e87eeca7aa872e7f6e4d1e7.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaCXX/warn-unused-variables.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8ff9a019563447..f03e5231215eb2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -121,9 +121,6 @@ Improvements to Clang's diagnostics
 ---
 - Clang constexpr evaluator now prints template arguments when displaying
   template-specialization function calls.
-- Clang now warns on unused variables declared and initialized in condition
-  expressions.
-  (`#61681: `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 6ea3b88389735a..a24856b64ec92b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1995,7 +1995,7 @@ static bool ShouldDiagnoseUnusedDecl(const LangOptions 
&LangOpts,
   return false;
   } else if (!D->getDeclName()) {
 return false;
-  } else if (D->isReferenced() || (!isa(D) && D->isUsed())) {
+  } else if (D->isReferenced() || D->isUsed()) {
 return false;
   }
 

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index ec7c146f08d2ea..423d5372a6f65a 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -4015,10 +4015,6 @@ ExprResult Sema::CheckConditionVariable(VarDecl 
*ConditionVar,
   ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
   ConditionVar->getLocation());
 
-  // Ensure that `-Wunused-variable` will be emitted for condition variables
-  // that are not referenced later. e.g.: if (int var = init());
-  ConditionVar->setReferenced(/*R=*/false);
-
   switch (CK) {
   case ConditionKind::Boolean:
 return CheckBooleanCondition(StmtLoc, Condition.get());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 522ec12de3d368..f78d46f5950360 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5352,7 +5352,7 @@ void Sema::BuildVariableInstantiation(
   // will have been deferred.
   if (!NewVar->isInvalidDecl() &&
   NewVar->getDeclContext()->isFunctionOrMethod() &&
-  OldVar->getType()->isDependentType() && !OldVar->isImplicit())
+  OldVar->getType()->isDependentType())
 DiagnoseUnusedDecl(NewVar);
 }
 

diff  --git a/clang/test/SemaCXX/warn-unused-variables.cpp 
b/clang/test/SemaCXX/warn-unused-variables.cpp
index db33086436d3af..4db8bdf12e5de0 100644
--- a/clang/test/SemaCXX/warn-unused-variables.cpp
+++ b/clang/test/SemaCXX/warn-unused-variables.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify %s
-// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++14-extensions -Wno-c++17-extensions -verify -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=c++11 %s
 template void f() {
   T t;
   t = 17;
@@ -294,115 +294,3 @@ void RAIIWrapperTest() {
 }
 
 } // namespace gh54489
-
-namespace inside_condition {
-  void ifs() {
-if (int hoge = 0) // expected-warning {{unused variable 'hoge'}}
-  return;
-if (const int const_hoge = 0) // expected-warning {{unused variable 
'const_hoge'}}
-  return;
-else if (int fuga = 0)
-  (void)fuga;
-else if (int used = 1; int catched = used) // expected-warning {{unused 
variable 'catched'}}
-  return;
-else if (int refed = 1; int used = refed)
-  (void)used;
-else if (int unused1 = 2; int unused2 = 3) // expected-warning {{unused 
variable 'unused1'}} \
-   // expected-warning {{unused 
variable 'unused2'}}
-  return;
-else if (int unused = 4; int used = 5) // expected-warning {{unused 
variable 'unused'}}
-  (void)used;
-else if (int used = 6; int unused = 7) // expected-warning {{unused 
variable 'unused'}}
-  (

[clang] 24c91d4 - [clang][ExprConstant] Fix crash on uninitialized base class subobject

2023-08-07 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-08T15:53:17+09:00
New Revision: 24c91d443222bdb20205630d300ae61bfa07067e

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

LOG: [clang][ExprConstant] Fix crash on uninitialized base class subobject

This patch fixes the reported regression caused by D146358 through adding notes 
about an uninitialized base class when we diagnose uninitialized constructor.

This also changes the wording from the old one in order to make it clear that 
the uninitialized subobject is a base class and its constructor is not called.
Wording changes:
BEFORE: `subobject of type 'Base' is not initialized`
AFTER: `constructor of base class 'Base' is not called`

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

Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D153969

Added: 
clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
clang/test/SemaCXX/constexpr-subobj-initialization.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticASTKinds.td
clang/lib/AST/ExprConstant.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 44f6ad807daf8f..babade1c70b067 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -121,6 +121,8 @@ Improvements to Clang's diagnostics
 ---
 - Clang constexpr evaluator now prints template arguments when displaying
   template-specialization function calls.
+- Clang contexpr evaluator now displays notes as well as an error when a 
constructor
+  of a base class is not called in the constructor of its derived class.
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index f73a289f80ca95..d2656310e79c9b 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -70,6 +70,8 @@ def note_consteval_address_accessible : Note<
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
   "subobject %0 is not initialized">;
+def note_constexpr_uninitialized_base : Note<
+  "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
   "control flows through the definition of a %select{static|thread_local}0 
variable">;
 def note_constexpr_subobject_declared_here : Note<

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 361e8efe4cdf33..7d6796dd9d3598 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2450,9 +2450,16 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
 if (const CXXRecordDecl *CD = dyn_cast(RD)) {
   unsigned BaseIndex = 0;
   for (const CXXBaseSpecifier &BS : CD->bases()) {
-if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
-   Value.getStructBase(BaseIndex), Kind,
-   /*SubobjectDecl=*/nullptr, CheckedTemps))
+const APValue &BaseValue = Value.getStructBase(BaseIndex);
+if (!BaseValue.hasValue()) {
+  SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
+  Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
+  << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
+  return false;
+}
+if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 
BaseValue,
+   Kind, /*SubobjectDecl=*/nullptr,
+   CheckedTemps))
   return false;
 ++BaseIndex;
   }

diff  --git a/clang/test/Misc/constexpr-subobj-init-source-ranges.cpp 
b/clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
new file mode 100644
index 00..342da2d8866687
--- /dev/null
+++ b/clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
@@ -0,0 +1,11 @@
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 
2>&1 | FileCheck %s --strict-whitespace
+
+struct DelBase {
+  constexpr DelBase() = delete;
+};
+
+// CHECK:  :{[[@LINE+1]]:21-[[@LINE+1]]:28}
+struct Foo : public DelBase {
+  constexpr Foo() {};
+};
+constexpr Foo f;

diff  --git a/clang/test/SemaCXX/constexpr-subobj-initialization.cpp 
b/clang/test/SemaCXX/constexpr-subobj-initialization.cpp
new file mode 100644
index 00..cd096a92709378
--- /dev/null
+++ b/clang/test/SemaCXX/constexpr-subobj-initialization.cpp
@@ -0,0 +1,58 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+namespace baseclass_uninit {
+struct DelBase {
+  constexpr DelBase() = delete; // expected-note {{'DelBase' has been 
explicitly marked deleted here}}
+};
+
+stru

[clang] 615d812 - [clang][ExprConstant] Improve error message of compound assignment against uninitialized object

2023-08-25 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-25T16:08:07+09:00
New Revision: 615d812696ee8827d6d78ad106d6022ff2778137

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

LOG: [clang][ExprConstant] Improve error message of compound assignment against 
uninitialized object

BEFORE this patch, compound assignment operator against uninitialized object 
such as uninit += 1 was diagnosed as subexpression not valid
This patch clarifies the reason for the error by saying that uninit is an 
uninitialized object.

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

Reviewed By: shafik, tbaeder
Differential Revision: https://reviews.llvm.org/D157855

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/constant-expression-cxx14.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a7c39bad615406..f0e601fc2df88b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -140,6 +140,9 @@ Improvements to Clang's diagnostics
   tautologies like ``x && !x`` and ``!x || x`` in expressions. This also
   makes ``-Winfinite-recursion`` diagnose more cases.
   (`#56035: `_).
+- Clang constexpr evaluator now diagnoses compound assignment operators against
+  uninitialized variables as a read of uninitialized object.
+  (`#51536 _`)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 51fdef708dde5a..d77c5d3f84a8d7 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4442,6 +4442,10 @@ struct CompoundAssignSubobjectHandler {
   return foundPointer(Subobj, SubobjType);
 case APValue::Vector:
   return foundVector(Subobj, SubobjType);
+case APValue::Indeterminate:
+  Info.FFDiag(E, diag::note_constexpr_access_uninit)
+  << /*read of=*/0 << /*uninitialized object=*/1;
+  return false;
 default:
   // FIXME: can this happen?
   Info.FFDiag(E);

diff  --git a/clang/test/SemaCXX/constant-expression-cxx14.cpp 
b/clang/test/SemaCXX/constant-expression-cxx14.cpp
index a43ee74e3df56c..273d7ff3a208e2 100644
--- a/clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1275,3 +1275,33 @@ namespace TemporaryWithBadPointer {
 (dbt2.wp = nullptr, 0)
   };
 }
+
+namespace UninitCompoundAssign {
+constexpr int scalar(int a) {
+  int sum; // cxx14-warning {{uninitialized variable in a constexpr function 
is a C++20 extension}}
+  sum += a; // expected-note {{read of uninitialized object}};
+  return 0;
+}
+static_assert(scalar(3), ""); // expected-error {{constant expression}} \
+  // expected-note {{in call to 'scalar(3)'}}
+
+constexpr int array(int a) {
+  int arr[3]; // cxx14-warning {{uninitialized variable in a constexpr 
function is a C++20 extension}}
+  arr[1] += a; // expected-note {{read of uninitialized object}};
+  return 0;
+}
+static_assert(array(3), ""); // expected-error {{constant expression}} \
+ // expected-note {{in call to 'array(3)'}}
+
+struct Foo {
+  int val; // cxx14-note{{member not initialized by constructor}}
+  constexpr Foo() {} // cxx14-warning {{constexpr constructor that does not 
initialize all members is a C++20 extension}}
+};
+constexpr int field(int a) {
+  Foo f;
+  f.val += a; // expected-note {{read of uninitialized object}};
+  return 0;
+}
+static_assert(field(3), ""); // expected-error {{constant expression}} \
+ // expected-note {{in call to 'field(3)'}}
+}



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


[clang] 0c9c9dd - [clang][Sema] Add truncation warning on fortified snprintf

2023-08-25 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-26T14:41:05+09:00
New Revision: 0c9c9dd9a24f9d715d950fef0ac7aae01437af96

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

LOG: [clang][Sema] Add truncation warning on fortified snprintf

This patch warns on snprintf calls whose n argument is known to be smaller than 
the size of the formatted string like

```
char buf[5];
snprintf(buf, 5, "Hello");
```
This is a counterpart of gcc's Wformat-truncation
Fixes https://github.com/llvm/llvm-project/issues/64871

Reviewed By: aaron.ballman, nickdesaulniers
Differential Revision: https://reviews.llvm.org/D158562

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp
clang/test/Analysis/taint-generic.c
clang/test/Sema/format-strings.c
clang/test/Sema/warn-fortify-source.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0fff49c2c5108a..1ba4215e603349 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -150,6 +150,11 @@ Improvements to Clang's diagnostics
 - Clang constexpr evaluator now diagnoses compound assignment operators against
   uninitialized variables as a read of uninitialized object.
   (`#51536 _`)
+- Clang's ``-Wfortify-source`` now diagnoses ``snprintf`` call that is known to
+  result in string truncation.
+  (`#64871: `_).
+  Also clang no longer emits false positive warnings about the output length of
+  ``%g`` format specifier.
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index cf6f422ee47167..7f0cfb29cddeac 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -857,6 +857,11 @@ def warn_fortify_source_format_overflow : Warning<
   " but format string expands to at least %2">,
   InGroup;
 
+def warn_fortify_source_format_truncation: Warning<
+  "'%0' will always be truncated; specified size is %1,"
+  " but format string expands to at least %2">,
+  InGroup;
+
 def warn_fortify_scanf_overflow : Warning<
   "'%0' may overflow; destination buffer in argument %1 has size "
   "%2, but the corresponding specifier may require size %3">,

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index e3b4d151536528..c78a6b9c510767 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -888,9 +888,12 @@ class EstimateSizeFormatHandler
   break;
 
 // %g style conversion switches between %f or %e style dynamically.
-// %f always takes less space, so default to it.
+// %g removes trailing zeros, and does not print decimal point if there are
+// no digits that follow it. Thus %g can print a single digit.
 case analyze_format_string::ConversionSpecifier::gArg:
 case analyze_format_string::ConversionSpecifier::GArg:
+  Size += 1;
+  break;
 
 // Floating point number in the form '[+]ddd.ddd'.
 case analyze_format_string::ConversionSpecifier::fArg:
@@ -1032,6 +1035,23 @@ class EstimateSizeFormatHandler
 
 } // namespace
 
+static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
+   StringRef &FormatStrRef, size_t &StrLen,
+   ASTContext &Context) {
+  if (const auto *Format = dyn_cast(FormatExpr);
+  Format && (Format->isOrdinary() || Format->isUTF8())) {
+FormatStrRef = Format->getString();
+const ConstantArrayType *T =
+Context.getAsConstantArrayType(Format->getType());
+assert(T && "String literal not of constant array type!");
+size_t TypeSize = T->getSize().getZExtValue();
+// In case there's a null byte somewhere.
+StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
+return true;
+  }
+  return false;
+}
+
 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
CallExpr *TheCall) {
   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
@@ -1183,11 +1203,9 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 const auto *FormatExpr =
 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
 
-const auto *Format = dyn_cast(FormatExpr);
-if (!Format)
-  return;
-
-if (!Format->isOrdinary() && !Format->isUTF8())
+StringRef FormatStrRef;
+size_t StrLen;
+if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
   return;
 
 auto Diagnose = [&](unsigned Ar

[clang] 01b88dd - [NFC] Remove unused variables declared in conditions

2023-08-29 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-30T10:05:06+09:00
New Revision: 01b88dd66d9d52d3f531a7d490e18c549f36f445

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

LOG: [NFC] Remove unused variables declared in conditions

D152495 makes clang warn on unused variables that are declared in conditions 
like `if (int var = init) {}`
This patch is an NFC fix to suppress the new warning in llvm,clang,lld builds 
to pass CI in the above patch.

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

Added: 


Modified: 
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/AST/Interp/ByteCodeStmtGen.cpp
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Driver/ToolChains/Cuda.cpp
clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
clang/lib/StaticAnalyzer/Checkers/Yaml.h
clang/tools/clang-scan-deps/ClangScanDeps.cpp
lld/MachO/Driver.cpp
llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp
llvm/lib/IR/PrintPasses.cpp
llvm/lib/Passes/StandardInstrumentations.cpp
llvm/lib/Support/VirtualFileSystem.cpp
llvm/tools/llvm-profgen/ProfiledBinary.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index bdc9a5624ce3af..c1ffe1a2dd3ed5 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -3928,7 +3928,7 @@ AST_MATCHER_P(CallExpr, callee, internal::Matcher,
 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
 callee, AST_POLYMORPHIC_SUPPORTED_TYPES(ObjCMessageExpr, CallExpr),
 internal::Matcher, InnerMatcher, 1) {
-  if (const auto *CallNode = dyn_cast(&Node))
+  if (isa(&Node))
 return callExpr(hasDeclaration(InnerMatcher))
 .matches(Node, Finder, Builder);
   else {

diff  --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp 
b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
index f048b2c218a4ca..b7553d8963ff0e 100644
--- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -341,7 +341,7 @@ bool ByteCodeStmtGen::visitIfStmt(const IfStmt 
*IS) {
 return IS->getElse() ? visitStmt(IS->getElse()) : true;
 
   if (auto *CondInit = IS->getInit())
-if (!visitStmt(IS->getInit()))
+if (!visitStmt(CondInit))
   return false;
 
   if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt())

diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 3e8b2b78a3928b..79b23a85040970 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -1353,7 +1353,7 @@ void clang::EmbedObject(llvm::Module *M, const 
CodeGenOptions &CGOpts,
   for (StringRef OffloadObject : CGOpts.OffloadObjects) {
 llvm::ErrorOr> ObjectOrErr =
 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
-if (std::error_code EC = ObjectOrErr.getError()) {
+if (ObjectOrErr.getError()) {
   auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   "could not open '%0' for embedding");
   Diags.Report(DiagID) << OffloadObject;

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index ac04b838602345..336cb04b9ad2be 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1557,7 +1557,7 @@ static llvm::TargetRegionEntryInfo 
getEntryInfoFromPresumedLoc(
 PresumedLoc PLoc = SM.getPresumedLoc(BeginLoc);
 
 llvm::sys::fs::UniqueID ID;
-if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
+if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
   PLoc = SM.getPresumedLoc(BeginLoc, /*UseLineDirectives=*/false);
 }
 

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 4f3cdb00f1cc18..21e1363b613e0e 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -7423,7 +7423,7 @@ void 
CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
 
 // Get the UniqueID for the file containing the decl.
 llvm::sys::fs::UniqueID ID;
-if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
+if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
   PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
   assert(PLoc.isValid() && "Source location is expected to be valid.");
   if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))

diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 47187f554db29d..97472a302715

[clang] 92023b1 - Reland "[Clang][SemaCXX] Add unused warning for variables declared in condition expressions"

2023-08-29 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-08-30T10:05:10+09:00
New Revision: 92023b15099012a657da07ebf49dd7d94a260f84

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

LOG: Reland "[Clang][SemaCXX] Add unused warning for variables declared in 
condition expressions"

This patch marks the declarations with initializations in condition expressions 
such as
if (int var = init) as unused and unreferenced so that -Wunused can warn on 
them.

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

Reviewed By: cor3ntin
Differential Revision: https://reviews.llvm.org/D152495

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaCXX/warn-unused-variables.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index dc7569cf79f43e..262bebfc0bde9b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -156,6 +156,9 @@ Improvements to Clang's diagnostics
   (`#64871: `_).
   Also clang no longer emits false positive warnings about the output length of
   ``%g`` format specifier.
+- Clang now warns on unused variables declared and initialized in condition
+  expressions.
+  (`#61681: `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 2ee216fffaa275..9facf2187f76a5 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1995,7 +1995,7 @@ static bool ShouldDiagnoseUnusedDecl(const LangOptions 
&LangOpts,
   return false;
   } else if (!D->getDeclName()) {
 return false;
-  } else if (D->isReferenced() || D->isUsed()) {
+  } else if (D->isReferenced() || (!isa(D) && D->isUsed())) {
 return false;
   }
 

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index a6e0a8abf81b9a..a9096af70fce4e 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -4013,6 +4013,10 @@ ExprResult Sema::CheckConditionVariable(VarDecl 
*ConditionVar,
   ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
   ConditionVar->getLocation());
 
+  // Ensure that `-Wunused-variable` will be emitted for condition variables
+  // that are not referenced later. e.g.: if (int var = init());
+  ConditionVar->setReferenced(/*R=*/false);
+
   switch (CK) {
   case ConditionKind::Boolean:
 return CheckBooleanCondition(StmtLoc, Condition.get());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 63f022d5c2ff09..bb8ea187ecf91c 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5353,7 +5353,7 @@ void Sema::BuildVariableInstantiation(
   // will have been deferred.
   if (!NewVar->isInvalidDecl() &&
   NewVar->getDeclContext()->isFunctionOrMethod() &&
-  OldVar->getType()->isDependentType())
+  OldVar->getType()->isDependentType() && !OldVar->isImplicit())
 DiagnoseUnusedDecl(NewVar);
 }
 

diff  --git a/clang/test/SemaCXX/warn-unused-variables.cpp 
b/clang/test/SemaCXX/warn-unused-variables.cpp
index 4db8bdf12e5de0..db33086436d3af 100644
--- a/clang/test/SemaCXX/warn-unused-variables.cpp
+++ b/clang/test/SemaCXX/warn-unused-variables.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify %s
-// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++14-extensions -Wno-c++17-extensions -verify -std=c++11 %s
 template void f() {
   T t;
   t = 17;
@@ -294,3 +294,115 @@ void RAIIWrapperTest() {
 }
 
 } // namespace gh54489
+
+namespace inside_condition {
+  void ifs() {
+if (int hoge = 0) // expected-warning {{unused variable 'hoge'}}
+  return;
+if (const int const_hoge = 0) // expected-warning {{unused variable 
'const_hoge'}}
+  return;
+else if (int fuga = 0)
+  (void)fuga;
+else if (int used = 1; int catched = used) // expected-warning {{unused 
variable 'catched'}}
+  return;
+else if (int refed = 1; int used = refed)
+  (void)used;
+else if (int unused1 = 2; int unused2 = 3) // expected-warning {{unused 
variable 'unused1'}} \
+   // expected-warning {{unused 
variable 'unused2'}}
+  return;
+else if (int unused = 4; int used = 5) // expected-warning {{unused 
variable 'unused'}}
+  (void)used;
+else if (in

[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-03 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-03 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-03 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-03 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet created 
https://github.com/llvm/llvm-project/pull/65238:

When the caret location is lower than the lowest source range, clang is 
printing wrong line numbers. The first line number should consider caret 
location line even when there are source ranges provided.

Current wrong line example: https://godbolt.org/z/aj4qEjzs4

>From 2bc13f3b013a4bda4364e9c29bc792ca6a0c7cf1 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 4 Sep 2023 10:46:17 +0900
Subject: [PATCH] [clang][Diagnostics] Fix wrong line number display

When the caret location is lower than the lowest source range, clang is 
printing wrong line numbers.
The first line number should consider caret location line even when there are 
source ranges provided.

Current wrong line example: https://godbolt.org/z/aj4qEjzs4
---
 clang/lib/Frontend/TextDiagnostic.cpp |  3 +--
 clang/test/Misc/diag-style.cpp| 17 +
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 3a3cc246d3afc2..1b58261b22a265 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1160,8 +1160,7 @@ void TextDiagnostic::emitSnippetAndCaret(
   // Find the set of lines to include.
   const unsigned MaxLines = DiagOpts->SnippetLineLimit;
   std::pair Lines = {CaretLineNo, CaretLineNo};
-  unsigned DisplayLineNo =
-  Ranges.empty() ? Loc.getPresumedLoc().getLine() : ~0u;
+  unsigned DisplayLineNo = Loc.getPresumedLoc().getLine();
   for (const auto &I : Ranges) {
 if (auto OptionalRange = findLinesForRange(I, FID, SM))
   Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
diff --git a/clang/test/Misc/diag-style.cpp b/clang/test/Misc/diag-style.cpp
index 3b24df974730a8..967b51a07b6a65 100644
--- a/clang/test/Misc/diag-style.cpp
+++ b/clang/test/Misc/diag-style.cpp
@@ -24,3 +24,20 @@ void f(int x) {
 // CHECK-NEXT: {{^}}  |
 // CHECK-NEXT: {{^}}  |
 // CHECK-NEXT: {{^}}   12 |
+
+#line 10
+int func(
+  int a, int b,
+  int&
+  r);
+
+void test() {
+  func(3, 4, 5);
+}
+// CHECK: 10:5: note: candidate function not viable
+// CHECK-NEXT: {{^}}   10 |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}   11 |
+// CHECK-NEXT: {{^}}   12 |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}   13 |

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-03 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-03 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-03 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-03 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

When the `Loc` is higher than the lowest begin source location, `DisplayLineNo` 
still points to the lowest begin location line because we have
```c++
  DisplayLineNo =
std::min(DisplayLineNo, SM.getPresumedLineNumber(I.getBegin()));
```
in L1169, correct?
This does not break the test added in the commit at least locally.

I don't think we need to ignore `Loc.getPresumedLoc().getLine()` when `Ranges` 
is not empty.

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-04 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

> Ouch the inability to comment outside of modified code is going to be painful.
> 
> The changed code being
> 
> ```c++
>   unsigned DisplayLineNo = Loc.getPresumedLoc().getLine();
>   for (const auto &I : Ranges) {
>   DisplayLineNo = 
> std::min(DisplayLineNo, SM.getPresumedLineNumber(I.getBegin()));
>   }
> ```
> 
> If the range starts before `DisplayLineNo`, it still works. Am I missing 
> something?

Thanks, that's my point.

When I provided an invalid source location, the diagnostics looked like the 
following. Filename, line/column number and code snippet are not printed.
```
source:7:3: error: no matching function for call to 'func'
7 |   func(3, 4, 5);
  |   ^~~~
note: candidate function not viable: expects an lvalue for 3rd argument
1 error generated.
```
When `Loc` is invalid, calling `Loc.getPresumedLoc().getLine()` should cause 
validness assertion failure in `PresumedLoc::getLine`, so invalid `Loc` seems 
to be handled elsewhere.

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-04 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-04 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet created 
https://github.com/llvm/llvm-project/pull/65248:

Loss of `__unaligned` qualifier does not invalidate overload candidates.
This fixes a regression reported in https://reviews.llvm.org/D153690

>From eee4c3aee9350be51c9333f284810ffebd9d1663 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 4 Sep 2023 16:23:00 +0900
Subject: [PATCH] [clang][MSExtentions] Fix invalid overload failure about the
 loss of `__unaligned` qualifier

Loss of `__unaligned` qualifier does not invalidate overload
candidates.
This fixes a regression reported in https://reviews.llvm.org/D153690
---
 clang/lib/Sema/SemaOverload.cpp|  8 +---
 clang/test/SemaCXX/MicrosoftExtensions.cpp | 11 +++
 2 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 5d0299dfa752f92..9833d0d312186b6 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -5557,9 +5557,11 @@ TryObjectArgumentInitialization(Sema &S, SourceLocation 
Loc, QualType FromType,
 
   // First check the qualifiers.
   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
-  if (ImplicitParamType.getCVRQualifiers()
-!= FromTypeCanon.getLocalCVRQualifiers() &&
-  !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
+  // MSVC ignores __unaligned qualifier for overload candidates; do the same.
+  if (ImplicitParamType.getCVRQualifiers() !=
+  FromTypeCanon.getLocalCVRQualifiers() &&
+  !ImplicitParamType.isAtLeastAsQualifiedAs(
+  withoutUnaligned(S.Context, FromTypeCanon))) {
 ICS.setBad(BadConversionSequence::bad_qualifiers,
FromType, ImplicitParamType);
 return ICS;
diff --git a/clang/test/SemaCXX/MicrosoftExtensions.cpp 
b/clang/test/SemaCXX/MicrosoftExtensions.cpp
index 960030d44f0c155..71618048014cc74 100644
--- a/clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -589,6 +589,17 @@ namespace PR42089 {
   __attribute__((nothrow)) void S::Bar(){}
 }
 
+namespace UnalignedConv {
+struct S {
+  bool operator==(int) const;
+};
+
+int func() {
+  S __unaligned s;
+  return s == 42;
+}
+}
+
 #elif TEST2
 
 // Check that __unaligned is not recognized if MS extensions are not enabled

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-04 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-04 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-04 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-04 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-04 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65238:

>From 2bc13f3b013a4bda4364e9c29bc792ca6a0c7cf1 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 4 Sep 2023 10:46:17 +0900
Subject: [PATCH 1/2] [clang][Diagnostics] Fix wrong line number display

When the caret location is lower than the lowest source range, clang is 
printing wrong line numbers.
The first line number should consider caret location line even when there are 
source ranges provided.

Current wrong line example: https://godbolt.org/z/aj4qEjzs4
---
 clang/lib/Frontend/TextDiagnostic.cpp |  3 +--
 clang/test/Misc/diag-style.cpp| 17 +
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 3a3cc246d3afc2a..1b58261b22a2653 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1160,8 +1160,7 @@ void TextDiagnostic::emitSnippetAndCaret(
   // Find the set of lines to include.
   const unsigned MaxLines = DiagOpts->SnippetLineLimit;
   std::pair Lines = {CaretLineNo, CaretLineNo};
-  unsigned DisplayLineNo =
-  Ranges.empty() ? Loc.getPresumedLoc().getLine() : ~0u;
+  unsigned DisplayLineNo = Loc.getPresumedLoc().getLine();
   for (const auto &I : Ranges) {
 if (auto OptionalRange = findLinesForRange(I, FID, SM))
   Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
diff --git a/clang/test/Misc/diag-style.cpp b/clang/test/Misc/diag-style.cpp
index 3b24df974730a80..967b51a07b6a65d 100644
--- a/clang/test/Misc/diag-style.cpp
+++ b/clang/test/Misc/diag-style.cpp
@@ -24,3 +24,20 @@ void f(int x) {
 // CHECK-NEXT: {{^}}  |
 // CHECK-NEXT: {{^}}  |
 // CHECK-NEXT: {{^}}   12 |
+
+#line 10
+int func(
+  int a, int b,
+  int&
+  r);
+
+void test() {
+  func(3, 4, 5);
+}
+// CHECK: 10:5: note: candidate function not viable
+// CHECK-NEXT: {{^}}   10 |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}   11 |
+// CHECK-NEXT: {{^}}   12 |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}   13 |

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-04 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65238:

>From 2bc13f3b013a4bda4364e9c29bc792ca6a0c7cf1 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 4 Sep 2023 10:46:17 +0900
Subject: [PATCH 1/3] [clang][Diagnostics] Fix wrong line number display

When the caret location is lower than the lowest source range, clang is 
printing wrong line numbers.
The first line number should consider caret location line even when there are 
source ranges provided.

Current wrong line example: https://godbolt.org/z/aj4qEjzs4
---
 clang/lib/Frontend/TextDiagnostic.cpp |  3 +--
 clang/test/Misc/diag-style.cpp| 17 +
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Frontend/TextDiagnostic.cpp 
b/clang/lib/Frontend/TextDiagnostic.cpp
index 3a3cc246d3afc2a..1b58261b22a2653 100644
--- a/clang/lib/Frontend/TextDiagnostic.cpp
+++ b/clang/lib/Frontend/TextDiagnostic.cpp
@@ -1160,8 +1160,7 @@ void TextDiagnostic::emitSnippetAndCaret(
   // Find the set of lines to include.
   const unsigned MaxLines = DiagOpts->SnippetLineLimit;
   std::pair Lines = {CaretLineNo, CaretLineNo};
-  unsigned DisplayLineNo =
-  Ranges.empty() ? Loc.getPresumedLoc().getLine() : ~0u;
+  unsigned DisplayLineNo = Loc.getPresumedLoc().getLine();
   for (const auto &I : Ranges) {
 if (auto OptionalRange = findLinesForRange(I, FID, SM))
   Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
diff --git a/clang/test/Misc/diag-style.cpp b/clang/test/Misc/diag-style.cpp
index 3b24df974730a80..967b51a07b6a65d 100644
--- a/clang/test/Misc/diag-style.cpp
+++ b/clang/test/Misc/diag-style.cpp
@@ -24,3 +24,20 @@ void f(int x) {
 // CHECK-NEXT: {{^}}  |
 // CHECK-NEXT: {{^}}  |
 // CHECK-NEXT: {{^}}   12 |
+
+#line 10
+int func(
+  int a, int b,
+  int&
+  r);
+
+void test() {
+  func(3, 4, 5);
+}
+// CHECK: 10:5: note: candidate function not viable
+// CHECK-NEXT: {{^}}   10 |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}   11 |
+// CHECK-NEXT: {{^}}   12 |
+// CHECK-NEXT: {{^}}  |
+// CHECK-NEXT: {{^}}   13 |

>From 426980354ef97e7ef8e7cf5cbfd47fc790c515ad Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Tue, 5 Sep 2023 01:05:42 +0900
Subject: [PATCH 3/3] Try non-empty commit to trigger CI build/test

---
 clang/test/Misc/diag-style.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/test/Misc/diag-style.cpp b/clang/test/Misc/diag-style.cpp
index 967b51a07b6a65d..626edef9b7e6149 100644
--- a/clang/test/Misc/diag-style.cpp
+++ b/clang/test/Misc/diag-style.cpp
@@ -41,3 +41,5 @@ void test() {
 // CHECK-NEXT: {{^}}   12 |
 // CHECK-NEXT: {{^}}  |
 // CHECK-NEXT: {{^}}   13 |
+// CHECK-NEXT: {{^}}  |
+

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-04 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65248:

>From eee4c3aee9350be51c9333f284810ffebd9d1663 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 4 Sep 2023 16:23:00 +0900
Subject: [PATCH 1/2] [clang][MSExtentions] Fix invalid overload failure about
 the loss of `__unaligned` qualifier

Loss of `__unaligned` qualifier does not invalidate overload
candidates.
This fixes a regression reported in https://reviews.llvm.org/D153690
---
 clang/lib/Sema/SemaOverload.cpp|  8 +---
 clang/test/SemaCXX/MicrosoftExtensions.cpp | 11 +++
 2 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 5d0299dfa752f92..9833d0d312186b6 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -5557,9 +5557,11 @@ TryObjectArgumentInitialization(Sema &S, SourceLocation 
Loc, QualType FromType,
 
   // First check the qualifiers.
   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
-  if (ImplicitParamType.getCVRQualifiers()
-!= FromTypeCanon.getLocalCVRQualifiers() &&
-  !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
+  // MSVC ignores __unaligned qualifier for overload candidates; do the same.
+  if (ImplicitParamType.getCVRQualifiers() !=
+  FromTypeCanon.getLocalCVRQualifiers() &&
+  !ImplicitParamType.isAtLeastAsQualifiedAs(
+  withoutUnaligned(S.Context, FromTypeCanon))) {
 ICS.setBad(BadConversionSequence::bad_qualifiers,
FromType, ImplicitParamType);
 return ICS;
diff --git a/clang/test/SemaCXX/MicrosoftExtensions.cpp 
b/clang/test/SemaCXX/MicrosoftExtensions.cpp
index 960030d44f0c155..71618048014cc74 100644
--- a/clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -589,6 +589,17 @@ namespace PR42089 {
   __attribute__((nothrow)) void S::Bar(){}
 }
 
+namespace UnalignedConv {
+struct S {
+  bool operator==(int) const;
+};
+
+int func() {
+  S __unaligned s;
+  return s == 42;
+}
+}
+
 #elif TEST2
 
 // Check that __unaligned is not recognized if MS extensions are not enabled

>From d76263dacae363fe8b82e40babada9fa50a1f830 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Tue, 5 Sep 2023 01:09:47 +0900
Subject: [PATCH 2/2] Dummy commit to trigger CI build/test

---
 clang/test/SemaCXX/MicrosoftExtensions.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/test/SemaCXX/MicrosoftExtensions.cpp 
b/clang/test/SemaCXX/MicrosoftExtensions.cpp
index 71618048014cc74..7286217b1644f3e 100644
--- a/clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -600,6 +600,7 @@ int func() {
 }
 }
 
+
 #elif TEST2
 
 // Check that __unaligned is not recognized if MS extensions are not enabled

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


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

2023-09-04 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

FWIW, an empty commit didn't trigger CI correctly yesterday, so pushing a 
non-empty commit might fix the CI issue.

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-04 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65248:

>From eee4c3aee9350be51c9333f284810ffebd9d1663 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 4 Sep 2023 16:23:00 +0900
Subject: [PATCH 1/3] [clang][MSExtentions] Fix invalid overload failure about
 the loss of `__unaligned` qualifier

Loss of `__unaligned` qualifier does not invalidate overload
candidates.
This fixes a regression reported in https://reviews.llvm.org/D153690
---
 clang/lib/Sema/SemaOverload.cpp|  8 +---
 clang/test/SemaCXX/MicrosoftExtensions.cpp | 11 +++
 2 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 5d0299dfa752f9..9833d0d312186b 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -5557,9 +5557,11 @@ TryObjectArgumentInitialization(Sema &S, SourceLocation 
Loc, QualType FromType,
 
   // First check the qualifiers.
   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
-  if (ImplicitParamType.getCVRQualifiers()
-!= FromTypeCanon.getLocalCVRQualifiers() &&
-  !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
+  // MSVC ignores __unaligned qualifier for overload candidates; do the same.
+  if (ImplicitParamType.getCVRQualifiers() !=
+  FromTypeCanon.getLocalCVRQualifiers() &&
+  !ImplicitParamType.isAtLeastAsQualifiedAs(
+  withoutUnaligned(S.Context, FromTypeCanon))) {
 ICS.setBad(BadConversionSequence::bad_qualifiers,
FromType, ImplicitParamType);
 return ICS;
diff --git a/clang/test/SemaCXX/MicrosoftExtensions.cpp 
b/clang/test/SemaCXX/MicrosoftExtensions.cpp
index 960030d44f0c15..71618048014cc7 100644
--- a/clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -589,6 +589,17 @@ namespace PR42089 {
   __attribute__((nothrow)) void S::Bar(){}
 }
 
+namespace UnalignedConv {
+struct S {
+  bool operator==(int) const;
+};
+
+int func() {
+  S __unaligned s;
+  return s == 42;
+}
+}
+
 #elif TEST2
 
 // Check that __unaligned is not recognized if MS extensions are not enabled

>From d76263dacae363fe8b82e40babada9fa50a1f830 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Tue, 5 Sep 2023 01:09:47 +0900
Subject: [PATCH 2/3] Dummy commit to trigger CI build/test

---
 clang/test/SemaCXX/MicrosoftExtensions.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/test/SemaCXX/MicrosoftExtensions.cpp 
b/clang/test/SemaCXX/MicrosoftExtensions.cpp
index 71618048014cc7..7286217b1644f3 100644
--- a/clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -600,6 +600,7 @@ int func() {
 }
 }
 
+
 #elif TEST2
 
 // Check that __unaligned is not recognized if MS extensions are not enabled

>From 4f184b9b6f2f2e236fea2c7d8e358cd4779ea1ed Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Tue, 5 Sep 2023 11:32:28 +0900
Subject: [PATCH 3/3] Add release note

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c6d2c3466a0962..dbb719eb338dc6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -211,6 +211,8 @@ Bug Fixes in This Version
 - Clang now reports ``-Wformat`` for bool value and char specifier confusion
   in scanf. Fixes
   (`#64987 `_)
+- Clang no longer considers the loss of ``__unaligned`` qualifier from objects 
as
+  an invalid conversion during method function overload resolution.
 
 Bug Fixes to Compiler Builtins
 ^^

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


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

2023-09-04 Thread Takuya Shimizu via cfe-commits

hazohelet wrote:

Adding an irrelevant new line in a modified test file would suffice to trigger 
the CI build.
Force-pushing doesn't seem to be desirable during code review.

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


[clang] [clang][Diagnostics] Fix wrong line number display (PR #65238)

2023-09-04 Thread Takuya Shimizu via cfe-commits

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


[clang] [clang][MSExtentions] Fix invalid overload failure about the loss of `__unaligned` qualifier (PR #65248)

2023-09-07 Thread Takuya Shimizu via cfe-commits

https://github.com/hazohelet updated 
https://github.com/llvm/llvm-project/pull/65248:

>From eee4c3aee9350be51c9333f284810ffebd9d1663 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Mon, 4 Sep 2023 16:23:00 +0900
Subject: [PATCH 1/3] [clang][MSExtentions] Fix invalid overload failure about
 the loss of `__unaligned` qualifier

Loss of `__unaligned` qualifier does not invalidate overload
candidates.
This fixes a regression reported in https://reviews.llvm.org/D153690
---
 clang/lib/Sema/SemaOverload.cpp|  8 +---
 clang/test/SemaCXX/MicrosoftExtensions.cpp | 11 +++
 2 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 5d0299dfa752f92..9833d0d312186b6 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -5557,9 +5557,11 @@ TryObjectArgumentInitialization(Sema &S, SourceLocation 
Loc, QualType FromType,
 
   // First check the qualifiers.
   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
-  if (ImplicitParamType.getCVRQualifiers()
-!= FromTypeCanon.getLocalCVRQualifiers() &&
-  !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
+  // MSVC ignores __unaligned qualifier for overload candidates; do the same.
+  if (ImplicitParamType.getCVRQualifiers() !=
+  FromTypeCanon.getLocalCVRQualifiers() &&
+  !ImplicitParamType.isAtLeastAsQualifiedAs(
+  withoutUnaligned(S.Context, FromTypeCanon))) {
 ICS.setBad(BadConversionSequence::bad_qualifiers,
FromType, ImplicitParamType);
 return ICS;
diff --git a/clang/test/SemaCXX/MicrosoftExtensions.cpp 
b/clang/test/SemaCXX/MicrosoftExtensions.cpp
index 960030d44f0c155..71618048014cc74 100644
--- a/clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -589,6 +589,17 @@ namespace PR42089 {
   __attribute__((nothrow)) void S::Bar(){}
 }
 
+namespace UnalignedConv {
+struct S {
+  bool operator==(int) const;
+};
+
+int func() {
+  S __unaligned s;
+  return s == 42;
+}
+}
+
 #elif TEST2
 
 // Check that __unaligned is not recognized if MS extensions are not enabled

>From d76263dacae363fe8b82e40babada9fa50a1f830 Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Tue, 5 Sep 2023 01:09:47 +0900
Subject: [PATCH 2/3] Dummy commit to trigger CI build/test

---
 clang/test/SemaCXX/MicrosoftExtensions.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/test/SemaCXX/MicrosoftExtensions.cpp 
b/clang/test/SemaCXX/MicrosoftExtensions.cpp
index 71618048014cc74..7286217b1644f3e 100644
--- a/clang/test/SemaCXX/MicrosoftExtensions.cpp
+++ b/clang/test/SemaCXX/MicrosoftExtensions.cpp
@@ -600,6 +600,7 @@ int func() {
 }
 }
 
+
 #elif TEST2
 
 // Check that __unaligned is not recognized if MS extensions are not enabled

>From 4f184b9b6f2f2e236fea2c7d8e358cd4779ea1ed Mon Sep 17 00:00:00 2001
From: Takuya Shimizu 
Date: Tue, 5 Sep 2023 11:32:28 +0900
Subject: [PATCH 3/3] Add release note

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c6d2c3466a09622..dbb719eb338dc63 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -211,6 +211,8 @@ Bug Fixes in This Version
 - Clang now reports ``-Wformat`` for bool value and char specifier confusion
   in scanf. Fixes
   (`#64987 `_)
+- Clang no longer considers the loss of ``__unaligned`` qualifier from objects 
as
+  an invalid conversion during method function overload resolution.
 
 Bug Fixes to Compiler Builtins
 ^^

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


[clang] [clang][Diagnostics] Add source range to uninitialized diagnostics (PR #65896)

2023-09-10 Thread Takuya Shimizu via cfe-commits


@@ -4443,7 +,7 @@ struct CompoundAssignSubobjectHandler {
   return foundVector(Subobj, SubobjType);
 case APValue::Indeterminate:
   Info.FFDiag(E, diag::note_constexpr_access_uninit)
-  << /*read of=*/0 << /*uninitialized object=*/1;
+  << /*read of=*/0 << /*uninitialized object=*/1 << 
E->getSourceRange();

hazohelet wrote:

I prefer `E->getLHS()->getSourceRange()` because the uninitialized object is 
known to exist in LHS.

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


[clang] [clang][Diagnostics] Add source range to uninitialized diagnostics (PR #65896)

2023-09-10 Thread Takuya Shimizu via cfe-commits

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

LGTM

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


[clang] 176981a - [clang][Diagnostics] Fix distant source ranges in bad-conversion notes

2023-07-14 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-07-14T22:59:41+09:00
New Revision: 176981ac58d3e4beb02b9d110524e72be509375d

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

LOG: [clang][Diagnostics] Fix distant source ranges in bad-conversion notes

Now that clang supports printing of multiple lines of code snippet in 
diagnostics, source ranges in diagnostics that are located in different lines 
from the diagnosed source location get to be printed if the gap happened to be 
less than the maximum number of lines clang is allowed to print in.
Many of the bad-conversion notes in overload resolution failures have their 
source location in the function declaration and source range in the argument of 
function call. This can cause an unnecessarily many lines of snippet printing.
This patch fixes it by changing the source range from function callsite to the 
problematic parameter in function declaration.

e.g.

```
void func(int aa, int bb);

void test() { func(1, "two"); }
```
BEFORE this patch:

```
source:4:15: error: no matching function for call to 'func'
4 | void test() { func(1, "two"); }
  |   ^~~~
source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
1 | void func(int aa, int bb);
  |  ^
2 |
3 |
4 | void test() { func(1, "two"); }
  |   ~
1 error generated.
```
AFTER this patch:

```
source:4:15: error: no matching function for call to 'func'
4 | void test() { func(1, "two"); }
  |   ^~~~
source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
1 | void func(int aa, int bb);
  |  ^~~
```

Reviewed By: cjdb
Differential Revision: https://reviews.llvm.org/D153359

Added: 
clang/test/Misc/diag-overload-cand-ranges.cpp
clang/test/Misc/diag-overload-cand-ranges.mm

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

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 08d49bf72fbaaf..53a83b9c94176d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -384,6 +384,37 @@ Improvements to Clang's diagnostics
   (`#57081: `_)
 - Clang no longer emits inappropriate notes about the loss of ``__unaligned`` 
qualifier
   on overload resolution, when the actual reason for the failure is loss of 
other qualifiers.
+- Clang's notes about unconvertible types in overload resolution failure now 
covers
+  the source range of parameter declaration of the candidate function 
declaration.
+
+  *Example Code*:
+
+  .. code-block:: c++
+
+ void func(int aa, int bb);
+ void test() { func(1, "two"); }
+
+  *BEFORE*:
+
+  .. code-block:: text
+
+source:2:15: error: no matching function for call to 'func'
+void test() { func(1, "two");  }
+  ^~~~
+source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
+void func(int aa, int bb);
+ ^
+
+  *AFTER*:
+
+  .. code-block:: text
+
+source:2:15: error: no matching function for call to 'func'
+void test() { func(1, "two");  }
+  ^~~~
+source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
+void func(int aa, int bb);
+ ^~~
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index d45257ec7a4c7b..45a9e5dc98c032 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10753,6 +10753,8 @@ static void DiagnoseBadConversion(Sema &S, 
OverloadCandidate *Cand,
   Expr *FromExpr = Conv.Bad.FromExpr;
   QualType FromTy = Conv.Bad.getFromType();
   QualType ToTy = Conv.Bad.getToType();
+  SourceRange ToParamRange =
+  !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : 
SourceRange();
 
   if (FromTy == S.Context.OverloadTy) {
 assert(FromExpr && "overload set argument came from implicit argument?");
@@ -10763,8 +10765,7 @@ static void DiagnoseBadConversion(Sema &S, 
OverloadCandidate *Cand,
 
 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
-<< (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
-<< Name << I + 1;
+<< ToParamRange << ToTy << Name << I + 1;
 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
 return;
   }
@@ -10793,14 +10794,12 @@ static void DiagnoseBadConversion(Sema &S, 
OverloadCandidate *

[clang] 0e167fc - [clang][AST] Print name instead of type when diagnosing uninitialized subobject in constexpr variables

2023-05-16 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-05-16T21:49:57+09:00
New Revision: 0e167fc0a2147c9b673b8afd5fea001b0d127781

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

LOG: [clang][AST] Print name instead of type when diagnosing uninitialized 
subobject in constexpr variables

This patch improves the diagnostic on uninitialized subobjects in constexpr 
variables by modifying the diagnostic message to display the subobject's name 
instead of its type.

Fixes https://github.com/llvm/llvm-project/issues/58601
Differential Revision: https://reviews.llvm.org/D146358

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticASTKinds.td
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/Interp/Interp.cpp
clang/test/AST/Interp/cxx20.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p4.cpp
clang/test/SemaCXX/constant-expression-cxx2a.cpp
clang/test/SemaCXX/cxx2a-consteval.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9601849bd67d3..77990f330e4bb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -280,7 +280,9 @@ Improvements to Clang's diagnostics
   Clang ABI >= 15.
   (`#62353: `_,
   fallout from the non-POD packing ABI fix in LLVM 15).
-
+- Clang constexpr evaluator now prints subobject's name instead of its type in 
notes
+  when a constexpr variable has uninitialized subobjects after its constructor 
call.
+  (`#58601 `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index c283ee842e730..eb13467317963 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -65,7 +65,7 @@ def note_consteval_address_accessible : Note<
   "%select{pointer|reference}0 to a consteval declaration "
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
-  "%select{|sub}0object of type %1 is not initialized">;
+  "subobject %0 is not initialized">;
 def note_constexpr_static_local : Note<
   "control flows through the definition of a %select{static|thread_local}0 
variable">;
 def note_constexpr_subobject_declared_here : Note<

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index ce3c5257e7114..84c8623a0b8ae 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2119,7 +2119,7 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   EvalInfo &Info, SourceLocation DiagLoc,
   QualType Type, const APValue &Value,
   ConstantExprKind Kind,
-  SourceLocation SubobjectLoc,
+  const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps);
 
 /// Check that this reference or pointer core constant expression is a valid
@@ -2266,8 +2266,8 @@ static bool CheckLValueConstantExpression(EvalInfo &Info, 
SourceLocation Loc,
   APValue *V = MTE->getOrCreateValue(false);
   assert(V && "evasluation result refers to uninitialised temporary");
   if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
- Info, MTE->getExprLoc(), TempType, *V,
- Kind, SourceLocation(), CheckedTemps))
+ Info, MTE->getExprLoc(), TempType, *V, Kind,
+ /*SubobjectDecl=*/nullptr, CheckedTemps))
 return false;
 }
   }
@@ -2350,13 +2350,13 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   EvalInfo &Info, SourceLocation DiagLoc,
   QualType Type, const APValue &Value,
   ConstantExprKind Kind,
-  SourceLocation SubobjectLoc,
+  const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
-  << true << Type;
-if (SubobjectLoc.isValid())
-  Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
+assert(SubobjectDecl && "SubobjectDecl shall be non-null");
+Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
+Info.Note(SubobjectDecl->getLocation(),
+  diag::note_constexpr_subobject_declared_here);
 return 

[clang] 986cbd8 - [clang][AST] TextNodeDumper should not evaluate the initializer of constexpr variable declaration when it has a dependent type

2023-05-22 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-05-23T00:57:38+09:00
New Revision: 986cbd80d1dc838c61abff24b8d7ac28dcf4ac2a

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

LOG: [clang][AST] TextNodeDumper should not evaluate the initializer of 
constexpr variable declaration when it has a dependent type

`TextNodeDumper` enabed through `-ast-dump` flag should not evlauate the 
initializer when it visits a constexpr `VarDecl` node if it has a dependent 
type.

I found a crashing case fixed by this change and added it as a test case.
`template  constexpr T call_init(0);`
Link: https://godbolt.org/z/3bG9Pjj5E

This is a fix for the regression caused by D146358

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/TextNodeDumper.cpp
clang/test/AST/ast-dump-decl.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c80cc8994f383..a55e969fa21c1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -420,6 +420,8 @@ Bug Fixes in This Version
   (`#62711 `_).
 - Fix crash on attempt to initialize union with flexible array member.
   (`#61746 `_).
+- Clang `TextNodeDumper` enabled through `-ast-dump` flag no longer evaluates 
the
+  initializer of constexpr `VarDecl` if the declaration has a dependent type.
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/AST/TextNodeDumper.cpp 
b/clang/lib/AST/TextNodeDumper.cpp
index 3817025c051c5..b89a13dd9499c 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -1821,7 +1821,8 @@ void TextNodeDumper::VisitVarDecl(const VarDecl *D) {
   if (D->hasInit()) {
 const Expr *E = D->getInit();
 // Only dump the value of constexpr VarDecls for now.
-if (E && !E->isValueDependent() && D->isConstexpr()) {
+if (E && !E->isValueDependent() && D->isConstexpr() &&
+!D->getType()->isDependentType()) {
   const APValue *Value = D->evaluateValue();
   if (Value)
 AddChild("value", [=] { Visit(*Value, E->getType()); });

diff  --git a/clang/test/AST/ast-dump-decl.cpp 
b/clang/test/AST/ast-dump-decl.cpp
index 3be99c9489640..276a2095bec7c 100644
--- a/clang/test/AST/ast-dump-decl.cpp
+++ b/clang/test/AST/ast-dump-decl.cpp
@@ -818,3 +818,38 @@ namespace Comment {
 // CHECK:   `-TextComment
 // CHECK: VarDecl {{.*}} Test 'int' extern
 // CHECK-NOT: FullComment
+
+namespace TestConstexprVariableTemplateWithInitializer {
+  template constexpr T foo{};
+  // CHECK:  VarTemplateDecl 0x{{.+}} <{{.+}}:[[@LINE-1]]:3, col:40> 
col:36 foo
+  // CHECK-NEXT: |-TemplateTypeParmDecl 0x{{.+}}  col:21 
referenced typename depth 0 index 0 T
+  // CHECK-NEXT: `-VarDecl 0x{{.+}}  col:36 foo 'const T' 
constexpr listinit
+  // CHECK-NEXT:  `-InitListExpr 0x{{.+}}  'void'
+
+  template constexpr int val{42};
+  // CHECK:  VarTemplateDecl 0x{{.+}} <{{.+}}:[[@LINE-1]]:3, col:44> 
col:38 val
+  // CHECK-NEXT: |-TemplateTypeParmDecl 0x{{.+}}  col:21 
typename depth 0 index 0 T
+  // CHECK-NEXT: `-VarDecl 0x{{.+}}  col:38 val 'const int' 
constexpr listinit
+  // CHECK-NEXT:  |-value: Int 42
+  // CHECK-NEXT:  `-InitListExpr 0x{{.+}}  'int'
+
+  template 
+  struct in_place_type_t {
+explicit in_place_type_t() = default;
+  };
+
+  template 
+  inline constexpr in_place_type_t<_Tp> in_place_type{};
+  // CHECK: -VarTemplateDecl 0x{{.+}}  col:41 in_place_type
+  // CHECK-NEXT: |-TemplateTypeParmDecl 0x{{.+}}  
col:22 referenced typename depth 0 index 0 _Tp
+  // CHECK-NEXT: `-VarDecl 0x{{.+}}  col:41 
in_place_type 'const in_place_type_t<_Tp>':'const in_place_type_t<_Tp>' inline 
constexpr listinit
+  // CHECK-NEXT:  `-InitListExpr 0x{{.+}}  'void'
+
+  template  constexpr T call_init(0);
+  // CHECK: -VarTemplateDecl 0x{{.+}}  col:37 
call_init
+  // CHECK-NEXT: |-TemplateTypeParmDecl 0x{{.+}}  col:22 
referenced typename depth 0 index 0 T
+  // CHECK-NEXT: `-VarDecl 0x{{.+}}  col:37 call_init 'const 
T' constexpr callinit
+  // CHECK-NEXT:  `-ParenListExpr 0x{{.+}}  'NULL TYPE'
+  // CHECK-NEXT:   `-IntegerLiteral 0x{{.+}}  'int' 0
+
+}



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


[clang] 456d072 - Reland: [clang][AST] Print name instead of type when diagnosing uninitialized subobject in constexpr variables

2023-05-24 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-05-24T21:31:25+09:00
New Revision: 456d072405d29ac731ad22fa1ec198b9f8265c4e

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

LOG: Reland: [clang][AST] Print name instead of type when diagnosing 
uninitialized subobject in constexpr variables

This patch improves the diagnostic on uninitialized subobjects in constexpr 
variables by modifying the diagnostic message to display the subobject's name 
instead of its type.

Fixes https://github.com/llvm/llvm-project/issues/58601
Differential Revision: https://reviews.llvm.org/D146358

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticASTKinds.td
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/Interp/Interp.cpp
clang/test/AST/Interp/cxx20.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p4.cpp
clang/test/SemaCXX/constant-expression-cxx2a.cpp
clang/test/SemaCXX/cxx2a-consteval.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a124617fac8bb..0c369a7f45057 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -296,7 +296,9 @@ Improvements to Clang's diagnostics
   Clang ABI >= 15.
   (`#62353: `_,
   fallout from the non-POD packing ABI fix in LLVM 15).
-
+- Clang constexpr evaluator now prints subobject's name instead of its type in 
notes
+  when a constexpr variable has uninitialized subobjects after its constructor 
call.
+  (`#58601 `_)
 
 Bug Fixes in This Version
 -

diff  --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index c283ee842e730..eb13467317963 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -65,7 +65,7 @@ def note_consteval_address_accessible : Note<
   "%select{pointer|reference}0 to a consteval declaration "
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
-  "%select{|sub}0object of type %1 is not initialized">;
+  "subobject %0 is not initialized">;
 def note_constexpr_static_local : Note<
   "control flows through the definition of a %select{static|thread_local}0 
variable">;
 def note_constexpr_subobject_declared_here : Note<

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index d88f9535c1a4b..1f1ce2a18bd4a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2119,7 +2119,7 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   EvalInfo &Info, SourceLocation DiagLoc,
   QualType Type, const APValue &Value,
   ConstantExprKind Kind,
-  SourceLocation SubobjectLoc,
+  const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps);
 
 /// Check that this reference or pointer core constant expression is a valid
@@ -2266,8 +2266,8 @@ static bool CheckLValueConstantExpression(EvalInfo &Info, 
SourceLocation Loc,
   APValue *V = MTE->getOrCreateValue(false);
   assert(V && "evasluation result refers to uninitialised temporary");
   if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
- Info, MTE->getExprLoc(), TempType, *V,
- Kind, SourceLocation(), CheckedTemps))
+ Info, MTE->getExprLoc(), TempType, *V, Kind,
+ /*SubobjectDecl=*/nullptr, CheckedTemps))
 return false;
 }
   }
@@ -2350,13 +2350,13 @@ static bool 
CheckEvaluationResult(CheckEvaluationResultKind CERK,
   EvalInfo &Info, SourceLocation DiagLoc,
   QualType Type, const APValue &Value,
   ConstantExprKind Kind,
-  SourceLocation SubobjectLoc,
+  const FieldDecl *SubobjectDecl,
   CheckedTemporaries &CheckedTemps) {
   if (!Value.hasValue()) {
-Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
-  << true << Type;
-if (SubobjectLoc.isValid())
-  Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
+assert(SubobjectDecl && "SubobjectDecl shall be non-null");
+Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << SubobjectDecl;
+Info.Note(SubobjectDecl->getLocation(),
+  diag::note_constexpr_subobject_declared_here);

  1   2   >