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

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


@@ -494,6 +494,9 @@ BUILTIN(__builtin_isinf,  "i.", "FnctE")
 BUILTIN(__builtin_isinf_sign, "i.", "FnctE")
 BUILTIN(__builtin_isnan,  "i.", "FnctE")
 BUILTIN(__builtin_isnormal,   "i.", "FnctE")
+BUILTIN(__builtin_issubnormal,"i.", "FnctE")
+BUILTIN(__builtin_iszero, "i.", "FnctE")
+BUILTIN(__builtin_issignaling,"i.", "FnctE")

tbaederr wrote:

The `E` means they can be evaluated at compile time, but I don't see changes to 
`ExprConstant.cpp`?

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


[clang] [clang][Interp] IntegralAP zero-init (PR #68081)

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


@@ -100,12 +100,13 @@ template  class IntegralAP final {
   }
   static IntegralAP from(const Boolean &B) {
 assert(false);
-return IntegralAP::zero();
+return IntegralAP::zero(1);

tbaederr wrote:

I don't have such comments because I opted for `assert(false)` where things are 
unimplemented :)

I keep opening smaller PRs _to make review easier_ because I thought that... 
makes it easier. If larger (but complete) patches are better for you, I can try 
to do that instead.

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


[clang] a653749 - [clang][Interp] Implement compound assign operators on bitfields (#67306)

2023-10-14 Thread via cfe-commits

Author: Timm Baeder
Date: 2023-10-14T09:17:35+02:00
New Revision: a653749acab8d5cb84e7f1597e76ebe8c84b

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

LOG: [clang][Interp] Implement compound assign operators on bitfields (#67306)

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/bitfields.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 2b745d6a1509868..71aac8c6245c5af 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1170,8 +1170,13 @@ bool 
ByteCodeExprGen::VisitCompoundAssignOperator(
   }
 
   // And store the result in LHS.
-  if (DiscardResult)
+  if (DiscardResult) {
+if (LHS->refersToBitField())
+  return this->emitStoreBitFieldPop(*ResultT, E);
 return this->emitStorePop(*ResultT, E);
+  }
+  if (LHS->refersToBitField())
+return this->emitStoreBitField(*ResultT, E);
   return this->emitStore(*ResultT, E);
 }
 

diff  --git a/clang/test/AST/Interp/bitfields.cpp 
b/clang/test/AST/Interp/bitfields.cpp
index e078704fce51ff0..9a144e2f0d9610e 100644
--- a/clang/test/AST/Interp/bitfields.cpp
+++ b/clang/test/AST/Interp/bitfields.cpp
@@ -31,8 +31,6 @@ namespace Basic {
 return a.a = 10;
   }
   static_assert(storeA2() == 2, "");
-
-  // TODO: +=, -=, etc. operators.
 }
 
 namespace Overflow {
@@ -45,3 +43,39 @@ namespace Overflow {
 
   static_assert(f() == 3, "");
 }
+
+namespace Compound {
+  struct A {
+unsigned int a : 2;
+constexpr A() : a(0) {}
+constexpr A(int a) : a(a) {}
+  };
+
+  constexpr unsigned add() {
+A a;
+a.a += 10;
+return a.a;
+  }
+  static_assert(add() == 2, "");
+
+  constexpr unsigned sub() {
+A a;
+a.a -= 10;
+return a.a;
+  }
+  static_assert(sub() == 2, "");
+
+  constexpr unsigned mul() {
+A a(1);
+a.a *= 5;
+return a.a;
+  }
+  static_assert(mul() == 1, "");
+
+  constexpr unsigned div() {
+A a(2);
+a.a /= 2;
+return a.a;
+  }
+  static_assert(div() == 1, "");
+}



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


[clang] [clang][Interp] Implement compound assign operators on bitfields (PR #67306)

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

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


[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

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


tbaederr wrote:

We can easily get the size of the file in no time, right? What if we just use 
an upper limit of, say, 2MB and stop highlighting altogether if the input file 
is bigger than that? It's not perfect but that's what all the online tools do 
anyway and it would give us lexing without performance degradation.

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


[clang] [Clang] Implement the 'counted_by' attribute (PR #68750)

2023-10-14 Thread Nick Desaulniers via cfe-commits

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


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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

2023-10-14 Thread via cfe-commits

https://github.com/AMS21 created https://github.com/llvm/llvm-project/pull/69045

With this patch we no longer issue a warning for unused parameters which are 
marked as such.

This fixes #68209

>From 04eff97d2154edf49a21d276e3872cef0f64b654 Mon Sep 17 00:00:00 2001
From: AMS21 
Date: Sat, 14 Oct 2023 10:26:36 +0200
Subject: [PATCH] [clang-tidy] Ignore unused parameters in
 `rvalue-reference-param-not-moved check`

With this patch we no longer issue a warning for unused parameters which
are marked as such.

This fixes #68209
---
 .../RvalueReferenceParamNotMovedCheck.cpp |  3 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 
 .../rvalue-reference-param-not-moved.cpp  | 19 +++
 3 files changed, 26 insertions(+)

diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
index efcaffb45d9ad8a..88b00dc17470f32 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
@@ -84,6 +84,9 @@ void RvalueReferenceParamNotMovedCheck::check(
   if (IgnoreUnnamedParams && Param->getName().empty())
 return;
 
+  if (!Param->isUsed() && Param->hasAttr())
+return;
+
   const auto *Function = dyn_cast(Param->getDeclContext());
   if (!Function)
 return;
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 03e5dc6f164af2a..c732d4904df13fa 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -237,6 +237,10 @@ Changes in existing checks
   ` check to ignore
   false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).
 
+- Improved :doc:`cppcoreguidelines-rvalue-reference-param-not-moved
+  ` check
+  to ignore unused parameters when they are marked as unused.
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
index 8f8e272e1e8a90d..c6a70aef810ac90 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
@@ -333,3 +333,22 @@ void instantiate_a_class_template() {
   AClassTemplate withObjRef(o);
   withObjRef.never_moves(o);
 }
+
+namespace gh68209
+{
+  void f1([[maybe_unused]] int&& x) {}
+
+  void f2(__attribute__((unused)) int&& x) {}
+
+  void f3(int&& x) {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: rvalue reference parameter 'x' 
is never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
+
+  template 
+  void f4([[maybe_unused]] T&& x) {}
+
+  template 
+  void f5(__attribute((unused)) T&& x) {}
+
+  template
+  void f6(T&& x) {}
+} // namespace gh68209

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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: None (AMS21)


Changes

With this patch we no longer issue a warning for unused parameters which are 
marked as such.

This fixes #68209

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


3 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
 (+3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
 (+19) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
index efcaffb45d9ad8a..88b00dc17470f32 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
@@ -84,6 +84,9 @@ void RvalueReferenceParamNotMovedCheck::check(
   if (IgnoreUnnamedParams && Param->getName().empty())
 return;
 
+  if (!Param->isUsed() && Param->hasAttr())
+return;
+
   const auto *Function = dyn_cast(Param->getDeclContext());
   if (!Function)
 return;
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 03e5dc6f164af2a..c732d4904df13fa 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -237,6 +237,10 @@ Changes in existing checks
   ` check to ignore
   false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).
 
+- Improved :doc:`cppcoreguidelines-rvalue-reference-param-not-moved
+  ` check
+  to ignore unused parameters when they are marked as unused.
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
index 8f8e272e1e8a90d..c6a70aef810ac90 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
@@ -333,3 +333,22 @@ void instantiate_a_class_template() {
   AClassTemplate withObjRef(o);
   withObjRef.never_moves(o);
 }
+
+namespace gh68209
+{
+  void f1([[maybe_unused]] int&& x) {}
+
+  void f2(__attribute__((unused)) int&& x) {}
+
+  void f3(int&& x) {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: rvalue reference parameter 'x' 
is never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
+
+  template 
+  void f4([[maybe_unused]] T&& x) {}
+
+  template 
+  void f5(__attribute((unused)) T&& x) {}
+
+  template
+  void f6(T&& x) {}
+} // namespace gh68209

``




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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

2023-10-14 Thread via cfe-commits

AMS21 wrote:

I'm not sure if we should rather have this as an option like 
`IgnoreUnnamedParams`

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


[clang] [Sema] Add check for bitfield assignments to integral types (PR #69049)

2023-10-14 Thread via cfe-commits

https://github.com/vabridgers created 
https://github.com/llvm/llvm-project/pull/69049

This change introduces the bitfield conversion check after fixes to the test 
case. The original submission unfortunately did not comprehend differences in 
architecture for the diagnostic messages, leading to unanticipated failures in 
the arm build bots.

Original PR: https://github.com/llvm/llvm-project/pull/68276

Clang does not check for bitfield assignment widths, while gcc checks this.

gcc produced a warning like so for it's -Wconversion flag:
```
$ gcc -Wconversion -c test.c
test.c: In function 'foo':
test.c:10:15: warning: conversion from 'int' to 'signed char:7' may
change value [-Wconversion]
   10 |  vxx.bf = x; // no warning
  |   ^
```

This change simply adds this check for integral types under the 
-Wbitfield-conversion compiler option.

>From e11dd44ab0c89888b9531bbf4dc0cf6ee407be10 Mon Sep 17 00:00:00 2001
From: Vince Bridgers 
Date: Sat, 14 Oct 2023 10:14:52 +0200
Subject: [PATCH] [Sema] Add check for bitfield assignments to integral types

This change introduces the bitfield conversion check after fixes to the
test case. The original submission unfortunately did not comprehend
differences in architecture for the diagnostic messages, leading to
unanticipated failures in the arm build bots.

Original PR: https://github.com/llvm/llvm-project/pull/68276

Clang does not check for bitfield assignment widths, while gcc checks this.

gcc produced a warning like so for it's -Wconversion flag:
```
$ gcc -Wconversion -c test.c
test.c: In function 'foo':
test.c:10:15: warning: conversion from 'int' to 'signed char:7' may
change value [-Wconversion]
   10 |  vxx.bf = x; // no warning
  |   ^
```

This change simply adds this check for integral types under the
-Wbitfield-conversion compiler option.
---
 clang/docs/ReleaseNotes.rst   |  3 ++
 clang/include/clang/Basic/DiagnosticGroups.td |  2 +
 .../clang/Basic/DiagnosticSemaKinds.td|  3 ++
 clang/lib/Sema/SemaChecking.cpp   | 13 +-
 clang/test/SemaCXX/bitfield-width.c   | 42 +++
 5 files changed, 62 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/SemaCXX/bitfield-width.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..31969201a1cac8c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -185,6 +185,9 @@ New Compiler Flags
   the preprocessed text to the output. This can greatly reduce the size of the
   preprocessed output, which can be helpful when trying to reduce a test case.
 
+* ``-Wbitfield-conversion`` was added to detect assignments of integral
+  types to a bitfield that may change the value.
+
 Deprecated Compiler Flags
 -
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 0b09c002191848a..674eb9f4ef2e73f 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -53,6 +53,7 @@ def SingleBitBitFieldConstantConversion :
 def BitFieldConstantConversion : DiagGroup<"bitfield-constant-conversion",

[SingleBitBitFieldConstantConversion]>;
 def BitFieldEnumConversion : DiagGroup<"bitfield-enum-conversion">;
+def BitFieldConversion : DiagGroup<"bitfield-conversion">;
 def BitFieldWidth : DiagGroup<"bitfield-width">;
 def CompoundTokenSplitByMacro : DiagGroup<"compound-token-split-by-macro">;
 def CompoundTokenSplitBySpace : DiagGroup<"compound-token-split-by-space">;
@@ -933,6 +934,7 @@ def Conversion : DiagGroup<"conversion",
 ConstantConversion,
 EnumConversion,
 BitFieldEnumConversion,
+BitFieldConversion,
 FloatConversion,
 Shorten64To32,
 IntConversion,
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c1a6e3831127e56..ab7fe881976aad2 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6171,6 +6171,9 @@ def warn_signed_bitfield_enum_conversion : Warning<
   "signed bit-field %0 needs an extra bit to represent the largest positive "
   "enumerators of %1">,
   InGroup, DefaultIgnore;
+def warn_bitfield_too_small_for_integral_type : Warning<
+  "conversion from %2 (%3 bits) to bit-field %0 (%1 bits) may change value">,
+  InGroup, DefaultIgnore;
 def note_change_bitfield_sign : Note<
   "consider making the bitfield type %select{unsigned|signed}0">;
 
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 35b36db2049db09..cd61459cfbb13d6 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14298,6

[clang] [Sema] Add check for bitfield assignments to integral types (PR #69049)

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (vabridgers)


Changes

This change introduces the bitfield conversion check after fixes to the test 
case. The original submission unfortunately did not comprehend differences in 
architecture for the diagnostic messages, leading to unanticipated failures in 
the arm build bots.

Original PR: https://github.com/llvm/llvm-project/pull/68276

Clang does not check for bitfield assignment widths, while gcc checks this.

gcc produced a warning like so for it's -Wconversion flag:
```
$ gcc -Wconversion -c test.c
test.c: In function 'foo':
test.c:10:15: warning: conversion from 'int' to 'signed char:7' may
change value [-Wconversion]
   10 |  vxx.bf = x; // no warning
  |   ^
```

This change simply adds this check for integral types under the 
-Wbitfield-conversion compiler option.

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


5 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/Basic/DiagnosticGroups.td (+2) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+12-1) 
- (added) clang/test/SemaCXX/bitfield-width.c (+42) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..31969201a1cac8c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -185,6 +185,9 @@ New Compiler Flags
   the preprocessed text to the output. This can greatly reduce the size of the
   preprocessed output, which can be helpful when trying to reduce a test case.
 
+* ``-Wbitfield-conversion`` was added to detect assignments of integral
+  types to a bitfield that may change the value.
+
 Deprecated Compiler Flags
 -
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 0b09c002191848a..674eb9f4ef2e73f 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -53,6 +53,7 @@ def SingleBitBitFieldConstantConversion :
 def BitFieldConstantConversion : DiagGroup<"bitfield-constant-conversion",

[SingleBitBitFieldConstantConversion]>;
 def BitFieldEnumConversion : DiagGroup<"bitfield-enum-conversion">;
+def BitFieldConversion : DiagGroup<"bitfield-conversion">;
 def BitFieldWidth : DiagGroup<"bitfield-width">;
 def CompoundTokenSplitByMacro : DiagGroup<"compound-token-split-by-macro">;
 def CompoundTokenSplitBySpace : DiagGroup<"compound-token-split-by-space">;
@@ -933,6 +934,7 @@ def Conversion : DiagGroup<"conversion",
 ConstantConversion,
 EnumConversion,
 BitFieldEnumConversion,
+BitFieldConversion,
 FloatConversion,
 Shorten64To32,
 IntConversion,
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c1a6e3831127e56..ab7fe881976aad2 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6171,6 +6171,9 @@ def warn_signed_bitfield_enum_conversion : Warning<
   "signed bit-field %0 needs an extra bit to represent the largest positive "
   "enumerators of %1">,
   InGroup, DefaultIgnore;
+def warn_bitfield_too_small_for_integral_type : Warning<
+  "conversion from %2 (%3 bits) to bit-field %0 (%1 bits) may change value">,
+  InGroup, DefaultIgnore;
 def note_change_bitfield_sign : Note<
   "consider making the bitfield type %select{unsigned|signed}0">;
 
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 35b36db2049db09..cd61459cfbb13d6 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14298,6 +14298,18 @@ static bool AnalyzeBitFieldAssignment(Sema &S, 
FieldDecl *Bitfield, Expr *Init,
 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
 << BitsNeeded << ED << WidthExpr->getSourceRange();
   }
+} else if (OriginalInit->getType()->isIntegralType(S.Context)) {
+  IntRange LikelySourceRange =
+  GetExprRange(S.Context, Init, S.isConstantEvaluatedContext(),
+   /*Approximate=*/true);
+
+  if (LikelySourceRange.Width > FieldWidth) {
+Expr *WidthExpr = Bitfield->getBitWidth();
+S.Diag(InitLoc, diag::warn_bitfield_too_small_for_integral_type)
+<< Bitfield << FieldWidth << OriginalInit->getType()
+<< LikelySourceRange.Width;
+S.Diag(WidthExpr->getExprLoc(), diag::note_declared_at);
+  }
 }
 
 return false;
@@ -15195,7 +15207,6 @@ static void CheckImplicitConversion(Sema &S, Expr *E, 
QualType T,
 
   if (LikelySourceRange.Width > TargetRange.Width) {
 // 

[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

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


@@ -333,3 +333,22 @@ void instantiate_a_class_template() {
   AClassTemplate withObjRef(o);
   withObjRef.never_moves(o);
 }
+
+namespace gh68209
+{
+  void f1([[maybe_unused]] int&& x) {}
+
+  void f2(__attribute__((unused)) int&& x) {}

PiotrZSL wrote:

Add info to documentation, that params with such attributes are unused.

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


[clang] [Sema, Lex, Parse] Preprocessor embed in C and C++ (and Obj-C and Obj-C++ by-proxy) (PR #68620)

2023-10-14 Thread via cfe-commits

h-vetinari wrote:

OK, I've got a first rebase going. However, because iterating on a diff with 
1000s of lines is extremely hard to review and bound to lead to mistakes and 
iterations (making it harder still to follow what's going on), I've tried to 
follow a more structured approach.

Basically, I've pushed tags for intermediate milestones during the rebase to my 
fork, and am documenting below what I've done. That should make it easier to:
* understand how the diff evolved
* make comparisons between the various different stages (e.g. one can add 
`/compare/..` on Github)
* roll back to intermediate iterations if something goes wrong, without having 
to start from scratch
* validate what I did (for those so inclined) or branch off in a different 
direction

I've used a simple tag scheme `embed_vX[.Y]`, where X increases if exisiting 
commits were changed, and Y increases if changes happened without rebasing. I 
did some basic compilation tests to ensure I didn't accidentally drop/introduce 
changes that break the build, but no more than that.

The table is probably busted visually on mobile (sorry...), but I hope it reads 
alright on a desktop. Where used, equality (`==`) refers to the content of the 
tree at the commits being compared, not the diffs in those commits.

| tag | description | steps to reproduce | compile-tested[^1] | diff 
toprev. version | 
|-|-|-|-|-|
| [`embed_v0`](https://github.com/h-vetinari/llvm-project/commits/embed_v0) | 
the state of the PRas opened originally(base 
08b20d838549e8ff3939c6793b5067b0d9b36337) | check out 
[this](https://github.com/ThePhD/llvm-project/tree/thephd/embed-speed) | 
32c8097f983a65526516353082268f50a017e27d ✅ 
(presumably)357bda5d13594bbb47f8a76c935fd6aacbf2f67a ❌ (needs 
adc973776a526f97b6da2435edf143a10e7e0ad5)dfd638311acb61bab8113c41ddf138199b360dfa
 ❌adc973776a526f97b6da2435edf143a10e7e0ad5 ✅ |
| [`embed_v1`](https://github.com/h-vetinari/llvm-project/commits/embed_v1) | 
separated superfluousformatting changesfrom first 2 commits(base 
08b20d838549e8ff3939c6793b5067b0d9b36337) | Interactive rebase galore(the 
most painful part) | 0b4b6a654edf6fa2781e1c80983c124a0d0088c5 
✅a05117d39e372e0360655b5da2101f8296bfe5fb ✅ 
(==v0:[`32c8097`](https://github.com/llvm/llvm-project/commit/32c8097f983a65526516353082268f50a017e27d))8231b72fbe322bef74bba8177a6bc64754b5cede
 ❌ (needs 
36c1a5f04a61dff60d8326906a42c4bf8fdde2f9)0a6f48bbb00552b92401476871386f53cac83512
 ❌ 
(==v0:[`357bda5`](https://github.com/llvm/llvm-project/commit/357bda5d13594bbb47f8a76c935fd6aacbf2f67a))b356860919bd186bf2c340a545e6924dbd9decf0
 ❌ 
(==v0:[`dfd6383`](https://github.com/llvm/llvm-project/commit/dfd638311acb61bab8113c41ddf138199b360dfa))36c1a5f04a61dff60d8326906a42c4bf8fdde2f9
 ✅ 
(==v0:[`adc9737`](https://github.com/llvm/llvm-project/commit/adc973776a526f97b6da2435edf143a10e7e0ad5))
 | 
[empty](https://github.com/h-vetinari/llvm-project/compare/embed_v0..embed_v1) |
| [`embed_v1.1`](https://github.com/h-vetinari/llvm-project/commits/embed_v1.1) 
| added 
[suggestions](https://github.com/llvm/llvm-project/pull/68620#issuecomment-1753515605)
 from`git-clang-format`(base 
08b20d838549e8ff3939c6793b5067b0d9b36337) | C&P + `git apply` | v1 + 
26c6fcc8d9a85519a4b1d98aa8a0d11fd725855b ✅ | 1 commit;no rebase | 
| [`embed_v2`](https://github.com/h-vetinari/llvm-project/commits/embed_v2) | 
undo superfluousformatting changes(base 
08b20d838549e8ff3939c6793b5067b0d9b36337) | `git rebase -i ...`; 
dropa05117d39e372e0360655b5da2101f8296bfe5fb & 
0a6f48bbb00552b92401476871386f53cac83512, fixminor conflicts in 
26c6fcc8d9a85519a4b1d98aa8a0d11fd725855b | 
0b4b6a654edf6fa2781e1c80983c124a0d0088c5 ✅ (same as 
v1)07795f280fe6727f76fac5028bd5cbe3bc82a662 ❌ (needs 
748c3b54e2e3b00d8c7c1a6813886e3f338ae0d4)1179116dac7ccc37a38cb8ae2b37a15f994ebdf5
 ❌748c3b54e2e3b00d8c7c1a6813886e3f338ae0d4 ✅ (likely; untested) 
b6d053e62a8ea9c88c2bd7ffe0e02e75c7abcc0a ✅ | 
[uninteresting](https://github.com/h-vetinari/llvm-project/compare/embed_v1.1..embed_v2)
 | 
| [`embed_v3`](https://github.com/h-vetinari/llvm-project/commits/embed_v3) | 
squash small commits(base 08b20d838549e8ff3939c6793b5067b0d9b36337) | `git 
rebase -i ...`; squash | 0b4b6a654edf6fa2781e1c80983c124a0d0088c5 ✅ (same as 
v1)a6f134d30f0007efa339fd434ac109749c30bb11 ✅ | 
[empty](https://github.com/h-vetinari/llvm-project/compare/embed_v2..embed_v3) 
| 
| [`embed_v4`](https://github.com/h-vetinari/llvm-project/commits/embed_v4) | 
rebase (cleanly) on main(base 7060422265902f11a13f785a1a0ba246eff96114) | 
`git rebase -i ...` | 7050c932f63f9cb9e94636b287887f8241083117 ❔ (untested) 
5956fc215c905fa8520ded8368ceb6b1fab1f996 ❔ (untested) | 
[uninteresting](https://github.com/h-vetinari/llvm-project/compare/embed_v3..embed_v4)
 | 

Since the rebase from v3 to v4 went cleanly, I haven't run the compilation 
tests. I will push v4 now, and hope that this is a good enough jumping off 
point for further review and iteration.

[^1]: `cmake -G Ninja -DLLVM_ENABLE_PR

[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

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

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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

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

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

Looks fine, I don't thing that this needs to be configurable.
If someone put explicitly attribute, then there is assumption that such param 
can be unused.

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


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2023-10-14 Thread via cfe-commits

https://github.com/xbjfk updated https://github.com/llvm/llvm-project/pull/68690

>From 92899d94e91a6812de8fa5ec7c15c37a81280108 Mon Sep 17 00:00:00 2001
From: Reagan Bohan 
Date: Tue, 10 Oct 2023 11:32:47 +
Subject: [PATCH 1/7] [clang] Add /Zc:__STDC__ flag to clang-cl

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC,
that things that rely on __STDC__, such as autoconf, can work.
---
 clang/include/clang/Basic/LangOptions.def |  2 +-
 clang/include/clang/Driver/Options.td |  7 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 10 +-
 clang/lib/Frontend/InitPreprocessor.cpp   |  3 ++-
 clang/test/Driver/cl-zc.cpp   |  4 
 5 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching 
API for HIP")
 LANGOPT(OffloadUniformBlock, 1, 0, "Assume that kernels are launched with 
uniform block sizes (default true for CUDA/HIP and false otherwise)")
 LANGOPT(HIPStdPar, 1, 0, "Enable Standard Parallel Algorithm Acceleration for 
HIP (experimental)")
 LANGOPT(HIPStdParInterposeAlloc, 1, 0, "Replace allocations / deallocations 
with HIP RT calls when Standard Parallel Algorithm Acceleration for HIP is 
enabled (Experimental)")
-
+LANGOPT(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..2834786ba17decf 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7926,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..e7ce08a8766d80c 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,8 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) &&
+  !LangOpts.TraditionalCPP)

[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2023-10-14 Thread via cfe-commits

https://github.com/xbjfk updated https://github.com/llvm/llvm-project/pull/68690

>From 92899d94e91a6812de8fa5ec7c15c37a81280108 Mon Sep 17 00:00:00 2001
From: Reagan Bohan 
Date: Tue, 10 Oct 2023 11:32:47 +
Subject: [PATCH 1/8] [clang] Add /Zc:__STDC__ flag to clang-cl

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC,
that things that rely on __STDC__, such as autoconf, can work.
---
 clang/include/clang/Basic/LangOptions.def |  2 +-
 clang/include/clang/Driver/Options.td |  7 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 10 +-
 clang/lib/Frontend/InitPreprocessor.cpp   |  3 ++-
 clang/test/Driver/cl-zc.cpp   |  4 
 5 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching 
API for HIP")
 LANGOPT(OffloadUniformBlock, 1, 0, "Assume that kernels are launched with 
uniform block sizes (default true for CUDA/HIP and false otherwise)")
 LANGOPT(HIPStdPar, 1, 0, "Enable Standard Parallel Algorithm Acceleration for 
HIP (experimental)")
 LANGOPT(HIPStdParInterposeAlloc, 1, 0, "Replace allocations / deallocations 
with HIP RT calls when Standard Parallel Algorithm Acceleration for HIP is 
enabled (Experimental)")
-
+LANGOPT(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..2834786ba17decf 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7926,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..e7ce08a8766d80c 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,8 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) &&
+  !LangOpts.TraditionalCPP)

[clang] 769bc11 - [Clang] Implement the 'counted_by' attribute (#68750)

2023-10-14 Thread via cfe-commits

Author: Bill Wendling
Date: 2023-10-14T04:18:02-07:00
New Revision: 769bc11f684d376bff03649da41296a4fc710161

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

LOG: [Clang] Implement the 'counted_by' attribute (#68750)

The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member in the same
structure holding the count of elements in the flexible array. This
information can be used to improve the results of the array bound
sanitizer and the '__builtin_dynamic_object_size' builtin.

This example specifies the that the flexible array member 'array' has
the number of elements allocated for it in 'count':

  struct bar;
  struct foo {
size_t count;
 /* ... */
struct bar *array[] __attribute__((counted_by(count)));
  };

This establishes a relationship between 'array' and 'count',
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained through changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

  struct foo *p;

  void foo_alloc(size_t count) {
p = malloc(MAX(sizeof(struct foo),
   offsetof(struct foo, array[0]) + count *
   sizeof(struct bar *)));
p->count = count + 42;
  }

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

  struct foo *p;

  void foo_alloc(size_t count) {
p = malloc(MAX(sizeof(struct foo),
   offsetof(struct foo, array[0]) + count *
   sizeof(struct bar *)));
p->count = count + 42;
  }

  void use_foo(int index) {
p->count += 42;
p->array[index] = 0; /* The sanitizer cannot properly check this access */
  }

Reviewed By: nickdesaulniers, aaron.ballman

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

Added: 
clang/test/CodeGen/attr-counted-by.c
clang/test/Sema/attr-counted-by.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/Decl.h
clang/include/clang/AST/DeclBase.h
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/include/clang/Sema/TypoCorrection.h
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/DeclBase.cpp
clang/lib/AST/Expr.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/CodeGen/bounds-checking.c
clang/test/Misc/pragma-attribute-supported-attributes-list.test

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..1eebf5ea6b3e382 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -157,6 +157,11 @@ C Language Changes
 - ``structs``, ``unions``, and ``arrays`` that are const may now be used as
   constant expressions.  This change is more consistent with the behavior of
   GCC.
+- Clang now supports the C-only attribute ``counted_by``. When applied to a
+  struct's flexible array member, it points to the struct field that holds the
+  number of elements in the flexible array member. This information can improve
+  the results of the array bound sanitizer and the
+  ``__builtin_dynamic_object_size`` builtin.
 
 C23 Feature Support
 ^^^

diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 02e30e24c8be470..7f076cc77ea82cb 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -4302,6 +4302,30 @@ class RecordDecl : public TagDecl {
 return field_begin() == field_end();
   }
 
+  FieldDecl *getLastField() {
+FieldDecl *FD = nullptr;
+for (FieldDecl *Field : fields())
+  FD = Field;
+return FD;
+  }
+  const FieldDecl *getLastField() const {
+return const_cast(this)->getLastField();
+  }
+
+  template 
+  const FieldDecl *findFieldIf(Functor &Pred) const {
+for (const Decl *D : decls()) {
+  if (const auto *FD = dyn_cast(D); FD && Pred(FD))
+return FD;
+
+  if (const auto *RD = dyn_cast(D))
+if (const FieldDecl *FD = RD->findFieldIf(Pred))
+  return FD;
+}
+
+return nullptr;
+  }
+
   /// Note that the definition of this type is now complete.
   virtual void completeDefinition();
 

diff  --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h

[clang] [Clang] Implement the 'counted_by' attribute (PR #68750)

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

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


[PATCH] D156784: [AArch64][PAC] Declare FPAC subtarget feature

2023-10-14 Thread Momchil Velikov via Phabricator via cfe-commits
chill added a comment.

In D156784#4653741 , @atrosinenko 
wrote:

> As discussed in D156716 , it is not clear 
> if I have to add FeatureFPAC to every relevant CPU.

I would say, yes, it has to be added to each CPU that has that feature - that's 
what a subtarget feature is for. If we need to a way to alter code generation
as a response to a user choice, that ought to be done with a specific command 
line option and `TargetOptions` and/or function and module level
attributes.

> Maybe it is worth conservatively assuming that this feature should only be 
> enabled manually by the user as a precaution against "I have CPU core X but 
> it is not listed, so let's use cpu=Y because X supports all the instructions 
> supported by Y //(but not FEAT_FPAC)//" - that would not cause any obvious 
> run-time crashes under normal operation, but would make the code less secure.

As far as I can tell, the existing practice for security-related code 
generation is to have it disabled by default
and enable it explicitly by `clang` command line options (c.f 
`-mbranch-protection=...`, `-mharden-sls=...`, `-fstack-clash-protection`, 
`-fsanitize=memtag`, ...).

In that spirit, I would suggest not using target features to alter code 
generation in a rather obscure way but being quite explicit about it.
For example, have an option `-mauth-ret-check=default|force` where:

- the presence of the option enables LR check before tail calls
- `default` (or `enable`) would mean `FEAT_FPAC` takes precedence
- `force` would mean `FEAT_FPAC` is ignored

Alternatively, maybe even better, these could be options to 
`-mbranch-protection=...`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156784

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


[clang] [clang] Enable Wenum-constexpr-conversion also in system headers and … (PR #67528)

2023-10-14 Thread Carlos Galvez via cfe-commits
Carlos =?utf-8?q?Gálvez?= 
Message-ID:
In-Reply-To: 


https://github.com/carlosgalvezp updated 
https://github.com/llvm/llvm-project/pull/67528

>From 08b5c95bea5b7bfceeae6dfc4deac764faff87a6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Carlos=20G=C3=A1lvez?= 
Date: Wed, 27 Sep 2023 08:07:01 +
Subject: [PATCH 1/2] [clang] Enable Wenum-constexpr-conversion also in system
 headers and macros

As per review comments on https://reviews.llvm.org/D150226, we should
allow for one more release before turning this warning into a hard
error, by making it visible in system headers and macros, so that
people are aware of it and can work on it.
---
 clang/docs/ReleaseNotes.rst | 4 
 clang/include/clang/Basic/DiagnosticASTKinds.td | 3 ++-
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1eebf5ea6b3e382..ade3c33b3b9444c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -96,6 +96,10 @@ C++ Specific Potentially Breaking Changes
   Clang as a compiler, but it may break assumptions in Clang-based tools
   iterating over the AST.
 
+- The warning `-Wenum-constexpr-conversion` is now also enabled by default on
+  system headers and macros. It will be turned into a hard (non-downgradable)
+  error in the next Clang release.
+
 ABI Changes in This Version
 ---
 - Following the SystemV ABI for x86-64, ``__int128`` arguments will no longer
diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index d2656310e79c9b8..0019553233fdef6 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -405,7 +405,8 @@ def warn_fixedpoint_constant_overflow : Warning<
   InGroup>;
 def warn_constexpr_unscoped_enum_out_of_range : Warning<
   "integer value %0 is outside the valid range of values [%1, %2] for the "
-  "enumeration type %3">, DefaultError, 
InGroup>;
+  "enumeration type %3">, DefaultError, ShowInSystemHeader, ShowInSystemMacro,
+  InGroup>;
 
 // This is a temporary diagnostic, and shall be removed once our
 // implementation is complete, and like the preceding constexpr notes belongs

>From 83d8ad39ee5544ad9bab848901362de0b180b2b5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Carlos=20G=C3=A1lvez?= 
Date: Wed, 27 Sep 2023 09:15:33 +
Subject: [PATCH 2/2] Add test

---
 .../enum-constexpr-conversion-system-header.h | 19 +++
 .../SemaCXX/constant-expression-cxx11.cpp | 11 ---
 2 files changed, 27 insertions(+), 3 deletions(-)
 create mode 100644 
clang/test/SemaCXX/Inputs/enum-constexpr-conversion-system-header.h

diff --git 
a/clang/test/SemaCXX/Inputs/enum-constexpr-conversion-system-header.h 
b/clang/test/SemaCXX/Inputs/enum-constexpr-conversion-system-header.h
new file mode 100644
index 000..0850f3405eed3a4
--- /dev/null
+++ b/clang/test/SemaCXX/Inputs/enum-constexpr-conversion-system-header.h
@@ -0,0 +1,19 @@
+// System header for testing that -Wenum-constexpr-conversion leads to an error
+// when included in user code, or when the system macro is used.
+
+enum SystemEnum
+{
+a = 0,
+b = 1,
+};
+
+void testValueInRangeOfEnumerationValuesInSystemHeader()
+{
+constexpr SystemEnum x1 = static_cast(123);
+// expected-error@-1 {{integer value 123 is outside the valid range of 
values [0, 1] for the enumeration type 'SystemEnum'}}
+
+const SystemEnum x2 = static_cast(123);  // ok, not a constant 
expression context
+}
+
+#define CONSTEXPR_CAST_TO_SYSTEM_ENUM_OUTSIDE_OF_RANGE \
+constexpr SystemEnum system_enum = static_cast(123)
diff --git a/clang/test/SemaCXX/constant-expression-cxx11.cpp 
b/clang/test/SemaCXX/constant-expression-cxx11.cpp
index 89d1b3ea6de05ea..8fb994224853bf1 100644
--- a/clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify=expected,cxx20_23,cxx23
-triple x86_64-linux -Wno-string-plus-int -Wno-pointer-arith 
-Wno-zero-length-array -Wno-c99-designator -fcxx-exceptions -pedantic %s 
-Wno-comment -Wno-tautological-pointer-compare -Wno-bool-conversion
-// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected,cxx11_20,cxx20_23 
-triple x86_64-linux -Wno-string-plus-int -Wno-pointer-arith 
-Wno-zero-length-array -Wno-c99-designator -fcxx-exceptions -pedantic %s 
-Wno-comment -Wno-tautological-pointer-compare -Wno-bool-conversion
-// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify=expected,cxx11_20,cxx11
-triple x86_64-linux -Wno-string-plus-int -Wno-pointer-arith 
-Wno-zero-length-array -Wno-c99-designator -fcxx-exceptions -pedantic %s 
-Wno-comment -Wno-tautological-pointer-compare -Wno-bool-conversion
+// RUN: %clang_cc1 -std=c++23 -isystem %S/Inputs -fsyntax-only 
-verify=expected,cxx20_23,cxx23-triple x86_64-linux -Wno-string-plus-int 
-Wno-pointer-arit

[clang] e7a6171 - [clang] Enable Wenum-constexpr-conversion also in system headers and … (#67528)

2023-10-14 Thread via cfe-commits

Author: Carlos Galvez
Date: 2023-10-14T14:19:20+02:00
New Revision: e7a6171c4c0486aae051543e202d74c04178cfac

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

LOG: [clang] Enable Wenum-constexpr-conversion also in system headers and … 
(#67528)

…macros

As per review comments on https://reviews.llvm.org/D150226, we should
allow for one more release before turning this warning into a hard
error, by making it visible in system headers and macros, so that people
are aware of it and can work on it.

Added: 
clang/test/SemaCXX/Inputs/enum-constexpr-conversion-system-header.h

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticASTKinds.td
clang/test/SemaCXX/constant-expression-cxx11.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1eebf5ea6b3e382..ade3c33b3b9444c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -96,6 +96,10 @@ C++ Specific Potentially Breaking Changes
   Clang as a compiler, but it may break assumptions in Clang-based tools
   iterating over the AST.
 
+- The warning `-Wenum-constexpr-conversion` is now also enabled by default on
+  system headers and macros. It will be turned into a hard (non-downgradable)
+  error in the next Clang release.
+
 ABI Changes in This Version
 ---
 - Following the SystemV ABI for x86-64, ``__int128`` arguments will no longer

diff  --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index d2656310e79c9b8..0019553233fdef6 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -405,7 +405,8 @@ def warn_fixedpoint_constant_overflow : Warning<
   InGroup>;
 def warn_constexpr_unscoped_enum_out_of_range : Warning<
   "integer value %0 is outside the valid range of values [%1, %2] for the "
-  "enumeration type %3">, DefaultError, 
InGroup>;
+  "enumeration type %3">, DefaultError, ShowInSystemHeader, ShowInSystemMacro,
+  InGroup>;
 
 // This is a temporary diagnostic, and shall be removed once our
 // implementation is complete, and like the preceding constexpr notes belongs

diff  --git 
a/clang/test/SemaCXX/Inputs/enum-constexpr-conversion-system-header.h 
b/clang/test/SemaCXX/Inputs/enum-constexpr-conversion-system-header.h
new file mode 100644
index 000..0850f3405eed3a4
--- /dev/null
+++ b/clang/test/SemaCXX/Inputs/enum-constexpr-conversion-system-header.h
@@ -0,0 +1,19 @@
+// System header for testing that -Wenum-constexpr-conversion leads to an error
+// when included in user code, or when the system macro is used.
+
+enum SystemEnum
+{
+a = 0,
+b = 1,
+};
+
+void testValueInRangeOfEnumerationValuesInSystemHeader()
+{
+constexpr SystemEnum x1 = static_cast(123);
+// expected-error@-1 {{integer value 123 is outside the valid range of 
values [0, 1] for the enumeration type 'SystemEnum'}}
+
+const SystemEnum x2 = static_cast(123);  // ok, not a constant 
expression context
+}
+
+#define CONSTEXPR_CAST_TO_SYSTEM_ENUM_OUTSIDE_OF_RANGE \
+constexpr SystemEnum system_enum = static_cast(123)

diff  --git a/clang/test/SemaCXX/constant-expression-cxx11.cpp 
b/clang/test/SemaCXX/constant-expression-cxx11.cpp
index 89d1b3ea6de05ea..8fb994224853bf1 100644
--- a/clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify=expected,cxx20_23,cxx23
-triple x86_64-linux -Wno-string-plus-int -Wno-pointer-arith 
-Wno-zero-length-array -Wno-c99-designator -fcxx-exceptions -pedantic %s 
-Wno-comment -Wno-tautological-pointer-compare -Wno-bool-conversion
-// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected,cxx11_20,cxx20_23 
-triple x86_64-linux -Wno-string-plus-int -Wno-pointer-arith 
-Wno-zero-length-array -Wno-c99-designator -fcxx-exceptions -pedantic %s 
-Wno-comment -Wno-tautological-pointer-compare -Wno-bool-conversion
-// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify=expected,cxx11_20,cxx11
-triple x86_64-linux -Wno-string-plus-int -Wno-pointer-arith 
-Wno-zero-length-array -Wno-c99-designator -fcxx-exceptions -pedantic %s 
-Wno-comment -Wno-tautological-pointer-compare -Wno-bool-conversion
+// RUN: %clang_cc1 -std=c++23 -isystem %S/Inputs -fsyntax-only 
-verify=expected,cxx20_23,cxx23-triple x86_64-linux -Wno-string-plus-int 
-Wno-pointer-arith -Wno-zero-length-array -Wno-c99-designator -fcxx-exceptions 
-pedantic %s -Wno-comment -Wno-tautological-pointer-compare -Wno-bool-conversion
+// RUN: %clang_cc1 -std=c++20 -isystem %S/Inputs -fsyntax-only 
-verify=expected,cxx11_20,cxx20_23 -triple x86_64-linux -Wno-string-plus-int 
-Wno-poi

[clang] [clang] Enable Wenum-constexpr-conversion also in system headers and … (PR #67528)

2023-10-14 Thread Carlos Galvez via cfe-commits
Carlos =?utf-8?q?Gálvez?= 
Message-ID:
In-Reply-To: 


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


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

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

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

LGTM!

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


[clang] [Clang] Add __datasizeof (PR #67805)

2023-10-14 Thread via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/67805

>From e6770ca7735285e1e669032a5a99b07709957803 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Fri, 29 Sep 2023 15:45:56 +0200
Subject: [PATCH] [Clang] Add __datasizeof

---
 clang/docs/LanguageExtensions.rst| 12 ++
 clang/docs/ReleaseNotes.rst  |  3 ++
 clang/include/clang/Basic/Features.def   |  1 +
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/lib/AST/ExprConstant.cpp   | 20 +++--
 clang/lib/AST/ItaniumMangle.cpp  |  9 
 clang/lib/Parse/ParseExpr.cpp| 35 
 clang/lib/Sema/SemaExpr.cpp  |  5 ++-
 clang/test/SemaCXX/datasizeof.cpp| 53 
 9 files changed, 125 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/SemaCXX/datasizeof.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index b9466b5a0bc2087..98cb3de39284ef1 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -424,6 +424,18 @@ Builtin Macros
   "UTF-16" or "UTF-32" (but may change in the future if the
   ``-fwide-exec-charset="Encoding-Name"`` option is implemented.)
 
+Implementation-defined keywords
+===
+
+__datasizeof
+
+
+``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
+type ignoring tail padding.
+
+..
+  FIXME: This should list all the keyword extensions
+
 .. _langext-vectors:
 
 Vectors and Extended Vectors
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ea737fdb5fdad15..5421eb6c151f223 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -155,6 +155,9 @@ C23 Feature Support
 Non-comprehensive list of changes in this release
 -
 
+- The ``__datasizeof`` keyword has been added. It is similar to ``sizeof``
+  except that it returns the size of a type ignoring tail padding.
+
 New Compiler Flags
 --
 
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index cf626d0120cc7c7..4a4503ac2ec375d 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -277,6 +277,7 @@ EXTENSION(gnu_asm_goto_with_outputs_full, LangOpts.GNUAsm)
 EXTENSION(matrix_types, LangOpts.MatrixTypes)
 EXTENSION(matrix_types_scalar_division, true)
 EXTENSION(cxx_attributes_on_using_declarations, LangOpts.CPlusPlus11)
+EXTENSION(datasizeof, LangOpts.CPlusPlus)
 
 FEATURE(builtin_headers_in_system_modules, 
LangOpts.BuiltinHeadersInSystemModules)
 FEATURE(cxx_abi_relative_vtable, LangOpts.CPlusPlus && 
LangOpts.RelativeCXXABIVTables)
diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 94db56a9fd5d78c..7b6ac3bf81b1e46 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -310,6 +310,7 @@ KEYWORD(return  , KEYALL)
 KEYWORD(short   , KEYALL)
 KEYWORD(signed  , KEYALL)
 UNARY_EXPR_OR_TYPE_TRAIT(sizeof, SizeOf, KEYALL)
+UNARY_EXPR_OR_TYPE_TRAIT(__datasizeof, DataSizeOf, KEYCXX)
 KEYWORD(static  , KEYALL)
 KEYWORD(struct  , KEYALL)
 KEYWORD(switch  , KEYALL)
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5a33e918db8e8c0..c955234ef1bdebd 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -3226,9 +3226,14 @@ static bool HandleLValueIndirectMember(EvalInfo &Info, 
const Expr *E,
   return true;
 }
 
+enum class SizeOfType {
+  SizeOf,
+  DataSizeOf,
+};
+
 /// Get the size of the given type in char units.
-static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
- QualType Type, CharUnits &Size) {
+static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
+ CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) 
{
   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
   // extension.
   if (Type->isVoidType() || Type->isFunctionType()) {
@@ -3248,7 +3253,10 @@ static bool HandleSizeof(EvalInfo &Info, SourceLocation 
Loc,
 return false;
   }
 
-  Size = Info.Ctx.getTypeSizeInChars(Type);
+  if (SOT == SizeOfType::SizeOf)
+Size = Info.Ctx.getTypeSizeInChars(Type);
+  else
+Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
   return true;
 }
 
@@ -13576,6 +13584,7 @@ bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
   return Success(1, E);
   }
 
+  case UETT_DataSizeOf:
   case UETT_SizeOf: {
 QualType SrcTy = E->getTypeOfArgument();
 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
@@ -13584,8 +13593,11 @@ bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
   SrcTy = Ref->getPoin

[clang] [Clang] Add __datasizeof (PR #67805)

2023-10-14 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 5e1c2bf3e6fca35ee0445b2a81d47e8576024186 
e6770ca7735285e1e669032a5a99b07709957803 -- clang/test/SemaCXX/datasizeof.cpp 
clang/lib/AST/ExprConstant.cpp clang/lib/AST/ItaniumMangle.cpp 
clang/lib/Parse/ParseExpr.cpp clang/lib/Sema/SemaExpr.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 0d3e8d63072e..50051e6c1185 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -16798,10 +16798,10 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation 
BuiltinLoc,
 : diag::ext_offsetof_non_pod_type;
 
   if (!IsSafe && !DidWarnAboutNonPOD &&
-  DiagRuntimeBehavior(BuiltinLoc, nullptr,
-  PDiag(DiagID)
-  << SourceRange(Components[0].LocStart, OC.LocEnd)
-  << CurrentType))
+  DiagRuntimeBehavior(
+  BuiltinLoc, nullptr,
+  PDiag(DiagID) << SourceRange(Components[0].LocStart, OC.LocEnd)
+<< CurrentType))
 DidWarnAboutNonPOD = true;
 }
 

``




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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Emilia Kond (rymiel)


Changes

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

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

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

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

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


2 Files Affected:

- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+6-3) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+38) 


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

``




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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

2023-10-14 Thread via cfe-commits

https://github.com/AMS21 updated https://github.com/llvm/llvm-project/pull/69045

>From acf77633498bb0f8b67760628f0ac54f772ad1ac Mon Sep 17 00:00:00 2001
From: AMS21 
Date: Sat, 14 Oct 2023 10:26:36 +0200
Subject: [PATCH] [clang-tidy] Ignore unused parameters in
 `rvalue-reference-param-not-moved check`

With this patch we no longer issue a warning for unused parameters which
are marked as such.

This fixes #68209
---
 .../RvalueReferenceParamNotMovedCheck.cpp |  3 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 +++
 .../rvalue-reference-param-not-moved.rst  | 10 
 .../rvalue-reference-param-not-moved.cpp  | 25 +++
 4 files changed, 42 insertions(+)

diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
index efcaffb45d9ad8a..88b00dc17470f32 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
@@ -84,6 +84,9 @@ void RvalueReferenceParamNotMovedCheck::check(
   if (IgnoreUnnamedParams && Param->getName().empty())
 return;
 
+  if (!Param->isUsed() && Param->hasAttr())
+return;
+
   const auto *Function = dyn_cast(Param->getDeclContext());
   if (!Function)
 return;
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 03e5dc6f164af2a..c732d4904df13fa 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -237,6 +237,10 @@ Changes in existing checks
   ` check to ignore
   false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).
 
+- Improved :doc:`cppcoreguidelines-rvalue-reference-param-not-moved
+  ` check
+  to ignore unused parameters when they are marked as unused.
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst
index 9ab4ae7871e46e4..ffa3a9d61e48e9d 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst
@@ -18,6 +18,16 @@ Example:
 std::string Copy(Input); // Oops - forgot to std::move
   }
 
+Note that parameters that are unused and marked as such will not be diagnosed.
+
+Example:
+
+.. code-block:: c++
+
+  void conditional_use([[maybe_unused]] std::string&& Input) {
+// No diagnostic here since Input is unused and marked as such
+  }
+
 Options
 ---
 
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
index 8f8e272e1e8a90d..a9b87567a08cc0a 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
@@ -333,3 +333,28 @@ void instantiate_a_class_template() {
   AClassTemplate withObjRef(o);
   withObjRef.never_moves(o);
 }
+
+namespace gh68209
+{
+  void f1([[maybe_unused]] int&& x) {}
+
+  void f2(__attribute__((unused)) int&& x) {}
+
+  void f3(int&& x) {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: rvalue reference parameter 'x' 
is never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
+
+  template 
+  void f4([[maybe_unused]] T&& x) {}
+
+  template 
+  void f5(__attribute((unused)) T&& x) {}
+
+  template
+  void f6(T&& x) {}
+
+  void f7([[maybe_unused]] int&& x) { x += 1; }
+  // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: rvalue reference parameter 'x' 
is never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
+
+  void f8(__attribute__((unused)) int&& x) { x += 1; }
+  // CHECK-MESSAGES: :[[@LINE-1]]:41: warning: rvalue reference parameter 'x' 
is never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
+} // namespace gh68209

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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

2023-10-14 Thread via cfe-commits

AMS21 wrote:

Added the suggested change and also added another test case

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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

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

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


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


[clang] 343bed8 - Canonically identical types are allowed in compound expressions in C

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

Author: Aaron Ballman
Date: 2023-10-14T11:03:35-04:00
New Revision: 343bed8d3a9b632594a3f786bbb189613975d51e

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

LOG: Canonically identical types are allowed in compound expressions in C

We did not have a catch-all for when the two operand types are
identical after canonicalization. Instead, we handled that on a case by
case basis. Thus, we would diagnose code like:
```
mat4 test(int a) {
  typedef float mat4 __attribute((matrix_type(4, 4)));
  mat4 transform;
  return (a > 0) ? transform : transform;
}
```
This simplifies the logic and will be more forwards
compatible with other extended datatypes.

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

Added: 


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

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ade3c33b3b9444c..be7c8bf247f7af5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -386,10 +386,13 @@ Bug Fixes in This Version
   cannot be used with ``Release`` mode builds. (`#68237 
`_).
 - Fix crash in evaluating ``constexpr`` value for invalid template function.
   Fixes (`#68542 `_)
-
 - Fixed an issue when a shift count larger than ``__INT64_MAX__``, in a right
   shift operation, could result in missing warnings about
   ``shift count >= width of type`` or internal compiler error.
+- Fixed an issue with computing the common type for the LHS and RHS of a `?:`
+  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 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index d78f923b2cb2cb3..aa30a3a03887558 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -9186,7 +9186,7 @@ QualType Sema::CheckConditionalOperands(ExprResult &Cond, 
ExprResult &LHS,
   if (checkCondition(*this, Cond.get(), QuestionLoc))
 return QualType();
 
-  // Now check the two expressions.
+  // Handle vectors.
   if (LHS.get()->getType()->isVectorType() ||
   RHS.get()->getType()->isVectorType())
 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
@@ -9244,11 +9244,6 @@ QualType Sema::CheckConditionalOperands(ExprResult 
&Cond, ExprResult &LHS,
 return ResTy;
   }
 
-  // And if they're both bfloat (which isn't arithmetic), that's fine too.
-  if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
-return Context.getCommonSugaredType(LHSTy, RHSTy);
-  }
-
   // If both operands are the same structure or union type, the result is that
   // type.
   if (const RecordType *LHSRT = LHSTy->getAs()) {// C99 
6.5.15p3
@@ -9320,17 +9315,17 @@ QualType Sema::CheckConditionalOperands(ExprResult 
&Cond, ExprResult &LHS,
   /*IsIntFirstExpr=*/false))
 return LHSTy;
 
-  // Allow ?: operations in which both operands have the same
-  // built-in sizeless type.
-  if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
-return Context.getCommonSugaredType(LHSTy, RHSTy);
-
   // Emit a better diagnostic if one of the expressions is a null pointer
   // constant and the other is not a pointer type. In this case, the user most
   // likely forgot to take the address of the other expression.
   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
 return QualType();
 
+  // Finally, if the LHS and RHS types are canonically the same type, we can
+  // use the common sugared type.
+  if (Context.hasSameType(LHSTy, RHSTy))
+return Context.getCommonSugaredType(LHSTy, RHSTy);
+
   // Otherwise, the operands are not compatible.
   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
 << LHSTy << RHSTy << LHS.get()->getSourceRange()

diff  --git a/clang/test/Sema/conditional.c b/clang/test/Sema/conditional.c
index 666ac5416322d5d..cebdb7b4043a392 100644
--- a/clang/test/Sema/conditional.c
+++ b/clang/test/Sema/conditional.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -fsyntax-only -verify
+// RUN: %clang_cc1 %s -fsyntax-only -fenable-matrix -verify
 
 const char* test1 = 1 ? "i" : 1 == 1 ? "v" : "r";
 
@@ -19,3 +19,15 @@ void pr39809(void) {
   _Generic(0 ? (int volatile*)0 : (void const*)1, void volatile const*: 
(void)0);
   _Generic(0 ? (int volatile*)0 : (void const*)0, void volatile const*: 
(void)0);
 }
+
+// Ensure we compute the correct common type for extension types as well.
+void GH6

[PATCH] D153701: [Clang] Implement P2718R0 "Lifetime extension in range-based for loops"

2023-10-14 Thread Yurong via Phabricator via cfe-commits
yronglin updated this revision to Diff 557705.
yronglin added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153701

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/test/AST/ast-dump-for-range-lifetime.cpp
  clang/test/CXX/special/class.temporary/p6.cpp

Index: clang/test/CXX/special/class.temporary/p6.cpp
===
--- clang/test/CXX/special/class.temporary/p6.cpp
+++ clang/test/CXX/special/class.temporary/p6.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm -o - | FileCheck %s --implicit-check-not='call{{.*}}dtor'
+// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK-CXX23,CHECK-CXX23-NEXT
 
 namespace std {
   typedef decltype(sizeof(int)) size_t;
@@ -238,3 +239,236 @@
   // CHECK: call {{.*}}dtor
   // CHECK: }
 }
+
+namespace P2718R0 {
+
+// Test basic
+struct A {
+  int a[3] = {1, 2, 3};
+  A() {}
+  ~A() {}
+  const int *begin() const { return a; }
+  const int *end() const { return a + 3; }
+  A& r() { return *this; }
+  A g() { return A(); }
+};
+
+A g() { return A(); }
+const A &f1(const A &t) { return t; }
+
+void test1() {
+  [[maybe_unused]] int sum = 0;
+  // CHECK-CXX23: void @_ZN7P2718R05test1Ev()
+  // CHECK-CXX23: for.cond.cleanup:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: br label %for.end
+  for (auto e : f1(g()))
+sum += e;
+}
+
+struct B : A {};
+int (&f(const A *))[3];
+const A *g(const A &);
+void bar(int) {}
+
+void test2() {
+  // CHECK-CXX23: void @_ZN7P2718R05test2Ev()
+  // CHECK-CXX23: for.cond.cleanup:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01BD1Ev(
+  // CHECK-CXX23-NEXT: br label %for.end
+  for (auto e : f(g(B(
+bar(e);
+}
+
+// Test discard statement.
+struct LockGuard {
+LockGuard() {}
+~LockGuard() {}
+};
+
+void test3() {
+  int v[] = {42, 17, 13};
+
+  // CHECK-CXX23: void @_ZN7P2718R05test3Ev()
+  // CHECK-CXX23: for.cond.cleanup:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R09LockGuardD1Ev(
+  // CHECK-CXX23-NEXT: br label %for.end
+  for ([[maybe_unused]] int x : static_cast(LockGuard()), v)
+LockGuard guard;
+  
+  // CHECK-CXX23: for.cond.cleanup11:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R09LockGuardD1Ev(
+  // CHECK-CXX23-NEXT: br label %for.end17
+  for ([[maybe_unused]] int x : (void)LockGuard(), v)
+LockGuard guard;
+  
+  // CHECK-CXX23: for.cond.cleanup27:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R09LockGuardD1Ev(
+  // CHECK-CXX23-NEXT: br label %for.end33
+  for ([[maybe_unused]] int x : LockGuard(), v)
+LockGuard guard;
+}
+
+// Test default arg
+int (&default_arg_fn(const A & = A()))[3];
+void test4() {
+
+  // CHECK-CXX23: void @_ZN7P2718R05test4Ev()
+  // CHECK-CXX23: for.cond.cleanup:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: br label %for.end
+  for (auto e : default_arg_fn()) 
+bar(e);
+}
+
+struct DefaultA {
+  DefaultA() {}
+  ~DefaultA() {}
+};
+
+A foo(const A&, const DefaultA &Default = DefaultA()) {
+  return A();
+}
+
+void test5() {
+  // CHECK-CXX23: void @_ZN7P2718R05test5Ev()
+  // CHECK-CXX23: for.cond.cleanup:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R08DefaultAD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R08DefaultAD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R08DefaultAD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: br label %for.end
+  for (auto e : default_arg_fn(foo(foo(foo(A())
+bar(e);
+}
+
+struct C : public A {
+  C() {}
+  C(int, const C &, const DefaultA & = DefaultA()) {}
+};
+
+void test6() {
+  // CHECK-CXX23: void @_ZN7P2718R05test6Ev()
+  // CHECK-CXX23: for.cond.cleanup:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01CD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R08DefaultAD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01CD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R08DefaultAD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01CD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R08DefaultAD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01CD1Ev(
+  // CHECK-CXX23: br label %for.end
+  for (auto e : C(0, C(0, C(0, C()
+bar(e);
+}
+
+// Test member call
+void test7() {
+  // CHECK-CXX23: void @_ZN7P2718R05test7Ev()
+  // CHECK-CXX23: for.cond.cleanup:
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23-NEXT: call void @_ZN7P2718R01AD1Ev(
+  // CHECK-CXX23

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

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

https://github.com/steakhal created 
https://github.com/llvm/llvm-project/pull/69057

When doing a base to derived cast, and we should add a cast info recording that 
fact.
This information will be then used for example inside 
`CXXInstanceCall::getRuntimeDefinition` (CallEvent.cpp), where for virtual 
calls, it will query the associated dynamic type for the `*this` region.

Note that inside `ExprEngine::defaultEvalCall`, if the runtime definition is 
found but it might have other definitions, then we will split the path and have 
one where we inline the candidate and one other doing conservative call 
evaluation. This ensures that if we inlined the wrong definition, we still have 
a path where conservative evaluation happened. In addition to this, remember 
that once a function was conservatively evaluated on a path, then further calls 
to the same function will always result in conservative evaluation, see 
`ExprEngine::BifurcateCall` and the `DynamicDispatchBifurcationMap`.

As a consequence of these rules, we can have execution paths where a function 
call might be resolved to different implemetations, depending on the sequence 
of events, like here:

```C++
void top(Base *p) {
  p->fun(); // Will split into 2 paths:
  // 1) Inlines the virtual `Base::fun()`.
  // 2) Conservative eval calls, and remembers to always conservatively eval 
this function.

  // Perform a base to derived cast, and just discard the result.
  (void)static_cast(p);

  p->fun(); // Will split path (1) into 2:
  // 2.1) Inlines the virtual `Derived::fun()`.
  // 2.2) Conservative eval calls, and remembers to always conservatively eval 
this function.

  // Now, we have exactly 3 paths at this point.
}
```

Fixes #62663

>From 8ed4effd114ebd83d4ceaa37655ffd9b7105b28e Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Sat, 14 Oct 2023 15:51:42 +0200
Subject: [PATCH] [analyzer] Trust base to derived casts for dynamic types

When doing a base to derived cast, and we should add a cast info
recording that fact.
This information will be then used for example inside
`CXXInstanceCall::getRuntimeDefinition` (CallEvent.cpp), where for
virtual calls, it will query the associated dynamic type for the `*this` region.

Note that inside `ExprEngine::defaultEvalCall`, if the runtime
definition is found but it might have other definitions, then we will
split the path and have one where we inline the candidate and one other
doing conservative call evaluation. This ensures that if we inlined the
wrong definition, we still have a path where conservative evaluation happened.
In addition to this, remember that once a function was conservatively
evaluated on a path, then further calls to the same function will always
result in conservative evaluation, see `ExprEngine::BifurcateCall` and
the `DynamicDispatchBifurcationMap`.

As a consequence of these rules, we can have execution paths where a
function call might be resolved to different implemetations, depending
on the sequence of events, like here:

```C++
void top(Base *p) {
  p->fun(); // Will split into 2 paths:
  // 1) Inlines the virtual `Base::fun()`.
  // 2) Conservative eval calls, and remembers to always conservatively eval 
this function.

  // Perform a base to derived cast, and just discard the result.
  (void)static_cast(p);

  p->fun(); // Will split path (1) into 2:
  // 2.1) Inlines the virtual `Derived::fun()`.
  // 2.2) Conservative eval calls, and remembers to always conservatively eval 
this function.

  // Now, we have exactly 3 paths at this point.
}
```

Fixes #62663
---
 .../Checkers/DynamicTypePropagation.cpp   |  27 +++--
 .../Analysis/cast-trust-base-to-derived.cpp   | 105 ++
 .../test/Analysis/osobject-retain-release.cpp |  12 +-
 3 files changed, 129 insertions(+), 15 deletions(-)
 create mode 100644 clang/test/Analysis/cast-trust-base-to-derived.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp 
b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
index eda8302595ba4fb..6539f3c1e09e321 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
@@ -20,6 +20,7 @@
 //
 
//===--===//
 
+#include "clang/AST/OperationKinds.h"
 #include "clang/AST/ParentMap.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/Builtins.h"
@@ -392,10 +393,6 @@ void DynamicTypePropagation::checkPostCall(const CallEvent 
&Call,
   }
 }
 
-/// TODO: Handle explicit casts.
-///   Handle C++ casts.
-///
-/// Precondition: the cast is between ObjCObjectPointers.
 ExplodedNode *DynamicTypePropagation::dynamicTypePropagationOnCasts(
 const CastExpr *CE, ProgramStateRef &State, CheckerContext &C) const {
   // We only track type info for regions.
@@ -403,8 +400,19 @@ ExplodedNode 
*DynamicTypePropagation::dynamicTypePropagationOnCasts(
   if (!ToR)
 return C.getPredecessor

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

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Balazs Benics (steakhal)


Changes

When doing a base to derived cast, and we should add a cast info recording that 
fact.
This information will be then used for example inside 
`CXXInstanceCall::getRuntimeDefinition` (CallEvent.cpp), where for virtual 
calls, it will query the associated dynamic type for the `*this` region.

Note that inside `ExprEngine::defaultEvalCall`, if the runtime definition is 
found but it might have other definitions, then we will split the path and have 
one where we inline the candidate and one other doing conservative call 
evaluation. This ensures that if we inlined the wrong definition, we still have 
a path where conservative evaluation happened. In addition to this, remember 
that once a function was conservatively evaluated on a path, then further calls 
to the same function will always result in conservative evaluation, see 
`ExprEngine::BifurcateCall` and the `DynamicDispatchBifurcationMap`.

As a consequence of these rules, we can have execution paths where a function 
call might be resolved to different implemetations, depending on the sequence 
of events, like here:

```C++
void top(Base *p) {
  p->fun(); // Will split into 2 paths:
  // 1) Inlines the virtual `Base::fun()`.
  // 2) Conservative eval calls, and remembers to always conservatively eval 
this function.

  // Perform a base to derived cast, and just discard the result.
  (void)static_cast(p);

  p->fun(); // Will split path (1) into 2:
  // 2.1) Inlines the virtual `Derived::fun()`.
  // 2.2) Conservative eval calls, and remembers to always conservatively eval 
this function.

  // Now, we have exactly 3 paths at this point.
}
```

Fixes #62663

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


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp 
(+17-10) 
- (added) clang/test/Analysis/cast-trust-base-to-derived.cpp (+105) 
- (modified) clang/test/Analysis/osobject-retain-release.cpp (+7-5) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp 
b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
index eda8302595ba4fb..6539f3c1e09e321 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
@@ -20,6 +20,7 @@
 //
 
//===--===//
 
+#include "clang/AST/OperationKinds.h"
 #include "clang/AST/ParentMap.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/Builtins.h"
@@ -392,10 +393,6 @@ void DynamicTypePropagation::checkPostCall(const CallEvent 
&Call,
   }
 }
 
-/// TODO: Handle explicit casts.
-///   Handle C++ casts.
-///
-/// Precondition: the cast is between ObjCObjectPointers.
 ExplodedNode *DynamicTypePropagation::dynamicTypePropagationOnCasts(
 const CastExpr *CE, ProgramStateRef &State, CheckerContext &C) const {
   // We only track type info for regions.
@@ -403,8 +400,19 @@ ExplodedNode 
*DynamicTypePropagation::dynamicTypePropagationOnCasts(
   if (!ToR)
 return C.getPredecessor();
 
-  if (isa(CE))
+  if (CE->getCastKind() == CK_BaseToDerived) {
+bool CastSucceeds = true;
+QualType FromTy = CE->getSubExpr()->getType();
+QualType ToTy = CE->getType();
+ToR = ToR->StripCasts(/*StripBaseAndDerivedCasts=*/true);
+State = setDynamicTypeAndCastInfo(State, ToR, FromTy, ToTy, CastSucceeds);
+return C.addTransition(State);
+  }
+
+  // TODO: Handle the rest of explicit casts, inluding the regular C++ casts.
+  if (isa(CE)) {
 return C.getPredecessor();
+  }
 
   if (const Type *NewTy = getBetterObjCType(CE, C)) {
 State = setDynamicTypeInfo(State, ToR, QualType(NewTy, 0));
@@ -609,9 +617,13 @@ storeWhenMoreInformative(ProgramStateRef &State, SymbolRef 
Sym,
 /// symbol and the destination type of the cast are unrelated, report an error.
 void DynamicTypePropagation::checkPostStmt(const CastExpr *CE,
CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  ExplodedNode *AfterTypeProp = dynamicTypePropagationOnCasts(CE, State, C);
+
   if (CE->getCastKind() != CK_BitCast)
 return;
 
+  ASTContext &ASTCtxt = C.getASTContext();
   QualType OriginType = CE->getSubExpr()->getType();
   QualType DestType = CE->getType();
 
@@ -621,11 +633,6 @@ void DynamicTypePropagation::checkPostStmt(const CastExpr 
*CE,
   if (!OrigObjectPtrType || !DestObjectPtrType)
 return;
 
-  ProgramStateRef State = C.getState();
-  ExplodedNode *AfterTypeProp = dynamicTypePropagationOnCasts(CE, State, C);
-
-  ASTContext &ASTCtxt = C.getASTContext();
-
   // This checker detects the subtyping relationships using the assignment
   // rules. In order to be able to do this the kindofness must be stripped
   // first. The checker treats every type as kindof type anyways: when the
diff --git a/

[clang] Remove warnings from -Wchar-subscripts for known positive constants (PR #69061)

2023-10-14 Thread via cfe-commits

https://github.com/wheatman created 
https://github.com/llvm/llvm-project/pull/69061

This is to address https://github.com/llvm/llvm-project/issues/18763

it removes warnings from using a signed char as an array bound if the char is a 
known positives constant.

This goes one step farther than gcc does.

For example given the following code
```c++
char upper[300];

int main() {
  upper['a'] = 'A';
  char b = 'a';
  upper[b] = 'A';
  const char c = 'a';
  upper[c] = 'A';
  constexpr char d = 'a';
  upper[d] = 'A';
  char e = -1;
  upper[e] = 'A';
  const char f = -1;
  upper[f] = 'A';
  constexpr char g = -1;
  upper[g] = 'A';
  return 1;
}
```

clang currently gives warnings for all cases, while gcc gives warnings for all 
cases except for 'a' (https://godbolt.org/z/5ahjETTv3)

with the change there is no longer any warning for 'a', 'c', or 'd'.

```
../test.cpp:7:8: warning: array subscript is of type 'char' [-Wchar-subscripts]
7 |   upper[b] = 'A';
  |^~
../test.cpp:13:8: warning: array subscript is of type 'char' [-Wchar-subscripts]
   13 |   upper[e] = 'A';
  |^~
../test.cpp:15:8: warning: array subscript is of type 'char' [-Wchar-subscripts]
   15 |   upper[f] = 'A';
  |^~
../test.cpp:17:8: warning: array subscript is of type 'char' [-Wchar-subscripts]
   17 |   upper[g] = 'A';
  |^~
../test.cpp:15:3: warning: array index -1 is before the beginning of the array 
[-Warray-bounds]
   15 |   upper[f] = 'A';
  |   ^ ~
../test.cpp:1:1: note: array 'upper' declared here
1 | char upper[300];
  | ^
../test.cpp:17:3: warning: array index -1 is before the beginning of the array 
[-Warray-bounds]
   17 |   upper[g] = 'A';
  |   ^ ~
../test.cpp:1:1: note: array 'upper' declared here
1 | char upper[300];
  | ^
6 warnings generated.
```

This pull request in incomplete in that this is my first change submitted and I 
don't know how to add tests, any guidance on what sort of tests to add, and 
where to find documentation on the testing infrastructure  

>From b3111e99b8caf875bca6c59c5ac78cfc0a9f0d0f Mon Sep 17 00:00:00 2001
From: Brian Wheatman 
Date: Sat, 14 Oct 2023 12:02:19 -0400
Subject: [PATCH] Remove warnings from -Wchar-subscripts for known positive
 constants

---
 clang/lib/Sema/SemaExpr.cpp | 12 +---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index aa30a3a03887558..dd9ba5cecaf2404 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6018,9 +6018,15 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, 
SourceLocation LLoc,
  << IndexExpr->getSourceRange());
 
   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
-   IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
- && !IndexExpr->isTypeDependent())
-Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
+   IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
+  !IndexExpr->isTypeDependent()) {
+std::optional IntegerContantExpr =
+IndexExpr->getIntegerConstantExpr(getASTContext());
+if (!(IntegerContantExpr.has_value() &&
+  IntegerContantExpr.value().isNonNegative())) {
+  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
+}
+  }
 
   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object

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


[clang] Remove warnings from -Wchar-subscripts for known positive constants (PR #69061)

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (wheatman)


Changes

This is to address https://github.com/llvm/llvm-project/issues/18763

it removes warnings from using a signed char as an array bound if the char is a 
known positives constant.

This goes one step farther than gcc does.

For example given the following code
```c++
char upper[300];

int main() {
  upper['a'] = 'A';
  char b = 'a';
  upper[b] = 'A';
  const char c = 'a';
  upper[c] = 'A';
  constexpr char d = 'a';
  upper[d] = 'A';
  char e = -1;
  upper[e] = 'A';
  const char f = -1;
  upper[f] = 'A';
  constexpr char g = -1;
  upper[g] = 'A';
  return 1;
}
```

clang currently gives warnings for all cases, while gcc gives warnings for all 
cases except for 'a' (https://godbolt.org/z/5ahjETTv3)

with the change there is no longer any warning for 'a', 'c', or 'd'.

```
../test.cpp:7:8: warning: array subscript is of type 'char' [-Wchar-subscripts]
7 |   upper[b] = 'A';
  |^~
../test.cpp:13:8: warning: array subscript is of type 'char' [-Wchar-subscripts]
   13 |   upper[e] = 'A';
  |^~
../test.cpp:15:8: warning: array subscript is of type 'char' [-Wchar-subscripts]
   15 |   upper[f] = 'A';
  |^~
../test.cpp:17:8: warning: array subscript is of type 'char' [-Wchar-subscripts]
   17 |   upper[g] = 'A';
  |^~
../test.cpp:15:3: warning: array index -1 is before the beginning of the array 
[-Warray-bounds]
   15 |   upper[f] = 'A';
  |   ^ ~
../test.cpp:1:1: note: array 'upper' declared here
1 | char upper[300];
  | ^
../test.cpp:17:3: warning: array index -1 is before the beginning of the array 
[-Warray-bounds]
   17 |   upper[g] = 'A';
  |   ^ ~
../test.cpp:1:1: note: array 'upper' declared here
1 | char upper[300];
  | ^
6 warnings generated.
```

This pull request in incomplete in that this is my first change submitted and I 
don't know how to add tests, any guidance on what sort of tests to add, and 
where to find documentation on the testing infrastructure  

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaExpr.cpp (+9-3) 


``diff
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index aa30a3a03887558..dd9ba5cecaf2404 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6018,9 +6018,15 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, 
SourceLocation LLoc,
  << IndexExpr->getSourceRange());
 
   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
-   IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
- && !IndexExpr->isTypeDependent())
-Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
+   IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
+  !IndexExpr->isTypeDependent()) {
+std::optional IntegerContantExpr =
+IndexExpr->getIntegerConstantExpr(getASTContext());
+if (!(IntegerContantExpr.has_value() &&
+  IntegerContantExpr.value().isNonNegative())) {
+  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
+}
+  }
 
   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object

``




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


[clang-tools-extra] [clang-tidy][modernize-loop-convert]check isDependentSizedArrayType (PR #69062)

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

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/69062

None

>From bfeaa2eeaa3d20e1919288bcf1027ec196378236 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sun, 15 Oct 2023 00:20:08 +0800
Subject: [PATCH] [clang-tidy][modernize-loop-convert]check
 isDependentSizedArrayType before resolve type size

---
 .../clang-tidy/modernize/LoopConvertCheck.cpp| 1 +
 clang-tools-extra/docs/ReleaseNotes.rst  | 4 
 .../clang-tidy/checkers/modernize/loop-convert-basic.cpp | 9 +
 3 files changed, 14 insertions(+)

diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index f90d99a8d66069d..8beaa62c78ba0ab 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -753,6 +753,7 @@ void LoopConvertCheck::doConversion(
   bool IsCheapToCopy =
   !Descriptor.ElemType.isNull() &&
   Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
+  !Descriptor.ElemType->isDependentSizedArrayType() &&
   // TypeInfo::Width is in bits.
   Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
   bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 03e5dc6f164af2a..ae440210d8a4f2b 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -269,6 +269,10 @@ Changes in existing checks
   ` to support for-loops with
   iterators initialized by free functions like ``begin``, ``end``, or ``size``.
 
+- Improved :doc:`modernize-loop-convert
+   ` to avoid crash dor dependent
+   array.
+
 - Improved :doc:`modernize-return-braced-init-list
   ` check to ignore
   false-positives when constructing the container with ``count`` copies of
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
index 71ae4c46e6a5e95..8d8144a729bbdee 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
@@ -939,4 +939,13 @@ void fundamentalTypesTest() {
   // CHECK-FIXES: for (double Double : Doubles)
 }
 
+template  void test() {
+  unsigned int test[3][p];
+  // Initialize to zero
+  for (unsigned int i = 0; i < p; ++i)
+for (unsigned int j = 0; j < 3; ++j) // CHECK-MESSAGES: warning: use 
range-based for loop instead
+  // CHECK-FIXES: (auto & j : test)
+  test[j][i] = 0;
+}
+
 } // namespace PseudoArray

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


[PATCH] D153701: [Clang] Implement P2718R0 "Lifetime extension in range-based for loops"

2023-10-14 Thread Yurong via Phabricator via cfe-commits
yronglin marked 2 inline comments as done.
yronglin added a comment.

@rsmith Thanks a lot for your comments and sorry for the very late reply, I was 
on vacation some time ago.

In D153701#4643609 , @rsmith wrote:

> The changes in `SemaInit.cpp` don't look correct to me. Trying to recurse 
> through the initializer and find every nested temporary is highly 
> error-prone; I can't tell you which expression nodes you forgot to recurse 
> through, but I'm sure there are some.
>
> I think the approach being taken here is not really maintainable. We don't 
> want the initialization code to need to know how to recurse through an 
> expression after the fact and find all the temporaries that might need to be 
> lifetime-extended, and we don't need it to do that either. Instead, we should 
> make the expression evaluation context track the current for-range variable, 
> and in `Sema::CreateMaterializeTemporaryExpr`, we should create a temporary 
> that is already set to be lifetime-extended by the loop variable.

I agree, I have reverted the changes in `SemaInit.cpp`. I have ever tried to do 
lifetime-extend in `Sema::CreateMaterializeTemporaryExpr`, but I fall into some 
trouble, the `MaterializeTemporaryExpr` was created before the for-range 
VarDecl, so we don't have a VarDecl for 
`MaterializeTemporaryExpr::setExtendingDecl` in  
`Sema::CreateMaterializeTemporaryExpr`, I have a possible solution here, Eg. we 
allocate a memory block which has same size of VarDecl, and pass this pointer 
to `MaterializeTemporaryExpr::setExtendingDecl` as a placeholder VarDecl, when 
we build the for-range statement, we just construct a VarDecl in the memory 
block that we allocated before. But this approach doesn't look very good and 
not maintainable. So I use `ForRangeInitTemporaryLifetimeExtensionVisitor` to 
visit every temporaries in the initializer and extend the lifetime. And 
`ForRangeInitTemporaryLifetimeExtensionVisitor` was derived from 
`RecursiveASTVisitor`, maybe this approach be able to handle all temporaries. 
WDYT?




Comment at: clang/include/clang/Sema/Sema.h:1356-1357
 
+/// Whether rewrite the default argument.
+bool IsRewriteDefaultArgument = false;
+

rsmith wrote:
> Can you expand this comment to more fully describe what this flag governs? 
> Which default argument? How would it be rewritten?
Yeah, this variable has been removed. By default, all CallExprs in Clang share 
the same CXXDefaultArgExpr from parameters, but in some contexts (such as 
lifetime extension), the lifetime of the temporaries in the current default 
parameters needs to be extended, so the CXXDefaultArgExpr needs to be copied 
and the lifetime of temporaries in the copy need to be extended. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153701

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


[clang] Remove warnings from -Wchar-subscripts for known positive constants (PR #69061)

2023-10-14 Thread via cfe-commits

wheatman wrote:

I found the test I would want to modify here 
(llvm-project/clang/test/Sema/warn-char-subscripts.c)
I will work on updating it

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


[clang] 80737d2 - [clang][Interp][NFC] Pass PrimType to visitZeroInitializer()

2023-10-14 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-14T18:43:00+02:00
New Revision: 80737d2ddf05507d96cdd723fb33a6e44ac72a48

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

LOG: [clang][Interp][NFC] Pass PrimType to visitZeroInitializer()

This fixes an old FIXME comment. Almost all callers already classify()
the type anyway, so just pass the result of that
to visitZeroInitializer().

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 71aac8c6245c5af..bda9cf1500804f7 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -493,8 +493,8 @@ template 
 bool ByteCodeExprGen::VisitImplicitValueInitExpr(const 
ImplicitValueInitExpr *E) {
   QualType QT = E->getType();
 
-  if (classify(QT))
-return this->visitZeroInitializer(QT, E);
+  if (std::optional T = classify(QT))
+return this->visitZeroInitializer(*T, QT, E);
 
   if (QT->isRecordType())
 return false;
@@ -510,7 +510,7 @@ bool 
ByteCodeExprGen::VisitImplicitValueInitExpr(const ImplicitValueIni
   //   since we memset our Block*s to 0 and so we have the desired value
   //   without this.
   for (size_t I = 0; I != NumElems; ++I) {
-if (!this->visitZeroInitializer(CAT->getElementType(), E))
+if (!this->visitZeroInitializer(*ElemT, CAT->getElementType(), E))
   return false;
 if (!this->emitInitElem(*ElemT, I, E))
   return false;
@@ -620,7 +620,7 @@ bool ByteCodeExprGen::VisitInitListExpr(const 
InitListExpr *E) {
   if (std::optional T = classify(E->getType())) {
 assert(!DiscardResult);
 if (E->getNumInits() == 0)
-  return this->visitZeroInitializer(E->getType(), E);
+  return this->visitZeroInitializer(*T, E->getType(), E);
 assert(E->getNumInits() == 1);
 return this->delegate(E->inits()[0]);
   }
@@ -1560,7 +1560,8 @@ bool ByteCodeExprGen::VisitOffsetOfExpr(const 
OffsetOfExpr *E) {
 template 
 bool ByteCodeExprGen::VisitCXXScalarValueInitExpr(
 const CXXScalarValueInitExpr *E) {
-  return this->visitZeroInitializer(E->getType(), E);
+  return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
+E);
 }
 
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
@@ -1648,12 +1649,8 @@ bool ByteCodeExprGen::visitBool(const Expr *E) {
 }
 
 template 
-bool ByteCodeExprGen::visitZeroInitializer(QualType QT,
+bool ByteCodeExprGen::visitZeroInitializer(PrimType T, QualType QT,
 const Expr *E) {
-  // FIXME: We need the QualType to get the float semantics, but that means we
-  //   classify it over and over again in array situations.
-  PrimType T = classifyPrim(QT);
-
   switch (T) {
   case PT_Bool:
 return this->emitZeroBool(E);
@@ -1699,7 +1696,7 @@ bool 
ByteCodeExprGen::visitZeroRecordInitializer(const Record *R,
 if (D->isPrimitive()) {
   QualType QT = D->getType();
   PrimType T = classifyPrim(D->getType());
-  if (!this->visitZeroInitializer(QT, E))
+  if (!this->visitZeroInitializer(T, QT, E))
 return false;
   if (!this->emitInitField(T, Field.Offset, E))
 return false;
@@ -1716,7 +1713,7 @@ bool 
ByteCodeExprGen::visitZeroRecordInitializer(const Record *R,
   QualType ET = D->getElemQualType();
   PrimType T = classifyPrim(ET);
   for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
-if (!this->visitZeroInitializer(ET, E))
+if (!this->visitZeroInitializer(T, ET, E))
   return false;
 if (!this->emitInitElem(T, I, E))
   return false;

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 7cfe4d9251c5f05..2049dab140eaaae 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -222,7 +222,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   friend class SourceLocScope;
 
   /// Emits a zero initializer.
-  bool visitZeroInitializer(QualType QT, const Expr *E);
+  bool visitZeroInitializer(PrimType T, QualType QT, const Expr *E);
   bool visitZeroRecordInitializer(const Record *R, const Expr *E);
 
   enum class DerefKind {



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


[clang] Remove warnings from -Wchar-subscripts for known positive constants (PR #69061)

2023-10-14 Thread via cfe-commits

https://github.com/wheatman updated 
https://github.com/llvm/llvm-project/pull/69061

>From 44e66636bd886b263a15fe9e49d575d8ea53592d Mon Sep 17 00:00:00 2001
From: Brian Wheatman 
Date: Sat, 14 Oct 2023 12:02:19 -0400
Subject: [PATCH] Remove warnings from -Wchar-subscripts for known positive
 constants

---
 clang/lib/Sema/SemaExpr.cpp  |  12 ++-
 clang/test/Sema/warn-char-subscripts.c   |  25 ++
 clang/test/Sema/warn-char-subscripts.cpp | 103 +++
 3 files changed, 137 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/warn-char-subscripts.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index aa30a3a03887558..dd9ba5cecaf2404 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6018,9 +6018,15 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, 
SourceLocation LLoc,
  << IndexExpr->getSourceRange());
 
   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
-   IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
- && !IndexExpr->isTypeDependent())
-Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
+   IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
+  !IndexExpr->isTypeDependent()) {
+std::optional IntegerContantExpr =
+IndexExpr->getIntegerConstantExpr(getASTContext());
+if (!(IntegerContantExpr.has_value() &&
+  IntegerContantExpr.value().isNonNegative())) {
+  Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
+}
+  }
 
   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
diff --git a/clang/test/Sema/warn-char-subscripts.c 
b/clang/test/Sema/warn-char-subscripts.c
index 2e72d90fa612aed..61409c0a50daf47 100644
--- a/clang/test/Sema/warn-char-subscripts.c
+++ b/clang/test/Sema/warn-char-subscripts.c
@@ -62,3 +62,28 @@ void t10(void) {
   UnsignedCharTy subscript = 0;
   int val = array[subscript]; // no warning for unsigned char
 }
+
+void t11(void) {
+  int array[256] = { 0 };
+  int val = array['a']; // no warning for char with known positive value
+}
+
+void t12(void) {
+  int array[256] = { 0 };
+  char b = 'a';
+  int val = array[b]; // expected-warning{{array subscript is of type 'char'}}
+}
+
+void t13(void) {
+  int array[256] = { 0 };
+  const char b = 'a';
+  int val = array[b]; // expected-warning{{array subscript is of type 'char'}}
+}
+
+void t14(void) {
+  int array[256] = { 0 }; // expected-note {{array 'array' declared here}}
+  const char b = -1;
+  // expected-warning@+2 {{array subscript is of type 'char'}}
+  // expected-warning@+1 {{array index -1 is before the beginning of the 
array}}
+  int val = array[b];
+}
\ No newline at end of file
diff --git a/clang/test/Sema/warn-char-subscripts.cpp 
b/clang/test/Sema/warn-char-subscripts.cpp
new file mode 100644
index 000..21b991d83590937
--- /dev/null
+++ b/clang/test/Sema/warn-char-subscripts.cpp
@@ -0,0 +1,103 @@
+// RUN: %clang_cc1 -Wchar-subscripts -fsyntax-only -verify %s
+
+void t1(void) {
+  int array[1] = { 0 };
+  char subscript = 0;
+  int val = array[subscript]; // expected-warning{{array subscript is of type 
'char'}}
+}
+
+void t2(void) {
+  int array[1] = { 0 };
+  char subscript = 0;
+  int val = subscript[array]; // expected-warning{{array subscript is of type 
'char'}}
+}
+
+void t3(void) {
+  int *array = 0;
+  char subscript = 0;
+  int val = array[subscript]; // expected-warning{{array subscript is of type 
'char'}}
+}
+
+void t4(void) {
+  int *array = 0;
+  char subscript = 0;
+  int val = subscript[array]; // expected-warning{{array subscript is of type 
'char'}}
+}
+
+char returnsChar(void);
+void t5(void) {
+  int *array = 0;
+  int val = array[returnsChar()]; // expected-warning{{array subscript is of 
type 'char'}}
+}
+
+void t6(void) {
+  int array[1] = { 0 };
+  signed char subscript = 0;
+  int val = array[subscript]; // no warning for explicit signed char
+}
+
+void t7(void) {
+  int array[1] = { 0 };
+  unsigned char subscript = 0;
+  int val = array[subscript]; // no warning for unsigned char
+}
+
+typedef char CharTy;
+void t8(void) {
+  int array[1] = { 0 };
+  CharTy subscript = 0;
+  int val = array[subscript]; // expected-warning{{array subscript is of type 
'char'}}
+}
+
+typedef signed char SignedCharTy;
+void t9(void) {
+  int array[1] = { 0 };
+  SignedCharTy subscript = 0;
+  int val = array[subscript]; // no warning for explicit signed char
+}
+
+typedef unsigned char UnsignedCharTy;
+void t10(void) {
+  int array[1] = { 0 };
+  UnsignedCharTy subscript = 0;
+  int val = array[subscript]; // no warning for unsigned char
+}
+
+void t11(void) {
+  int array[256] = { 0 };
+  int val = array['a']; // no warning for char with known positive value
+}
+
+void t12(void) {
+  int array[256] = { 0 };
+  char b = 'a';
+  i

[clang] Remove warnings from -Wchar-subscripts for known positive constants (PR #69061)

2023-10-14 Thread via cfe-commits

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


[clang-tools-extra] [clang-tidy] Support functional cast in bugprone-dangling-handle (PR #69067)

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

https://github.com/PiotrZSL created 
https://github.com/llvm/llvm-project/pull/69067

Add support for constructor conversion based functional
cast. Allows to detect issues like:
const std::string_view test1 = std::string(a);


>From 6d4c7297e19193781d97fe19c3ccf8e65226ad0b Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Sat, 14 Oct 2023 14:51:16 +
Subject: [PATCH 1/2] [clang-tidy] Support functional cast in
 bugprone-dangling-handle

Add support for constructor conversion based functional
cast. Allows to detect issues like:
const std::string_view test1 = std::string(a);
---
 .../clang-tidy/bugprone/DanglingHandleCheck.cpp   | 11 ---
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 
 .../clang-tidy/checkers/bugprone/dangling-handle.cpp  |  8 
 3 files changed, 20 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
index 9ded699ba78e66b..ffaa1edc83e7299 100644
--- a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
@@ -33,14 +33,19 @@ handleFrom(const 
ast_matchers::internal::Matcher &IsAHandle,
 
 ast_matchers::internal::Matcher handleFromTemporaryValue(
 const ast_matchers::internal::Matcher &IsAHandle) {
+
+  const auto TemporaryExpr =
+  anyOf(cxxBindTemporaryExpr(),
+cxxFunctionalCastExpr(hasCastKind(CK_ConstructorConversion),
+  
hasSourceExpression(cxxBindTemporaryExpr(;
   // If a ternary operator returns a temporary value, then both branches hold a
   // temporary value. If one of them is not a temporary then it must be copied
   // into one to satisfy the type of the operator.
   const auto TemporaryTernary = conditionalOperator(
-  hasTrueExpression(ignoringParenImpCasts(cxxBindTemporaryExpr())),
-  hasFalseExpression(ignoringParenImpCasts(cxxBindTemporaryExpr(;
+  hasTrueExpression(ignoringParenImpCasts(TemporaryExpr)),
+  hasFalseExpression(ignoringParenImpCasts(TemporaryExpr)));
 
-  return handleFrom(IsAHandle, anyOf(cxxBindTemporaryExpr(), 
TemporaryTernary));
+  return handleFrom(IsAHandle, anyOf(TemporaryExpr, TemporaryTernary));
 }
 
 ast_matchers::internal::Matcher isASequence() {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 03e5dc6f164af2a..da4f55da65ad51f 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -190,6 +190,10 @@ New check aliases
 Changes in existing checks
 ^^
 
+- Improved :doc:`bugprone-dangling-handle
+  ` check to support functional
+  casting during type conversions at variable initialization.
+
 - Improved :doc:`bugprone-lambda-function-name
   ` check by adding option
   `IgnoreMacros` to ignore warnings in macros.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp
index 23cda5321764383..96c812617038a37 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp
@@ -108,6 +108,14 @@ void Positives() {
   std::string_view view4(ReturnsAString());
   // CHECK-MESSAGES-CXX14: [[@LINE-1]]:20: warning: std::basic_string_view 
outlives
   // CHECK-MESSAGES-CXX17: [[@LINE-2]]:26: warning: std::basic_string_view 
outlives
+
+  std::string_view view5 = std::string("test");
+  // CHECK-MESSAGES-CXX14: [[@LINE-1]]:20: warning: std::basic_string_view 
outlives its value [bugprone-dangling-handle]
+  // CHECK-MESSAGES-CXX17: [[@LINE-2]]:28: warning: std::basic_string_view 
outlives its value [bugprone-dangling-handle]
+
+  std::string_view view6 = std::string{"test"};
+  // CHECK-MESSAGES-CXX14: [[@LINE-1]]:20: warning: std::basic_string_view 
outlives its value [bugprone-dangling-handle]
+  // CHECK-MESSAGES-CXX17: [[@LINE-2]]:28: warning: std::basic_string_view 
outlives its value [bugprone-dangling-handle]
 }
 
 void OtherTypes() {

>From 8591cdb8288775ac660c2f3d9e2fa4ee2c30bed2 Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Sat, 14 Oct 2023 17:13:32 +
Subject: [PATCH 2/2] [clang-tidy][DOC] Improve release notes for
 bugprone-dangling-handle

Add info about change that were introduced in
commit f2e5000937235aa35a9ee4423045b265c2c79e85.
---
 clang-tools-extra/docs/ReleaseNotes.rst | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index da4f55da65ad51f..35d02f7c42f82fd 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -192,7 +192,8 @@ Changes in existing checks
 
 - Improved :doc:`bugprone-dangling-handle
   ` check to support functional
-  casting during type conversions

[clang-tools-extra] [clang-tidy] Support functional cast in bugprone-dangling-handle (PR #69067)

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Piotr Zegar (PiotrZSL)


Changes

Add support for constructor conversion based functional
cast. Allows to detect issues like:
const std::string_view test1 = std::string(a);


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


3 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp 
(+8-3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp (+8) 


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
index 9ded699ba78e66b..ffaa1edc83e7299 100644
--- a/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/DanglingHandleCheck.cpp
@@ -33,14 +33,19 @@ handleFrom(const 
ast_matchers::internal::Matcher &IsAHandle,
 
 ast_matchers::internal::Matcher handleFromTemporaryValue(
 const ast_matchers::internal::Matcher &IsAHandle) {
+
+  const auto TemporaryExpr =
+  anyOf(cxxBindTemporaryExpr(),
+cxxFunctionalCastExpr(hasCastKind(CK_ConstructorConversion),
+  
hasSourceExpression(cxxBindTemporaryExpr(;
   // If a ternary operator returns a temporary value, then both branches hold a
   // temporary value. If one of them is not a temporary then it must be copied
   // into one to satisfy the type of the operator.
   const auto TemporaryTernary = conditionalOperator(
-  hasTrueExpression(ignoringParenImpCasts(cxxBindTemporaryExpr())),
-  hasFalseExpression(ignoringParenImpCasts(cxxBindTemporaryExpr(;
+  hasTrueExpression(ignoringParenImpCasts(TemporaryExpr)),
+  hasFalseExpression(ignoringParenImpCasts(TemporaryExpr)));
 
-  return handleFrom(IsAHandle, anyOf(cxxBindTemporaryExpr(), 
TemporaryTernary));
+  return handleFrom(IsAHandle, anyOf(TemporaryExpr, TemporaryTernary));
 }
 
 ast_matchers::internal::Matcher isASequence() {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 03e5dc6f164af2a..35d02f7c42f82fd 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -190,6 +190,11 @@ New check aliases
 Changes in existing checks
 ^^
 
+- Improved :doc:`bugprone-dangling-handle
+  ` check to support functional
+  casting during type conversions at variable initialization, now with improved
+  compatibility for C++17 and later versions.
+
 - Improved :doc:`bugprone-lambda-function-name
   ` check by adding option
   `IgnoreMacros` to ignore warnings in macros.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp
index 23cda5321764383..96c812617038a37 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/dangling-handle.cpp
@@ -108,6 +108,14 @@ void Positives() {
   std::string_view view4(ReturnsAString());
   // CHECK-MESSAGES-CXX14: [[@LINE-1]]:20: warning: std::basic_string_view 
outlives
   // CHECK-MESSAGES-CXX17: [[@LINE-2]]:26: warning: std::basic_string_view 
outlives
+
+  std::string_view view5 = std::string("test");
+  // CHECK-MESSAGES-CXX14: [[@LINE-1]]:20: warning: std::basic_string_view 
outlives its value [bugprone-dangling-handle]
+  // CHECK-MESSAGES-CXX17: [[@LINE-2]]:28: warning: std::basic_string_view 
outlives its value [bugprone-dangling-handle]
+
+  std::string_view view6 = std::string{"test"};
+  // CHECK-MESSAGES-CXX14: [[@LINE-1]]:20: warning: std::basic_string_view 
outlives its value [bugprone-dangling-handle]
+  // CHECK-MESSAGES-CXX17: [[@LINE-2]]:28: warning: std::basic_string_view 
outlives its value [bugprone-dangling-handle]
 }
 
 void OtherTypes() {

``




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


[clang-tools-extra] [clang-tidy][modernize-loop-convert]check isDependentSizedArrayType (PR #69062)

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


@@ -269,6 +269,10 @@ Changes in existing checks
   ` to support for-loops with
   iterators initialized by free functions like ``begin``, ``end``, or ``size``.
 
+- Improved :doc:`modernize-loop-convert

PiotrZSL wrote:

Typo "dor" + leading spaces in second and third line,.
There is already entry for this check, just join this information with previous 
one.

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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

2023-10-14 Thread Maksim Levental via cfe-commits

https://github.com/makslevental created 
https://github.com/llvm/llvm-project/pull/69072

On Mac M1, if you load something that transitively loads `#include `, it 
will fail because 

```
In file included from <<< inputs >>>:1:
In file included from input_line_22:1:
In file included from 
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/usr/include/c++/v1/memory:671:
In file included from 
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/usr/include/c++/v1/__functional_base:23:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/usr/include/c++/v1/new:214:70:
 error: 'internal_linkage' attribute does not appear on the first declaration
  214 | _LIBCPP_NODISCARD_AFTER_CXX17 inline _LIBCPP_INLINE_VISIBILITY void* 
operator new  (std::size_t, void* __p) _NOEXCEPT {return __p;}
  |  ^
input_line_0:3:11: note: previous declaration is here
3 | void* operator new(__SIZE_TYPE__, void* __p) noexcept;
  |   ^
Assertion failed: (Ptr && "dereferencing end() iterator"), function operator*, 
file DeclBase.h, line 1315.
```

This is because `MacOSX12.3.sdk/usr/include/c++/v1/__config` sets 
`_LIBCPP_INLINE_VISIBILITY` to be `__attribute__((__visibility__("hidden"))) 
__attribute__((internal_linkage))`, which makes the `new` in `` 
incompatible with the hardcoded decl `void* operator new(__SIZE_TYPE__, void* 
__p) noexcept;` in `clang/lib/Interpreter/Interpreter::Runtimes`. I believe the 
correct thing to do is replace that decl with `#include ` (as I've done 
here).

>From d7c57d94d7e75ed1e0df87ebf3c4464e7b951453 Mon Sep 17 00:00:00 2001
From: max 
Date: Sat, 14 Oct 2023 12:46:42 -0500
Subject: [PATCH] [clang][repl] fix `new`

---
 clang/lib/Interpreter/Interpreter.cpp | 2 +-
 clang/test/Interpreter/execute.cpp| 2 ++
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 7968c62cbd3e7b3..ddfbc9ac01c6743 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -248,7 +248,7 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-void* operator new(__SIZE_TYPE__, void* __p) noexcept;
+#include 
 void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, void*);
diff --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 6e73ed3927e8155..d54ab99749c1bac 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -20,4 +20,6 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_cast
+
 %quit

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


[clang-tools-extra] [clang-tidy][modernize-loop-convert]check isDependentSizedArrayType (PR #69062)

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


@@ -939,4 +939,13 @@ void fundamentalTypesTest() {
   // CHECK-FIXES: for (double Double : Doubles)
 }
 
+template  void test() {
+  unsigned int test[3][p];
+  // Initialize to zero
+  for (unsigned int i = 0; i < p; ++i)
+for (unsigned int j = 0; j < 3; ++j) // CHECK-MESSAGES: warning: use 
range-based for loop instead

PiotrZSL wrote:

put check messages and check fixes in new lines, use @LINE like in other checks

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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Maksim Levental (makslevental)


Changes

On Mac M1, if you load something that transitively loads `#include 
`, it will fail because 

```
In file included from <<< inputs >>>:1:
In file included from input_line_22:1:
In file included from 
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/usr/include/c++/v1/memory:671:
In file included from 
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/usr/include/c++/v1/__functional_base:23:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/usr/include/c++/v1/new:214:70:
 error: 'internal_linkage' attribute does not appear on the first declaration
  214 | _LIBCPP_NODISCARD_AFTER_CXX17 inline _LIBCPP_INLINE_VISIBILITY void* 
operator new  (std::size_t, void* __p) _NOEXCEPT {return __p;}
  |  ^
input_line_0:3:11: note: previous declaration is here
3 | void* operator new(__SIZE_TYPE__, void* __p) noexcept;
  |   ^
Assertion failed: (Ptr && "dereferencing end() iterator"), function 
operator*, file DeclBase.h, line 1315.
```

This is because `MacOSX12.3.sdk/usr/include/c++/v1/__config` sets 
`_LIBCPP_INLINE_VISIBILITY` to be `__attribute__((__visibility__("hidden"))) 
__attribute__((internal_linkage))`, which makes the `new` in `` 
incompatible with the hardcoded decl `void* operator new(__SIZE_TYPE__, void* 
__p) noexcept;` in `clang/lib/Interpreter/Interpreter::Runtimes`. I believe the 
correct thing to do is replace that decl with `#include ` (as I've 
done here).

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


2 Files Affected:

- (modified) clang/lib/Interpreter/Interpreter.cpp (+1-1) 
- (modified) clang/test/Interpreter/execute.cpp (+2) 


``diff
diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 7968c62cbd3e7b3..ddfbc9ac01c6743 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -248,7 +248,7 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-void* operator new(__SIZE_TYPE__, void* __p) noexcept;
+#include 
 void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, void*);
diff --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 6e73ed3927e8155..d54ab99749c1bac 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -20,4 +20,6 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_cast
+
 %quit

``




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


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

2023-10-14 Thread via cfe-commits

https://github.com/LYP951018 created 
https://github.com/llvm/llvm-project/pull/69075

The dependence of a template argument is not only determined by the argument 
itself, but also by the type of the template parameter:

> Furthermore, a non-type 
> [template-argument](https://eel.is/c++draft/temp.names#nt:template-argument) 
> is dependent if the corresponding non-type 
> [template-parameter](https://eel.is/c++draft/temp.param#nt:template-parameter)
>  is of reference or pointer type and the 
> [template-argument](https://eel.is/c++draft/temp.names#nt:template-argument) 
> designates or points to a member of the current instantiation or a member of 
> a dependent type[.](https://eel.is/c++draft/temp.dep#temp-3.sentence-1)

For example:

```cpp
struct A{};

template 
const A JoinStringViews = T;

template 
class Builder {
public:
static constexpr A Equal{};
static constexpr auto Val = JoinStringViews;
};
```

The constant expression `Equal` is not dependent, but because the type of the 
template parameter is a reference type and `Equal` is a member of the current 
instantiation, the template argument of `JoinStringViews` is actually 
dependent, which makes `JoinStringViews` dependent.

When a template-id of a variable template is dependent, `CheckVarTemplateId` 
will return an `UnresolvedLookupExpr`, but `UnresolvedLookupExpr` calculates 
dependence by template arguments only (the `ConstantExpr` `Equal` here), which 
is not dependent. This causes type deduction to think that 
`JoinStringViews` is `OverloadTy` and treat it as a function template, 
which is clearly wrong.

This PR adds a `KnownDependent` parameter to the constructor of 
`UnresolvedLookupExpr`. After canonicalization, if `CanonicalConverted` 
contains any dependent argument, `KnownDependent` is set to `true`. This fixes 
the dependence calculation of  `UnresolvedLookupExpr` for dependent variable 
templates.

Fixes #65153 .

From 5f3557e274cc2229133fe9d39f787ae8f6eb86c7 Mon Sep 17 00:00:00 2001
From: letrec 
Date: Sun, 8 Oct 2023 00:44:11 +0800
Subject: [PATCH] Fix dependence handling for variable templates

---
 clang/include/clang/AST/ExprCXX.h  |  8 ++--
 clang/lib/AST/ASTImporter.cpp  |  5 -
 clang/lib/AST/ExprCXX.cpp  | 14 +++---
 clang/lib/Sema/SemaDeclCXX.cpp |  5 +++--
 clang/lib/Sema/SemaTemplate.cpp|  5 +++--
 clang/test/SemaTemplate/dependent-expr.cpp | 15 +++
 6 files changed, 38 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 17dbb5e888ebdd3..798c98cfcf2d4db 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -3191,7 +3191,8 @@ class UnresolvedLookupExpr final
const DeclarationNameInfo &NameInfo, bool RequiresADL,
bool Overloaded,
const TemplateArgumentListInfo *TemplateArgs,
-   UnresolvedSetIterator Begin, UnresolvedSetIterator End);
+   UnresolvedSetIterator Begin, UnresolvedSetIterator End,
+   bool KnownDependent);
 
   UnresolvedLookupExpr(EmptyShell Empty, unsigned NumResults,
bool HasTemplateKWAndArgsInfo);
@@ -3211,12 +3212,15 @@ class UnresolvedLookupExpr final
  const DeclarationNameInfo &NameInfo, bool RequiresADL, bool 
Overloaded,
  UnresolvedSetIterator Begin, UnresolvedSetIterator End);
 
+  // After canonicalization, there may be dependent template arguments in
+  // CanonicalConverted But none of Args is dependent. When any of
+  // CanonicalConverted dependent, KnownDependent is true.
   static UnresolvedLookupExpr *
   Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
  NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
  const DeclarationNameInfo &NameInfo, bool RequiresADL,
  const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
- UnresolvedSetIterator End);
+ UnresolvedSetIterator End, bool KnownDependent);
 
   static UnresolvedLookupExpr *CreateEmpty(const ASTContext &Context,
unsigned NumResults,
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index c7c2aecc8b179a4..706bbfcadd58b75 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -8391,10 +8391,13 @@ 
ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
 if (!ToTemplateKeywordLocOrErr)
   return ToTemplateKeywordLocOrErr.takeError();
 
+const bool KnownDependent =
+(E->getDependence() & ExprDependence::TypeValue) ==
+ExprDependence::TypeValue;
 return UnresolvedLookupExpr::Create(
 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
-ToDecls.

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

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

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


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


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

2023-10-14 Thread via cfe-commits

https://github.com/LYP951018 updated 
https://github.com/llvm/llvm-project/pull/69075

From 7a5eef02445d4d1969e5335d0ab7cb5edfb72889 Mon Sep 17 00:00:00 2001
From: letrec 
Date: Sun, 8 Oct 2023 00:44:11 +0800
Subject: [PATCH] Fix dependence handling for variable templates

---
 clang/include/clang/AST/ExprCXX.h  |  8 ++--
 clang/lib/AST/ASTImporter.cpp  |  5 -
 clang/lib/AST/ExprCXX.cpp  | 14 +++---
 clang/lib/Sema/SemaDeclCXX.cpp |  5 +++--
 clang/lib/Sema/SemaTemplate.cpp|  5 +++--
 clang/test/SemaTemplate/dependent-expr.cpp | 15 +++
 6 files changed, 38 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 17dbb5e888ebdd3..798c98cfcf2d4db 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -3191,7 +3191,8 @@ class UnresolvedLookupExpr final
const DeclarationNameInfo &NameInfo, bool RequiresADL,
bool Overloaded,
const TemplateArgumentListInfo *TemplateArgs,
-   UnresolvedSetIterator Begin, UnresolvedSetIterator End);
+   UnresolvedSetIterator Begin, UnresolvedSetIterator End,
+   bool KnownDependent);
 
   UnresolvedLookupExpr(EmptyShell Empty, unsigned NumResults,
bool HasTemplateKWAndArgsInfo);
@@ -3211,12 +3212,15 @@ class UnresolvedLookupExpr final
  const DeclarationNameInfo &NameInfo, bool RequiresADL, bool 
Overloaded,
  UnresolvedSetIterator Begin, UnresolvedSetIterator End);
 
+  // After canonicalization, there may be dependent template arguments in
+  // CanonicalConverted But none of Args is dependent. When any of
+  // CanonicalConverted dependent, KnownDependent is true.
   static UnresolvedLookupExpr *
   Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
  NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
  const DeclarationNameInfo &NameInfo, bool RequiresADL,
  const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
- UnresolvedSetIterator End);
+ UnresolvedSetIterator End, bool KnownDependent);
 
   static UnresolvedLookupExpr *CreateEmpty(const ASTContext &Context,
unsigned NumResults,
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 3adbabdb7fb878a..a9a841f28a4bf92 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -8394,10 +8394,13 @@ 
ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
 if (!ToTemplateKeywordLocOrErr)
   return ToTemplateKeywordLocOrErr.takeError();
 
+const bool KnownDependent =
+(E->getDependence() & ExprDependence::TypeValue) ==
+ExprDependence::TypeValue;
 return UnresolvedLookupExpr::Create(
 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
-ToDecls.begin(), ToDecls.end());
+ToDecls.begin(), ToDecls.end(), KnownDependent);
   }
 
   return UnresolvedLookupExpr::Create(
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 06163255f9b5e54..c88f297de8170f2 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -354,9 +354,9 @@ UnresolvedLookupExpr::UnresolvedLookupExpr(
 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
 const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
 const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
-UnresolvedSetIterator End)
+UnresolvedSetIterator End, bool KnownDependent)
 : OverloadExpr(UnresolvedLookupExprClass, Context, QualifierLoc,
-   TemplateKWLoc, NameInfo, TemplateArgs, Begin, End, false,
+   TemplateKWLoc, NameInfo, TemplateArgs, Begin, End, 
KnownDependent,
false, false),
   NamingClass(NamingClass) {
   UnresolvedLookupExprBits.RequiresADL = RequiresADL;
@@ -380,7 +380,7 @@ UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
   void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
   return new (Mem) UnresolvedLookupExpr(Context, NamingClass, QualifierLoc,
 SourceLocation(), NameInfo, 
RequiresADL,
-Overloaded, nullptr, Begin, End);
+Overloaded, nullptr, Begin, End, 
false);
 }
 
 UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
@@ -388,7 +388,7 @@ UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
 const DeclarationNameInfo &NameInfo, bool RequiresADL,
 const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
-

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

2023-10-14 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 8dd3bc18081657fee2352cf5b1c6abacb18fcc84 
7a5eef02445d4d1969e5335d0ab7cb5edfb72889 -- clang/include/clang/AST/ExprCXX.h 
clang/lib/AST/ASTImporter.cpp clang/lib/AST/ExprCXX.cpp 
clang/lib/Sema/SemaDeclCXX.cpp clang/lib/Sema/SemaTemplate.cpp 
clang/test/SemaTemplate/dependent-expr.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index c88f297de..5fbfa3a78 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -356,8 +356,8 @@ UnresolvedLookupExpr::UnresolvedLookupExpr(
 const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
 UnresolvedSetIterator End, bool KnownDependent)
 : OverloadExpr(UnresolvedLookupExprClass, Context, QualifierLoc,
-   TemplateKWLoc, NameInfo, TemplateArgs, Begin, End, 
KnownDependent,
-   false, false),
+   TemplateKWLoc, NameInfo, TemplateArgs, Begin, End,
+   KnownDependent, false, false),
   NamingClass(NamingClass) {
   UnresolvedLookupExprBits.RequiresADL = RequiresADL;
   UnresolvedLookupExprBits.Overloaded = Overloaded;
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 3860a90c4..6389ec708 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5003,13 +5003,10 @@ ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec 
&SS,
   // We don't want lookup warnings at this point.
   R.suppressDiagnostics();
 
-  UnresolvedLookupExpr *ULE
-= UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
-   SS.getWithLocInContext(Context),
-   TemplateKWLoc,
-   R.getLookupNameInfo(),
-   RequiresADL, TemplateArgs,
-   R.begin(), R.end(), KnownDependent);
+  UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
+  Context, R.getNamingClass(), SS.getWithLocInContext(Context),
+  TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
+  R.begin(), R.end(), KnownDependent);
 
   return ULE;
 }

``




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


[clang] [Clang][Frontend] Fix a crash when -Wdocumentation is used (PR #68525)

2023-10-14 Thread Daniel Höpfl via cfe-commits

dhoepfl wrote:

> Since **I'm not an expert in clang AST**, it is hard to reduce the failing 
> cases.

Double so for me.

> So the crash is happened because the result of `DeclLocDecomp.second - 
> CommentEndOffset` is overflowed, so operations over `StringRef Text` is 
> making the crash.
> 
> **The best way to fix this issue** is to find out why they are not from the 
> same source code and fix it. However, I'm not sure how to fix it, so I've 
> made a patch to avoid the crash.

While your fix resolves the specific crash we noticed, it does not fix the 
underlying problem. I found that the source of the problem is noted in [this 
comment](https://github.com/llvm/llvm-project/blob/80737d2ddf05507d96cdd723fb33a6e44ac72a48/clang/lib/Sema/SemaDecl.cpp#L14892).

I tried to “fix” this by removing a few lines starting 
[here](https://github.com/llvm/llvm-project/blob/80737d2ddf05507d96cdd723fb33a6e44ac72a48/clang/lib/AST/ASTContext.cpp#L575)
 (maybe you could also remove lines 561-574?) and moving them a few lines down 
to get:

```
void ASTContext::attachCommentsToJustParsedDecls(ArrayRef Decls,
 const Preprocessor *PP) {
  if (Comments.empty() || Decls.empty())
return;

  FileID File;
  for (Decl *D : Decls) {
SourceLocation Loc = D->getLocation();
if (Loc.isValid()) {
  // See if there are any new comments that are not attached to a decl.
  // The location doesn't have to be precise - we care only about the file.
  File = SourceMgr.getDecomposedLoc(Loc).first;
  break;
}
  }

  if (File.isInvalid())
return;

/* REMOVED HERE */

  // There is at least one comment not attached to a decl.
  // Maybe it should be attached to one of Decls?
  //
  // Note that this way we pick up not only comments that precede the
  // declaration, but also comments that *follow* the declaration -- thanks to
  // the lookahead in the lexer: we've consumed the semicolon and looked
  // ahead through comments.

  for (const Decl *D : Decls) {
assert(D);
if (D->isInvalidDecl())
  continue;

D = &adjustDeclToTemplate(*D);

const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);

if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  continue;

if (DeclRawComments.count(D) > 0)
  continue;

/* ADDED THIS */
FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
if (File.isInvalid())
  continue;

auto CommentsInThisFile = Comments.getCommentsInFile(File);
if (!CommentsInThisFile || CommentsInThisFile->empty() ||
CommentsInThisFile->rbegin()->second->isAttached())
  continue;
/* UNTIL HERE */

if (RawComment *const DocComment =
getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
  cacheRawCommentForDecl(*D, *DocComment);
  comments::FullComment *FC = DocComment->parse(*this, PP, D);
  ParsedComments[D->getCanonicalDecl()] = FC;
}
  }
}
```

That way it no longer crashes … I think this loads the correct comments for 
each decl but I am not sure if this is the correct way to fix it (or even if it 
still does what it is supposed to do).


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


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

2023-10-14 Thread via cfe-commits

https://github.com/LYP951018 updated 
https://github.com/llvm/llvm-project/pull/69075

From e7c7969f69755cff939c88f52987fedcb1ffcd76 Mon Sep 17 00:00:00 2001
From: letrec 
Date: Sun, 8 Oct 2023 00:44:11 +0800
Subject: [PATCH] Fix dependence handling for variable templates

---
 clang/include/clang/AST/ExprCXX.h  |  8 ++--
 clang/lib/AST/ASTImporter.cpp  |  5 -
 clang/lib/AST/ExprCXX.cpp  | 16 
 clang/lib/Sema/SemaDeclCXX.cpp |  5 +++--
 clang/lib/Sema/SemaTemplate.cpp| 14 ++
 clang/test/SemaTemplate/dependent-expr.cpp | 15 +++
 6 files changed, 42 insertions(+), 21 deletions(-)

diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 17dbb5e888ebdd3..798c98cfcf2d4db 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -3191,7 +3191,8 @@ class UnresolvedLookupExpr final
const DeclarationNameInfo &NameInfo, bool RequiresADL,
bool Overloaded,
const TemplateArgumentListInfo *TemplateArgs,
-   UnresolvedSetIterator Begin, UnresolvedSetIterator End);
+   UnresolvedSetIterator Begin, UnresolvedSetIterator End,
+   bool KnownDependent);
 
   UnresolvedLookupExpr(EmptyShell Empty, unsigned NumResults,
bool HasTemplateKWAndArgsInfo);
@@ -3211,12 +3212,15 @@ class UnresolvedLookupExpr final
  const DeclarationNameInfo &NameInfo, bool RequiresADL, bool 
Overloaded,
  UnresolvedSetIterator Begin, UnresolvedSetIterator End);
 
+  // After canonicalization, there may be dependent template arguments in
+  // CanonicalConverted But none of Args is dependent. When any of
+  // CanonicalConverted dependent, KnownDependent is true.
   static UnresolvedLookupExpr *
   Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
  NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
  const DeclarationNameInfo &NameInfo, bool RequiresADL,
  const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
- UnresolvedSetIterator End);
+ UnresolvedSetIterator End, bool KnownDependent);
 
   static UnresolvedLookupExpr *CreateEmpty(const ASTContext &Context,
unsigned NumResults,
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 3adbabdb7fb878a..a9a841f28a4bf92 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -8394,10 +8394,13 @@ 
ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
 if (!ToTemplateKeywordLocOrErr)
   return ToTemplateKeywordLocOrErr.takeError();
 
+const bool KnownDependent =
+(E->getDependence() & ExprDependence::TypeValue) ==
+ExprDependence::TypeValue;
 return UnresolvedLookupExpr::Create(
 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
-ToDecls.begin(), ToDecls.end());
+ToDecls.begin(), ToDecls.end(), KnownDependent);
   }
 
   return UnresolvedLookupExpr::Create(
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 06163255f9b5e54..5fbfa3a78124653 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -354,10 +354,10 @@ UnresolvedLookupExpr::UnresolvedLookupExpr(
 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
 const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
 const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
-UnresolvedSetIterator End)
+UnresolvedSetIterator End, bool KnownDependent)
 : OverloadExpr(UnresolvedLookupExprClass, Context, QualifierLoc,
-   TemplateKWLoc, NameInfo, TemplateArgs, Begin, End, false,
-   false, false),
+   TemplateKWLoc, NameInfo, TemplateArgs, Begin, End,
+   KnownDependent, false, false),
   NamingClass(NamingClass) {
   UnresolvedLookupExprBits.RequiresADL = RequiresADL;
   UnresolvedLookupExprBits.Overloaded = Overloaded;
@@ -380,7 +380,7 @@ UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
   void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
   return new (Mem) UnresolvedLookupExpr(Context, NamingClass, QualifierLoc,
 SourceLocation(), NameInfo, 
RequiresADL,
-Overloaded, nullptr, Begin, End);
+Overloaded, nullptr, Begin, End, 
false);
 }
 
 UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
@@ -388,7 +388,7 @@ UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
 const DeclarationNameInfo &NameI

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

2023-10-14 Thread via cfe-commits

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


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

2023-10-14 Thread via cfe-commits

LYP951018 wrote:

@erichkeane @cor3ntin could you review this PR, please? I’m not a collaborator, 
so I could not add reviewers.

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


[clang] Fix crash with modules and constexpr destructor (PR #69076)

2023-10-14 Thread Jonas Hahnfeld via cfe-commits

https://github.com/hahnjo created 
https://github.com/llvm/llvm-project/pull/69076

Closes https://github.com/llvm/llvm-project/issues/68702

>From d149de4d4e00b63e506441b516f35aeb41786408 Mon Sep 17 00:00:00 2001
From: Jonas Hahnfeld 
Date: Sat, 14 Oct 2023 20:10:28 +0200
Subject: [PATCH] Fix crash with modules and constexpr destructor

Closes https://github.com/llvm/llvm-project/issues/68702
---
 clang/lib/AST/ExprConstant.cpp | 11 +++---
 clang/test/Modules/pr68702.cpp | 65 ++
 2 files changed, 72 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/Modules/pr68702.cpp

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index e5539dedec02a4b..a97e7bd8140890e 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -15604,10 +15604,13 @@ bool Expr::EvaluateAsInitializer(APValue &Value, 
const ASTContext &Ctx,
 LValue LVal;
 LVal.set(VD);
 
-if (!EvaluateInPlace(Value, Info, LVal, this,
- /*AllowNonLiteralTypes=*/true) ||
-EStatus.HasSideEffects)
-  return false;
+{
+  FullExpressionRAII Scope(Info);
+  if (!EvaluateInPlace(Value, Info, LVal, this,
+   /*AllowNonLiteralTypes=*/true) ||
+  EStatus.HasSideEffects)
+return false;
+}
 
 // At this point, any lifetime-extended temporaries are completely
 // initialized.
diff --git a/clang/test/Modules/pr68702.cpp b/clang/test/Modules/pr68702.cpp
new file mode 100644
index 000..3f91a1001d1eecc
--- /dev/null
+++ b/clang/test/Modules/pr68702.cpp
@@ -0,0 +1,65 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -std=c++20 -emit-obj -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t %t/main.cpp -o %t/main.o
+
+//--- V.h
+#ifndef V_H
+#define V_H
+
+class A {
+public:
+  constexpr A() { }
+  constexpr ~A() { }
+};
+
+template 
+class V {
+public:
+  V() = default;
+
+  constexpr V(int n, const A& a = A()) {}
+};
+
+#endif
+
+//--- inst1.h
+#include "V.h"
+
+static void inst1() {
+  V v;
+}
+
+//--- inst2.h
+#include "V.h"
+
+static void inst2() {
+  V v(100);
+}
+
+//--- module.modulemap
+module "M" {
+  export *
+  module "V.h" {
+export *
+header "V.h"
+  }
+  module "inst1.h" {
+export *
+header "inst1.h"
+  }
+}
+
+module "inst2.h" {
+  export *
+  header "inst2.h"
+}
+
+//--- main.cpp
+#include "V.h"
+#include "inst2.h"
+
+static void m() {
+  static V v(100);
+}

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


[clang] Fix crash with modules and constexpr destructor (PR #69076)

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-modules

Author: Jonas Hahnfeld (hahnjo)


Changes

Closes https://github.com/llvm/llvm-project/issues/68702

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


2 Files Affected:

- (modified) clang/lib/AST/ExprConstant.cpp (+7-4) 
- (added) clang/test/Modules/pr68702.cpp (+65) 


``diff
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index e5539dedec02a4b..a97e7bd8140890e 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -15604,10 +15604,13 @@ bool Expr::EvaluateAsInitializer(APValue &Value, 
const ASTContext &Ctx,
 LValue LVal;
 LVal.set(VD);
 
-if (!EvaluateInPlace(Value, Info, LVal, this,
- /*AllowNonLiteralTypes=*/true) ||
-EStatus.HasSideEffects)
-  return false;
+{
+  FullExpressionRAII Scope(Info);
+  if (!EvaluateInPlace(Value, Info, LVal, this,
+   /*AllowNonLiteralTypes=*/true) ||
+  EStatus.HasSideEffects)
+return false;
+}
 
 // At this point, any lifetime-extended temporaries are completely
 // initialized.
diff --git a/clang/test/Modules/pr68702.cpp b/clang/test/Modules/pr68702.cpp
new file mode 100644
index 000..3f91a1001d1eecc
--- /dev/null
+++ b/clang/test/Modules/pr68702.cpp
@@ -0,0 +1,65 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -std=c++20 -emit-obj -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t %t/main.cpp -o %t/main.o
+
+//--- V.h
+#ifndef V_H
+#define V_H
+
+class A {
+public:
+  constexpr A() { }
+  constexpr ~A() { }
+};
+
+template 
+class V {
+public:
+  V() = default;
+
+  constexpr V(int n, const A& a = A()) {}
+};
+
+#endif
+
+//--- inst1.h
+#include "V.h"
+
+static void inst1() {
+  V v;
+}
+
+//--- inst2.h
+#include "V.h"
+
+static void inst2() {
+  V v(100);
+}
+
+//--- module.modulemap
+module "M" {
+  export *
+  module "V.h" {
+export *
+header "V.h"
+  }
+  module "inst1.h" {
+export *
+header "inst1.h"
+  }
+}
+
+module "inst2.h" {
+  export *
+  header "inst2.h"
+}
+
+//--- main.cpp
+#include "V.h"
+#include "inst2.h"
+
+static void m() {
+  static V v(100);
+}

``




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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

2023-10-14 Thread via cfe-commits

AMS21 wrote:

If there are no more problems I would kindly ask for someone to push this on my 
behalf :)

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


[clang-tools-extra] [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (PR #69045)

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

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


[clang-tools-extra] bb6a98c - [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved check` (#69045)

2023-10-14 Thread via cfe-commits

Author: AMS21
Date: 2023-10-14T22:51:50+02:00
New Revision: bb6a98c8d2beee78ab9dc1a4c81009410e4911a3

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

LOG: [clang-tidy] Ignore unused parameters in `rvalue-reference-param-not-moved 
check` (#69045)

With this patch we no longer issue a warning for unused parameters which
are marked as such.

This fixes #68209

Added: 


Modified: 

clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
index efcaffb45d9ad8a..88b00dc17470f32 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
@@ -84,6 +84,9 @@ void RvalueReferenceParamNotMovedCheck::check(
   if (IgnoreUnnamedParams && Param->getName().empty())
 return;
 
+  if (!Param->isUsed() && Param->hasAttr())
+return;
+
   const auto *Function = dyn_cast(Param->getDeclContext());
   if (!Function)
 return;

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 03e5dc6f164af2a..c732d4904df13fa 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -237,6 +237,10 @@ Changes in existing checks
   ` check to ignore
   false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).
 
+- Improved :doc:`cppcoreguidelines-rvalue-reference-param-not-moved
+  ` check
+  to ignore unused parameters when they are marked as unused.
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst
index 9ab4ae7871e46e4..ffa3a9d61e48e9d 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/rvalue-reference-param-not-moved.rst
@@ -18,6 +18,16 @@ Example:
 std::string Copy(Input); // Oops - forgot to std::move
   }
 
+Note that parameters that are unused and marked as such will not be diagnosed.
+
+Example:
+
+.. code-block:: c++
+
+  void conditional_use([[maybe_unused]] std::string&& Input) {
+// No diagnostic here since Input is unused and marked as such
+  }
+
 Options
 ---
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
index 8f8e272e1e8a90d..a9b87567a08cc0a 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
@@ -333,3 +333,28 @@ void instantiate_a_class_template() {
   AClassTemplate withObjRef(o);
   withObjRef.never_moves(o);
 }
+
+namespace gh68209
+{
+  void f1([[maybe_unused]] int&& x) {}
+
+  void f2(__attribute__((unused)) int&& x) {}
+
+  void f3(int&& x) {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: rvalue reference parameter 'x' 
is never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
+
+  template 
+  void f4([[maybe_unused]] T&& x) {}
+
+  template 
+  void f5(__attribute((unused)) T&& x) {}
+
+  template
+  void f6(T&& x) {}
+
+  void f7([[maybe_unused]] int&& x) { x += 1; }
+  // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: rvalue reference parameter 'x' 
is never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
+
+  void f8(__attribute__((unused)) int&& x) { x += 1; }
+  // CHECK-MESSAGES: :[[@LINE-1]]:41: warning: rvalue reference parameter 'x' 
is never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
+} // namespace gh68209



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


[clang] [clang] [unittest] Add a test for Generic_GCC::GCCVersion::Parse (PR #69078)

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

https://github.com/mstorsjo created 
https://github.com/llvm/llvm-project/pull/69078

This adds actual test cases for all the cases that are listed in a code comment 
in the implementation of this function; having such test coverage eases doing 
further modifications to the function.


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

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

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

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


[clang] [clang] [unittest] Add a test for Generic_GCC::GCCVersion::Parse (PR #69078)

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Martin Storsjö (mstorsjo)


Changes

This adds actual test cases for all the cases that are listed in a code comment 
in the implementation of this function; having such test coverage eases doing 
further modifications to the function.


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


2 Files Affected:

- (modified) clang/unittests/Driver/CMakeLists.txt (+1) 
- (added) clang/unittests/Driver/GCCVersionTest.cpp (+48) 


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

``




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


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

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

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

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

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

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

This allows Clang to find the GCC libraries and headers in Debian/Ubuntu 
provided MinGW cross compilers.

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

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

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

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

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

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

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

This allows Clang to find the GCC libraries and headers in
Debian/Ubuntu provided MinGW cross compilers.
---
 clang/lib/Driver/ToolChains/Gnu.cpp   | 82 +++
 clang/unittests/Driver/G

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

2023-10-14 Thread via cfe-commits
Martin =?utf-8?q?Storsjö?= 
Message-ID:
In-Reply-To: 


llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Martin Storsjö (mstorsjo)


Changes

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

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

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

This allows Clang to find the GCC libraries and headers in Debian/Ubuntu 
provided MinGW cross compilers.

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


3 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Gnu.cpp (+54-28) 
- (modified) clang/unittests/Driver/CMakeLists.txt (+1) 
- (added) clang/unittests/Driver/GCCVersionTest.cpp (+49) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index cdd911af9a73361..e6f94836c4110a1 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2007,45 +2007,71 @@ Generic_GCC::GCCVersion 
Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
   std::pair First = VersionText.split('.');
   std::pair Second = First.second.split('.');
 
-  GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
-  if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
-return BadVersion;
-  GoodVersion.MajorStr = First.first.str();
-  if (First.second.empty())
-return GoodVersion;
+  StringRef MajorStr = First.first;
   StringRef MinorStr = Second.first;
-  if (Second.second.empty()) {
-if (size_t EndNumber = MinorStr.find_first_not_of("0123456789")) {
-  GoodVersion.PatchSuffix = std::string(MinorStr.substr(EndNumber));
-  MinorStr = MinorStr.slice(0, EndNumber);
-}
-  }
-  if (MinorStr.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
-return BadVersion;
-  GoodVersion.MinorStr = MinorStr.str();
+  StringRef PatchStr = Second.second;
 
-  // First look for a number prefix and parse that if present. Otherwise just
-  // stash the entire patch string in the suffix, and leave the number
-  // unspecified. This covers versions strings such as:
-  //   5(handled above)
+  GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
+
+  // Parse version number strings such as:
+  //   5
   //   4.4
   //   4.4-patched
   //   4.4.0
   //   4.4.x
   //   4.4.2-rc4
   //   4.4.x-patched
-  // And retains any patch number it finds.
-  StringRef PatchText = Second.second;
-  if (!PatchText.empty()) {
-if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
-  // Try to parse the number and any suffix.
-  if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
-  GoodVersion.Patch < 0)
-return BadVersion;
-  GoodVersion.PatchSuffix = std::string(PatchText.substr(EndNumber));
+  //   10-win32
+  // Split on '.', handle 1, 2 or 3 such segments. Each segment must contain
+  // purely a number, except for the last one, where a non-number suffix
+  // is stored in PatchSuffix. The third segment is allowed to not contain
+  // a number at all.
+
+  auto HandleLastNumber = [&](StringRef Segment, int &Number,
+  std::string &OutStr) -> bool {
+// Look for a number prefix and parse that, and split out any trailing
+// string into GoodVersion.PatchSuffix.
+
+if (size_t EndNumber = Segment.find_first_not_of("0123456789")) {
+  StringRef NumberStr = Segment.slice(0, EndNumber);
+  if (NumberStr.getAsInteger(10, Number) || Number < 0)
+return false;
+  OutStr = NumberStr;
+  GoodVersion.PatchSuffix = Segment.substr(EndNumber);
+  return true;
 }
+return false;
+  };
+  auto HandleNumber = [](StringRef Segment, int &Number) -> bool {
+if (Segment.getAsInteger(10, Number) || Number < 0)
+  return false;
+return true;
+  };
+
+  if (MinorStr.empty()) {
+// If no minor string, major is the last segment
+if (!HandleLastNumber(MajorStr, GoodVersion.Major, GoodVersion.MajorStr))
+  return BadVersion;
+return GoodVersion;
+  } else {
+if (!HandleNumber(MajorStr, GoodVersion.Major))
+  return BadVersion;
+GoodVersion.MajorStr = MajorStr;
+  }
+  if (PatchStr.empty()) {
+// If no patch string, minor is the last segment
+if (!HandleLastNumber(MinorStr, GoodVersion.Minor, GoodVersion.MinorStr))
+  return BadVersion;
+return GoodVersion;
+  } else {
+ 

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

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

mstorsjo wrote:

This goes on top of #69078 - the first commit is reviewed there, thus within 
this PR, only review the second commit on its own.

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


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

2023-10-14 Thread via cfe-commits
Martin =?utf-8?q?Storsjö?= 
Message-ID:
In-Reply-To: 


github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff bb6a98c8d2beee78ab9dc1a4c81009410e4911a3 
2c923927f2aaf58e0879fe88b573fd1bc80063a5 -- 
clang/unittests/Driver/GCCVersionTest.cpp clang/lib/Driver/ToolChains/Gnu.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/unittests/Driver/GCCVersionTest.cpp 
b/clang/unittests/Driver/GCCVersionTest.cpp
index 91842a2ea959..5dd8a7d94b08 100644
--- a/clang/unittests/Driver/GCCVersionTest.cpp
+++ b/clang/unittests/Driver/GCCVersionTest.cpp
@@ -32,7 +32,7 @@ const VersionParseTest TestCases[] = {
 {"4.4.2-rc4", 4, 4, 2, "4", "4", "-rc4"},
 {"4.4.x-patched", 4, 4, -1, "4", "4", ""},
 {"not-a-version", -1, -1, -1, "", "", ""},
-{ "10-win32", 10, -1, -1, "10", "", "-win32" },
+{"10-win32", 10, -1, -1, "10", "", "-win32"},
 };
 
 TEST(GCCVersionTest, Parse) {

``




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


[clang-tools-extra] [clang-tidy] Add recursion protection in ExceptionSpecAnalyzer (PR #66810)

2023-10-14 Thread via cfe-commits

AMS21 wrote:

I think this is a very reasonable change and something I didn't think about 
when implementing it originally.
LGTM :+1: 

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


[clang-tools-extra] llvm-canon (PR #68176)

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

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

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

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

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

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

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

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


[clang] [LLVM] Add Normalizer Pass (PR #68176)

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

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


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

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

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


[clang] [Clang][OHOS] Keep ARM ABI selection logic in sync between Clang and LLVM (PR #68656)

2023-10-14 Thread Brad Smith via cfe-commits

brad0 wrote:

ping.

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


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

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

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

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

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

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

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

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

justinfargnoli wrote:

Renamed to IRNormalizer. Requesting another round of review. 

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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

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


@@ -20,4 +20,6 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_cast

vgvassilev wrote:

Why do we need this?

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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

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


@@ -248,7 +248,7 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-void* operator new(__SIZE_TYPE__, void* __p) noexcept;
+#include 

vgvassilev wrote:

```suggestion
```

I'd prefer to drop it for now. We cannot really re-declare the operator new 
with placement in a platform independent way. We cannot really rely on 
including `` because it won't work across our build bots.

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


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

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


@@ -103,6 +103,13 @@ function (gen_rst_file_from_td output_file td_option 
source docs_targets)
 endfunction()
 
 if (LLVM_ENABLE_SPHINX)
+  llvm_find_program(dot)

vgvassilev wrote:

@Krishna-13-cyber, could we drop the `llvm_find_program(dot)` and rely on 
handling the `dot` discovery from llvm. This is what we do a few lines above 
for the case of doxygen.

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


[clang] [Clang][OHOS] Keep ARM ABI selection logic in sync between Clang and LLVM (PR #68656)

2023-10-14 Thread Anton Korobeynikov via cfe-commits


@@ -519,6 +519,7 @@ StringRef ARM::computeDefaultTargetABI(const Triple &TT, 
StringRef CPU) {
   case Triple::GNUEABIHF:
   case Triple::MuslEABI:
   case Triple::MuslEABIHF:
+  case llvm::Triple::OpenHOS:

asl wrote:

```suggestion
  case Triple::OpenHOS:
```

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


[clang] [Clang][OHOS] Keep ARM ABI selection logic in sync between Clang and LLVM (PR #68656)

2023-10-14 Thread Brad Smith via cfe-commits

https://github.com/brad0 updated https://github.com/llvm/llvm-project/pull/68656

>From bf8c7540cefb423b7a89a938bfb0ad00b0cd555b Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Mon, 9 Oct 2023 22:41:36 -0400
Subject: [PATCH] [Clang][OHOS] Keep ARM ABI selection logic in sync between
 Clang and LLVM

---
 clang/lib/Basic/Targets/ARM.cpp   | 3 ++-
 llvm/lib/TargetParser/ARMTargetParser.cpp | 1 +
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Basic/Targets/ARM.cpp b/clang/lib/Basic/Targets/ARM.cpp
index 1e809283748b66c..ce7e4d4639ceacb 100644
--- a/clang/lib/Basic/Targets/ARM.cpp
+++ b/clang/lib/Basic/Targets/ARM.cpp
@@ -258,6 +258,7 @@ ARMTargetInfo::ARMTargetInfo(const llvm::Triple &Triple,
   bool IsOpenBSD = Triple.isOSOpenBSD();
   bool IsNetBSD = Triple.isOSNetBSD();
   bool IsHaiku = Triple.isOSHaiku();
+  bool IsOHOS = Triple.isOHOSFamily();
 
   // FIXME: the isOSBinFormatMachO is a workaround for identifying a 
Darwin-like
   // environment where size_t is `unsigned long` rather than `unsigned int`
@@ -324,7 +325,7 @@ ARMTargetInfo::ARMTargetInfo(const llvm::Triple &Triple,
 default:
   if (IsNetBSD)
 setABI("apcs-gnu");
-  else if (IsFreeBSD || IsOpenBSD || IsHaiku)
+  else if (IsFreeBSD || IsOpenBSD || IsHaiku || IsOHOS)
 setABI("aapcs-linux");
   else
 setABI("aapcs");
diff --git a/llvm/lib/TargetParser/ARMTargetParser.cpp 
b/llvm/lib/TargetParser/ARMTargetParser.cpp
index 20225232b3cccb7..240c449fb86f54e 100644
--- a/llvm/lib/TargetParser/ARMTargetParser.cpp
+++ b/llvm/lib/TargetParser/ARMTargetParser.cpp
@@ -519,6 +519,7 @@ StringRef ARM::computeDefaultTargetABI(const Triple &TT, 
StringRef CPU) {
   case Triple::GNUEABIHF:
   case Triple::MuslEABI:
   case Triple::MuslEABIHF:
+  case Triple::OpenHOS:
 return "aapcs-linux";
   case Triple::EABIHF:
   case Triple::EABI:

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


[clang] [CUDA][HIP] Fix init var diag in temmplate (PR #69081)

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

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

Currently clang diagnoses the following code:
(https://godbolt.org/z/s8zK3E5P5) but nvcc
does not.

`
struct A {
   constexpr A(){}
};

struct  B {
  A a;
  int b;
};

template
__global__ void kernel( )
{
   __shared__ B x;
}
`

Clang generates an implicit trivial ctor for struct B, which should be allowed 
for initializing a shared variable.

However, the body of the ctor is defined only if the template kernel is 
instantiated. Clang checks the initialization of variable in non-instantiated 
templates, where it cannot find the body of the ctor, therefore diagnoses it.

This patch skips the check for non-instantiated templates.

>From 0b0833af4494276e11b6c9e881dbf8e09491b5bd Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Sat, 14 Oct 2023 17:37:29 -0400
Subject: [PATCH] [CUDA][HIP] Fix init var diag in temmplate

Currently clang diagnoses the following code:
(https://godbolt.org/z/s8zK3E5P5) but nvcc
does not.

`
struct A {
   constexpr A(){}
};

struct  B {
  A a;
  int b;
};

template
__global__ void kernel( )
{
   __shared__ B x;
}
`

Clang generates an implicit trivial ctor for struct B, which
should be allowed for initializing a shared variable.

However, the body of the ctor is defined only if the template
kernel is instantiated. Clang checks the initialization
of variable in non-instantiated templates, where it cannot
find the body of the ctor, therefore diagnoses it.

This patch skips the check for non-instantiated templates.
---
 clang/lib/Sema/SemaCUDA.cpp   |  7 +++
 .../test/SemaCUDA/Inputs/cuda-initializers.h  | 11 +
 clang/test/SemaCUDA/device-var-init.cu| 48 +++
 3 files changed, 66 insertions(+)

diff --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index 7c4083e4ec4d4bb..d993499cf4a6e6e 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -632,6 +632,13 @@ bool HasAllowedCUDADeviceStaticInitializer(Sema &S, 
VarDecl *VD,
 } // namespace
 
 void Sema::checkAllowedCUDAInitializer(VarDecl *VD) {
+  // Return early if VD is inside a non-instantiated template function since
+  // the implicit constructor is not defined yet.
+  if (const FunctionDecl *FD =
+  dyn_cast_or_null(VD->getDeclContext()))
+if (FD->isDependentContext())
+  return;
+
   // Do not check dependent variables since the ctor/dtor/initializer are not
   // determined. Do it after instantiation.
   if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
diff --git a/clang/test/SemaCUDA/Inputs/cuda-initializers.h 
b/clang/test/SemaCUDA/Inputs/cuda-initializers.h
index 837b726a13e0f4b..b1e7a1bd48fb576 100644
--- a/clang/test/SemaCUDA/Inputs/cuda-initializers.h
+++ b/clang/test/SemaCUDA/Inputs/cuda-initializers.h
@@ -143,3 +143,14 @@ struct T_F_NED {
 struct T_FA_NED {
   NED ned[2];
 };
+
+// contexpr empty ctor -- allowed
+struct CEEC {
+  constexpr CEEC() {}
+};
+
+// Compiler generated trivial ctor -- allowed
+struct CGTC {
+  CEEC ceec;
+  int a;
+};
diff --git a/clang/test/SemaCUDA/device-var-init.cu 
b/clang/test/SemaCUDA/device-var-init.cu
index 9d499bddbe1b31a..ee7a9e2276f2df0 100644
--- a/clang/test/SemaCUDA/device-var-init.cu
+++ b/clang/test/SemaCUDA/device-var-init.cu
@@ -31,6 +31,14 @@ __device__ ECD d_ecd_i{};
 __shared__ ECD s_ecd_i{};
 __constant__ ECD c_ecd_i{};
 
+__device__ CEEC d_ceec;
+__shared__ CEEC s_ceec;
+__constant__ CEEC c_ceec;
+
+__device__ CGTC d_cgtc;
+__shared__ CGTC s_cgtc;
+__constant__ CGTC c_cgtc;
+
 __device__ EC d_ec_i(3);
 // expected-error@-1 {{dynamic initialization is not supported for __device__, 
__constant__, __shared__, and __managed__ variables.}}
 __shared__ EC s_ec_i(3);
@@ -213,6 +221,17 @@ __device__ void df_sema() {
   static const __device__ int cds = 1;
   static const __constant__ int cdc = 1;
 
+  for (int i = 0; i < 10; i++) {
+static __device__ CEEC sd_ceec;
+static __shared__ CEEC ss_ceec;
+static __constant__ CEEC sc_ceec;
+__shared__ CEEC s_ceec;
+
+static __device__ CGTC sd_cgtc;
+static __shared__ CGTC ss_cgtc;
+static __constant__ CGTC sc_cgtc;
+__shared__ CGTC s_cgtc;
+  }
 
   // __shared__ does not need to be explicitly static.
   __shared__ int lsi;
@@ -431,6 +450,35 @@ template 
 __global__ void bar() {
   __shared__ T bad;
 // expected-error@-1 {{initialization is not supported for __shared__ 
variables.}}
+  for (int i = 0; i < 10; i++) {
+static __device__ CEEC sd_ceec;
+static __shared__ CEEC ss_ceec;
+static __constant__ CEEC sc_ceec;
+__shared__ CEEC s_ceec;
+
+static __device__ CGTC sd_cgtc;
+static __shared__ CGTC ss_cgtc;
+static __constant__ CGTC sc_cgtc;
+__shared__ CGTC s_cgtc;
+  }
+}
+
+// Check specialization of template function.
+template <>
+__global__ void bar() {
+  __shared__ NontrivialInitializer bad;
+// expected-error@-1 {{initialization is not supported for __share

[clang] [CUDA][HIP] Fix init var diag in temmplate (PR #69081)

2023-10-14 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Yaxun (Sam) Liu (yxsamliu)


Changes

Currently clang diagnoses the following code:
(https://godbolt.org/z/s8zK3E5P5) but nvcc
does not.

`
struct A {
   constexpr A(){}
};

struct  B {
  A a;
  int b;
};

template
__global__ void kernel( )
{
   __shared__ B x;
}
`

Clang generates an implicit trivial ctor for struct B, which should be allowed 
for initializing a shared variable.

However, the body of the ctor is defined only if the template kernel is 
instantiated. Clang checks the initialization of variable in non-instantiated 
templates, where it cannot find the body of the ctor, therefore diagnoses it.

This patch skips the check for non-instantiated templates.

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


3 Files Affected:

- (modified) clang/lib/Sema/SemaCUDA.cpp (+7) 
- (modified) clang/test/SemaCUDA/Inputs/cuda-initializers.h (+11) 
- (modified) clang/test/SemaCUDA/device-var-init.cu (+48) 


``diff
diff --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index 7c4083e4ec4d4bb..d993499cf4a6e6e 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -632,6 +632,13 @@ bool HasAllowedCUDADeviceStaticInitializer(Sema &S, 
VarDecl *VD,
 } // namespace
 
 void Sema::checkAllowedCUDAInitializer(VarDecl *VD) {
+  // Return early if VD is inside a non-instantiated template function since
+  // the implicit constructor is not defined yet.
+  if (const FunctionDecl *FD =
+  dyn_cast_or_null(VD->getDeclContext()))
+if (FD->isDependentContext())
+  return;
+
   // Do not check dependent variables since the ctor/dtor/initializer are not
   // determined. Do it after instantiation.
   if (VD->isInvalidDecl() || !VD->hasInit() || !VD->hasGlobalStorage() ||
diff --git a/clang/test/SemaCUDA/Inputs/cuda-initializers.h 
b/clang/test/SemaCUDA/Inputs/cuda-initializers.h
index 837b726a13e0f4b..b1e7a1bd48fb576 100644
--- a/clang/test/SemaCUDA/Inputs/cuda-initializers.h
+++ b/clang/test/SemaCUDA/Inputs/cuda-initializers.h
@@ -143,3 +143,14 @@ struct T_F_NED {
 struct T_FA_NED {
   NED ned[2];
 };
+
+// contexpr empty ctor -- allowed
+struct CEEC {
+  constexpr CEEC() {}
+};
+
+// Compiler generated trivial ctor -- allowed
+struct CGTC {
+  CEEC ceec;
+  int a;
+};
diff --git a/clang/test/SemaCUDA/device-var-init.cu 
b/clang/test/SemaCUDA/device-var-init.cu
index 9d499bddbe1b31a..ee7a9e2276f2df0 100644
--- a/clang/test/SemaCUDA/device-var-init.cu
+++ b/clang/test/SemaCUDA/device-var-init.cu
@@ -31,6 +31,14 @@ __device__ ECD d_ecd_i{};
 __shared__ ECD s_ecd_i{};
 __constant__ ECD c_ecd_i{};
 
+__device__ CEEC d_ceec;
+__shared__ CEEC s_ceec;
+__constant__ CEEC c_ceec;
+
+__device__ CGTC d_cgtc;
+__shared__ CGTC s_cgtc;
+__constant__ CGTC c_cgtc;
+
 __device__ EC d_ec_i(3);
 // expected-error@-1 {{dynamic initialization is not supported for __device__, 
__constant__, __shared__, and __managed__ variables.}}
 __shared__ EC s_ec_i(3);
@@ -213,6 +221,17 @@ __device__ void df_sema() {
   static const __device__ int cds = 1;
   static const __constant__ int cdc = 1;
 
+  for (int i = 0; i < 10; i++) {
+static __device__ CEEC sd_ceec;
+static __shared__ CEEC ss_ceec;
+static __constant__ CEEC sc_ceec;
+__shared__ CEEC s_ceec;
+
+static __device__ CGTC sd_cgtc;
+static __shared__ CGTC ss_cgtc;
+static __constant__ CGTC sc_cgtc;
+__shared__ CGTC s_cgtc;
+  }
 
   // __shared__ does not need to be explicitly static.
   __shared__ int lsi;
@@ -431,6 +450,35 @@ template 
 __global__ void bar() {
   __shared__ T bad;
 // expected-error@-1 {{initialization is not supported for __shared__ 
variables.}}
+  for (int i = 0; i < 10; i++) {
+static __device__ CEEC sd_ceec;
+static __shared__ CEEC ss_ceec;
+static __constant__ CEEC sc_ceec;
+__shared__ CEEC s_ceec;
+
+static __device__ CGTC sd_cgtc;
+static __shared__ CGTC ss_cgtc;
+static __constant__ CGTC sc_cgtc;
+__shared__ CGTC s_cgtc;
+  }
+}
+
+// Check specialization of template function.
+template <>
+__global__ void bar() {
+  __shared__ NontrivialInitializer bad;
+// expected-error@-1 {{initialization is not supported for __shared__ 
variables.}}
+  for (int i = 0; i < 10; i++) {
+static __device__ CEEC sd_ceec;
+static __shared__ CEEC ss_ceec;
+static __constant__ CEEC sc_ceec;
+__shared__ CEEC s_ceec;
+
+static __device__ CGTC sd_cgtc;
+static __shared__ CGTC ss_cgtc;
+static __constant__ CGTC sc_cgtc;
+__shared__ CGTC s_cgtc;
+  }
 }
 
 void instantiate() {

``




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


[clang] [Clang][OHOS] Keep ARM ABI selection logic in sync between Clang and LLVM (PR #68656)

2023-10-14 Thread Brad Smith via cfe-commits


@@ -519,6 +519,7 @@ StringRef ARM::computeDefaultTargetABI(const Triple &TT, 
StringRef CPU) {
   case Triple::GNUEABIHF:
   case Triple::MuslEABI:
   case Triple::MuslEABIHF:
+  case llvm::Triple::OpenHOS:

brad0 wrote:

Oops, my bad. That has been corrected.

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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

2023-10-14 Thread Maksim Levental via cfe-commits


@@ -248,7 +248,7 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-void* operator new(__SIZE_TYPE__, void* __p) noexcept;
+#include 

makslevental wrote:

There's a placement `new` just below here (in this block of lines that's always 
interpreted). I didn't try just removing but I can.

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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

2023-10-14 Thread Maksim Levental via cfe-commits


@@ -20,4 +20,6 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_cast

makslevental wrote:

This was to test (since `` transitively includes ``).

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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

2023-10-14 Thread Maksim Levental via cfe-commits

https://github.com/makslevental updated 
https://github.com/llvm/llvm-project/pull/69072

>From d7c57d94d7e75ed1e0df87ebf3c4464e7b951453 Mon Sep 17 00:00:00 2001
From: max 
Date: Sat, 14 Oct 2023 12:46:42 -0500
Subject: [PATCH 1/2] [clang][repl] fix `new`

---
 clang/lib/Interpreter/Interpreter.cpp | 2 +-
 clang/test/Interpreter/execute.cpp| 2 ++
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 7968c62cbd3e7b3..ddfbc9ac01c6743 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -248,7 +248,7 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-void* operator new(__SIZE_TYPE__, void* __p) noexcept;
+#include 
 void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, void*);
diff --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 6e73ed3927e8155..d54ab99749c1bac 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -20,4 +20,6 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_cast
+
 %quit

>From b3c62d0d295129ad94f94fc641e789038c78f03a Mon Sep 17 00:00:00 2001
From: Maksim Levental 
Date: Sat, 14 Oct 2023 19:26:04 -0500
Subject: [PATCH 2/2] Update clang/lib/Interpreter/Interpreter.cpp

Remove include new

Co-authored-by: Vassil Vassilev 
---
 clang/lib/Interpreter/Interpreter.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index ddfbc9ac01c6743..30348e1c03f8c76 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -248,7 +248,6 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-#include 
 void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, void*);

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


[clang] [InstCombine] Refactor matchFunnelShift to allow more pattern (NFC) (PR #68474)

2023-10-14 Thread via cfe-commits


@@ -2732,100 +2732,114 @@ static Instruction *matchFunnelShift(Instruction &Or, 
InstCombinerImpl &IC) {
   // rotate matching code under visitSelect and visitTrunc?
   unsigned Width = Or.getType()->getScalarSizeInBits();
 
-  // First, find an or'd pair of opposite shifts:
-  // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
-  BinaryOperator *Or0, *Or1;
-  if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
-  !match(Or.getOperand(1), m_BinOp(Or1)))
-return nullptr;
-
-  Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
-  if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0 
||
-  !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1 
||
-  Or0->getOpcode() == Or1->getOpcode())
+  Instruction *Or0, *Or1;
+  if (!match(Or.getOperand(0), m_Instruction(Or0)) ||
+  !match(Or.getOperand(1), m_Instruction(Or1)))
 return nullptr;
 
-  // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
-  if (Or0->getOpcode() == BinaryOperator::LShr) {
-std::swap(Or0, Or1);
-std::swap(ShVal0, ShVal1);
-std::swap(ShAmt0, ShAmt1);
-  }
-  assert(Or0->getOpcode() == BinaryOperator::Shl &&
- Or1->getOpcode() == BinaryOperator::LShr &&
- "Illegal or(shift,shift) pair");
-
-  // Match the shift amount operands for a funnel shift pattern. This always
-  // matches a subtraction on the R operand.
-  auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
-// Check for constant shift amounts that sum to the bitwidth.
-const APInt *LI, *RI;
-if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
-  if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
-return ConstantInt::get(L->getType(), *LI);
-
-Constant *LC, *RC;
-if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
-match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) 
&&
-match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) 
&&
-match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
-  return ConstantExpr::mergeUndefsWith(LC, RC);
-
-// (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
-// We limit this to X < Width in case the backend re-expands the intrinsic,
-// and has to reintroduce a shift modulo operation (InstCombine might 
remove
-// it after this fold). This still doesn't guarantee that the final codegen
-// will match this original pattern.
-if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L) {
-  KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
-  return KnownL.getMaxValue().ult(Width) ? L : nullptr;
-}
+  bool IsFshl = true; // Sub on LSHR.
+  SmallVector FShiftArgs;
 
-// For non-constant cases, the following patterns currently only work for
-// rotation patterns.
-// TODO: Add general funnel-shift compatible patterns.
-if (ShVal0 != ShVal1)
+  // First, find an or'd pair of opposite shifts:
+  // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
+  if (isa(Or0) && isa(Or1)) {

HaohaiWen wrote:

> This code seems new? Not that its wrong or anything.

I added this if statement in this patch.


It can be early returned in this patch, but I'd like to add another else if on 
https://github.com/llvm/llvm-project/pull/68502/commits/5b3b1bbb5b263bc5711adde031d85b1461ccbab6.
 If I removed this if statement, then I need to add the if back and indent the 
code in the if statement on https://github.com/llvm/llvm-project/pull/68502. 
This make the diff not clear.

![image](https://github.com/llvm/llvm-project/assets/87643006/0bb081cb-97ee-4580-957b-a884110ee332)


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


[clang-tools-extra] [InstCombine] Refactor matchFunnelShift to allow more pattern (NFC) (PR #68474)

2023-10-14 Thread via cfe-commits


@@ -2732,100 +2732,114 @@ static Instruction *matchFunnelShift(Instruction &Or, 
InstCombinerImpl &IC) {
   // rotate matching code under visitSelect and visitTrunc?
   unsigned Width = Or.getType()->getScalarSizeInBits();
 
-  // First, find an or'd pair of opposite shifts:
-  // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
-  BinaryOperator *Or0, *Or1;
-  if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
-  !match(Or.getOperand(1), m_BinOp(Or1)))
-return nullptr;
-
-  Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
-  if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0 
||
-  !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1 
||
-  Or0->getOpcode() == Or1->getOpcode())
+  Instruction *Or0, *Or1;
+  if (!match(Or.getOperand(0), m_Instruction(Or0)) ||
+  !match(Or.getOperand(1), m_Instruction(Or1)))
 return nullptr;
 
-  // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
-  if (Or0->getOpcode() == BinaryOperator::LShr) {
-std::swap(Or0, Or1);
-std::swap(ShVal0, ShVal1);
-std::swap(ShAmt0, ShAmt1);
-  }
-  assert(Or0->getOpcode() == BinaryOperator::Shl &&
- Or1->getOpcode() == BinaryOperator::LShr &&
- "Illegal or(shift,shift) pair");
-
-  // Match the shift amount operands for a funnel shift pattern. This always
-  // matches a subtraction on the R operand.
-  auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
-// Check for constant shift amounts that sum to the bitwidth.
-const APInt *LI, *RI;
-if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
-  if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
-return ConstantInt::get(L->getType(), *LI);
-
-Constant *LC, *RC;
-if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
-match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) 
&&
-match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) 
&&
-match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
-  return ConstantExpr::mergeUndefsWith(LC, RC);
-
-// (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
-// We limit this to X < Width in case the backend re-expands the intrinsic,
-// and has to reintroduce a shift modulo operation (InstCombine might 
remove
-// it after this fold). This still doesn't guarantee that the final codegen
-// will match this original pattern.
-if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L) {
-  KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
-  return KnownL.getMaxValue().ult(Width) ? L : nullptr;
-}
+  bool IsFshl = true; // Sub on LSHR.
+  SmallVector FShiftArgs;
 
-// For non-constant cases, the following patterns currently only work for
-// rotation patterns.
-// TODO: Add general funnel-shift compatible patterns.
-if (ShVal0 != ShVal1)
+  // First, find an or'd pair of opposite shifts:
+  // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
+  if (isa(Or0) && isa(Or1)) {

HaohaiWen wrote:

> This code seems new? Not that its wrong or anything.

I added this if statement in this patch.


It can be early returned in this patch, but I'd like to add another else if on 
https://github.com/llvm/llvm-project/pull/68502/commits/5b3b1bbb5b263bc5711adde031d85b1461ccbab6.
 If I removed this if statement, then I need to add the if back and indent the 
code in the if statement on https://github.com/llvm/llvm-project/pull/68502. 
This make the diff not clear.

![image](https://github.com/llvm/llvm-project/assets/87643006/0bb081cb-97ee-4580-957b-a884110ee332)


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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

2023-10-14 Thread Maksim Levental via cfe-commits


@@ -248,7 +248,7 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-void* operator new(__SIZE_TYPE__, void* __p) noexcept;
+#include 

makslevental wrote:

Ya so you need something here.

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


[clang-tools-extra] [clang-tidy][modernize-loop-convert]check isDependentSizedArrayType (PR #69062)

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

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

>From bfeaa2eeaa3d20e1919288bcf1027ec196378236 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sun, 15 Oct 2023 00:20:08 +0800
Subject: [PATCH 1/2] [clang-tidy][modernize-loop-convert]check
 isDependentSizedArrayType before resolve type size

---
 .../clang-tidy/modernize/LoopConvertCheck.cpp| 1 +
 clang-tools-extra/docs/ReleaseNotes.rst  | 4 
 .../clang-tidy/checkers/modernize/loop-convert-basic.cpp | 9 +
 3 files changed, 14 insertions(+)

diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index f90d99a8d66069d..8beaa62c78ba0ab 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -753,6 +753,7 @@ void LoopConvertCheck::doConversion(
   bool IsCheapToCopy =
   !Descriptor.ElemType.isNull() &&
   Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
+  !Descriptor.ElemType->isDependentSizedArrayType() &&
   // TypeInfo::Width is in bits.
   Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
   bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 03e5dc6f164af2a..ae440210d8a4f2b 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -269,6 +269,10 @@ Changes in existing checks
   ` to support for-loops with
   iterators initialized by free functions like ``begin``, ``end``, or ``size``.
 
+- Improved :doc:`modernize-loop-convert
+   ` to avoid crash dor dependent
+   array.
+
 - Improved :doc:`modernize-return-braced-init-list
   ` check to ignore
   false-positives when constructing the container with ``count`` copies of
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
index 71ae4c46e6a5e95..8d8144a729bbdee 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
@@ -939,4 +939,13 @@ void fundamentalTypesTest() {
   // CHECK-FIXES: for (double Double : Doubles)
 }
 
+template  void test() {
+  unsigned int test[3][p];
+  // Initialize to zero
+  for (unsigned int i = 0; i < p; ++i)
+for (unsigned int j = 0; j < 3; ++j) // CHECK-MESSAGES: warning: use 
range-based for loop instead
+  // CHECK-FIXES: (auto & j : test)
+  test[j][i] = 0;
+}
+
 } // namespace PseudoArray

>From 89ddc2510e74b7b7460384860ce691a6784fa82b Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sun, 15 Oct 2023 09:42:33 +0800
Subject: [PATCH 2/2] fix

---
 clang-tools-extra/docs/ReleaseNotes.rst| 7 ++-
 .../clang-tidy/checkers/modernize/loop-convert-basic.cpp   | 6 --
 2 files changed, 6 insertions(+), 7 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index ae440210d8a4f2b..63f9a2418eca5aa 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -267,11 +267,8 @@ Changes in existing checks
 
 - Improved :doc:`modernize-loop-convert
   ` to support for-loops with
-  iterators initialized by free functions like ``begin``, ``end``, or ``size``.
-
-- Improved :doc:`modernize-loop-convert
-   ` to avoid crash dor dependent
-   array.
+  iterators initialized by free functions like ``begin``, ``end``, or ``size``
+  and avoid crash for array of dependent array.
 
 - Improved :doc:`modernize-return-braced-init-list
   ` check to ignore
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
index 8d8144a729bbdee..2e43bc6ff96e4e5 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
@@ -943,9 +943,11 @@ template  void test() {
   unsigned int test[3][p];
   // Initialize to zero
   for (unsigned int i = 0; i < p; ++i)
-for (unsigned int j = 0; j < 3; ++j) // CHECK-MESSAGES: warning: use 
range-based for loop instead
-  // CHECK-FIXES: (auto & j : test)
+for (unsigned int j = 0; j < 3; ++j)
   test[j][i] = 0;
+  // CHECK-MESSAGES: :[[@LINE-2]]:5: warning: use range-based for loop instead
+  // CHECK-FIXES: (auto & j : test)
+  // CHECK-FIXES: j[i] = 0;
 }
 
 } // namespace PseudoArray

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


[clang-tools-extra] [clang-tidy][modernize-loop-convert]check isDependentSizedArrayType (PR #69062)

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

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


[clang] 2dc6579 - clang: Switch SYCL test to generated checks

2023-10-14 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2023-10-15T11:44:40+09:00
New Revision: 2dc6579f6fb12470559a68886c2a4aecaa8495dd

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

LOG: clang: Switch SYCL test to generated checks

Added: 


Modified: 
clang/test/CodeGenSYCL/function-attrs.cpp

Removed: 




diff  --git a/clang/test/CodeGenSYCL/function-attrs.cpp 
b/clang/test/CodeGenSYCL/function-attrs.cpp
index 8f5c0ea5c512cd5..1606f961f2d3913 100644
--- a/clang/test/CodeGenSYCL/function-attrs.cpp
+++ b/clang/test/CodeGenSYCL/function-attrs.cpp
@@ -1,16 +1,29 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --check-globals --version 3
 // RUN: %clang_cc1 -fsycl-is-device -emit-llvm -disable-llvm-passes \
-// RUN:  -triple spir64 -fexceptions -emit-llvm %s -o - | FileCheck %s
+// RUN:  -triple spir64 -fexceptions -emit-llvm -fno-ident %s -o - | FileCheck 
%s
 
 int foo();
 
-// CHECK: define dso_local spir_func void @_Z3barv() [[BAR:#[0-9]+]]
-// CHECK: attributes [[BAR]] =
-// CHECK-SAME: convergent
-// CHECK-SAME: nounwind
+// CHECK-LABEL: define dso_local spir_func void @_Z3barv(
+// CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[A_ASCAST:%.*]] = addrspacecast ptr [[A]] to ptr 
addrspace(4)
+// CHECK-NEXT:[[CALL:%.*]] = call spir_func noundef i32 @_Z3foov() 
#[[ATTR1:[0-9]+]]
+// CHECK-NEXT:store i32 [[CALL]], ptr addrspace(4) [[A_ASCAST]], align 4
+// CHECK-NEXT:ret void
+//
 void bar() {
   int a = foo();
 }
 
+// CHECK-LABEL: define dso_local spir_func noundef i32 @_Z3foov(
+// CHECK-SAME: ) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[RETVAL_ASCAST:%.*]] = addrspacecast ptr [[RETVAL]] to ptr 
addrspace(4)
+// CHECK-NEXT:ret i32 1
+//
 int foo() {
   return 1;
 }
@@ -20,7 +33,24 @@ __attribute__((sycl_kernel)) void kernel_single_task(const 
Func &kernelFunc) {
   kernelFunc();
 }
 
+// CHECK-LABEL: define dso_local noundef i32 @main(
+// CHECK-SAME: ) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[REF_TMP:%.*]] = alloca [[CLASS_ANON:%.*]], align 1
+// CHECK-NEXT:[[RETVAL_ASCAST:%.*]] = addrspacecast ptr [[RETVAL]] to ptr 
addrspace(4)
+// CHECK-NEXT:[[REF_TMP_ASCAST:%.*]] = addrspacecast ptr [[REF_TMP]] to 
ptr addrspace(4)
+// CHECK-NEXT:store i32 0, ptr addrspace(4) [[RETVAL_ASCAST]], align 4
+// CHECK-NEXT:call spir_func void 
@_Z18kernel_single_taskIZ4mainE11fake_kernelZ4mainEUlvE_EvRKT0_(ptr 
addrspace(4) noundef align 1 dereferenceable(1) [[REF_TMP_ASCAST]]) #[[ATTR1]]
+// CHECK-NEXT:ret i32 0
+//
 int main() {
   kernel_single_task([] { bar(); });
   return 0;
 }
+//.
+// CHECK: attributes #0 = { convergent mustprogress noinline norecurse 
nounwind optnone "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
+// CHECK: attributes #1 = { convergent nounwind }
+//.
+// CHECK: !0 = !{i32 1, !"wchar_size", i32 4}
+//.



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


[clang] [RISCV] Implement shadow stack on shadow stack mode with Zicfiss. (PR #68075)

2023-10-14 Thread Yeting Kuo via cfe-commits


@@ -106,9 +111,14 @@ static void emitSCSEpilogue(MachineFunction &MF, 
MachineBasicBlock &MBB,
   CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
 return;
 
+  const RISCVInstrInfo *TII = STI.getInstrInfo();
+  if (STI.hasFeature(RISCV::FeatureStdExtZicfiss)) {

yetingk wrote:

> Do we need an enable other than just the feature being in -march? The shadow 
> stack pointer has to be set up when the application starts.

The hardware shadow stack support in this pr needs 
`-fsanitize=shadow-call-stack` now.  

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


[clang] [RISCV] Implement shadow stack on shadow stack mode with Zicfiss. (PR #68075)

2023-10-14 Thread Craig Topper via cfe-commits


@@ -106,9 +111,14 @@ static void emitSCSEpilogue(MachineFunction &MF, 
MachineBasicBlock &MBB,
   CSI, [&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
 return;
 
+  const RISCVInstrInfo *TII = STI.getInstrInfo();
+  if (STI.hasFeature(RISCV::FeatureStdExtZicfiss)) {

topperc wrote:

> > Do we need an enable other than just the feature being in -march? The 
> > shadow stack pointer has to be set up when the application starts.
> 
> The hardware shadow stack support in this pr needs 
> `-fsanitize=shadow-call-stack` now.

What if we're compiling for a platform that only uses the software shadow stack 
and does not support the hardware shadow stack even if the CPU supports it?

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


[clang] [clang][repl] fix `new` on Mac M1 (PR #69072)

2023-10-14 Thread Maksim Levental via cfe-commits

https://github.com/makslevental updated 
https://github.com/llvm/llvm-project/pull/69072

>From d7c57d94d7e75ed1e0df87ebf3c4464e7b951453 Mon Sep 17 00:00:00 2001
From: max 
Date: Sat, 14 Oct 2023 12:46:42 -0500
Subject: [PATCH 1/3] [clang][repl] fix `new`

---
 clang/lib/Interpreter/Interpreter.cpp | 2 +-
 clang/test/Interpreter/execute.cpp| 2 ++
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 7968c62cbd3e7b3..ddfbc9ac01c6743 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -248,7 +248,7 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-void* operator new(__SIZE_TYPE__, void* __p) noexcept;
+#include 
 void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, void*);
diff --git a/clang/test/Interpreter/execute.cpp 
b/clang/test/Interpreter/execute.cpp
index 6e73ed3927e8155..d54ab99749c1bac 100644
--- a/clang/test/Interpreter/execute.cpp
+++ b/clang/test/Interpreter/execute.cpp
@@ -20,4 +20,6 @@ auto r2 = printf("S[f=%f, m=0x%llx]\n", s.f, 
reinterpret_cast
+
 %quit

>From b3c62d0d295129ad94f94fc641e789038c78f03a Mon Sep 17 00:00:00 2001
From: Maksim Levental 
Date: Sat, 14 Oct 2023 19:26:04 -0500
Subject: [PATCH 2/3] Update clang/lib/Interpreter/Interpreter.cpp

Remove include new

Co-authored-by: Vassil Vassilev 
---
 clang/lib/Interpreter/Interpreter.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index ddfbc9ac01c6743..30348e1c03f8c76 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -248,7 +248,6 @@ Interpreter::~Interpreter() {
 // can't find the precise resource directory in unittests so we have to hard
 // code them.
 const char *const Runtimes = R"(
-#include 
 void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*);
 void __clang_Interpreter_SetValueNoAlloc(void*, void*, void*, void*);

>From cfb0771a5040d48f3a41108e541ed6f467438f4e Mon Sep 17 00:00:00 2001
From: max 
Date: Sat, 14 Oct 2023 23:44:01 -0500
Subject: [PATCH 3/3] branch on isdarwin

---
 clang/lib/Interpreter/Interpreter.cpp | 9 -
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 30348e1c03f8c76..dcb214a88806916 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -274,7 +274,14 @@ Interpreter::create(std::unique_ptr CI) {
   if (Err)
 return std::move(Err);
 
-  auto PTU = Interp->Parse(Runtimes);
+  std::string runtimes = "";
+  if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin())
+runtimes += "#include \n";
+  else
+runtimes += "void* operator new(__SIZE_TYPE__, void* __p) noexcept;\n";
+  runtimes += Runtimes;
+
+  auto PTU = Interp->Parse(runtimes);
   if (!PTU)
 return PTU.takeError();
 

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


[clang-tools-extra] 0d661e9 - [clangd] Use DenseMap::contains (NFC)

2023-10-14 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2023-10-14T22:11:09-07:00
New Revision: 0d661e965ad1a54e46317f38677bd88875bfcf1d

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

LOG: [clangd] Use DenseMap::contains (NFC)

Added: 


Modified: 
clang-tools-extra/clangd/index/SymbolCollector.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 74aca9b99c8a584..aac6676a995fedf 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -893,7 +893,7 @@ void SymbolCollector::finish() {
 const Symbol *S = Symbols.find(SID);
 if (!S)
   continue;
-assert(IncludeFiles.find(SID) != IncludeFiles.end());
+assert(IncludeFiles.contains(SID));
 
 const auto FID = IncludeFiles.at(SID);
 // Determine if the FID is #include'd or #import'ed.



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


[clang] 169f60f - [clang][driver] Add avr-libc's default linker script to lld (#68507)

2023-10-14 Thread via cfe-commits

Author: Ben Shi
Date: 2023-10-15T13:47:56+08:00
New Revision: 169f60f7c76cb6f7d234ab5dfb2b5e367a35ccbb

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

LOG: [clang][driver] Add avr-libc's default linker script to lld (#68507)

If `-fuse-ld=lld` is specified but no user linker script is offered, we
try to use avr-libc's default one for lld. (not needed for GNU ld)

Added: 
clang/test/Driver/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avrtiny.x

clang/test/Driver/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avrxmega6.x

Modified: 
clang/lib/Driver/ToolChains/AVR.cpp
clang/test/Driver/avr-ld.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AVR.cpp 
b/clang/lib/Driver/ToolChains/AVR.cpp
index e312fa155e11bf8..2e46b25aeba75ef 100644
--- a/clang/lib/Driver/ToolChains/AVR.cpp
+++ b/clang/lib/Driver/ToolChains/AVR.cpp
@@ -554,8 +554,18 @@ void AVR::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 
 CmdArgs.push_back("--end-group");
 
-// Add user specified linker script.
-Args.AddAllArgs(CmdArgs, options::OPT_T);
+// Add avr-libc's linker script to lld by default, if it exists.
+if (!Args.hasArg(options::OPT_T) &&
+Linker.find("lld") != std::string::npos) {
+  std::string Path(*AVRLibcRoot + "/lib/ldscripts/");
+  Path += *FamilyName;
+  Path += ".x";
+  if (llvm::sys::fs::exists(Path))
+CmdArgs.push_back(Args.MakeArgString("-T" + Path));
+}
+// Otherwise add user specified linker script to either avr-ld or lld.
+else
+  Args.AddAllArgs(CmdArgs, options::OPT_T);
 
 if (Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true))
   CmdArgs.push_back("--relax");

diff  --git 
a/clang/test/Driver/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avrtiny.x 
b/clang/test/Driver/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avrtiny.x
new file mode 100644
index 000..e69de29bb2d1d64

diff  --git 
a/clang/test/Driver/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avrxmega6.x 
b/clang/test/Driver/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avrxmega6.x
new file mode 100644
index 000..e69de29bb2d1d64

diff  --git a/clang/test/Driver/avr-ld.c b/clang/test/Driver/avr-ld.c
index 0f12607fe9d69eb..3e4114485332fcd 100644
--- a/clang/test/Driver/avr-ld.c
+++ b/clang/test/Driver/avr-ld.c
@@ -58,6 +58,28 @@
 // LINKS: {{".*ld.*"}} {{.*}} "--defsym=__DATA_REGION_ORIGIN__=0x800100" 
"-plugin-opt=mcpu=atmega328"
 // LINKS-NOT: "-plugin-opt=thinlto"
 
+// RUN: %clang -### --target=avr -mmcu=attiny40 -fuse-ld=lld --sysroot 
%S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKT0 %s
+// LINKT0: {{".*lld.*"}} {{.*}} {{"-T.*avrtiny.x"}}
+// LINKT0-NOT: "-m
+
+// RUN: %clang -### --target=avr -mmcu=atxmega384c3 -fuse-ld=lld --sysroot 
%S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKT1 %s
+// LINKT1: {{".*lld.*"}} {{.*}} {{"-T.*avrxmega6.x"}}
+// LINKT1-NOT: "-m
+
+// RUN: %clang -### --target=avr -mmcu=atmega328 -fuse-ld=lld --sysroot 
%S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKT2 %s
+// LINKT2: {{".*lld.*"}} {{.*}} "--start-group" {{.*}} "--end-group"
+// LINKT2-NOT: "-T
+// LINKT2-NOT: "-m
+
+// RUN: %clang -### --target=avr -mmcu=attiny40 --sysroot 
%S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKT3 %s
+// LINKT3: {{".*ld.*"}} {{.*}} "-mavrtiny"
+// LINKT3-NOT: "-T
+
+// RUN: %clang -### --target=avr -mmcu=attiny40 --sysroot 
%S/Inputs/basic_avr_tree -fuse-ld=lld -T 
%S/Inputs/basic_avr_tree/usr/lib/avr/lib/ldscripts/avrxmega6.x %s 2>&1 | 
FileCheck -check-prefix LINKT4 %s
+// LINKT4: {{".*lld.*"}} {{.*}} {{"-T.*avrxmega6.x"}}
+// LINKT4-NOT: {{"-T.*avrtiny.x"}}
+// LINKT4-NOT: "-m
+
 // RUN: %clang -### -r --target=avr -mmcu=atmega328 --sysroot 
%S/Inputs/basic_avr_tree %s 2>&1 | FileCheck --check-prefix=LINKU %s
 // LINKU: {{".*ld.*"}} {{.*}} "-r" {{.*}} "-mavr5"
 // LINKU-NOT: "--gc-sections"



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


[clang] [clang][driver] Add avr-libc's default linker script to lld (PR #68507)

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

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


[clang] 3c4ecc4 - [clang][Interp][NFC] Refactor VisitImplicitValueInitExpr

2023-10-14 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-15T08:52:43+02:00
New Revision: 3c4ecc4628601d07201780ea9ed23770a5a2d86c

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

LOG: [clang][Interp][NFC] Refactor VisitImplicitValueInitExpr

The FIXME comment here is not really correct. Also, handle the case of
non-primitive array element types differently, to reduce indentation.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index bda9cf1500804f7..e9e20b222d5d34f 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -504,19 +504,13 @@ bool 
ByteCodeExprGen::VisitImplicitValueInitExpr(const ImplicitValueIni
 assert(AT);
 const auto *CAT = cast(AT);
 size_t NumElems = CAT->getSize().getZExtValue();
+PrimType ElemT = classifyPrim(CAT->getElementType());
 
-if (std::optional ElemT = classify(CAT->getElementType())) {
-  // TODO(perf): For int and bool types, we can probably just skip this
-  //   since we memset our Block*s to 0 and so we have the desired value
-  //   without this.
-  for (size_t I = 0; I != NumElems; ++I) {
-if (!this->visitZeroInitializer(*ElemT, CAT->getElementType(), E))
-  return false;
-if (!this->emitInitElem(*ElemT, I, E))
-  return false;
-  }
-} else {
-  assert(false && "default initializer for non-primitive type");
+for (size_t I = 0; I != NumElems; ++I) {
+  if (!this->visitZeroInitializer(ElemT, CAT->getElementType(), E))
+return false;
+  if (!this->emitInitElem(ElemT, I, E))
+return false;
 }
 
 return true;



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


  1   2   >