[clang] [lldb] fixing issue #64441 (PR #74814)

2024-06-01 Thread Jeevan Ghimire via cfe-commits

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


[clang] [llvm] [mlir] Use llvm::less_first (NFC) (PR #94136)

2024-06-01 Thread Fangrui Song via cfe-commits

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


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


[clang] [llvm] [mlir] Use llvm::less_first (NFC) (PR #94136)

2024-06-01 Thread Mehdi Amini via cfe-commits

https://github.com/joker-eph approved this pull request.


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


[clang] [clang-format] add an option to insert a space only for non-code block empty braces, not for empty parentheses (PR #93634)

2024-06-01 Thread Kohei Asano via cfe-commits

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


[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)

2024-06-01 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-pgo

Author: Lambdaris (Lambdaris)


Changes

To close #93560 .

# Changes

1. Clang only sets the counter in folded branch to `Zero`. And llvm-cov shows a 
branch as folded as long as either of its counters is `Zero`.
2. Add two additional results, `uncoverable` and `unreachable` to MCDC 
conditions. `uncoverable` means the condition can not effect value of the 
decision, while `unreachable` means the condition is always short-circuited. 
Since both the two kinds of conditions is by no means covered, they are 
excluded from MCDC and informed to users. The scheme to identify such 
conditions is described at this 
[comment](https://github.com/llvm/llvm-project/issues/93560#issuecomment-2142551335).

---

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


18 Files Affected:

- (modified) clang/docs/SourceBasedCodeCoverage.rst (+12) 
- (modified) clang/lib/CodeGen/CoverageMappingGen.cpp (+19-8) 
- (modified) clang/test/CoverageMapping/branch-constfolded.cpp (+20-20) 
- (modified) clang/test/CoverageMapping/if.cpp (+2-2) 
- (modified) clang/test/CoverageMapping/macro-expansion.c (+5-5) 
- (modified) clang/test/CoverageMapping/mcdc-scratch-space.c (+2-2) 
- (modified) clang/test/CoverageMapping/mcdc-system-headers.cpp (+2-2) 
- (modified) llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h (+50-21) 
- (modified) llvm/lib/ProfileData/Coverage/CoverageMapping.cpp (+103-13) 
- (modified) llvm/test/tools/llvm-cov/Inputs/mcdc-const-folding.o () 
- (modified) llvm/test/tools/llvm-cov/Inputs/mcdc-const.o () 
- (modified) llvm/test/tools/llvm-cov/Inputs/mcdc-macro.o () 
- (modified) llvm/test/tools/llvm-cov/branch-c-general.test (+6-6) 
- (modified) llvm/test/tools/llvm-cov/mcdc-const.test (+47-47) 
- (modified) llvm/tools/llvm-cov/CoverageReport.cpp (+4-1) 
- (modified) llvm/tools/llvm-cov/CoverageSummaryInfo.cpp (+1-1) 
- (modified) llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp (+6-1) 
- (modified) llvm/tools/llvm-cov/SourceCoverageViewText.cpp (+10-4) 


``diff
diff --git a/clang/docs/SourceBasedCodeCoverage.rst 
b/clang/docs/SourceBasedCodeCoverage.rst
index cee706289284d..f875187c80608 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -496,6 +496,18 @@ starts a new boolean expression that is separated from the 
other conditions by
 the operator ``func()``.  When this is encountered, a warning will be generated
 and the boolean expression will not be instrumented.
 
+Similar as branch coverage, MCDC also is not tracked for constant folded 
conditions.
+Moreover it's even not tracked for conditions that can not effect outcomes of 
decisions
+due to other constants. These conditions will be shown as ``uncoverable`` or 
+``unreachable``, determined by whether they can be visited. For instance, in 
+``a || true || b``, value of the decision is always ``true`` by reason of the 
constant
+condition. Thus ``a`` can not lead the decision to ``false`` even though it 
could branch, 
+while ``b`` is always short-circuited. Hence ``a`` is shown as ``uncoverable``
+and ``b`` is marked as ``unreachable``. Statistics of MCDC does not count 
constant 
+conditions which do not vary or such conditions which make no difference on 
value of 
+decisions. If a decision is proved to no branch theoretically, it shows mark 
``Folded``
+rather than coverage percent.
+
 Switch statements
 -
 
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 6ce2d32dd292e..37e6543795558 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1084,9 +1084,13 @@ struct CounterCoverageMappingBuilder
   }
 
   /// Determine whether the given condition can be constant folded.
-  bool ConditionFoldsToBool(const Expr *Cond) {
+  bool ConditionFoldsToBool(const Expr *Cond, bool ) {
 Expr::EvalResult Result;
-return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
+if (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext())) {
+  ResultBool = Result.Val.getInt().getBoolValue();
+  return true;
+}
+return false;
   }
 
   /// Create a Branch Region around an instrumentable condition for coverage
@@ -1113,15 +1117,22 @@ struct CounterCoverageMappingBuilder
 BranchParams = mcdc::BranchParameters{ID, Conds};
 
   // If a condition can fold to true or false, the corresponding branch
-  // will be removed.  Create a region with both counters hard-coded to
-  // zero. This allows us to visualize them in a special way.
+  // will be removed. Create a region with the relative counter hard-coded
+  // to zero. This allows us to visualize them in a special way.
   // Alternatively, we can prevent any optimization done via
   // constant-folding by ensuring that 

[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)

2024-06-01 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)

2024-06-01 Thread via cfe-commits

https://github.com/Lambdaris created 
https://github.com/llvm/llvm-project/pull/94137

To close #93560 .

# Changes

1. Clang only sets the counter in folded branch to `Zero`. And llvm-cov shows a 
branch as folded as long as either of its counters is `Zero`.
2. Add two additional results, `uncoverable` and `unreachable` to MCDC 
conditions. `uncoverable` means the condition can not effect value of the 
decision, while `unreachable` means the condition is always short-circuited. 
Since both the two kinds of conditions is by no means covered, they are 
excluded from MCDC and informed to users. The scheme to identify such 
conditions is described at this 
[comment](https://github.com/llvm/llvm-project/issues/93560#issuecomment-2142551335).

>From d2fe89a625e84b585362e8800d7fac2d034ec85a Mon Sep 17 00:00:00 2001
From: Lambdaris 
Date: Sun, 2 Jun 2024 10:19:31 +0800
Subject: [PATCH 1/2] [coverage] Mark branches with either counter is zero as
 folded

---
 clang/lib/CodeGen/CoverageMappingGen.cpp  | 27 +
 .../CoverageMapping/branch-constfolded.cpp| 40 +--
 clang/test/CoverageMapping/if.cpp |  4 +-
 clang/test/CoverageMapping/macro-expansion.c  | 10 ++---
 .../test/CoverageMapping/mcdc-scratch-space.c |  4 +-
 .../CoverageMapping/mcdc-system-headers.cpp   |  4 +-
 .../ProfileData/Coverage/CoverageMapping.h|  4 +-
 .../ProfileData/Coverage/CoverageMapping.cpp  |  4 +-
 .../test/tools/llvm-cov/branch-c-general.test | 12 +++---
 9 files changed, 61 insertions(+), 48 deletions(-)

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 6ce2d32dd292e..37e6543795558 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1084,9 +1084,13 @@ struct CounterCoverageMappingBuilder
   }
 
   /// Determine whether the given condition can be constant folded.
-  bool ConditionFoldsToBool(const Expr *Cond) {
+  bool ConditionFoldsToBool(const Expr *Cond, bool ) {
 Expr::EvalResult Result;
-return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
+if (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext())) {
+  ResultBool = Result.Val.getInt().getBoolValue();
+  return true;
+}
+return false;
   }
 
   /// Create a Branch Region around an instrumentable condition for coverage
@@ -1113,15 +1117,22 @@ struct CounterCoverageMappingBuilder
 BranchParams = mcdc::BranchParameters{ID, Conds};
 
   // If a condition can fold to true or false, the corresponding branch
-  // will be removed.  Create a region with both counters hard-coded to
-  // zero. This allows us to visualize them in a special way.
+  // will be removed. Create a region with the relative counter hard-coded
+  // to zero. This allows us to visualize them in a special way.
   // Alternatively, we can prevent any optimization done via
   // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
   // CodeGenFunction.c always returns false, but that is very heavy-handed.
-  if (ConditionFoldsToBool(C))
-popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
-  Counter::getZero(), BranchParams));
-  else
+  bool ConstantBool = false;
+  if (ConditionFoldsToBool(C, ConstantBool)) {
+if (ConstantBool) {
+  popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C),
+Counter::getZero(), BranchParams));
+} else {
+  popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
+FalseCnt, BranchParams));
+}
+
+  } else
 // Otherwise, create a region with the True counter and False counter.
 popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt,
   BranchParams));
diff --git a/clang/test/CoverageMapping/branch-constfolded.cpp 
b/clang/test/CoverageMapping/branch-constfolded.cpp
index c8755d5d752b6..1e1639ba796df 100644
--- a/clang/test/CoverageMapping/branch-constfolded.cpp
+++ b/clang/test/CoverageMapping/branch-constfolded.cpp
@@ -5,94 +5,94 @@
 
 // CHECK-LABEL: _Z6fand_0b:
 bool fand_0(bool a) {  // MCDC: Decision,File 0, [[@LINE+1]]:10 -> 
[[@LINE+1]]:20 = M:0, C:2
-  return false && a;   // CHECK: Branch,File 0, [[@LINE]]:10 -> 
[[@LINE]]:15 = 0, 0
+  return false && a;   // CHECK: Branch,File 0, [[@LINE]]:10 -> 
[[@LINE]]:15 = 0, (#0 - #1)
 }  // CHECK: Branch,File 0, [[@LINE-1]]:19 -> 
[[@LINE-1]]:20 = #2, (#1 - #2)
 
 // CHECK-LABEL: _Z6fand_1b:
 bool fand_1(bool a) {  // MCDC: Decision,File 0, [[@LINE+1]]:10 -> 
[[@LINE+1]]:19 = M:0, C:2
   return a && true;// CHECK: Branch,File 0, [[@LINE]]:10 -> 
[[@LINE]]:11 = #1, (#0 - #1)
-}  // CHECK: Branch,File 0, [[@LINE-1]]:15 -> 
[[@LINE-1]]:19 = 0, 0
+}  

[clang] [llvm] [mlir] Use llvm::less_first (NFC) (PR #94136)

2024-06-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes



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


6 Files Affected:

- (modified) clang/lib/Serialization/ASTWriter.cpp (+1-3) 
- (modified) clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
(+1-3) 
- (modified) llvm/lib/MC/MCPseudoProbe.cpp (+2-8) 
- (modified) llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h (+1-4) 
- (modified) mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp 
(+1-3) 
- (modified) mlir/lib/Dialect/SparseTensor/Transforms/Utils/LoopEmitter.cpp 
(+1-2) 


``diff
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index e830c4026ea78..eb41a205bc82c 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -3205,9 +3205,7 @@ void ASTWriter::WritePragmaDiagnosticMappings(const 
DiagnosticsEngine ,
   }
 
   // Sort by diag::kind for deterministic output.
-  llvm::sort(Mappings, [](const auto , const auto ) {
-return LHS.first < RHS.first;
-  });
+  llvm::sort(Mappings, llvm::less_first());
 
   for (const auto  : Mappings) {
 Record.push_back(I.first);
diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 0c047b6c5da2f..0f82f22d8b9a8 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -259,9 +259,7 @@ static void canonicalizeDefines(PreprocessorOptions 
) {
 ++Index;
   }
 
-  llvm::stable_sort(SimpleNames, [](const MacroOpt , const MacroOpt ) {
-return A.first < B.first;
-  });
+  llvm::stable_sort(SimpleNames, llvm::less_first());
   // Keep the last instance of each macro name by going in reverse
   auto NewEnd = std::unique(
   SimpleNames.rbegin(), SimpleNames.rend(),
diff --git a/llvm/lib/MC/MCPseudoProbe.cpp b/llvm/lib/MC/MCPseudoProbe.cpp
index cec50322bb9f9..040f3aab88128 100644
--- a/llvm/lib/MC/MCPseudoProbe.cpp
+++ b/llvm/lib/MC/MCPseudoProbe.cpp
@@ -182,13 +182,10 @@ void MCPseudoProbeInlineTree::emit(MCObjectStreamer *MCOS,
   // Emit sorted descendant. InlineSite is unique for each pair, so there will
   // be no ordering of Inlinee based on MCPseudoProbeInlineTree*
   using InlineeType = std::pair;
-  auto Comparer = [](const InlineeType , const InlineeType ) {
-return A.first < B.first;
-  };
   std::vector Inlinees;
   for (const auto  : Children)
 Inlinees.emplace_back(Child.first, Child.second.get());
-  std::sort(Inlinees.begin(), Inlinees.end(), Comparer);
+  llvm::sort(Inlinees, llvm::less_first());
 
   for (const auto  : Inlinees) {
 // Emit probe index
@@ -230,13 +227,10 @@ void MCPseudoProbeSections::emit(MCObjectStreamer *MCOS) {
   // Emit sorted descendant. InlineSite is unique for each pair, so there
   // will be no ordering of Inlinee based on MCPseudoProbeInlineTree*
   using InlineeType = std::pair;
-  auto Comparer = [](const InlineeType , const InlineeType ) {
-return A.first < B.first;
-  };
   std::vector Inlinees;
   for (const auto  : Root.getChildren())
 Inlinees.emplace_back(Child.first, Child.second.get());
-  std::sort(Inlinees.begin(), Inlinees.end(), Comparer);
+  llvm::sort(Inlinees, llvm::less_first());
 
   for (const auto  : Inlinees) {
 // Emit the group guarded by a sentinel probe.
diff --git a/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h 
b/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
index 8c014832f5e46..9fe02e24c8a15 100644
--- a/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
+++ b/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
@@ -597,10 +597,7 @@ class SIMachineFunctionInfo final : public 
AMDGPUMachineFunction,
   const ReservedRegSet () const { return WWMReservedRegs; }
 
   ArrayRef getPrologEpilogSGPRSpills() const {
-assert(
-is_sorted(PrologEpilogSGPRSpills, [](const auto , const auto ) 
{
-  return LHS.first < RHS.first;
-}));
+assert(is_sorted(PrologEpilogSGPRSpills, llvm::less_first()));
 return PrologEpilogSGPRSpills;
   }
 
diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp 
b/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
index 36ecf692b02c5..ce7f6b2865375 100644
--- a/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
+++ b/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
@@ -557,9 +557,7 @@ struct GenericOpScheduler : public 
OpRewritePattern {
 unsigned lvl = llvm::cast(expr).getPosition();
 lvlSeq.push_back(std::make_pair(lvl, lvlSeq.size()));
   }
-  std::sort(lvlSeq.begin(), lvlSeq.end(), [](auto , auto ) -> bool 
{
-return lhs.first < rhs.first;
-  });
+  llvm::sort(lvlSeq, llvm::less_first());
   

[clang] [llvm] [mlir] Use llvm::less_first (NFC) (PR #94136)

2024-06-01 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-amdgpu

@llvm/pr-subscribers-clang-modules

Author: Kazu Hirata (kazutakahirata)


Changes



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


6 Files Affected:

- (modified) clang/lib/Serialization/ASTWriter.cpp (+1-3) 
- (modified) clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
(+1-3) 
- (modified) llvm/lib/MC/MCPseudoProbe.cpp (+2-8) 
- (modified) llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h (+1-4) 
- (modified) mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp 
(+1-3) 
- (modified) mlir/lib/Dialect/SparseTensor/Transforms/Utils/LoopEmitter.cpp 
(+1-2) 


``diff
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index e830c4026ea78..eb41a205bc82c 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -3205,9 +3205,7 @@ void ASTWriter::WritePragmaDiagnosticMappings(const 
DiagnosticsEngine ,
   }
 
   // Sort by diag::kind for deterministic output.
-  llvm::sort(Mappings, [](const auto , const auto ) {
-return LHS.first < RHS.first;
-  });
+  llvm::sort(Mappings, llvm::less_first());
 
   for (const auto  : Mappings) {
 Record.push_back(I.first);
diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 0c047b6c5da2f..0f82f22d8b9a8 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -259,9 +259,7 @@ static void canonicalizeDefines(PreprocessorOptions 
) {
 ++Index;
   }
 
-  llvm::stable_sort(SimpleNames, [](const MacroOpt , const MacroOpt ) {
-return A.first < B.first;
-  });
+  llvm::stable_sort(SimpleNames, llvm::less_first());
   // Keep the last instance of each macro name by going in reverse
   auto NewEnd = std::unique(
   SimpleNames.rbegin(), SimpleNames.rend(),
diff --git a/llvm/lib/MC/MCPseudoProbe.cpp b/llvm/lib/MC/MCPseudoProbe.cpp
index cec50322bb9f9..040f3aab88128 100644
--- a/llvm/lib/MC/MCPseudoProbe.cpp
+++ b/llvm/lib/MC/MCPseudoProbe.cpp
@@ -182,13 +182,10 @@ void MCPseudoProbeInlineTree::emit(MCObjectStreamer *MCOS,
   // Emit sorted descendant. InlineSite is unique for each pair, so there will
   // be no ordering of Inlinee based on MCPseudoProbeInlineTree*
   using InlineeType = std::pair;
-  auto Comparer = [](const InlineeType , const InlineeType ) {
-return A.first < B.first;
-  };
   std::vector Inlinees;
   for (const auto  : Children)
 Inlinees.emplace_back(Child.first, Child.second.get());
-  std::sort(Inlinees.begin(), Inlinees.end(), Comparer);
+  llvm::sort(Inlinees, llvm::less_first());
 
   for (const auto  : Inlinees) {
 // Emit probe index
@@ -230,13 +227,10 @@ void MCPseudoProbeSections::emit(MCObjectStreamer *MCOS) {
   // Emit sorted descendant. InlineSite is unique for each pair, so there
   // will be no ordering of Inlinee based on MCPseudoProbeInlineTree*
   using InlineeType = std::pair;
-  auto Comparer = [](const InlineeType , const InlineeType ) {
-return A.first < B.first;
-  };
   std::vector Inlinees;
   for (const auto  : Root.getChildren())
 Inlinees.emplace_back(Child.first, Child.second.get());
-  std::sort(Inlinees.begin(), Inlinees.end(), Comparer);
+  llvm::sort(Inlinees, llvm::less_first());
 
   for (const auto  : Inlinees) {
 // Emit the group guarded by a sentinel probe.
diff --git a/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h 
b/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
index 8c014832f5e46..9fe02e24c8a15 100644
--- a/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
+++ b/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
@@ -597,10 +597,7 @@ class SIMachineFunctionInfo final : public 
AMDGPUMachineFunction,
   const ReservedRegSet () const { return WWMReservedRegs; }
 
   ArrayRef getPrologEpilogSGPRSpills() const {
-assert(
-is_sorted(PrologEpilogSGPRSpills, [](const auto , const auto ) 
{
-  return LHS.first < RHS.first;
-}));
+assert(is_sorted(PrologEpilogSGPRSpills, llvm::less_first()));
 return PrologEpilogSGPRSpills;
   }
 
diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp 
b/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
index 36ecf692b02c5..ce7f6b2865375 100644
--- a/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
+++ b/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
@@ -557,9 +557,7 @@ struct GenericOpScheduler : public 
OpRewritePattern {
 unsigned lvl = llvm::cast(expr).getPosition();
 lvlSeq.push_back(std::make_pair(lvl, lvlSeq.size()));
   }
-  std::sort(lvlSeq.begin(), lvlSeq.end(), [](auto , auto ) -> bool 
{
-return lhs.first < rhs.first;
-  });
+  

[clang] [llvm] [mlir] Use llvm::less_first (NFC) (PR #94136)

2024-06-01 Thread Kazu Hirata via cfe-commits

https://github.com/kazutakahirata created 
https://github.com/llvm/llvm-project/pull/94136

None

>From f154605958e5bb7481013861c96fe3c42156a834 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Sat, 1 Jun 2024 18:15:17 -0700
Subject: [PATCH] Use llvm::less_first (NFC)

---
 clang/lib/Serialization/ASTWriter.cpp  |  4 +---
 .../DependencyScanning/DependencyScanningWorker.cpp|  4 +---
 llvm/lib/MC/MCPseudoProbe.cpp  | 10 ++
 llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h |  5 +
 .../SparseTensor/Transforms/SparseReinterpretMap.cpp   |  4 +---
 .../SparseTensor/Transforms/Utils/LoopEmitter.cpp  |  3 +--
 6 files changed, 7 insertions(+), 23 deletions(-)

diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index e830c4026ea78..eb41a205bc82c 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -3205,9 +3205,7 @@ void ASTWriter::WritePragmaDiagnosticMappings(const 
DiagnosticsEngine ,
   }
 
   // Sort by diag::kind for deterministic output.
-  llvm::sort(Mappings, [](const auto , const auto ) {
-return LHS.first < RHS.first;
-  });
+  llvm::sort(Mappings, llvm::less_first());
 
   for (const auto  : Mappings) {
 Record.push_back(I.first);
diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 0c047b6c5da2f..0f82f22d8b9a8 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -259,9 +259,7 @@ static void canonicalizeDefines(PreprocessorOptions 
) {
 ++Index;
   }
 
-  llvm::stable_sort(SimpleNames, [](const MacroOpt , const MacroOpt ) {
-return A.first < B.first;
-  });
+  llvm::stable_sort(SimpleNames, llvm::less_first());
   // Keep the last instance of each macro name by going in reverse
   auto NewEnd = std::unique(
   SimpleNames.rbegin(), SimpleNames.rend(),
diff --git a/llvm/lib/MC/MCPseudoProbe.cpp b/llvm/lib/MC/MCPseudoProbe.cpp
index cec50322bb9f9..040f3aab88128 100644
--- a/llvm/lib/MC/MCPseudoProbe.cpp
+++ b/llvm/lib/MC/MCPseudoProbe.cpp
@@ -182,13 +182,10 @@ void MCPseudoProbeInlineTree::emit(MCObjectStreamer *MCOS,
   // Emit sorted descendant. InlineSite is unique for each pair, so there will
   // be no ordering of Inlinee based on MCPseudoProbeInlineTree*
   using InlineeType = std::pair;
-  auto Comparer = [](const InlineeType , const InlineeType ) {
-return A.first < B.first;
-  };
   std::vector Inlinees;
   for (const auto  : Children)
 Inlinees.emplace_back(Child.first, Child.second.get());
-  std::sort(Inlinees.begin(), Inlinees.end(), Comparer);
+  llvm::sort(Inlinees, llvm::less_first());
 
   for (const auto  : Inlinees) {
 // Emit probe index
@@ -230,13 +227,10 @@ void MCPseudoProbeSections::emit(MCObjectStreamer *MCOS) {
   // Emit sorted descendant. InlineSite is unique for each pair, so there
   // will be no ordering of Inlinee based on MCPseudoProbeInlineTree*
   using InlineeType = std::pair;
-  auto Comparer = [](const InlineeType , const InlineeType ) {
-return A.first < B.first;
-  };
   std::vector Inlinees;
   for (const auto  : Root.getChildren())
 Inlinees.emplace_back(Child.first, Child.second.get());
-  std::sort(Inlinees.begin(), Inlinees.end(), Comparer);
+  llvm::sort(Inlinees, llvm::less_first());
 
   for (const auto  : Inlinees) {
 // Emit the group guarded by a sentinel probe.
diff --git a/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h 
b/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
index 8c014832f5e46..9fe02e24c8a15 100644
--- a/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
+++ b/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h
@@ -597,10 +597,7 @@ class SIMachineFunctionInfo final : public 
AMDGPUMachineFunction,
   const ReservedRegSet () const { return WWMReservedRegs; }
 
   ArrayRef getPrologEpilogSGPRSpills() const {
-assert(
-is_sorted(PrologEpilogSGPRSpills, [](const auto , const auto ) 
{
-  return LHS.first < RHS.first;
-}));
+assert(is_sorted(PrologEpilogSGPRSpills, llvm::less_first()));
 return PrologEpilogSGPRSpills;
   }
 
diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp 
b/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
index 36ecf692b02c5..ce7f6b2865375 100644
--- a/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
+++ b/mlir/lib/Dialect/SparseTensor/Transforms/SparseReinterpretMap.cpp
@@ -557,9 +557,7 @@ struct GenericOpScheduler : public 
OpRewritePattern {
 unsigned lvl = llvm::cast(expr).getPosition();
 lvlSeq.push_back(std::make_pair(lvl, lvlSeq.size()));
   }
-  std::sort(lvlSeq.begin(), lvlSeq.end(), [](auto , auto ) -> bool 
{
-return 

[clang] [ObjC] Expand isClassLayoutKnownStatically to base classes as long as the implementation of it is known (PR #85465)

2024-06-01 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/85465

>From 1c241ddd7f44deef8f495bfeb84eaeb0806b5291 Mon Sep 17 00:00:00 2001
From: Rose 
Date: Fri, 15 Mar 2024 16:43:10 -0400
Subject: [PATCH] [ObjC] Expand isClassLayoutKnownStatically to base classes as
 long as the implementation of it is known

Only NSObject we can trust the layout of won't change even though we cannot 
directly see its @implementation.
---
 clang/lib/CodeGen/CGObjCMac.cpp   |  9 -
 clang/test/CodeGenObjC/arc-blocks.m   |  8 ++---
 clang/test/CodeGenObjC/arc-property.m | 22 +---
 clang/test/CodeGenObjC/arc-weak-property.m|  5 ++-
 clang/test/CodeGenObjC/arc.m  | 18 --
 clang/test/CodeGenObjC/arm64-int32-ivar.m |  5 ++-
 .../test/CodeGenObjC/bitfield-ivar-offsets.m  |  5 ++-
 .../constant-non-fragile-ivar-offset.m| 34 +--
 clang/test/CodeGenObjC/direct-method.m|  3 +-
 clang/test/CodeGenObjC/hidden-visibility.m|  2 +-
 clang/test/CodeGenObjC/interface-layout-64.m  | 16 +
 .../CodeGenObjC/ivar-base-as-invariant-load.m |  5 ++-
 clang/test/CodeGenObjC/metadata-symbols-64.m  |  4 +--
 .../nontrivial-c-struct-property.m|  4 ++-
 .../CodeGenObjC/objc-asm-attribute-test.m |  5 +--
 clang/test/CodeGenObjC/ubsan-bool.m   |  4 ++-
 16 files changed, 96 insertions(+), 53 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 042cd5d46da4b..78ebf445ea003 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1595,6 +1595,11 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
 // Test a class by checking its superclasses up to
 // its base class if it has one.
+
+// Cannot check a null class
+if (!ID)
+  return false;
+
 for (; ID; ID = ID->getSuperClass()) {
   // The layout of base class NSObject
   // is guaranteed to be statically known
@@ -1606,7 +1611,9 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   if (!ID->getImplementation())
 return false;
 }
-return false;
+
+// We know the layout of all the intermediate classes and superclasses.
+return true;
   }
 
 public:
diff --git a/clang/test/CodeGenObjC/arc-blocks.m 
b/clang/test/CodeGenObjC/arc-blocks.m
index f718e8bbf9a61..b8547e927ac8c 100644
--- a/clang/test/CodeGenObjC/arc-blocks.m
+++ b/clang/test/CodeGenObjC/arc-blocks.m
@@ -422,16 +422,16 @@ @interface Test12
 @implementation Test12
 @synthesize ablock, nblock;
 // CHECK:define internal ptr @"\01-[Test12 ablock]"(
-// CHECK:call ptr @objc_getProperty(ptr noundef {{%.*}}, ptr noundef 
{{%.*}}, i64 noundef {{%.*}}, i1 noundef zeroext true)
+// CHECK:call ptr @objc_getProperty(ptr noundef {{%.*}}, ptr noundef 
{{%.*}}, i64 noundef 0, i1 noundef zeroext true)
 
 // CHECK:define internal void @"\01-[Test12 setAblock:]"(
-// CHECK:call void @objc_setProperty(ptr noundef {{%.*}}, ptr noundef 
{{%.*}}, i64 noundef {{%.*}}, ptr noundef {{%.*}}, i1 noundef zeroext true, i1 
noundef zeroext true)
+// CHECK:call void @objc_setProperty(ptr noundef {{%.*}}, ptr noundef 
{{%.*}}, i64 noundef 0, ptr noundef {{%.*}}, i1 noundef zeroext true, i1 
noundef zeroext true)
 
 // CHECK:define internal ptr @"\01-[Test12 nblock]"(
-// CHECK:%add.ptr = getelementptr inbounds i8, ptr %0, i64 %ivar
+// CHECK:%add.ptr = getelementptr inbounds i8, ptr %0, i64 8
 
 // CHECK:define internal void @"\01-[Test12 setNblock:]"(
-// CHECK:call void @objc_setProperty(ptr noundef {{%.*}}, ptr noundef 
{{%.*}}, i64 noundef {{%.*}}, ptr noundef {{%.*}}, i1 noundef zeroext false, i1 
noundef zeroext true)
+// CHECK:call void @objc_setProperty(ptr noundef {{%.*}}, ptr noundef 
{{%.*}}, i64 noundef 8, ptr noundef {{%.*}}, i1 noundef zeroext false, i1 
noundef zeroext true)
 @end
 
 void test13(id x) {
diff --git a/clang/test/CodeGenObjC/arc-property.m 
b/clang/test/CodeGenObjC/arc-property.m
index f57be6b4f6be4..3209993cc6d32 100644
--- a/clang/test/CodeGenObjC/arc-property.m
+++ b/clang/test/CodeGenObjC/arc-property.m
@@ -22,16 +22,14 @@ @implementation Test1
 @end
 //   The getter should be a simple load.
 // CHECK:define internal ptr @"\01-[Test1 pointer]"(
-// CHECK:  [[OFFSET:%.*]] = load i64, ptr @"OBJC_IVAR_$_Test1.pointer"
-// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8, ptr {{%.*}}, i64 
[[OFFSET]]
+// CHECK: [[T1:%.*]] = getelementptr inbounds i8, ptr {{%.*}}, i64 0
 // CHECK-NEXT: [[T3:%.*]] = load ptr, ptr [[T1]], align 8
 // CHECK-NEXT: ret ptr [[T3]]
 
 //   The setter should be using objc_setProperty.
 // CHECK:define internal void @"\01-[Test1 setPointer:]"(
-// CHECK: [[OFFSET:%.*]] = load i64, ptr @"OBJC_IVAR_$_Test1.pointer"
-// CHECK-NEXT: [[T1:%.*]] = load ptr, ptr {{%.*}}
-// CHECK-NEXT: call void 

[clang] [llvm] [AMDGPU] Implement variadic functions by IR lowering (PR #93362)

2024-06-01 Thread Jon Chesterfield via cfe-commits

JonChesterfield wrote:

Finally managed to reproduce the libc failure. Thanks to Joseph for helping 
debug through the cmake. This patch as written was too optimistic about 
addrspacecast, a significantly more paranoid version behaves correctly (i.e. 
all the libc tests pass, this patch can be amended to enable the variadic ones 
on amdgpu). Libc tests don't seem to pick up changes to clang without a clean 
build (i.e. delete the whole build tree).

The memory error was on the dereference implied by va_arg. Valid addresses 
(read as void*) have a high bit pattern of 2. and invalid ones of 
f., I'm unsure what that implies. I note that 
https://llvm.org/docs/AMDGPUUsage.html doesn't say much about the semantics of 
addrspace.

Trying to isolate that further. The error is definitely in the amdgpu-specific 
addrspace handling part though, the target agnostic part worked as intended.

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


[clang] [clang-format] Handle attributes before lambda return arrow (PR #94119)

2024-06-01 Thread Owen Pan via cfe-commits

owenca wrote:

> Do we want a token annotator test?

The bug was in the unwrapped line parser, but it doesn't hurt to add an 
annotator test.

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


[clang] [clang-format] Handle attributes before lambda return arrow (PR #94119)

2024-06-01 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/94119

>From 0ef24a51b4f831c49efe956662764f0b2c2cca61 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 1 Jun 2024 12:53:08 -0700
Subject: [PATCH 1/2] [clang-format] Handle attributes before lambda return
 arrow

Fixes #92657.
---
 clang/lib/Format/UnwrappedLineParser.cpp | 2 +-
 clang/unittests/Format/FormatTest.cpp| 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 5c0ff0f6132b2..053fd3d4df559 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2236,7 +2236,7 @@ bool UnwrappedLineParser::tryToParseLambda() {
   bool InTemplateParameterList = false;
 
   while (FormatTok->isNot(tok::l_brace)) {
-if (FormatTok->isTypeName(LangOpts)) {
+if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
   nextToken();
   continue;
 }
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 59f1ff6a4b296..6057d5b724bf9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22664,6 +22664,7 @@ TEST_F(FormatTest, FormatsLambdas) {
   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
   verifyFormat("SomeFunction({[]() -> ns::type { return {}; }});");
+  verifyFormat("foo([&](u32 bar) __attribute__((always_inline)) -> void {});");
   verifyFormat("return int{[x = x]() { return x; }()};");
 
   // Lambdas with explicit template argument lists.

>From 189ec3ee752d2cd625a8226c0ede028c32b1d986 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 1 Jun 2024 15:12:55 -0700
Subject: [PATCH 2/2] Added an annotator test.

---
 clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 3339a749df3a5..df268f49e1eca 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1577,6 +1577,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   EXPECT_TOKEN(Tokens[2], tok::arrow, TT_TrailingReturnArrow);
   EXPECT_TOKEN(Tokens[4], tok::l_brace, TT_LambdaLBrace);
 
+  Tokens = annotate("foo([&](u32 bar) __attribute__((attr)) -> void {});");
+  ASSERT_EQ(Tokens.size(), 22u) << Tokens;
+  EXPECT_TOKEN(Tokens[2], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[15], tok::arrow, TT_TrailingReturnArrow);
+  EXPECT_TOKEN(Tokens[17], tok::l_brace, TT_LambdaLBrace);
+
   Tokens = annotate("[]  () {}");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);

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


[clang] feat(92583): [C++23] "no return statement in constexpr function" no longer an error with P2448 (PR #94123)

2024-06-01 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/94123

>From 90eeafc82ee08129c2d290e6382f42ec89680049 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Sun, 2 Jun 2024 00:07:35 +0300
Subject: [PATCH] feat(92583): [C++23] update constexpr diagnostics for missing
 return statements per P2448

---
 clang/lib/Sema/SemaDeclCXX.cpp| 34 ---
 .../CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp |  2 +-
 .../SemaCXX/constant-expression-cxx14.cpp |  2 +-
 .../constexpr-return-non-void-cxx2b.cpp   |  7 
 4 files changed, 31 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 631fd4e354927..d4401a427282c 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -1806,6 +1806,7 @@ static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) 
{
 static bool CheckConstexprFunctionBody(Sema , const FunctionDecl *Dcl,
Stmt *Body,
Sema::CheckConstexprKind Kind);
+static bool CheckConstexprMissingReturn(Sema , const FunctionDecl 
*Dcl);
 
 // Check whether a function declaration satisfies the requirements of a
 // constexpr function definition or a constexpr constructor definition. If so,
@@ -2411,20 +2412,9 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
 }
   } else {
 if (ReturnStmts.empty()) {
-  // C++1y doesn't require constexpr functions to contain a 'return'
-  // statement. We still do, unless the return type might be void, because
-  // otherwise if there's no return statement, the function cannot
-  // be used in a core constant expression.
-  bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
-(Dcl->getReturnType()->isVoidType() ||
- Dcl->getReturnType()->isDependentType());
   switch (Kind) {
   case Sema::CheckConstexprKind::Diagnose:
-SemaRef.Diag(Dcl->getLocation(),
- OK ? diag::warn_cxx11_compat_constexpr_body_no_return
-: diag::err_constexpr_body_no_return)
-<< Dcl->isConsteval();
-if (!OK)
+if (!CheckConstexprMissingReturn(SemaRef, Dcl))
   return false;
 break;
 
@@ -2487,6 +2477,26 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool CheckConstexprMissingReturn(Sema ,
+const FunctionDecl *Dcl) {
+  bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
+   Dcl->getReturnType()->isDependentType();
+
+  if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
+return true;
+
+  // C++1y doesn't require constexpr functions to contain a 'return'
+  // statement. We still do, unless the return type might be void, because
+  // otherwise if there's no return statement, the function cannot
+  // be used in a core constant expression.
+  bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
+  SemaRef.Diag(Dcl->getLocation(),
+   OK ? diag::warn_cxx11_compat_constexpr_body_no_return
+  : diag::err_constexpr_body_no_return)
+  << Dcl->isConsteval();
+  return OK;
+}
+
 bool Sema::CheckImmediateEscalatingFunctionDefinition(
 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
   if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
diff --git a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp 
b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
index 4416c82522649..51990ee4341d2 100644
--- a/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
+++ b/clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
@@ -212,7 +212,7 @@ constexpr int ClassDecl3() {
   return 0;
 }
 
-constexpr int NoReturn() {} // expected-error {{no return statement in 
constexpr function}}
+constexpr int NoReturn() {} // beforecxx23-error {{no return statement in 
constexpr function}}
 constexpr int MultiReturn() {
   return 0; // beforecxx14-note {{return statement}}
   return 0; // beforecxx14-warning {{multiple return statements in constexpr 
function}}
diff --git a/clang/test/SemaCXX/constant-expression-cxx14.cpp 
b/clang/test/SemaCXX/constant-expression-cxx14.cpp
index 80a7a2dd31531..70ab5dcd357c1 100644
--- a/clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -82,7 +82,7 @@ constexpr void k() {
 
 // If the return type is not 'void', no return statements => never a constant
 // expression, so still diagnose that case.
-[[noreturn]] constexpr int fn() { // expected-error {{no return statement in 
constexpr function}}
+[[noreturn]] constexpr int fn() { // cxx14_20-error {{no return statement in 
constexpr function}}
   fn();
 }
 
diff --git 

[clang] feat(92583): [C++23] "no return statement in constexpr function" no longer an error with P2448 (PR #94123)

2024-06-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Oleksandr T. (a-tarasyuk)


Changes

Fixes #92583

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


3 Files Affected:

- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+22-12) 
- (modified) clang/test/SemaCXX/constant-expression-cxx14.cpp (+1-1) 
- (added) clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp (+7) 


``diff
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 631fd4e354927..d4401a427282c 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -1806,6 +1806,7 @@ static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) 
{
 static bool CheckConstexprFunctionBody(Sema , const FunctionDecl *Dcl,
Stmt *Body,
Sema::CheckConstexprKind Kind);
+static bool CheckConstexprMissingReturn(Sema , const FunctionDecl 
*Dcl);
 
 // Check whether a function declaration satisfies the requirements of a
 // constexpr function definition or a constexpr constructor definition. If so,
@@ -2411,20 +2412,9 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
 }
   } else {
 if (ReturnStmts.empty()) {
-  // C++1y doesn't require constexpr functions to contain a 'return'
-  // statement. We still do, unless the return type might be void, because
-  // otherwise if there's no return statement, the function cannot
-  // be used in a core constant expression.
-  bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
-(Dcl->getReturnType()->isVoidType() ||
- Dcl->getReturnType()->isDependentType());
   switch (Kind) {
   case Sema::CheckConstexprKind::Diagnose:
-SemaRef.Diag(Dcl->getLocation(),
- OK ? diag::warn_cxx11_compat_constexpr_body_no_return
-: diag::err_constexpr_body_no_return)
-<< Dcl->isConsteval();
-if (!OK)
+if (!CheckConstexprMissingReturn(SemaRef, Dcl))
   return false;
 break;
 
@@ -2487,6 +2477,26 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool CheckConstexprMissingReturn(Sema ,
+const FunctionDecl *Dcl) {
+  bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
+   Dcl->getReturnType()->isDependentType();
+
+  if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
+return true;
+
+  // C++1y doesn't require constexpr functions to contain a 'return'
+  // statement. We still do, unless the return type might be void, because
+  // otherwise if there's no return statement, the function cannot
+  // be used in a core constant expression.
+  bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
+  SemaRef.Diag(Dcl->getLocation(),
+   OK ? diag::warn_cxx11_compat_constexpr_body_no_return
+  : diag::err_constexpr_body_no_return)
+  << Dcl->isConsteval();
+  return OK;
+}
+
 bool Sema::CheckImmediateEscalatingFunctionDefinition(
 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
   if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
diff --git a/clang/test/SemaCXX/constant-expression-cxx14.cpp 
b/clang/test/SemaCXX/constant-expression-cxx14.cpp
index 80a7a2dd31531..70ab5dcd357c1 100644
--- a/clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -82,7 +82,7 @@ constexpr void k() {
 
 // If the return type is not 'void', no return statements => never a constant
 // expression, so still diagnose that case.
-[[noreturn]] constexpr int fn() { // expected-error {{no return statement in 
constexpr function}}
+[[noreturn]] constexpr int fn() { // cxx14_20-error {{no return statement in 
constexpr function}}
   fn();
 }
 
diff --git a/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp 
b/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp
new file mode 100644
index 0..91a8bb656b317
--- /dev/null
+++ b/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -Wno-return-type -std=c++23 -fsyntax-only -verify %s
+// expected-no-diagnostics
+constexpr int f() { }
+static_assert(__is_same(decltype([] constexpr -> int { }( )), int));
+
+consteval int g() { }
+static_assert(__is_same(decltype([] consteval -> int { }( )), int));

``




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


[clang] feat(92583): [C++23] "no return statement in constexpr function" no longer an error with P2448 (PR #94123)

2024-06-01 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk created 
https://github.com/llvm/llvm-project/pull/94123

Fixes #92583

>From d7267a9746f6e947237e84514892177a8acef5b3 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Sun, 2 Jun 2024 00:07:35 +0300
Subject: [PATCH] feat(92583): [C++23] update constexpr diagnostics for missing
 return statements per P2448

---
 clang/lib/Sema/SemaDeclCXX.cpp| 34 ---
 .../SemaCXX/constant-expression-cxx14.cpp |  2 +-
 .../constexpr-return-non-void-cxx2b.cpp   |  7 
 3 files changed, 30 insertions(+), 13 deletions(-)
 create mode 100644 clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 631fd4e354927..d4401a427282c 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -1806,6 +1806,7 @@ static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) 
{
 static bool CheckConstexprFunctionBody(Sema , const FunctionDecl *Dcl,
Stmt *Body,
Sema::CheckConstexprKind Kind);
+static bool CheckConstexprMissingReturn(Sema , const FunctionDecl 
*Dcl);
 
 // Check whether a function declaration satisfies the requirements of a
 // constexpr function definition or a constexpr constructor definition. If so,
@@ -2411,20 +2412,9 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
 }
   } else {
 if (ReturnStmts.empty()) {
-  // C++1y doesn't require constexpr functions to contain a 'return'
-  // statement. We still do, unless the return type might be void, because
-  // otherwise if there's no return statement, the function cannot
-  // be used in a core constant expression.
-  bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
-(Dcl->getReturnType()->isVoidType() ||
- Dcl->getReturnType()->isDependentType());
   switch (Kind) {
   case Sema::CheckConstexprKind::Diagnose:
-SemaRef.Diag(Dcl->getLocation(),
- OK ? diag::warn_cxx11_compat_constexpr_body_no_return
-: diag::err_constexpr_body_no_return)
-<< Dcl->isConsteval();
-if (!OK)
+if (!CheckConstexprMissingReturn(SemaRef, Dcl))
   return false;
 break;
 
@@ -2487,6 +2477,26 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool CheckConstexprMissingReturn(Sema ,
+const FunctionDecl *Dcl) {
+  bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
+   Dcl->getReturnType()->isDependentType();
+
+  if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
+return true;
+
+  // C++1y doesn't require constexpr functions to contain a 'return'
+  // statement. We still do, unless the return type might be void, because
+  // otherwise if there's no return statement, the function cannot
+  // be used in a core constant expression.
+  bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
+  SemaRef.Diag(Dcl->getLocation(),
+   OK ? diag::warn_cxx11_compat_constexpr_body_no_return
+  : diag::err_constexpr_body_no_return)
+  << Dcl->isConsteval();
+  return OK;
+}
+
 bool Sema::CheckImmediateEscalatingFunctionDefinition(
 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
   if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
diff --git a/clang/test/SemaCXX/constant-expression-cxx14.cpp 
b/clang/test/SemaCXX/constant-expression-cxx14.cpp
index 80a7a2dd31531..70ab5dcd357c1 100644
--- a/clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -82,7 +82,7 @@ constexpr void k() {
 
 // If the return type is not 'void', no return statements => never a constant
 // expression, so still diagnose that case.
-[[noreturn]] constexpr int fn() { // expected-error {{no return statement in 
constexpr function}}
+[[noreturn]] constexpr int fn() { // cxx14_20-error {{no return statement in 
constexpr function}}
   fn();
 }
 
diff --git a/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp 
b/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp
new file mode 100644
index 0..91a8bb656b317
--- /dev/null
+++ b/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -Wno-return-type -std=c++23 -fsyntax-only -verify %s
+// expected-no-diagnostics
+constexpr int f() { }
+static_assert(__is_same(decltype([] constexpr -> int { }( )), int));
+
+consteval int g() { }
+static_assert(__is_same(decltype([] consteval -> int { }( )), int));

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


[clang] [clang-format] Handle attributes before lambda return arrow (PR #94119)

2024-06-01 Thread Björn Schäpers via cfe-commits

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

Do we want a token annotator test?

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


[clang] [clang-format] Improve BlockIndent at ColumnLimit (PR #93140)

2024-06-01 Thread Björn Schäpers via cfe-commits


@@ -803,6 +803,60 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
, bool DryRun,
 return !Tok.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
   tok::kw_switch);
   };
+  // Detecting functions is brittle. It would be better if we could annotate
+  // the LParen type of functions/calls.
+  const auto IsFunctionDeclParen = [&](const FormatToken ) {
+return Tok.is(tok::l_paren) && Tok.Previous &&
+   (Tok.Previous->is(TT_FunctionDeclarationName) ||
+(Tok.Previous->Previous &&
+ Tok.Previous->Previous->is(tok::coloncolon) &&
+ Tok.Previous->Previous->Previous &&
+ 
Tok.Previous->Previous->Previous->is(TT_FunctionDeclarationName)));
+  };
+  const auto IsLambdaParameterList = [](const FormatToken *Left) {

HazardyKnusperkeks wrote:

In your other lamdbas it's a reference called `Tok`, please be consistent.

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


[clang] [clang-format] Improve BlockIndent at ColumnLimit (PR #93140)

2024-06-01 Thread Björn Schäpers via cfe-commits


@@ -803,6 +803,60 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
, bool DryRun,
 return !Tok.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
   tok::kw_switch);
   };
+  // Detecting functions is brittle. It would be better if we could annotate
+  // the LParen type of functions/calls.

HazardyKnusperkeks wrote:

Did you try it?

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


[clang] [clang-format] Handle attributes before lambda return arrow (PR #94119)

2024-06-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Fixes #92657.

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


2 Files Affected:

- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+1-1) 
- (modified) clang/unittests/Format/FormatTest.cpp (+1) 


``diff
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 5c0ff0f6132b2..053fd3d4df559 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2236,7 +2236,7 @@ bool UnwrappedLineParser::tryToParseLambda() {
   bool InTemplateParameterList = false;
 
   while (FormatTok->isNot(tok::l_brace)) {
-if (FormatTok->isTypeName(LangOpts)) {
+if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
   nextToken();
   continue;
 }
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 59f1ff6a4b296..6057d5b724bf9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22664,6 +22664,7 @@ TEST_F(FormatTest, FormatsLambdas) {
   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
   verifyFormat("SomeFunction({[]() -> ns::type { return {}; }});");
+  verifyFormat("foo([&](u32 bar) __attribute__((always_inline)) -> void {});");
   verifyFormat("return int{[x = x]() { return x; }()};");
 
   // Lambdas with explicit template argument lists.

``




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


[clang] [clang-format] Handle attributes before lambda return arrow (PR #94119)

2024-06-01 Thread Owen Pan via cfe-commits

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

Fixes #92657.

>From 0ef24a51b4f831c49efe956662764f0b2c2cca61 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 1 Jun 2024 12:53:08 -0700
Subject: [PATCH] [clang-format] Handle attributes before lambda return arrow

Fixes #92657.
---
 clang/lib/Format/UnwrappedLineParser.cpp | 2 +-
 clang/unittests/Format/FormatTest.cpp| 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 5c0ff0f6132b2..053fd3d4df559 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2236,7 +2236,7 @@ bool UnwrappedLineParser::tryToParseLambda() {
   bool InTemplateParameterList = false;
 
   while (FormatTok->isNot(tok::l_brace)) {
-if (FormatTok->isTypeName(LangOpts)) {
+if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
   nextToken();
   continue;
 }
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 59f1ff6a4b296..6057d5b724bf9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22664,6 +22664,7 @@ TEST_F(FormatTest, FormatsLambdas) {
   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
   verifyFormat("SomeFunction({[]() -> ns::type { return {}; }});");
+  verifyFormat("foo([&](u32 bar) __attribute__((always_inline)) -> void {});");
   verifyFormat("return int{[x = x]() { return x; }()};");
 
   // Lambdas with explicit template argument lists.

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


[clang] [Clang] `constexpr` builtin floating point classification / comparison functions (PR #94118)

2024-06-01 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/94118

>From ed1c00ee4474a626965290f2d16aaaf0f4519ec9 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sat, 1 Jun 2024 17:45:21 +0100
Subject: [PATCH 1/3] constexpr __builtin_signbit

---
 clang/include/clang/Basic/Builtins.td  |  8 +---
 clang/lib/AST/ExprConstant.cpp |  8 
 clang/lib/AST/Interp/InterpBuiltin.cpp | 15 +++
 clang/test/Sema/constant-builtins-2.c  | 13 +
 4 files changed, 41 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 11982af3fa609..f784711bc04dc 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -646,19 +646,21 @@ def IsFPClass : Builtin {
 def Signbit : Builtin {
   let Spellings = ["__builtin_signbit"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
 def SignbitF : Builtin {
   let Spellings = ["__builtin_signbitf"];
-  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const];
+  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
+Constexpr];
   let Prototype = "int(float)";
 }
 
 def SignbitL : Builtin {
   let Spellings = ["__builtin_signbitl"];
-  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const];
+  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
+Constexpr];
   let Prototype = "int(long double)";
 }
 
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index f1aa19e4409e1..b4de743c4d95b 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -12650,6 +12650,14 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const 
CallExpr *E,
Success(Val.isZero() ? 1 : 0, E);
   }
 
+  case Builtin::BI__builtin_signbit:
+  case Builtin::BI__builtin_signbitf:
+  case Builtin::BI__builtin_signbitl: {
+APFloat Val(0.0);
+return EvaluateFloat(E->getArg(0), Val, Info) &&
+   Success(Val.isNegative() ? 1 : 0, E);
+  }
+
   case Builtin::BI__builtin_issignaling: {
 APFloat Val(0.0);
 return EvaluateFloat(E->getArg(0), Val, Info) &&
diff --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index 00206d09c113d..4ca92e66b2912 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -430,6 +430,15 @@ static bool interp__builtin_iszero(InterpState , CodePtr 
OpPC,
   return true;
 }
 
+static bool interp__builtin_signbit(InterpState , CodePtr OpPC,
+const InterpFrame *Frame, const Function 
*F,
+const CallExpr *Call) {
+  const Floating  = S.Stk.peek();
+
+  pushInteger(S, Arg.isNegative(), Call->getType());
+  return true;
+}
+
 /// First parameter to __builtin_isfpclass is the floating value, the
 /// second one is an integral value.
 static bool interp__builtin_isfpclass(InterpState , CodePtr OpPC,
@@ -1214,6 +1223,12 @@ bool InterpretBuiltin(InterpState , CodePtr OpPC, 
const Function *F,
 if (!interp__builtin_iszero(S, OpPC, Frame, F, Call))
   return false;
 break;
+  case Builtin::BI__builtin_signbit:
+  case Builtin::BI__builtin_signbitf:
+  case Builtin::BI__builtin_signbitl:
+if (!interp__builtin_signbit(S, OpPC, Frame, F, Call))
+  return false;
+break;
   case Builtin::BI__builtin_isfpclass:
 if (!interp__builtin_isfpclass(S, OpPC, Frame, F, Call))
   return false;
diff --git a/clang/test/Sema/constant-builtins-2.c 
b/clang/test/Sema/constant-builtins-2.c
index a60a1f16a4587..fca4ac2a26898 100644
--- a/clang/test/Sema/constant-builtins-2.c
+++ b/clang/test/Sema/constant-builtins-2.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fexperimental-new-constant-interpreter 
-verify %s
 
 // Math stuff
 
@@ -204,6 +205,18 @@ char isfpclass_snan_1   
[!__builtin_isfpclass(__builtin_nans(""), 0x0002) ? 1 :
 char isfpclass_snan_2   [__builtin_isfpclass(__builtin_nansl(""), 0x0207) ? 1 
: -1]; // ~fcFinite
 char isfpclass_snan_3   [!__builtin_isfpclass(__builtin_nans(""), 0x01F8) ? 1 
: -1]; // fcFinite
 
+__extension__ _Static_assert(
+  !__builtin_signbit(1.0) && __builtin_signbit(-1.0) && 
!__builtin_signbit(0.0) && __builtin_signbit(-0.0) &&
+  !__builtin_signbitf(1.0f) && __builtin_signbitf(-1.0f) && 
!__builtin_signbitf(0.0f) && __builtin_signbitf(-0.0f) &&
+  !__builtin_signbitl(1.0L) && __builtin_signbitf(-1.0L) && 
!__builtin_signbitf(0.0L) && __builtin_signbitf(-0.0L) &&
+  !__builtin_signbit(1.0f) && __builtin_signbit(-1.0f) && 
!__builtin_signbit(0.0f) && __builtin_signbit(-0.0f) &&
+  !__builtin_signbit(1.0L) && __builtin_signbit(-1.0L) && 
!__builtin_signbit(0.0L) && __builtin_signbit(-0.0L) &&
+#if 

[clang] [Clang] `constexpr` builtin floating point classification / comparison functions (PR #94118)

2024-06-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Mital Ashok (MitalAshok)


Changes

As per [P0533R9](https://wg21.link/P0533R9), the corresponding C++ 
`[c.math.fpclass]` standard library functions for the C macros are now 
`constexpr`.

The only classification function that wasn't already `constexpr` was 
`__builtin_signbit`.
The floating point comparison functions `__builtin_isgreater`, 
`__builtin_isgreaterequal`, `__builtin_isless`, `__builtin_islessequal`, 
`__builtin_islessgreater` and `__builtin_isunordered` are now `constexpr`.
The C23 macro `iseqsig` is not currently supported because `__bulitin_iseqsig` 
doesn't exist yet (and C++26 is still currently based on C18).

This also allows them to be constant folded in C, matching the behaviour of GCC.


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


4 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.td (+11-9) 
- (modified) clang/lib/AST/ExprConstant.cpp (+67) 
- (modified) clang/lib/AST/Interp/InterpBuiltin.cpp (+87) 
- (modified) clang/test/Sema/constant-builtins-2.c (+48) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 11982af3fa609..7b335e43f8c0e 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -533,42 +533,42 @@ def BuiltinComplex : Builtin {
 def IsGreater : Builtin {
   let Spellings = ["__builtin_isgreater"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
 def IsGreaterEqual : Builtin {
   let Spellings = ["__builtin_isgreaterequal"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
 def IsLess : Builtin {
   let Spellings = ["__builtin_isless"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
 def IsLessEqual : Builtin {
   let Spellings = ["__builtin_islessequal"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
 def IsLessGreater : Builtin {
   let Spellings = ["__builtin_islessgreater"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
 def IsUnordered : Builtin {
   let Spellings = ["__builtin_isunordered"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
@@ -646,19 +646,21 @@ def IsFPClass : Builtin {
 def Signbit : Builtin {
   let Spellings = ["__builtin_signbit"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
 def SignbitF : Builtin {
   let Spellings = ["__builtin_signbitf"];
-  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const];
+  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
+Constexpr];
   let Prototype = "int(float)";
 }
 
 def SignbitL : Builtin {
   let Spellings = ["__builtin_signbitl"];
-  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const];
+  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
+Constexpr];
   let Prototype = "int(long double)";
 }
 
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index f1aa19e4409e1..cf715857f1370 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -12650,6 +12650,73 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const 
CallExpr *E,
Success(Val.isZero() ? 1 : 0, E);
   }
 
+  case Builtin::BI__builtin_signbit:
+  case Builtin::BI__builtin_signbitf:
+  case Builtin::BI__builtin_signbitl: {
+APFloat Val(0.0);
+return EvaluateFloat(E->getArg(0), Val, Info) &&
+   Success(Val.isNegative() ? 1 : 0, E);
+  }
+
+  case Builtin::BI__builtin_isgreater:
+  case Builtin::BI__builtin_isgreaterequal:
+  case Builtin::BI__builtin_isless:
+  case Builtin::BI__builtin_islessequal:
+  case Builtin::BI__builtin_islessgreater:
+  case Builtin::BI__builtin_isunordered: {
+APFloat LHS(0.0);
+APFloat RHS(0.0);
+if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
+!EvaluateFloat(E->getArg(1), RHS, Info))
+  return false;
+
+APFloat::cmpResult Cmp = LHS.compare(RHS);
+bool FunctionResult;
+if (BuiltinOp == Builtin::BI__builtin_isunordered ||

[clang] [Clang] `constexpr` builtin floating point classification / comparison functions (PR #94118)

2024-06-01 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok created 
https://github.com/llvm/llvm-project/pull/94118

As per [P0533R9](https://wg21.link/P0533R9), the corresponding C++ 
`[c.math.fpclass]` standard library functions for the C macros are now 
`constexpr`.

The only classification function that wasn't already `constexpr` was 
`__builtin_signbit`.
The floating point comparison functions `__builtin_isgreater`, 
`__builtin_isgreaterequal`, `__builtin_isless`, `__builtin_islessequal`, 
`__builtin_islessgreater` and `__builtin_isunordered` are now `constexpr`.
The C23 macro `iseqsig` is not currently supported because `__bulitin_iseqsig` 
doesn't exist yet (and C++26 is still currently based on C18).

This also allows them to be constant folded in C, matching the behaviour of GCC.


>From ed1c00ee4474a626965290f2d16aaaf0f4519ec9 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Sat, 1 Jun 2024 17:45:21 +0100
Subject: [PATCH 1/2] constexpr __builtin_signbit

---
 clang/include/clang/Basic/Builtins.td  |  8 +---
 clang/lib/AST/ExprConstant.cpp |  8 
 clang/lib/AST/Interp/InterpBuiltin.cpp | 15 +++
 clang/test/Sema/constant-builtins-2.c  | 13 +
 4 files changed, 41 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 11982af3fa609..f784711bc04dc 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -646,19 +646,21 @@ def IsFPClass : Builtin {
 def Signbit : Builtin {
   let Spellings = ["__builtin_signbit"];
   let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
-CustomTypeChecking];
+CustomTypeChecking, Constexpr];
   let Prototype = "int(...)";
 }
 
 def SignbitF : Builtin {
   let Spellings = ["__builtin_signbitf"];
-  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const];
+  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
+Constexpr];
   let Prototype = "int(float)";
 }
 
 def SignbitL : Builtin {
   let Spellings = ["__builtin_signbitl"];
-  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const];
+  let Attributes = [FunctionWithBuiltinPrefix, NoThrow, Const,
+Constexpr];
   let Prototype = "int(long double)";
 }
 
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index f1aa19e4409e1..b4de743c4d95b 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -12650,6 +12650,14 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const 
CallExpr *E,
Success(Val.isZero() ? 1 : 0, E);
   }
 
+  case Builtin::BI__builtin_signbit:
+  case Builtin::BI__builtin_signbitf:
+  case Builtin::BI__builtin_signbitl: {
+APFloat Val(0.0);
+return EvaluateFloat(E->getArg(0), Val, Info) &&
+   Success(Val.isNegative() ? 1 : 0, E);
+  }
+
   case Builtin::BI__builtin_issignaling: {
 APFloat Val(0.0);
 return EvaluateFloat(E->getArg(0), Val, Info) &&
diff --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index 00206d09c113d..4ca92e66b2912 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -430,6 +430,15 @@ static bool interp__builtin_iszero(InterpState , CodePtr 
OpPC,
   return true;
 }
 
+static bool interp__builtin_signbit(InterpState , CodePtr OpPC,
+const InterpFrame *Frame, const Function 
*F,
+const CallExpr *Call) {
+  const Floating  = S.Stk.peek();
+
+  pushInteger(S, Arg.isNegative(), Call->getType());
+  return true;
+}
+
 /// First parameter to __builtin_isfpclass is the floating value, the
 /// second one is an integral value.
 static bool interp__builtin_isfpclass(InterpState , CodePtr OpPC,
@@ -1214,6 +1223,12 @@ bool InterpretBuiltin(InterpState , CodePtr OpPC, 
const Function *F,
 if (!interp__builtin_iszero(S, OpPC, Frame, F, Call))
   return false;
 break;
+  case Builtin::BI__builtin_signbit:
+  case Builtin::BI__builtin_signbitf:
+  case Builtin::BI__builtin_signbitl:
+if (!interp__builtin_signbit(S, OpPC, Frame, F, Call))
+  return false;
+break;
   case Builtin::BI__builtin_isfpclass:
 if (!interp__builtin_isfpclass(S, OpPC, Frame, F, Call))
   return false;
diff --git a/clang/test/Sema/constant-builtins-2.c 
b/clang/test/Sema/constant-builtins-2.c
index a60a1f16a4587..fca4ac2a26898 100644
--- a/clang/test/Sema/constant-builtins-2.c
+++ b/clang/test/Sema/constant-builtins-2.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fexperimental-new-constant-interpreter 
-verify %s
 
 // Math stuff
 
@@ -204,6 +205,18 @@ char isfpclass_snan_1   
[!__builtin_isfpclass(__builtin_nans(""), 0x0002) ? 1 :
 char isfpclass_snan_2   [__builtin_isfpclass(__builtin_nansl(""), 0x0207) ? 1 
: -1]; // ~fcFinite
 char isfpclass_snan_3   

[clang] [llvm] [AArch64] Support preserve_none calling convention (PR #91046)

2024-06-01 Thread via cfe-commits

https://github.com/antangelo updated 
https://github.com/llvm/llvm-project/pull/91046

>From 767173a0dfde9858c90867cc5d476da90e5ba898 Mon Sep 17 00:00:00 2001
From: Antonio Abbatangelo 
Date: Tue, 30 Apr 2024 22:58:18 -0400
Subject: [PATCH 1/8] [AArch64] Support preserve_none calling convention

---
 clang/include/clang/Basic/Attr.td |   3 +-
 clang/include/clang/Basic/AttrDocs.td |  19 +-
 clang/lib/Basic/Targets/AArch64.cpp   |   1 +
 clang/test/CodeGen/preserve-call-conv.c   |   6 +-
 llvm/docs/LangRef.rst |   2 +-
 .../Target/AArch64/AArch64CallingConvention.h |   3 +
 .../AArch64/AArch64CallingConvention.td   |  27 ++
 .../Target/AArch64/AArch64ISelLowering.cpp|  34 +-
 .../Target/AArch64/AArch64RegisterInfo.cpp|  12 +-
 .../AArch64/GISel/AArch64CallLowering.cpp |   1 +
 .../AArch64/dynamic-regmask-preserve-none.ll  |  88 +
 llvm/test/CodeGen/AArch64/preserve.ll |   9 +-
 llvm/test/CodeGen/AArch64/preserve_nonecc.ll  |  92 +
 .../CodeGen/AArch64/preserve_nonecc_call.ll   | 325 ++
 .../AArch64/preserve_nonecc_musttail.ll   |  11 +
 .../CodeGen/AArch64/preserve_nonecc_swift.ll  |  16 +
 16 files changed, 631 insertions(+), 18 deletions(-)
 create mode 100644 llvm/test/CodeGen/AArch64/dynamic-regmask-preserve-none.ll
 create mode 100644 llvm/test/CodeGen/AArch64/preserve_nonecc.ll
 create mode 100644 llvm/test/CodeGen/AArch64/preserve_nonecc_call.ll
 create mode 100644 llvm/test/CodeGen/AArch64/preserve_nonecc_musttail.ll
 create mode 100644 llvm/test/CodeGen/AArch64/preserve_nonecc_swift.ll

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 0225598cbbe8a..712c79927304e 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3038,7 +3038,8 @@ def M68kRTD: DeclOrTypeAttr {
   let Documentation = [M68kRTDDocs];
 }
 
-def PreserveNone : DeclOrTypeAttr, TargetSpecificAttr {
+def PreserveNone : DeclOrTypeAttr,
+   
TargetSpecificAttr> {
   let Spellings = [Clang<"preserve_none">];
   let Subjects = SubjectList<[FunctionLike]>;
   let Documentation = [PreserveNoneDocs];
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index f8253143b596c..d23465b77e7ed 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5658,17 +5658,20 @@ experimental at this time.
 def PreserveNoneDocs : Documentation {
   let Category = DocCatCallingConvs;
   let Content = [{
-On X86-64 target, this attribute changes the calling convention of a function.
+On X86-64 and AArch64 targets, this attribute changes the calling convention 
of a function.
 The ``preserve_none`` calling convention tries to preserve as few general
 registers as possible. So all general registers are caller saved registers. It
 also uses more general registers to pass arguments. This attribute doesn't
-impact floating-point registers (XMMs/YMMs). Floating-point registers still
-follow the c calling convention.
-
-- Only RSP and RBP are preserved by callee.
-
-- Register RDI, RSI, RDX, RCX, R8, R9, R11, R12, R13, R14, R15 and RAX now can
-  be used to pass function arguments.
+impact floating-point registers. 
+
+- On X86-64, only RSP and RBP are preserved by the callee.
+  Registers RDI, RSI, RDX, RCX, R8, R9, R11, R12, R13, R14, R15 and RAX now can
+  be used to pass function arguments. Floating-point registers (XMMs/YMMs) 
still
+  follow the C calling convention.
+- On AArch64, only LR and FP are preserved by the callee.
+  Registers X19-X28 and X0-X17 are used to pass function arguments.
+  X18, SIMD and floating-point registers follow the AAPCS calling
+  convention.
   }];
 }
 
diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index c8d243a8fb7ae..e1f7dbf1d9f20 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -1202,6 +1202,7 @@ AArch64TargetInfo::checkCallingConvention(CallingConv CC) 
const {
   case CC_SwiftAsync:
   case CC_PreserveMost:
   case CC_PreserveAll:
+  case CC_PreserveNone:
   case CC_OpenCLKernel:
   case CC_AArch64VectorCall:
   case CC_AArch64SVEPCS:
diff --git a/clang/test/CodeGen/preserve-call-conv.c 
b/clang/test/CodeGen/preserve-call-conv.c
index 74bf695e6f331..65973206403f7 100644
--- a/clang/test/CodeGen/preserve-call-conv.c
+++ b/clang/test/CodeGen/preserve-call-conv.c
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm < %s | FileCheck 
%s --check-prefixes=CHECK,X86-LINUX
-// RUN: %clang_cc1 -triple arm64-unknown-unknown -emit-llvm < %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm < %s | FileCheck 
%s --check-prefixes=CHECK,LINUX
+// RUN: %clang_cc1 -triple arm64-unknown-unknown -emit-llvm < %s | FileCheck 
%s --check-prefixes=CHECK,LINUX
 
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-msvc -emit-llvm %s -o - 

[clang] [clang][Interp] Member Pointers (PR #91303)

2024-06-01 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?= 
Message-ID:
In-Reply-To: 


https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/91303

>From 30d86295dda9b7aaa06c23b67c54806475266e5d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Wed, 10 Apr 2024 16:42:36 +0200
Subject: [PATCH 1/7] Memberpointers

---
 clang/lib/AST/CMakeLists.txt  |   1 +
 clang/lib/AST/Interp/ByteCodeExprGen.cpp  | 103 +-
 clang/lib/AST/Interp/Context.cpp  |  15 +-
 clang/lib/AST/Interp/Context.h|   2 +
 clang/lib/AST/Interp/Descriptor.cpp   |   1 +
 clang/lib/AST/Interp/Disasm.cpp   |   3 +
 clang/lib/AST/Interp/Interp.cpp   |  30 ++-
 clang/lib/AST/Interp/Interp.h |  99 ++
 clang/lib/AST/Interp/InterpFrame.cpp  |   1 +
 clang/lib/AST/Interp/InterpStack.cpp  |   1 +
 clang/lib/AST/Interp/InterpStack.h|   3 +
 clang/lib/AST/Interp/MemberPointer.cpp|  73 +++
 clang/lib/AST/Interp/MemberPointer.h  | 112 +++
 clang/lib/AST/Interp/Opcodes.td   |  18 +-
 clang/lib/AST/Interp/Pointer.cpp  |   1 +
 clang/lib/AST/Interp/Pointer.h|   1 +
 clang/lib/AST/Interp/PrimType.cpp |   1 +
 clang/lib/AST/Interp/PrimType.h   |   8 +-
 clang/test/AST/Interp/eval-order.cpp  |   4 +-
 clang/test/AST/Interp/literals.cpp|   7 +-
 clang/test/AST/Interp/memberpointers.cpp  | 184 ++
 .../mangle-ms-templates-memptrs.cpp   |   2 +-
 .../CodeGenCXX/pointers-to-data-members.cpp   |   2 +-
 clang/test/SemaCXX/attr-weak.cpp  |   1 +
 .../SemaCXX/nullptr_in_arithmetic_ops.cpp |   2 +-
 clang/unittests/AST/Interp/toAPValue.cpp  |  46 +
 26 files changed, 692 insertions(+), 29 deletions(-)
 create mode 100644 clang/lib/AST/Interp/MemberPointer.cpp
 create mode 100644 clang/lib/AST/Interp/MemberPointer.h
 create mode 100644 clang/test/AST/Interp/memberpointers.cpp

diff --git a/clang/lib/AST/CMakeLists.txt b/clang/lib/AST/CMakeLists.txt
index 3faefb54f599f..a5d3dacfc1a84 100644
--- a/clang/lib/AST/CMakeLists.txt
+++ b/clang/lib/AST/CMakeLists.txt
@@ -87,6 +87,7 @@ add_clang_library(clangAST
   Interp/Record.cpp
   Interp/Source.cpp
   Interp/State.cpp
+  Interp/MemberPointer.cpp
   Interp/InterpShared.cpp
   ItaniumCXXABI.cpp
   ItaniumMangle.cpp
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 6607727b5246f..5f8b94c3a0f94 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -100,6 +100,35 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 return this->emitMemcpy(CE);
   }
 
+  case CK_DerivedToBaseMemberPointer: {
+assert(classifyPrim(CE->getType()) == PT_MemberPtr);
+assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr);
+const auto *FromMP = SubExpr->getType()->getAs();
+const auto *ToMP = CE->getType()->getAs();
+
+unsigned DerivedOffset = collectBaseOffset(QualType(ToMP->getClass(), 0),
+   QualType(FromMP->getClass(), 
0));
+
+if (!this->visit(SubExpr))
+  return false;
+
+return this->emitGetMemberPtrBasePop(DerivedOffset, CE);
+  }
+
+  case CK_BaseToDerivedMemberPointer: {
+assert(classifyPrim(CE) == PT_MemberPtr);
+assert(classifyPrim(SubExpr) == PT_MemberPtr);
+const auto *FromMP = SubExpr->getType()->getAs();
+const auto *ToMP = CE->getType()->getAs();
+
+unsigned DerivedOffset = collectBaseOffset(QualType(FromMP->getClass(), 0),
+   QualType(ToMP->getClass(), 0));
+
+if (!this->visit(SubExpr))
+  return false;
+return this->emitGetMemberPtrBasePop(-DerivedOffset, CE);
+  }
+
   case CK_UncheckedDerivedToBase:
   case CK_DerivedToBase: {
 if (!this->visit(SubExpr))
@@ -187,7 +216,8 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
 return this->emitCastFloatingIntegral(*ToT, CE);
   }
 
-  case CK_NullToPointer: {
+  case CK_NullToPointer:
+  case CK_NullToMemberPointer: {
 if (DiscardResult)
   return true;
 
@@ -326,7 +356,8 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
 return this->emitCast(*FromT, *ToT, CE);
   }
 
-  case CK_PointerToBoolean: {
+  case CK_PointerToBoolean:
+  case CK_MemberPointerToBoolean: {
 PrimType PtrT = classifyPrim(SubExpr->getType());
 
 // Just emit p != nullptr for this.
@@ -534,8 +565,23 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
   BO->isComparisonOp())
 return this->emitComplexComparison(LHS, RHS, BO);
 
-  if (BO->isPtrMemOp())
-return this->visit(RHS);
+  if (BO->isPtrMemOp()) {
+if (!this->visit(LHS))
+  

[clang] [llvm] [AArch64] Support preserve_none calling convention (PR #91046)

2024-06-01 Thread via cfe-commits

https://github.com/antangelo updated 
https://github.com/llvm/llvm-project/pull/91046

>From 767173a0dfde9858c90867cc5d476da90e5ba898 Mon Sep 17 00:00:00 2001
From: Antonio Abbatangelo 
Date: Tue, 30 Apr 2024 22:58:18 -0400
Subject: [PATCH 1/7] [AArch64] Support preserve_none calling convention

---
 clang/include/clang/Basic/Attr.td |   3 +-
 clang/include/clang/Basic/AttrDocs.td |  19 +-
 clang/lib/Basic/Targets/AArch64.cpp   |   1 +
 clang/test/CodeGen/preserve-call-conv.c   |   6 +-
 llvm/docs/LangRef.rst |   2 +-
 .../Target/AArch64/AArch64CallingConvention.h |   3 +
 .../AArch64/AArch64CallingConvention.td   |  27 ++
 .../Target/AArch64/AArch64ISelLowering.cpp|  34 +-
 .../Target/AArch64/AArch64RegisterInfo.cpp|  12 +-
 .../AArch64/GISel/AArch64CallLowering.cpp |   1 +
 .../AArch64/dynamic-regmask-preserve-none.ll  |  88 +
 llvm/test/CodeGen/AArch64/preserve.ll |   9 +-
 llvm/test/CodeGen/AArch64/preserve_nonecc.ll  |  92 +
 .../CodeGen/AArch64/preserve_nonecc_call.ll   | 325 ++
 .../AArch64/preserve_nonecc_musttail.ll   |  11 +
 .../CodeGen/AArch64/preserve_nonecc_swift.ll  |  16 +
 16 files changed, 631 insertions(+), 18 deletions(-)
 create mode 100644 llvm/test/CodeGen/AArch64/dynamic-regmask-preserve-none.ll
 create mode 100644 llvm/test/CodeGen/AArch64/preserve_nonecc.ll
 create mode 100644 llvm/test/CodeGen/AArch64/preserve_nonecc_call.ll
 create mode 100644 llvm/test/CodeGen/AArch64/preserve_nonecc_musttail.ll
 create mode 100644 llvm/test/CodeGen/AArch64/preserve_nonecc_swift.ll

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 0225598cbbe8a..712c79927304e 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3038,7 +3038,8 @@ def M68kRTD: DeclOrTypeAttr {
   let Documentation = [M68kRTDDocs];
 }
 
-def PreserveNone : DeclOrTypeAttr, TargetSpecificAttr {
+def PreserveNone : DeclOrTypeAttr,
+   
TargetSpecificAttr> {
   let Spellings = [Clang<"preserve_none">];
   let Subjects = SubjectList<[FunctionLike]>;
   let Documentation = [PreserveNoneDocs];
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index f8253143b596c..d23465b77e7ed 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5658,17 +5658,20 @@ experimental at this time.
 def PreserveNoneDocs : Documentation {
   let Category = DocCatCallingConvs;
   let Content = [{
-On X86-64 target, this attribute changes the calling convention of a function.
+On X86-64 and AArch64 targets, this attribute changes the calling convention 
of a function.
 The ``preserve_none`` calling convention tries to preserve as few general
 registers as possible. So all general registers are caller saved registers. It
 also uses more general registers to pass arguments. This attribute doesn't
-impact floating-point registers (XMMs/YMMs). Floating-point registers still
-follow the c calling convention.
-
-- Only RSP and RBP are preserved by callee.
-
-- Register RDI, RSI, RDX, RCX, R8, R9, R11, R12, R13, R14, R15 and RAX now can
-  be used to pass function arguments.
+impact floating-point registers. 
+
+- On X86-64, only RSP and RBP are preserved by the callee.
+  Registers RDI, RSI, RDX, RCX, R8, R9, R11, R12, R13, R14, R15 and RAX now can
+  be used to pass function arguments. Floating-point registers (XMMs/YMMs) 
still
+  follow the C calling convention.
+- On AArch64, only LR and FP are preserved by the callee.
+  Registers X19-X28 and X0-X17 are used to pass function arguments.
+  X18, SIMD and floating-point registers follow the AAPCS calling
+  convention.
   }];
 }
 
diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index c8d243a8fb7ae..e1f7dbf1d9f20 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -1202,6 +1202,7 @@ AArch64TargetInfo::checkCallingConvention(CallingConv CC) 
const {
   case CC_SwiftAsync:
   case CC_PreserveMost:
   case CC_PreserveAll:
+  case CC_PreserveNone:
   case CC_OpenCLKernel:
   case CC_AArch64VectorCall:
   case CC_AArch64SVEPCS:
diff --git a/clang/test/CodeGen/preserve-call-conv.c 
b/clang/test/CodeGen/preserve-call-conv.c
index 74bf695e6f331..65973206403f7 100644
--- a/clang/test/CodeGen/preserve-call-conv.c
+++ b/clang/test/CodeGen/preserve-call-conv.c
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm < %s | FileCheck 
%s --check-prefixes=CHECK,X86-LINUX
-// RUN: %clang_cc1 -triple arm64-unknown-unknown -emit-llvm < %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm < %s | FileCheck 
%s --check-prefixes=CHECK,LINUX
+// RUN: %clang_cc1 -triple arm64-unknown-unknown -emit-llvm < %s | FileCheck 
%s --check-prefixes=CHECK,LINUX
 
 // RUN: %clang_cc1 -triple x86_64-unknown-windows-msvc -emit-llvm %s -o - 

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-01 Thread Younan Zhang via cfe-commits

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

>From b8a69cbd9e0ee0aa35b38b7e3a78048cbe61447e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 23:30:10 +0800
Subject: [PATCH 01/14] [clangd] Support go-to-definition on type hints. The
 core part

---
 clang-tools-extra/clangd/AST.cpp  |   9 +
 clang-tools-extra/clangd/AST.h|   2 +
 clang-tools-extra/clangd/InlayHints.cpp   | 251 +-
 .../clangd/index/IndexAction.cpp  |   9 +-
 .../clangd/unittests/InlayHintTests.cpp   |  22 ++
 5 files changed, 279 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 1b86ea19cf28d..ef87f1bcb8443 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -1019,5 +1019,14 @@ bool isExpandedFromParameterPack(const ParmVarDecl *D) {
   return getUnderlyingPackType(D) != nullptr;
 }
 
+std::optional toURI(OptionalFileEntryRef File) {
+  if (!File)
+return std::nullopt;
+  auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
+  if (AbsolutePath.empty())
+return std::nullopt;
+  return URI::create(AbsolutePath);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fb0722d697cd0..3ae624b1ab741 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -250,6 +250,8 @@ resolveForwardingParameters(const FunctionDecl *D, unsigned 
MaxDepth = 10);
 /// reference to one (e.g. `Args&...` or `Args&&...`).
 bool isExpandedFromParameterPack(const ParmVarDecl *D);
 
+std::optional toURI(OptionalFileEntryRef File);
+
 } // namespace clangd
 } // namespace clang
 
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index cd4f1931b3ce1..f9e0a51ddcc9f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/SourceManager.h"
@@ -372,6 +373,197 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+std::optional toLocation(SourceManager , SourceRange Range) {
+  if (Range.isInvalid())
+return std::nullopt;
+  if (auto URI =
+  toURI(SM.getFileEntryRefForID(SM.getFileID(Range.getBegin() {
+Location L;
+L.range.start = sourceLocToPosition(SM, Range.getBegin());
+L.range.end = sourceLocToPosition(SM, Range.getEnd());
+if (auto File = URIForFile::fromURI(*URI, ""))
+  L.uri = File.get();
+return L;
+  }
+  return std::nullopt;
+}
+
+class TypeInlayHintLabelPartBuilder
+: public TypeVisitor {
+  QualType Current;
+  ASTContext 
+  const PrintingPolicy 
+  std::vector 
+
+  bool ShouldAddLinksToTagTypes = false;
+
+  struct CurrentTypeRAII {
+TypeInlayHintLabelPartBuilder 
+QualType PreviousType;
+bool PreviousShouldAddLinksToTagTypes;
+CurrentTypeRAII(TypeInlayHintLabelPartBuilder , QualType New,
+bool ShouldAddLinksToTagTypes)
+: Builder(Builder), PreviousType(Builder.Current) {
+  Builder.Current = New;
+  Builder.ShouldAddLinksToTagTypes = ShouldAddLinksToTagTypes;
+}
+~CurrentTypeRAII() {
+  Builder.Current = PreviousType;
+  Builder.ShouldAddLinksToTagTypes = PreviousShouldAddLinksToTagTypes;
+}
+  };
+
+  void addLabel(llvm::function_ref NamePrinter,
+llvm::function_ref SourceRangeGetter) {
+auto  = LabelChunks.emplace_back();
+llvm::raw_string_ostream OS(Name.value);
+NamePrinter(OS);
+Name.location = toLocation(Context.getSourceManager(), 
SourceRangeGetter());
+  }
+
+  void printTemplateArgumentList(llvm::ArrayRef Args) {
+unsigned Size = Args.size();
+for (unsigned I = 0; I < Size; ++I) {
+  auto  = Args[I];
+  if (PP.SuppressDefaultTemplateArgs && TA.getIsDefaulted())
+continue;
+  if (I)
+LabelChunks.emplace_back(", ");
+  printTemplateArgument(TA);
+}
+  }
+
+  void printTemplateArgument(const TemplateArgument ) {
+if (TA.getKind() == TemplateArgument::Pack)
+  return printTemplateArgumentList(TA.pack_elements());
+if (TA.getKind() == TemplateArgument::Type) {
+  CurrentTypeRAII Guard(*this, TA.getAsType(),
+/*ShouldAddLinksToTagTypes=*/true);
+  return Visit(TA.getAsType().getTypePtr());
+}
+llvm::raw_string_ostream OS(LabelChunks.emplace_back().value);
+TA.print(PP, OS, /*IncludeType=*/true);
+  }
+
+  void
+  processTemplateSpecialization(TemplateName TN,
+llvm::ArrayRef Args,
+SourceRange TemplateNameRange = SourceRange()) 
{
+

[clang] [llvm] [CUDA] Mark CUDA-12.5 as supported and introduce ptx 8.5. (PR #94113)

2024-06-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Andrey Portnoy (andportnoy)


Changes

This PR is based on https://github.com/llvm/llvm-project/pull/91516.

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


6 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1-1) 
- (modified) clang/include/clang/Basic/BuiltinsNVPTX.def (+4-1) 
- (modified) clang/include/clang/Basic/Cuda.h (+2-1) 
- (modified) clang/lib/Basic/Cuda.cpp (+1) 
- (modified) clang/lib/Driver/ToolChains/Cuda.cpp (+3) 
- (modified) llvm/lib/Target/NVPTX/NVPTX.td (+2-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0c700d23257bf..61269e6db93e5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -934,7 +934,7 @@ CUDA/HIP Language Changes
 
 CUDA Support
 
-- Clang now supports CUDA SDK up to 12.4
+- Clang now supports CUDA SDK up to 12.5
 
 AIX Support
 ^^^
diff --git a/clang/include/clang/Basic/BuiltinsNVPTX.def 
b/clang/include/clang/Basic/BuiltinsNVPTX.def
index 9e243d740ed7a..504314d8d96e9 100644
--- a/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -62,7 +62,9 @@
 #pragma push_macro("PTX82")
 #pragma push_macro("PTX83")
 #pragma push_macro("PTX84")
-#define PTX84 "ptx84"
+#pragma push_macro("PTX85")
+#define PTX85 "ptx85"
+#define PTX84 "ptx84|" PTX85
 #define PTX83 "ptx83|" PTX84
 #define PTX82 "ptx82|" PTX83
 #define PTX81 "ptx81|" PTX82
@@ -1094,3 +1096,4 @@ TARGET_BUILTIN(__nvvm_getctarank_shared_cluster, "iv*3", 
"", AND(SM_90,PTX78))
 #pragma pop_macro("PTX82")
 #pragma pop_macro("PTX83")
 #pragma pop_macro("PTX84")
+#pragma pop_macro("PTX85")
diff --git a/clang/include/clang/Basic/Cuda.h b/clang/include/clang/Basic/Cuda.h
index 2d67c4181d129..961ddaf57fc00 100644
--- a/clang/include/clang/Basic/Cuda.h
+++ b/clang/include/clang/Basic/Cuda.h
@@ -42,9 +42,10 @@ enum class CudaVersion {
   CUDA_122,
   CUDA_123,
   CUDA_124,
+  CUDA_125,
   FULLY_SUPPORTED = CUDA_123,
   PARTIALLY_SUPPORTED =
-  CUDA_124, // Partially supported. Proceed with a warning.
+  CUDA_125, // Partially supported. Proceed with a warning.
   NEW = 1,  // Too new. Issue a warning, but allow using it.
 };
 const char *CudaVersionToString(CudaVersion V);
diff --git a/clang/lib/Basic/Cuda.cpp b/clang/lib/Basic/Cuda.cpp
index e8ce15eb0decb..2ee17f0ad4ca0 100644
--- a/clang/lib/Basic/Cuda.cpp
+++ b/clang/lib/Basic/Cuda.cpp
@@ -42,6 +42,7 @@ static const CudaVersionMapEntry CudaNameVersionMap[] = {
 CUDA_ENTRY(12, 2),
 CUDA_ENTRY(12, 3),
 CUDA_ENTRY(12, 4),
+CUDA_ENTRY(12, 5),
 {"", CudaVersion::NEW, 
llvm::VersionTuple(std::numeric_limits::max())},
 {"unknown", CudaVersion::UNKNOWN, {}} // End of list tombstone.
 };
diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index d5f93c9c830fa..bbc8be91fd70b 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -84,6 +84,8 @@ CudaVersion getCudaVersion(uint32_t raw_version) {
 return CudaVersion::CUDA_123;
   if (raw_version < 12050)
 return CudaVersion::CUDA_124;
+  if (raw_version < 12060)
+return CudaVersion::CUDA_125;
   return CudaVersion::NEW;
 }
 
@@ -690,6 +692,7 @@ void NVPTX::getNVPTXTargetFeatures(const Driver , const 
llvm::Triple ,
   case CudaVersion::CUDA_##CUDA_VER:   
\
 PtxFeature = "+ptx" #PTX_VER;  
\
 break;
+CASE_CUDA_VERSION(125, 85);
 CASE_CUDA_VERSION(124, 84);
 CASE_CUDA_VERSION(123, 83);
 CASE_CUDA_VERSION(122, 82);
diff --git a/llvm/lib/Target/NVPTX/NVPTX.td b/llvm/lib/Target/NVPTX/NVPTX.td
index 05457c71cd392..bb4549a5e6078 100644
--- a/llvm/lib/Target/NVPTX/NVPTX.td
+++ b/llvm/lib/Target/NVPTX/NVPTX.td
@@ -41,7 +41,8 @@ foreach sm = [20, 21, 30, 32, 35, 37, 50, 52, 53,
 def SM90a: FeatureSM<"90a", 901>;
 
 foreach version = [32, 40, 41, 42, 43, 50, 60, 61, 62, 63, 64, 65,
-   70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84] in
+   70, 71, 72, 73, 74, 75, 76, 77, 78,
+   80, 81, 82, 83, 84, 85] in
   def PTX#version: FeaturePTX;
 
 
//===--===//

``




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


[clang] [llvm] [CUDA] Mark CUDA-12.5 as supported and introduce ptx 8.5. (PR #94113)

2024-06-01 Thread Andrey Portnoy via cfe-commits

https://github.com/andportnoy created 
https://github.com/llvm/llvm-project/pull/94113

This PR is based on https://github.com/llvm/llvm-project/pull/91516.

>From 1e1853e013b2e253944efe52bffd0b108108101c Mon Sep 17 00:00:00 2001
From: Andrey Portnoy 
Date: Sat, 1 Jun 2024 10:35:40 -0400
Subject: [PATCH] [CUDA] Mark CUDA-12.5 as supported and introduce ptx 8.5.

---
 clang/docs/ReleaseNotes.rst | 2 +-
 clang/include/clang/Basic/BuiltinsNVPTX.def | 5 -
 clang/include/clang/Basic/Cuda.h| 3 ++-
 clang/lib/Basic/Cuda.cpp| 1 +
 clang/lib/Driver/ToolChains/Cuda.cpp| 3 +++
 llvm/lib/Target/NVPTX/NVPTX.td  | 3 ++-
 6 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0c700d23257bf..61269e6db93e5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -934,7 +934,7 @@ CUDA/HIP Language Changes
 
 CUDA Support
 
-- Clang now supports CUDA SDK up to 12.4
+- Clang now supports CUDA SDK up to 12.5
 
 AIX Support
 ^^^
diff --git a/clang/include/clang/Basic/BuiltinsNVPTX.def 
b/clang/include/clang/Basic/BuiltinsNVPTX.def
index 9e243d740ed7a..504314d8d96e9 100644
--- a/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -62,7 +62,9 @@
 #pragma push_macro("PTX82")
 #pragma push_macro("PTX83")
 #pragma push_macro("PTX84")
-#define PTX84 "ptx84"
+#pragma push_macro("PTX85")
+#define PTX85 "ptx85"
+#define PTX84 "ptx84|" PTX85
 #define PTX83 "ptx83|" PTX84
 #define PTX82 "ptx82|" PTX83
 #define PTX81 "ptx81|" PTX82
@@ -1094,3 +1096,4 @@ TARGET_BUILTIN(__nvvm_getctarank_shared_cluster, "iv*3", 
"", AND(SM_90,PTX78))
 #pragma pop_macro("PTX82")
 #pragma pop_macro("PTX83")
 #pragma pop_macro("PTX84")
+#pragma pop_macro("PTX85")
diff --git a/clang/include/clang/Basic/Cuda.h b/clang/include/clang/Basic/Cuda.h
index 2d67c4181d129..961ddaf57fc00 100644
--- a/clang/include/clang/Basic/Cuda.h
+++ b/clang/include/clang/Basic/Cuda.h
@@ -42,9 +42,10 @@ enum class CudaVersion {
   CUDA_122,
   CUDA_123,
   CUDA_124,
+  CUDA_125,
   FULLY_SUPPORTED = CUDA_123,
   PARTIALLY_SUPPORTED =
-  CUDA_124, // Partially supported. Proceed with a warning.
+  CUDA_125, // Partially supported. Proceed with a warning.
   NEW = 1,  // Too new. Issue a warning, but allow using it.
 };
 const char *CudaVersionToString(CudaVersion V);
diff --git a/clang/lib/Basic/Cuda.cpp b/clang/lib/Basic/Cuda.cpp
index e8ce15eb0decb..2ee17f0ad4ca0 100644
--- a/clang/lib/Basic/Cuda.cpp
+++ b/clang/lib/Basic/Cuda.cpp
@@ -42,6 +42,7 @@ static const CudaVersionMapEntry CudaNameVersionMap[] = {
 CUDA_ENTRY(12, 2),
 CUDA_ENTRY(12, 3),
 CUDA_ENTRY(12, 4),
+CUDA_ENTRY(12, 5),
 {"", CudaVersion::NEW, 
llvm::VersionTuple(std::numeric_limits::max())},
 {"unknown", CudaVersion::UNKNOWN, {}} // End of list tombstone.
 };
diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index d5f93c9c830fa..bbc8be91fd70b 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -84,6 +84,8 @@ CudaVersion getCudaVersion(uint32_t raw_version) {
 return CudaVersion::CUDA_123;
   if (raw_version < 12050)
 return CudaVersion::CUDA_124;
+  if (raw_version < 12060)
+return CudaVersion::CUDA_125;
   return CudaVersion::NEW;
 }
 
@@ -690,6 +692,7 @@ void NVPTX::getNVPTXTargetFeatures(const Driver , const 
llvm::Triple ,
   case CudaVersion::CUDA_##CUDA_VER:   
\
 PtxFeature = "+ptx" #PTX_VER;  
\
 break;
+CASE_CUDA_VERSION(125, 85);
 CASE_CUDA_VERSION(124, 84);
 CASE_CUDA_VERSION(123, 83);
 CASE_CUDA_VERSION(122, 82);
diff --git a/llvm/lib/Target/NVPTX/NVPTX.td b/llvm/lib/Target/NVPTX/NVPTX.td
index 05457c71cd392..bb4549a5e6078 100644
--- a/llvm/lib/Target/NVPTX/NVPTX.td
+++ b/llvm/lib/Target/NVPTX/NVPTX.td
@@ -41,7 +41,8 @@ foreach sm = [20, 21, 30, 32, 35, 37, 50, 52, 53,
 def SM90a: FeatureSM<"90a", 901>;
 
 foreach version = [32, 40, 41, 42, 43, 50, 60, 61, 62, 63, 64, 65,
-   70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84] in
+   70, 71, 72, 73, 74, 75, 76, 77, 78,
+   80, 81, 82, 83, 84, 85] in
   def PTX#version: FeaturePTX;
 
 
//===--===//

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


[clang] [Clang] Implement resolution for CWG1835 (PR #92957)

2024-06-01 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

> This means that we must perform the second (unqualified) lookup during 
> parsing even when the type of the object expression is dependent, but those 
> results are not used to determine whether a < token is the start of a 
> template-argument_list; they are stored so we can replicate the second lookup 
> during instantiation.

If I understand correctly, you point to a conflict between 
http://eel.is/c++draft/basic.lookup#qual.general-3.sentence-3 and 
http://eel.is/c++draft/temp.res#temp.dep.type-6. Have you considered filing a 
Core issue?

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


[clang] [compiler-rt] [ubsan] Display correct runtime messages for negative _BitInt (PR #93612)

2024-06-01 Thread via cfe-commits


@@ -0,0 +1,188 @@
+// RUN: %clang -Wno-constant-conversion -Wno-array-bounds 
-Wno-division-by-zero -Wno-shift-negative-value -Wno-shift-count-negative 
-Wno-int-to-pointer-cast -O0 
-fsanitize=alignment,array-bounds,bool,float-cast-overflow,implicit-integer-sign-change,implicit-signed-integer-truncation,implicit-unsigned-integer-truncation,integer-divide-by-zero,nonnull-attribute,null,nullability-arg,nullability-assign,nullability-return,pointer-overflow,returns-nonnull-attribute,shift-base,shift-exponent,signed-integer-overflow,unreachable,unsigned-integer-overflow,unsigned-shift-base,vla-bound
 %s -o %t1 && %run %t1 2>&1 | FileCheck %s --check-prefix=CHECK-R
+// RUN: %clang -Wno-constant-conversion -Wno-array-bounds 
-Wno-division-by-zero -Wno-shift-negative-value -Wno-shift-count-negative 
-Wno-int-to-pointer-cast 
-fsanitize=array-bounds,enum,float-cast-overflow,integer-divide-by-zero,implicit-unsigned-integer-truncation,implicit-signed-integer-truncation,implicit-integer-sign-change,unsigned-integer-overflow,signed-integer-overflow,shift-base,shift-exponent
 -O0 -S -emit-llvm -o - %s | FileCheck %s --check-prefix=CHECK-IR
+
+#include 
+#include 
+
+uint32_t float_divide_by_zero() {
+  float f = 1.0f / 0.0f;
+  // CHECK-IR: constant { i16, i16, [8 x i8] } { i16 1, i16 32, [8 x i8] 
c"'float'\00" }
+  _BitInt(37) r = (_BitInt(37))f;
+  // CHECK-R: {{.*}}bit-int.c:[[@LINE-1]]:19: runtime error: inf is outside 
the range of representable values of type
+  // CHECK-IR: constant { i16, i16, [20 x i8] } { i16 2, i16 13, [20 x i8] 
c"'_BitInt(37)'\00%\00\00\00\00\00" }
+  return r;
+}
+
+uint32_t integer_divide_by_zero() __attribute__((no_sanitize("memory"))) {
+  _BitInt(37) x = 1 / 0;
+  // CHECK-R: {{.*}}bit-int.c:[[@LINE-1]]:21: runtime error: division by zero
+  // CHECK-IR: constant { i16, i16, [32 x i8] } { i16 0, i16 10, [32 x i8] 
c"'uint32_t' (aka 'unsigned int')\00" }
+  return x;
+}
+
+uint32_t implicit_unsigned_integer_truncation() {
+  unsigned _BitInt(37) x = 2U;
+  x += float_divide_by_zero();
+  x += integer_divide_by_zero();
+  x = x + 0xULL;
+  // CHECK-R: {{.*}}bit-int.c:[[@LINE-1]]:9: runtime error: unsigned integer 
overflow:
+  // CHECK-IR: constant { i16, i16, [23 x i8] } { i16 0, i16 12, [23 x i8] 
c"'unsigned _BitInt(37)'\00" }
+  uint32_t r = x & 0x;
+  return r;
+}
+
+uint32_t pointer_overflow() __attribute__((no_sanitize("address"))) {
+  _BitInt(37) *x = (_BitInt(37) *)1;
+  _BitInt(37) *y = x - 1;
+  // CHECK-R: {{.*}}bit-int.c:[[@LINE-1]]:22: runtime error: pointer index 
expression with base
+  uint32_t r = *(_BitInt(37) *)
+  // CHECK-R: {{.*}}bit-int.c:[[@LINE-1]]:16: runtime error: implicit 
conversion from type
+  return r;
+}
+
+uint32_t vla_bound(_BitInt(37) x) {
+  _BitInt(37) a[x - 1];
+  // CHECK-R: {{.*}}bit-int.c:[[@LINE-1]]:17: runtime error: variable length 
array bound evaluates to non-positive value
+  return 0;
+}
+
+uint32_t nullability_arg(_BitInt(37) *_Nonnull x)
+__attribute__((no_sanitize("address"))) {
+  _BitInt(37) y = *(_BitInt(37) *)
+  return y;
+}

earnol wrote:

> hmm, does no `CHECK:` line imply that there isn't a diagnostic? I think it 
> will just silently pass... maybe if these are in a different file where there 
> are no diagnostics expected it would work as intended?

Yes. It will silently pass, yet unexpected diagnostics in the middle of the 
check script can throw the FileCheck off and it will barf. My idea is having at 
least some check (which can provide false negative error detection: detects not 
error when there is an error) is better compared to no check at all completely.

CHECK-NOT will not work here as it will require the line which should not be 
encountered and line is not known in this case.
CHECK-EMPTY also does not look like a right choice. 

> That could be brittle though if the diagnostic gets spelled differently, or 
> if there's a typo in the check. Maybe its easy if UBSAN errors change the 
> return code, though?

You have given me a great idea. These examples can be moved to different test 
file which will be compiled with -fsanitize-trap option. It this case it would 
be easy to detect the ubsan activation did not happened. On the other hand it 
will require extra file and i wanted to pack all ubsan _BitInt tests into 
single file. But probably it is not that bad, if it is the price for check 
precision.
Alternatively FileCheck can be used with with "--implicit-check-not error" 
option to verify the fact runtime error was not thrown.
What approach do you think will be the best?



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


[clang] [clang-format] Don't always break before << between string literals (PR #92214)

2024-06-01 Thread via cfe-commits

mydeveloperday wrote:

I agree


On Sat, 1 Jun 2024 at 04:12, Owen Pan ***@***.***> wrote:

> We should backport it to 18.1.7 IMO. See #93034
>  and #93958
> . WDYT @mydeveloperday
>  @HazardyKnusperkeks
> ?
>
> —
> Reply to this email directly, view it on GitHub
> ,
> or unsubscribe
> 
> .
> You are receiving this because you were mentioned.Message ID:
> ***@***.***>
>


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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-01 Thread Younan Zhang via cfe-commits

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

>From b8a69cbd9e0ee0aa35b38b7e3a78048cbe61447e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 23:30:10 +0800
Subject: [PATCH 01/13] [clangd] Support go-to-definition on type hints. The
 core part

---
 clang-tools-extra/clangd/AST.cpp  |   9 +
 clang-tools-extra/clangd/AST.h|   2 +
 clang-tools-extra/clangd/InlayHints.cpp   | 251 +-
 .../clangd/index/IndexAction.cpp  |   9 +-
 .../clangd/unittests/InlayHintTests.cpp   |  22 ++
 5 files changed, 279 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 1b86ea19cf28d..ef87f1bcb8443 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -1019,5 +1019,14 @@ bool isExpandedFromParameterPack(const ParmVarDecl *D) {
   return getUnderlyingPackType(D) != nullptr;
 }
 
+std::optional toURI(OptionalFileEntryRef File) {
+  if (!File)
+return std::nullopt;
+  auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
+  if (AbsolutePath.empty())
+return std::nullopt;
+  return URI::create(AbsolutePath);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fb0722d697cd0..3ae624b1ab741 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -250,6 +250,8 @@ resolveForwardingParameters(const FunctionDecl *D, unsigned 
MaxDepth = 10);
 /// reference to one (e.g. `Args&...` or `Args&&...`).
 bool isExpandedFromParameterPack(const ParmVarDecl *D);
 
+std::optional toURI(OptionalFileEntryRef File);
+
 } // namespace clangd
 } // namespace clang
 
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index cd4f1931b3ce1..f9e0a51ddcc9f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/SourceManager.h"
@@ -372,6 +373,197 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+std::optional toLocation(SourceManager , SourceRange Range) {
+  if (Range.isInvalid())
+return std::nullopt;
+  if (auto URI =
+  toURI(SM.getFileEntryRefForID(SM.getFileID(Range.getBegin() {
+Location L;
+L.range.start = sourceLocToPosition(SM, Range.getBegin());
+L.range.end = sourceLocToPosition(SM, Range.getEnd());
+if (auto File = URIForFile::fromURI(*URI, ""))
+  L.uri = File.get();
+return L;
+  }
+  return std::nullopt;
+}
+
+class TypeInlayHintLabelPartBuilder
+: public TypeVisitor {
+  QualType Current;
+  ASTContext 
+  const PrintingPolicy 
+  std::vector 
+
+  bool ShouldAddLinksToTagTypes = false;
+
+  struct CurrentTypeRAII {
+TypeInlayHintLabelPartBuilder 
+QualType PreviousType;
+bool PreviousShouldAddLinksToTagTypes;
+CurrentTypeRAII(TypeInlayHintLabelPartBuilder , QualType New,
+bool ShouldAddLinksToTagTypes)
+: Builder(Builder), PreviousType(Builder.Current) {
+  Builder.Current = New;
+  Builder.ShouldAddLinksToTagTypes = ShouldAddLinksToTagTypes;
+}
+~CurrentTypeRAII() {
+  Builder.Current = PreviousType;
+  Builder.ShouldAddLinksToTagTypes = PreviousShouldAddLinksToTagTypes;
+}
+  };
+
+  void addLabel(llvm::function_ref NamePrinter,
+llvm::function_ref SourceRangeGetter) {
+auto  = LabelChunks.emplace_back();
+llvm::raw_string_ostream OS(Name.value);
+NamePrinter(OS);
+Name.location = toLocation(Context.getSourceManager(), 
SourceRangeGetter());
+  }
+
+  void printTemplateArgumentList(llvm::ArrayRef Args) {
+unsigned Size = Args.size();
+for (unsigned I = 0; I < Size; ++I) {
+  auto  = Args[I];
+  if (PP.SuppressDefaultTemplateArgs && TA.getIsDefaulted())
+continue;
+  if (I)
+LabelChunks.emplace_back(", ");
+  printTemplateArgument(TA);
+}
+  }
+
+  void printTemplateArgument(const TemplateArgument ) {
+if (TA.getKind() == TemplateArgument::Pack)
+  return printTemplateArgumentList(TA.pack_elements());
+if (TA.getKind() == TemplateArgument::Type) {
+  CurrentTypeRAII Guard(*this, TA.getAsType(),
+/*ShouldAddLinksToTagTypes=*/true);
+  return Visit(TA.getAsType().getTypePtr());
+}
+llvm::raw_string_ostream OS(LabelChunks.emplace_back().value);
+TA.print(PP, OS, /*IncludeType=*/true);
+  }
+
+  void
+  processTemplateSpecialization(TemplateName TN,
+llvm::ArrayRef Args,
+SourceRange TemplateNameRange = SourceRange()) 
{
+

[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (PR #94104)

2024-06-01 Thread Piotr Zegar via cfe-commits

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

Overall LGTM, consider adding release note entry for modernize-use-std-print 
(as it were added in previous release)

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


[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (PR #94104)

2024-06-01 Thread Piotr Zegar via cfe-commits


@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||

PiotrZSL wrote:

Note: you ay also verify that ActualType is not null

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


[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (PR #94104)

2024-06-01 Thread Piotr Zegar via cfe-commits


@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}

PiotrZSL wrote:

consider moving this to some exist file in utils directory

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


[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (PR #94104)

2024-06-01 Thread Piotr Zegar via cfe-commits

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


[clang] [llvm] Intrinsic: introduce minimumnum and maximumnum (PR #93841)

2024-06-01 Thread YunQiang Su via cfe-commits


@@ -32,27 +32,29 @@ class StoreInst;
 
 /// These are the kinds of recurrences that we support.
 enum class RecurKind {
-  None, ///< Not a recurrence.
-  Add,  ///< Sum of integers.
-  Mul,  ///< Product of integers.
-  Or,   ///< Bitwise or logical OR of integers.
-  And,  ///< Bitwise or logical AND of integers.
-  Xor,  ///< Bitwise or logical XOR of integers.
-  SMin, ///< Signed integer min implemented in terms of select(cmp()).
-  SMax, ///< Signed integer max implemented in terms of select(cmp()).
-  UMin, ///< Unsigned integer min implemented in terms of select(cmp()).
-  UMax, ///< Unsigned integer max implemented in terms of select(cmp()).
-  FAdd, ///< Sum of floats.
-  FMul, ///< Product of floats.
-  FMin, ///< FP min implemented in terms of select(cmp()).
-  FMax, ///< FP max implemented in terms of select(cmp()).
-  FMinimum, ///< FP min with llvm.minimum semantics
-  FMaximum, ///< FP max with llvm.maximum semantics
-  FMulAdd,  ///< Sum of float products with llvm.fmuladd(a * b + sum).
-  IAnyOf,   ///< Any_of reduction with select(icmp(),x,y) where one of (x,y) is
-///< loop invariant, and both x and y are integer type.
-  FAnyOf///< Any_of reduction with select(fcmp(),x,y) where one of (x,y) is
-///< loop invariant, and both x and y are integer type.
+  None,///< Not a recurrence.
+  Add, ///< Sum of integers.
+  Mul, ///< Product of integers.
+  Or,  ///< Bitwise or logical OR of integers.
+  And, ///< Bitwise or logical AND of integers.
+  Xor, ///< Bitwise or logical XOR of integers.
+  SMin,///< Signed integer min implemented in terms of select(cmp()).
+  SMax,///< Signed integer max implemented in terms of select(cmp()).
+  UMin,///< Unsigned integer min implemented in terms of select(cmp()).
+  UMax,///< Unsigned integer max implemented in terms of select(cmp()).
+  FAdd,///< Sum of floats.
+  FMul,///< Product of floats.
+  FMin,///< FP min implemented in terms of select(cmp()).
+  FMax,///< FP max implemented in terms of select(cmp()).
+  FMinimum,///< FP min with llvm.minimum semantics
+  FMaximum,///< FP max with llvm.maximum semantics
+  FMinimumnum, ///< FP min with llvm.minimumnum semantics
+  FMaximumnum, ///< FP max with llvm.maximumnum semantics

wzssyqa wrote:

Removed from this PR, and add them into TODOs.

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-01 Thread Younan Zhang via cfe-commits

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-01 Thread Younan Zhang via cfe-commits


@@ -1637,6 +1678,144 @@ TEST(TypeHints, SubstTemplateParameterAliases) {
 ExpectedHint{": static_vector", "vector_name"});
 }
 
+template 
+void assertTypeLinkHints(StringRef Code, StringRef HintRange,
+ Labels... ExpectedLabels) {
+  Annotations Source(Code);
+  auto HintAt = [&](llvm::ArrayRef InlayHints,
+llvm::StringRef Range) {
+auto *Hint = llvm::find_if(InlayHints, [&](const InlayHint ) {
+  return InlayHint.range == Source.range(Range);
+});
+assert(Hint && "No range was found");
+return llvm::ArrayRef(Hint->label);
+  };
+
+  TestTU TU = TestTU::withCode(Source.code());
+  TU.ExtraArgs.push_back("-std=c++2c");
+  auto AST = TU.build();
+
+  Config C;
+  C.InlayHints.TypeNameLimit = 0;
+  WithContextValue WithCfg(Config::Key, std::move(C));
+
+  auto Hints = hintsOfKind(AST, InlayHintKind::Type);
+  EXPECT_THAT(HintAt(Hints, HintRange),
+  ElementsAre(HintLabelPieceMatcher(ExpectedLabels, Source)...));
+}
+
+TEST(TypeHints, Links) {
+  StringRef Source(R"cpp(
+$Package[[template 
+struct Package {]]};
+
+$SpecializationOfPackage[[template <>
+struct Package {]]};
+
+$Container[[template 
+struct Container {]]};
+
+$NttpContainer[[template 
+struct NttpContainer {]]};
+
+enum struct ScopedEnum {
+  X = 1,
+};
+
+enum Enum {
+  E = 2,
+};
+
+namespace ns {
+  $Nested[[template 
+  struct Nested {
+$NestedClass[[template 
+struct ]]Class {
+};
+  ]]};
+
+  $NestedInt[[using NestedInt = Nested;
+}
+
+void basic() {
+  auto $1[[C]] = Container>();
+  auto $2[[D]] = Container>();
+  auto $3[[E]] = Container, long>();
+  auto $4[[F]] = NttpContainer();
+  auto $5[[G]] = ns::Nested>::Class>();
+}
+
+void compounds() {
+  auto $6[[A]] = Container::Class&>();
+  auto $7[[B]] = Container::Class&&>();
+  auto $8[[C]] = Container::Class> 
*>();
+}
+
+namespace nns {
+  $UsingShadow[[using ns::]]NestedInt;
+
+  void aliases() {
+auto $9[[A]] = Container();
+auto $10[[B]] = Container();
+  }
+}
+
+  )cpp");
+
+  assertTypeLinkHints(Source, "1", ExpectedHintLabelPiece{": Container<"},

zyn0217 wrote:

Thanks! That makes sense and I'll take that.

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


[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-01 Thread Younan Zhang via cfe-commits

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

>From b8a69cbd9e0ee0aa35b38b7e3a78048cbe61447e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 23:30:10 +0800
Subject: [PATCH 01/11] [clangd] Support go-to-definition on type hints. The
 core part

---
 clang-tools-extra/clangd/AST.cpp  |   9 +
 clang-tools-extra/clangd/AST.h|   2 +
 clang-tools-extra/clangd/InlayHints.cpp   | 251 +-
 .../clangd/index/IndexAction.cpp  |   9 +-
 .../clangd/unittests/InlayHintTests.cpp   |  22 ++
 5 files changed, 279 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 1b86ea19cf28d..ef87f1bcb8443 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -1019,5 +1019,14 @@ bool isExpandedFromParameterPack(const ParmVarDecl *D) {
   return getUnderlyingPackType(D) != nullptr;
 }
 
+std::optional toURI(OptionalFileEntryRef File) {
+  if (!File)
+return std::nullopt;
+  auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
+  if (AbsolutePath.empty())
+return std::nullopt;
+  return URI::create(AbsolutePath);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fb0722d697cd0..3ae624b1ab741 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -250,6 +250,8 @@ resolveForwardingParameters(const FunctionDecl *D, unsigned 
MaxDepth = 10);
 /// reference to one (e.g. `Args&...` or `Args&&...`).
 bool isExpandedFromParameterPack(const ParmVarDecl *D);
 
+std::optional toURI(OptionalFileEntryRef File);
+
 } // namespace clangd
 } // namespace clang
 
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index cd4f1931b3ce1..f9e0a51ddcc9f 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/SourceManager.h"
@@ -372,6 +373,197 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+std::optional toLocation(SourceManager , SourceRange Range) {
+  if (Range.isInvalid())
+return std::nullopt;
+  if (auto URI =
+  toURI(SM.getFileEntryRefForID(SM.getFileID(Range.getBegin() {
+Location L;
+L.range.start = sourceLocToPosition(SM, Range.getBegin());
+L.range.end = sourceLocToPosition(SM, Range.getEnd());
+if (auto File = URIForFile::fromURI(*URI, ""))
+  L.uri = File.get();
+return L;
+  }
+  return std::nullopt;
+}
+
+class TypeInlayHintLabelPartBuilder
+: public TypeVisitor {
+  QualType Current;
+  ASTContext 
+  const PrintingPolicy 
+  std::vector 
+
+  bool ShouldAddLinksToTagTypes = false;
+
+  struct CurrentTypeRAII {
+TypeInlayHintLabelPartBuilder 
+QualType PreviousType;
+bool PreviousShouldAddLinksToTagTypes;
+CurrentTypeRAII(TypeInlayHintLabelPartBuilder , QualType New,
+bool ShouldAddLinksToTagTypes)
+: Builder(Builder), PreviousType(Builder.Current) {
+  Builder.Current = New;
+  Builder.ShouldAddLinksToTagTypes = ShouldAddLinksToTagTypes;
+}
+~CurrentTypeRAII() {
+  Builder.Current = PreviousType;
+  Builder.ShouldAddLinksToTagTypes = PreviousShouldAddLinksToTagTypes;
+}
+  };
+
+  void addLabel(llvm::function_ref NamePrinter,
+llvm::function_ref SourceRangeGetter) {
+auto  = LabelChunks.emplace_back();
+llvm::raw_string_ostream OS(Name.value);
+NamePrinter(OS);
+Name.location = toLocation(Context.getSourceManager(), 
SourceRangeGetter());
+  }
+
+  void printTemplateArgumentList(llvm::ArrayRef Args) {
+unsigned Size = Args.size();
+for (unsigned I = 0; I < Size; ++I) {
+  auto  = Args[I];
+  if (PP.SuppressDefaultTemplateArgs && TA.getIsDefaulted())
+continue;
+  if (I)
+LabelChunks.emplace_back(", ");
+  printTemplateArgument(TA);
+}
+  }
+
+  void printTemplateArgument(const TemplateArgument ) {
+if (TA.getKind() == TemplateArgument::Pack)
+  return printTemplateArgumentList(TA.pack_elements());
+if (TA.getKind() == TemplateArgument::Type) {
+  CurrentTypeRAII Guard(*this, TA.getAsType(),
+/*ShouldAddLinksToTagTypes=*/true);
+  return Visit(TA.getAsType().getTypePtr());
+}
+llvm::raw_string_ostream OS(LabelChunks.emplace_back().value);
+TA.print(PP, OS, /*IncludeType=*/true);
+  }
+
+  void
+  processTemplateSpecialization(TemplateName TN,
+llvm::ArrayRef Args,
+SourceRange TemplateNameRange = SourceRange()) 
{
+

[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-06-01 Thread Younan Zhang via cfe-commits


@@ -1637,6 +1678,144 @@ TEST(TypeHints, SubstTemplateParameterAliases) {
 ExpectedHint{": static_vector", "vector_name"});
 }
 
+template 
+void assertTypeLinkHints(StringRef Code, StringRef HintRange,
+ Labels... ExpectedLabels) {
+  Annotations Source(Code);
+  auto HintAt = [&](llvm::ArrayRef InlayHints,
+llvm::StringRef Range) {
+auto *Hint = llvm::find_if(InlayHints, [&](const InlayHint ) {
+  return InlayHint.range == Source.range(Range);
+});
+assert(Hint && "No range was found");
+return llvm::ArrayRef(Hint->label);
+  };
+
+  TestTU TU = TestTU::withCode(Source.code());
+  TU.ExtraArgs.push_back("-std=c++2c");
+  auto AST = TU.build();
+
+  Config C;
+  C.InlayHints.TypeNameLimit = 0;
+  WithContextValue WithCfg(Config::Key, std::move(C));
+
+  auto Hints = hintsOfKind(AST, InlayHintKind::Type);
+  EXPECT_THAT(HintAt(Hints, HintRange),
+  ElementsAre(HintLabelPieceMatcher(ExpectedLabels, Source)...));
+}
+
+TEST(TypeHints, Links) {
+  StringRef Source(R"cpp(
+$Package[[template 

zyn0217 wrote:

> Is there a reason to prefer putting full decl source ranges into 
> InlayHintLabelPart.location, rather than single-token source ranges (e.g. 
> just the range Package) like in the go-to-definition response?

Frankly, it is because the protocol requires a source range of something, and 
I'm concerned that providing only one source location doesn't really make a 
better experience. But I have to say I've never attempted it before, so I think 
it's worth a try.

> What vscode seems to do is call textDocument/definition at the start position 
> of the range, and navigate to the resulting definition location.

I have realized that problem; it looks like a call to `textDocument/definition` 
is not cheap and it usually takes a few seconds to respond (taking us to the 
definition/getting the hover content) on my other large project.

> We have [some 
> utilities](https://searchfox.org/llvm/rev/1664610130b88ef168e33eddfe973a3f11bd4261/clang-tools-extra/clangd/XRefs.cpp#414-415)
>  for getting the single-token source range for the go-to-def response, which 
> we could probably reuse.
> (As a bonus, it makes the tests a bit easier to write and read.)

Thanks! I really appreciate that and will explore it soon. :)

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


[clang] [amdgpu] Pass variadic arguments without splitting (PR #94083)

2024-06-01 Thread Jon Chesterfield via cfe-commits

JonChesterfield wrote:

That's our call really. Right now this passes everything as whatever type it 
claimed to be as far as creating the call instruction goes, then variadic 
lowering pastes them all into a single structure with four byte alignment on 
every field.

Tagging some parameters as byval or byref is fine as far as variadic lowering 
goes. They'll tend to end up in their own alloca, then a ptr in the call frame. 
It means more test variation but the common path knows what byval is, and 
adding byref will be fine.

I'm not immediately worried about sdag crashing if people pass loads of data to 
a variadic call, considering our baseline capability here is no variadics at 
all. Likewise I'm not sure what the performance tradeoffs of copying into the 
frame vs indirect reference are and not very worried about making an optimal 
choice there.

I'll add some more structs to show they're also passed unchanged. If you want 
more complicated rules you're welcome to them - happy to pass arguments in 
whatever pattern you like, though the splitting them into multiple fields as we 
currently do would push the va_arg lowering complexity up alarmingly.

What would you sign off on? The current approach is the simplest. Next up is 
using the same when-to-pass-byref as fixed arguments without the splitting. 
Otherwise we can have some other heuristic.

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


[clang] [Clang] Implement resolution for CWG1835 (PR #92957)

2024-06-01 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

> Per [[basic.lookup.qual.general] 
> p1](http://eel.is/c++draft/basic.lookup.qual.general#1), lookup for a 
> member-qualified name is type-only if it's an identifier followed by ::;

Per my reading, type-only lookup is performed only for elaborated type 
specifiers (http://eel.is/c++draft/basic.lookup#elab-1.sentence-1) and 
base-specifiers (http://eel.is/c++draft/class.derived#general-2.sentence-4). 
What [basic.lookup.qual.general] p1 describes is much like type-only lookup, 
but namespaces are considered. Another important difference is that 
http://eel.is/c++draft/basic.lookup#general-4.sentence-2 do apply to lookup of 
identifiers followed by `::`.

Not saying that this materially changes anything, but we should be more 
cautions with terminology.

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


[clang] [lldb] [llvm] Remove some `try_compile` CMake checks for compiler flags (PR #92953)

2024-06-01 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

@vvereschaka Thank you for letting me know! I wonder how this got past our pre- 
and post-commit CI, because we do build lldb with MSVC there. You fix makes 
total sense, so I applied it.

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


[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (PR #94104)

2024-06-01 Thread Mike Crowe via cfe-commits

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


[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (PR #94104)

2024-06-01 Thread Mike Crowe via cfe-commits

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


[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (#92896) (PR #94104)

2024-06-01 Thread Mike Crowe via cfe-commits

https://github.com/mikecrowe updated 
https://github.com/llvm/llvm-project/pull/94104

>From 2972062997ca582100b5797cd548c4dc2f80c69a Mon Sep 17 00:00:00 2001
From: Mike Crowe 
Date: Fri, 31 May 2024 21:27:03 +0100
Subject: [PATCH] [clang-tidy] Fix assert in modernize-use-std-format/print

Ensure that FormatStringConverter's constructor fails with a sensible
error message rather than asserting if the format string is not a narrow
string literal.

Also, ensure that we don't even get that far in modernize-use-std-print
and modernize-use-std-format by checking that the format string
parameter is a char pointer.

Fixes #92896
---
 .../modernize/UseStdFormatCheck.cpp   | 18 -
 .../clang-tidy/modernize/UseStdPrintCheck.cpp |  8 ++
 .../utils/FormatStringConverter.cpp   |  8 +++---
 .../modernize/use-std-format-custom.cpp   | 18 +++--
 .../modernize/use-std-print-custom.cpp| 26 +--
 5 files changed, 65 insertions(+), 13 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
index 6cef21f1318a2..5c72f8f22dec7 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context)
@@ -47,13 +52,14 @@ void UseStdFormatCheck::registerPPCallbacks(const 
SourceManager ,
 }
 
 void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   Finder->addMatcher(
-  callExpr(argumentCountAtLeast(1),
-   hasArgument(0, stringLiteral(isOrdinary())),
-   callee(functionDecl(unless(cxxMethodDecl()),
-   matchers::matchesAnyListedName(
-   StrFormatLikeFunctions))
-  .bind("func_decl")))
+  callExpr(
+  argumentCountAtLeast(1), hasArgument(0, stringLiteral(isOrdinary())),
+  callee(functionDecl(
+ unless(cxxMethodDecl()), hasParameter(0, CharPointerType),
+ matchers::matchesAnyListedName(StrFormatLikeFunctions))
+ .bind("func_decl")))
   .bind("strformat"),
   this);
 }
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
index ff990feadc0c1..6a4497eaf7f60 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdPrintCheck::UseStdPrintCheck(StringRef Name, ClangTidyContext *Context)
@@ -95,12 +100,14 @@ unusedReturnValue(clang::ast_matchers::StatementMatcher 
MatchedCallExpr) {
 }
 
 void UseStdPrintCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   if (!PrintfLikeFunctions.empty())
 Finder->addMatcher(
 unusedReturnValue(
 callExpr(argumentCountAtLeast(1),
  hasArgument(0, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(0, CharPointerType),
  matchers::matchesAnyListedName(
  PrintfLikeFunctions))
 .bind("func_decl")))
@@ -113,6 +120,7 @@ void UseStdPrintCheck::registerMatchers(MatchFinder 
*Finder) {
 callExpr(argumentCountAtLeast(2),
  hasArgument(1, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(1, CharPointerType),
  matchers::matchesAnyListedName(
  FprintfLikeFunctions))
 .bind("func_decl")))
diff --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
index 

[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (#92896) (PR #94104)

2024-06-01 Thread Mike Crowe via cfe-commits

https://github.com/mikecrowe updated 
https://github.com/llvm/llvm-project/pull/94104

>From 54135a6f8fd9491e6b94e4d96e46f2909e344307 Mon Sep 17 00:00:00 2001
From: Mike Crowe 
Date: Fri, 31 May 2024 21:27:03 +0100
Subject: [PATCH] [clang-tidy] Fix assert in modernize-use-std-format/print
 (#92896)

Ensure that FormatStringConverter's constructor fails with a sensible
error message rather than asserting if the format string is not a narrow
string literal.

Also, ensure that we don't even get that far in modernize-use-std-print
and modernize-use-std-format by checking that the format string
parameter is a char pointer.

Fixes #92896
---
 .../modernize/UseStdFormatCheck.cpp   | 18 -
 .../clang-tidy/modernize/UseStdPrintCheck.cpp |  8 ++
 .../utils/FormatStringConverter.cpp   |  8 +++---
 .../modernize/use-std-format-custom.cpp   | 18 +++--
 .../modernize/use-std-print-custom.cpp| 26 +--
 5 files changed, 65 insertions(+), 13 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
index 6cef21f1318a2..5c72f8f22dec7 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context)
@@ -47,13 +52,14 @@ void UseStdFormatCheck::registerPPCallbacks(const 
SourceManager ,
 }
 
 void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   Finder->addMatcher(
-  callExpr(argumentCountAtLeast(1),
-   hasArgument(0, stringLiteral(isOrdinary())),
-   callee(functionDecl(unless(cxxMethodDecl()),
-   matchers::matchesAnyListedName(
-   StrFormatLikeFunctions))
-  .bind("func_decl")))
+  callExpr(
+  argumentCountAtLeast(1), hasArgument(0, stringLiteral(isOrdinary())),
+  callee(functionDecl(
+ unless(cxxMethodDecl()), hasParameter(0, CharPointerType),
+ matchers::matchesAnyListedName(StrFormatLikeFunctions))
+ .bind("func_decl")))
   .bind("strformat"),
   this);
 }
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
index ff990feadc0c1..6a4497eaf7f60 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdPrintCheck::UseStdPrintCheck(StringRef Name, ClangTidyContext *Context)
@@ -95,12 +100,14 @@ unusedReturnValue(clang::ast_matchers::StatementMatcher 
MatchedCallExpr) {
 }
 
 void UseStdPrintCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   if (!PrintfLikeFunctions.empty())
 Finder->addMatcher(
 unusedReturnValue(
 callExpr(argumentCountAtLeast(1),
  hasArgument(0, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(0, CharPointerType),
  matchers::matchesAnyListedName(
  PrintfLikeFunctions))
 .bind("func_decl")))
@@ -113,6 +120,7 @@ void UseStdPrintCheck::registerMatchers(MatchFinder 
*Finder) {
 callExpr(argumentCountAtLeast(2),
  hasArgument(1, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(1, CharPointerType),
  matchers::matchesAnyListedName(
  FprintfLikeFunctions))
 .bind("func_decl")))
diff --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp

[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (#92896) (PR #94104)

2024-06-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Mike Crowe (mikecrowe)


Changes

Ensure that FormatStringConverter's constructor fails with a sensible error 
message rather than asserting if the format string is not a narrow string 
literal.

Also, ensure that we don't even get that far in modernize-use-std-print and 
modernize-use-std-format by checking that the format string parameter is a char 
pointer.

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


5 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp 
(+12-6) 
- (modified) clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp (+8) 
- (modified) clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
(+5-3) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-format-custom.cpp 
(+16-2) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp 
(+24-2) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
index 6cef21f1318a2..5c72f8f22dec7 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context)
@@ -47,13 +52,14 @@ void UseStdFormatCheck::registerPPCallbacks(const 
SourceManager ,
 }
 
 void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   Finder->addMatcher(
-  callExpr(argumentCountAtLeast(1),
-   hasArgument(0, stringLiteral(isOrdinary())),
-   callee(functionDecl(unless(cxxMethodDecl()),
-   matchers::matchesAnyListedName(
-   StrFormatLikeFunctions))
-  .bind("func_decl")))
+  callExpr(
+  argumentCountAtLeast(1), hasArgument(0, stringLiteral(isOrdinary())),
+  callee(functionDecl(
+ unless(cxxMethodDecl()), hasParameter(0, CharPointerType),
+ matchers::matchesAnyListedName(StrFormatLikeFunctions))
+ .bind("func_decl")))
   .bind("strformat"),
   this);
 }
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
index ff990feadc0c1..6a4497eaf7f60 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdPrintCheck::UseStdPrintCheck(StringRef Name, ClangTidyContext *Context)
@@ -95,12 +100,14 @@ unusedReturnValue(clang::ast_matchers::StatementMatcher 
MatchedCallExpr) {
 }
 
 void UseStdPrintCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   if (!PrintfLikeFunctions.empty())
 Finder->addMatcher(
 unusedReturnValue(
 callExpr(argumentCountAtLeast(1),
  hasArgument(0, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(0, CharPointerType),
  matchers::matchesAnyListedName(
  PrintfLikeFunctions))
 .bind("func_decl")))
@@ -113,6 +120,7 @@ void UseStdPrintCheck::registerMatchers(MatchFinder 
*Finder) {
 callExpr(argumentCountAtLeast(2),
  hasArgument(1, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(1, CharPointerType),
  matchers::matchesAnyListedName(
  FprintfLikeFunctions))
 .bind("func_decl")))
diff --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
index 845e71c5003b8..33f3ea47df1e3 

[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (#92896) (PR #94104)

2024-06-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Mike Crowe (mikecrowe)


Changes

Ensure that FormatStringConverter's constructor fails with a sensible error 
message rather than asserting if the format string is not a narrow string 
literal.

Also, ensure that we don't even get that far in modernize-use-std-print and 
modernize-use-std-format by checking that the format string parameter is a char 
pointer.

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


5 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp 
(+12-6) 
- (modified) clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp (+8) 
- (modified) clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
(+5-3) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-format-custom.cpp 
(+16-2) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp 
(+24-2) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
index 6cef21f1318a2..5c72f8f22dec7 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context)
@@ -47,13 +52,14 @@ void UseStdFormatCheck::registerPPCallbacks(const 
SourceManager ,
 }
 
 void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   Finder->addMatcher(
-  callExpr(argumentCountAtLeast(1),
-   hasArgument(0, stringLiteral(isOrdinary())),
-   callee(functionDecl(unless(cxxMethodDecl()),
-   matchers::matchesAnyListedName(
-   StrFormatLikeFunctions))
-  .bind("func_decl")))
+  callExpr(
+  argumentCountAtLeast(1), hasArgument(0, stringLiteral(isOrdinary())),
+  callee(functionDecl(
+ unless(cxxMethodDecl()), hasParameter(0, CharPointerType),
+ matchers::matchesAnyListedName(StrFormatLikeFunctions))
+ .bind("func_decl")))
   .bind("strformat"),
   this);
 }
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
index ff990feadc0c1..6a4497eaf7f60 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdPrintCheck::UseStdPrintCheck(StringRef Name, ClangTidyContext *Context)
@@ -95,12 +100,14 @@ unusedReturnValue(clang::ast_matchers::StatementMatcher 
MatchedCallExpr) {
 }
 
 void UseStdPrintCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   if (!PrintfLikeFunctions.empty())
 Finder->addMatcher(
 unusedReturnValue(
 callExpr(argumentCountAtLeast(1),
  hasArgument(0, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(0, CharPointerType),
  matchers::matchesAnyListedName(
  PrintfLikeFunctions))
 .bind("func_decl")))
@@ -113,6 +120,7 @@ void UseStdPrintCheck::registerMatchers(MatchFinder 
*Finder) {
 callExpr(argumentCountAtLeast(2),
  hasArgument(1, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(1, CharPointerType),
  matchers::matchesAnyListedName(
  FprintfLikeFunctions))
 .bind("func_decl")))
diff --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
index 

[clang-tools-extra] [clang-tidy] Fix assert in modernize-use-std-format/print (#92896) (PR #94104)

2024-06-01 Thread Mike Crowe via cfe-commits

https://github.com/mikecrowe created 
https://github.com/llvm/llvm-project/pull/94104

Ensure that FormatStringConverter's constructor fails with a sensible error 
message rather than asserting if the format string is not a narrow string 
literal.

Also, ensure that we don't even get that far in modernize-use-std-print and 
modernize-use-std-format by checking that the format string parameter is a char 
pointer.

>From 845879284bf80f5abb99eb2a86f90255fc57827b Mon Sep 17 00:00:00 2001
From: Mike Crowe 
Date: Fri, 31 May 2024 21:27:03 +0100
Subject: [PATCH] [clang-tidy] Avoid assertion failure in
 modernize-use-std-format/print (#92896)

Ensure that FormatStringConverter's constructor fails with a sensible
error message rather than asserting if the format string is not a narrow
string literal.

Also, ensure that we don't even get that far in modernize-use-std-print
and modernize-use-std-format by checking that the format string
parameter is a char pointer.
---
 .../modernize/UseStdFormatCheck.cpp   | 18 -
 .../clang-tidy/modernize/UseStdPrintCheck.cpp |  8 ++
 .../utils/FormatStringConverter.cpp   |  8 +++---
 .../modernize/use-std-format-custom.cpp   | 18 +++--
 .../modernize/use-std-print-custom.cpp| 26 +--
 5 files changed, 65 insertions(+), 13 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
index 6cef21f1318a2..5c72f8f22dec7 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdFormatCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdFormatCheck::UseStdFormatCheck(StringRef Name, ClangTidyContext *Context)
@@ -47,13 +52,14 @@ void UseStdFormatCheck::registerPPCallbacks(const 
SourceManager ,
 }
 
 void UseStdFormatCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   Finder->addMatcher(
-  callExpr(argumentCountAtLeast(1),
-   hasArgument(0, stringLiteral(isOrdinary())),
-   callee(functionDecl(unless(cxxMethodDecl()),
-   matchers::matchesAnyListedName(
-   StrFormatLikeFunctions))
-  .bind("func_decl")))
+  callExpr(
+  argumentCountAtLeast(1), hasArgument(0, stringLiteral(isOrdinary())),
+  callee(functionDecl(
+ unless(cxxMethodDecl()), hasParameter(0, CharPointerType),
+ matchers::matchesAnyListedName(StrFormatLikeFunctions))
+ .bind("func_decl")))
   .bind("strformat"),
   this);
 }
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
index ff990feadc0c1..6a4497eaf7f60 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdPrintCheck.cpp
@@ -20,6 +20,11 @@ namespace clang::tidy::modernize {
 
 namespace {
 AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); }
+AST_MATCHER(QualType, isSimpleChar) {
+  const auto ActualType = Node.getTypePtr();
+  return ActualType->isSpecificBuiltinType(BuiltinType::Char_S) ||
+ ActualType->isSpecificBuiltinType(BuiltinType::Char_U);
+}
 } // namespace
 
 UseStdPrintCheck::UseStdPrintCheck(StringRef Name, ClangTidyContext *Context)
@@ -95,12 +100,14 @@ unusedReturnValue(clang::ast_matchers::StatementMatcher 
MatchedCallExpr) {
 }
 
 void UseStdPrintCheck::registerMatchers(MatchFinder *Finder) {
+  auto CharPointerType = hasType(pointerType(pointee(isSimpleChar(;
   if (!PrintfLikeFunctions.empty())
 Finder->addMatcher(
 unusedReturnValue(
 callExpr(argumentCountAtLeast(1),
  hasArgument(0, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(0, CharPointerType),
  matchers::matchesAnyListedName(
  PrintfLikeFunctions))
 .bind("func_decl")))
@@ -113,6 +120,7 @@ void UseStdPrintCheck::registerMatchers(MatchFinder 
*Finder) {
 callExpr(argumentCountAtLeast(2),
  hasArgument(1, stringLiteral(isOrdinary())),
  callee(functionDecl(unless(cxxMethodDecl()),
+ hasParameter(1, CharPointerType),

[clang] [Clang][Sema] Push an evaluation context for type constraints (PR #93945)

2024-06-01 Thread Younan Zhang via cfe-commits

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


[clang] 16397e8 - [Clang][Sema] Push an evaluation context for type constraints (#93945)

2024-06-01 Thread via cfe-commits

Author: Younan Zhang
Date: 2024-06-01T16:16:15+08:00
New Revision: 16397e8ec7ffbee2907dfec698356f67672086e8

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

LOG: [Clang][Sema] Push an evaluation context for type constraints (#93945)

This helps getTemplateInstantiationArgs() to properly recover template
arguments of an enclosing concept Decl.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/test/SemaTemplate/concepts-lambda.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 22b4dc172c840..0c700d23257bf 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -822,6 +822,7 @@ Bug Fixes to C++ Support
 - Fix a regression introduced in Clang 18 causing incorrect overload 
resolution in the presence of functions only
   
diff erering by their constraints when only one of these function was variadic.
 - Fix a crash when a variable is captured by a block nested inside a lambda. 
(Fixes #GH93625).
+- Fixed a type constraint substitution issue involving a generic lambda 
expression. (#GH93821)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 3e3ed77de710e..40a759ea330de 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5660,7 +5660,7 @@ Sema::CheckConceptTemplateId(const CXXScopeSpec ,
   LocalInstantiationScope Scope(*this);
 
   EnterExpressionEvaluationContext EECtx{
-  *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
+  *this, ExpressionEvaluationContext::Unevaluated, CSD};
 
   if (!AreArgsDependent &&
   CheckConstraintSatisfaction(

diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 8ec49fcf553d0..1011db2d2830d 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -5134,6 +5134,20 @@ static bool CheckDeducedPlaceholderConstraints(Sema , 
const AutoType ,
 return true;
   MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
/*Final=*/false);
+  // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
+  // that the template arguments of the constraint can be preserved. For
+  // example:
+  //
+  //  template 
+  //  concept C = []() { return true; }();
+  //
+  // We need the argument for T while evaluating type constraint D in
+  // building the CallExpr to the lambda.
+  EnterExpressionEvaluationContext EECtx(
+  S, Sema::ExpressionEvaluationContext::Unevaluated,
+  ImplicitConceptSpecializationDecl::Create(
+  S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
+  CanonicalConverted));
   if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
 MLTAL, TypeLoc.getLocalSourceRange(),
 Satisfaction))

diff  --git a/clang/test/SemaTemplate/concepts-lambda.cpp 
b/clang/test/SemaTemplate/concepts-lambda.cpp
index fac790d09f9cf..280be71284f97 100644
--- a/clang/test/SemaTemplate/concepts-lambda.cpp
+++ b/clang/test/SemaTemplate/concepts-lambda.cpp
@@ -225,3 +225,15 @@ void foo() {
   }(x);
 }
 } // namespace GH73418
+
+namespace GH93821 {
+
+template 
+concept C = true;
+
+template 
+concept D = []() { return true; }();
+
+D auto x = 0;
+
+} // namespace GH93821



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


[clang] [Clang][Sema] Push an evaluation context for type constraints (PR #93945)

2024-06-01 Thread Younan Zhang via cfe-commits

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

>From 088c4199dd37172a57d965fe1b22f782084e127e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Fri, 31 May 2024 18:15:54 +0800
Subject: [PATCH 1/2] [Clang][Sema] Push an evaluation context for type
 constraints

This helps getTemplateInstantiationArgs to properly recover template
arguments of an enclosing concept Decl.

Fixes https://github.com/llvm/llvm-project/issues/93821
---
 clang/docs/ReleaseNotes.rst |  1 +
 clang/lib/Sema/SemaTemplateDeduction.cpp| 14 ++
 clang/test/SemaTemplate/concepts-lambda.cpp | 12 
 3 files changed, 27 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 49ab222bec405..83eb285e9ca48 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -710,6 +710,7 @@ Bug Fixes to C++ Support
 - Correctly treat the compound statement of an ``if consteval`` as an 
immediate context. Fixes (#GH91509).
 - When partial ordering alias templates against template template parameters,
   allow pack expansions when the alias has a fixed-size parameter list. Fixes 
(#GH62529).
+- Fixed a type constraint substitution issue involving a generic lambda 
expression. (#GH93821)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 853c0e1b50619..56529b4d852e7 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -5004,6 +5004,20 @@ static bool CheckDeducedPlaceholderConstraints(Sema , 
const AutoType ,
 return true;
   MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
/*Final=*/false);
+  // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
+  // that the template arguments of the constraint can be preserved. For
+  // example:
+  //
+  //  template 
+  //  concept C = []() { return true; }();
+  //
+  // We need the argument for T while evaluating type constraint D in
+  // building the CallExpr to the lambda.
+  EnterExpressionEvaluationContext EECtx(
+  S, Sema::ExpressionEvaluationContext::ConstantEvaluated,
+  ImplicitConceptSpecializationDecl::Create(
+  S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
+  CanonicalConverted));
   if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
 MLTAL, TypeLoc.getLocalSourceRange(),
 Satisfaction))
diff --git a/clang/test/SemaTemplate/concepts-lambda.cpp 
b/clang/test/SemaTemplate/concepts-lambda.cpp
index fac790d09f9cf..280be71284f97 100644
--- a/clang/test/SemaTemplate/concepts-lambda.cpp
+++ b/clang/test/SemaTemplate/concepts-lambda.cpp
@@ -225,3 +225,15 @@ void foo() {
   }(x);
 }
 } // namespace GH73418
+
+namespace GH93821 {
+
+template 
+concept C = true;
+
+template 
+concept D = []() { return true; }();
+
+D auto x = 0;
+
+} // namespace GH93821

>From dad1d8a4a0f517fe3c548fc6c4b9d7730f8991cd Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Fri, 31 May 2024 22:29:19 +0800
Subject: [PATCH 2/2] Set context kinds to Unevaluated

---
 clang/lib/Sema/SemaTemplate.cpp  | 2 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 8219d5eed8db7..33a7af8fa8ce3 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5595,7 +5595,7 @@ Sema::CheckConceptTemplateId(const CXXScopeSpec ,
   LocalInstantiationScope Scope(*this);
 
   EnterExpressionEvaluationContext EECtx{
-  *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
+  *this, ExpressionEvaluationContext::Unevaluated, CSD};
 
   if (!AreArgsDependent &&
   CheckConstraintSatisfaction(
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 56529b4d852e7..2e8e8d0708d24 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -5014,7 +5014,7 @@ static bool CheckDeducedPlaceholderConstraints(Sema , 
const AutoType ,
   // We need the argument for T while evaluating type constraint D in
   // building the CallExpr to the lambda.
   EnterExpressionEvaluationContext EECtx(
-  S, Sema::ExpressionEvaluationContext::ConstantEvaluated,
+  S, Sema::ExpressionEvaluationContext::Unevaluated,
   ImplicitConceptSpecializationDecl::Create(
   S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
   CanonicalConverted));

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


[clang] [clang][analyzer] Improved PointerSubChecker (PR #93676)

2024-06-01 Thread Balazs Benics via cfe-commits
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,74 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.core.PointerSub -verify %s
+
+void f1(void) {
+  int x, y, z[10];
+  int d =  -  // expected-warning{{Subtraction of two pointers that do 
not point into the same array is undefined behavior}}
+  d = z -  // expected-warning{{Subtraction of two pointers that do not 
point into the same array is undefined behavior}}
+  d =  -  // expected-warning{{Subtraction of two pointers that do not 
point into the same array is undefined behavior}}
+  d = (long*) - (long*)
+}
+
+void f2(void) {
+  int a[10], b[10], c;
+  int *p = [2];
+  int *q = [8];
+  int d = q - p; // no-warning
+
+  q = [3];
+  d = q - p; // expected-warning{{Subtraction of two pointers that}}
+
+  q = a + 10;
+  d = q - p; // no warning (use of pointer to one after the end is allowed)
+  d = [4] - a; // no warning
+
+  q = a + 11;
+  d = q - a; // ?
+
+  d =  - p; // expected-warning{{Subtraction of two pointers that}}
+}
+
+void f3(void) {
+  int a[3][4];
+  int d;
+
+  d = &(a[2]) - &(a[1]);
+  d = a[2] - a[1]; // expected-warning{{Subtraction of two pointers that}}
+  d = a[1] - a[1];
+  d = &(a[1][2]) - &(a[1][0]);
+  d = &(a[1][2]) - &(a[0][0]); // expected-warning{{Subtraction of two 
pointers that}}
+}
+
+void f4(void) {
+  int n = 4, m = 3;
+  int a[n][m];
+  int (*p)[m] = a; // p == [0]
+  p += 1; // p == [1]
+  int d = p - a; // d == 1 // expected-warning{{subtraction of pointers to 
type 'int[m]' of zero size has undefined behavior}}
+
+  d = &(a[2]) - &(a[1]); // expected-warning{{subtraction of pointers to type 
'int[m]' of zero size has undefined behavior}}
+  d = a[2] - a[1]; // expected-warning{{Subtraction of two pointers that}}

steakhal wrote:

Ah, that's gotta be it. Thanks!

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


[clang] [clang][analyzer] Move PutenvStackArrayChecker out of alpha package. (PR #93980)

2024-06-01 Thread Balazs Benics via cfe-commits


@@ -1179,6 +1179,41 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+.. _security-putenv-stack-array:
+
+security.PutenvStackArray (C)
+"
+Finds calls to the ``putenv`` function which pass a pointer to a 
stack-allocated
+(automatic) array as the argument. Function ``putenv`` does not copy the passed
+string, only a pointer to the data is stored and this data can be read even by
+other threads. Content of a stack-allocated array is likely to be overwritten
+after returning from the parent function.

steakhal wrote:

```suggestion
after returning to the parent function.
```

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


[clang] [clang][analyzer] Move PutenvStackArrayChecker out of alpha package. (PR #93980)

2024-06-01 Thread Balazs Benics via cfe-commits

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


[clang] [clang][analyzer] Move PutenvStackArrayChecker out of alpha package. (PR #93980)

2024-06-01 Thread Balazs Benics via cfe-commits


@@ -1179,6 +1179,41 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+.. _security-putenv-stack-array:
+
+security.PutenvStackArray (C)
+"
+Finds calls to the ``putenv`` function which pass a pointer to a 
stack-allocated
+(automatic) array as the argument. Function ``putenv`` does not copy the passed
+string, only a pointer to the data is stored and this data can be read even by
+other threads. Content of a stack-allocated array is likely to be overwritten
+after returning from the parent function.
+
+The problem can be solved by using a static array variable or dynamically
+allocated memory. Even better is to avoid using ``putenv`` (it has other
+problems related to memory leaks) and use ``setenv`` instead.
+
+The check corresponds to CERT rule
+`POS34-C. Do not call putenv() with a pointer to an automatic variable as the 
argument
+`_.
+
+.. code-block:: c
+
+  int f() {
+char env[] = "NAME=value";
+return putenv(env); // putenv function should not be called with 
stack-allocated string
+  }
+
+There is one case where the checker can report a false positive. This is when
+the stack-allocated array is used at `putenv` in a function or code branch that
+does not return (calls `fork` or `exec` like function).

steakhal wrote:

I feel this isn't accurate. Both `fork` and `exec` eventually returns.
I think the reason for having an FP for these is because these will copy the 
environment variables and not directly use the one we manipulated by `putenv`.

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


[clang] [clang][analyzer] Move PutenvStackArrayChecker out of alpha package. (PR #93980)

2024-06-01 Thread Balazs Benics via cfe-commits

https://github.com/steakhal commented:

I have only a handful of remarks. LGTM otherwise.

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


[clang] [Clang] Fix __is_trivially_equality_comparable returning true with ineligebile defaulted overloads (PR #93113)

2024-06-01 Thread Nikolas Klauser via cfe-commits

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

>From cabff5972424393e9d76bce4f8015ceed331a5f9 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Thu, 23 May 2024 01:48:06 +0200
Subject: [PATCH] [Clang] Fix __is_trivially_equality_comparable returning true
 with ineligebile defaulted overloads

---
 clang/docs/ReleaseNotes.rst|  3 ++
 clang/include/clang/AST/Type.h |  3 --
 clang/lib/AST/Type.cpp | 60 
 clang/lib/Sema/SemaExprCXX.cpp | 74 +-
 clang/test/SemaCXX/type-traits.cpp | 37 +++
 5 files changed, 113 insertions(+), 64 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 22b4dc172c840..fabc0fdbcc551 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -640,6 +640,9 @@ Bug Fixes in This Version
 - Correctly reject declarations where a statement is required in C.
   Fixes #GH92775
 
+- ``__is_trivially_equality_comparable`` no longer returns true for types which
+  have a constrained defaulted comparison operator (#GH89293).
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 263b632df23ce..53d2ae2905a56 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1126,9 +1126,6 @@ class QualType {
   /// Return true if this is a trivially relocatable type.
   bool isTriviallyRelocatableType(const ASTContext ) const;
 
-  /// Return true if this is a trivially equality comparable type.
-  bool isTriviallyEqualityComparableType(const ASTContext ) const;
-
   /// Returns true if it is a class and it might be dynamic.
   bool mayBeDynamicClass() const;
 
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 2097b29b7e0b6..6121612687f55 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -2778,66 +2778,6 @@ bool QualType::isTriviallyRelocatableType(const 
ASTContext ) const {
   }
 }
 
-static bool
-HasNonDeletedDefaultedEqualityComparison(const CXXRecordDecl *Decl) {
-  if (Decl->isUnion())
-return false;
-  if (Decl->isLambda())
-return Decl->isCapturelessLambda();
-
-  auto IsDefaultedOperatorEqualEqual = [&](const FunctionDecl *Function) {
-return Function->getOverloadedOperator() ==
-   OverloadedOperatorKind::OO_EqualEqual &&
-   Function->isDefaulted() && Function->getNumParams() > 0 &&
-   (Function->getParamDecl(0)->getType()->isReferenceType() ||
-Decl->isTriviallyCopyable());
-  };
-
-  if (llvm::none_of(Decl->methods(), IsDefaultedOperatorEqualEqual) &&
-  llvm::none_of(Decl->friends(), [&](const FriendDecl *Friend) {
-if (NamedDecl *ND = Friend->getFriendDecl()) {
-  return ND->isFunctionOrFunctionTemplate() &&
- IsDefaultedOperatorEqualEqual(ND->getAsFunction());
-}
-return false;
-  }))
-return false;
-
-  return llvm::all_of(Decl->bases(),
-  [](const CXXBaseSpecifier ) {
-if (const auto *RD = 
BS.getType()->getAsCXXRecordDecl())
-  return HasNonDeletedDefaultedEqualityComparison(RD);
-return true;
-  }) &&
- llvm::all_of(Decl->fields(), [](const FieldDecl *FD) {
-   auto Type = FD->getType();
-   if (Type->isArrayType())
- Type = 
Type->getBaseElementTypeUnsafe()->getCanonicalTypeUnqualified();
-
-   if (Type->isReferenceType() || Type->isEnumeralType())
- return false;
-   if (const auto *RD = Type->getAsCXXRecordDecl())
- return HasNonDeletedDefaultedEqualityComparison(RD);
-   return true;
- });
-}
-
-bool QualType::isTriviallyEqualityComparableType(
-const ASTContext ) const {
-  QualType CanonicalType = getCanonicalType();
-  if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
-  CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
-return false;
-
-  if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
-if (!HasNonDeletedDefaultedEqualityComparison(RD))
-  return false;
-  }
-
-  return Context.hasUniqueObjectRepresentations(
-  CanonicalType, /*CheckIfTriviallyCopyable=*/false);
-}
-
 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext ) const {
   return !Context.getLangOpts().ObjCAutoRefCount &&
  Context.getLangOpts().ObjCWeak &&
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 4487c618862c5..d6be724d1cc2a 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5197,6 +5197,78 @@ static bool HasNoThrowOperator(const RecordType *RT, 
OverloadedOperatorKind Op,
   return false;
 }
 
+static bool
+HasNonDeletedDefaultedEqualityComparison(Sema , const CXXRecordDecl *Decl) {
+  if 

[clang] [clang][analyzer] Move unix.BlockInCriticalSection out of alpha (PR #93815)

2024-06-01 Thread Balazs Benics via cfe-commits


@@ -1235,6 +1235,49 @@ Check calls to various UNIX/Posix functions: ``open, 
pthread_once, calloc, mallo
 .. literalinclude:: checkers/unix_api_example.c
 :language: c
 
+.. _unix-BlockInCriticalSection:
+
+unix.BlockInCriticalSection (C)
+"
+Check for calls to blocking functions inside a critical section.
+Blocking functions detected by this checker: ``sleep, getc, fgets, read, 
recv``.
+Critical section handling functions modelled by this checker: ``lock, unlock, 
pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock, mtx_lock, 
mtx_timedlock, mtx_trylock, mtx_unlock, lock_guard, unique_lock``.

steakhal wrote:

This line is probably already too long. Let's break it.

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


[clang] [clang][analyzer] Move unix.BlockInCriticalSection out of alpha (PR #93815)

2024-06-01 Thread Balazs Benics via cfe-commits


@@ -1235,6 +1235,49 @@ Check calls to various UNIX/Posix functions: ``open, 
pthread_once, calloc, mallo
 .. literalinclude:: checkers/unix_api_example.c
 :language: c
 
+.. _unix-BlockInCriticalSection:
+
+unix.BlockInCriticalSection (C)
+"
+Check for calls to blocking functions inside a critical section.
+Blocking functions detected by this checker: ``sleep, getc, fgets, read, 
recv``.
+Critical section handling functions modelled by this checker: ``lock, unlock, 
pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock, mtx_lock, 
mtx_timedlock, mtx_trylock, mtx_unlock, lock_guard, unique_lock``.
+
+.. code-block:: c
+
+ void pthread_lock_example(pthread_mutex_t *m) {
+   pthread_mutex_lock(m); // note: entering critical section here
+   sleep(10); // warn: Call to blocking function 'sleep' inside of critical 
section
+   pthread_mutex_unlock(m);
+ }
+
+.. code-block:: cpp
+
+ void overlapping_critical_sections(mtx_t *m1, std::mutex ) {
+   std::lock_guard lg{m2}; // note: entering critical section here
+   mtx_lock(m1); // note: entering critical section here
+   sleep(10); // warn: Call to blocking function 'sleep' inside of critical 
section
+   mtx_unlock(m1);
+   sleep(10); // warn: Call to blocking function 'sleep' inside of critical 
section
+ // still inside of the critical section of the std::lock_guard

steakhal wrote:

```suggestion
  // still inside of the critical section of the std::lock_guard
```

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


[clang] [clang][analyzer] Move unix.BlockInCriticalSection out of alpha (PR #93815)

2024-06-01 Thread Balazs Benics via cfe-commits


@@ -1235,6 +1235,49 @@ Check calls to various UNIX/Posix functions: ``open, 
pthread_once, calloc, mallo
 .. literalinclude:: checkers/unix_api_example.c
 :language: c
 
+.. _unix-BlockInCriticalSection:
+
+unix.BlockInCriticalSection (C)
+"
+Check for calls to blocking functions inside a critical section.
+Blocking functions detected by this checker: ``sleep, getc, fgets, read, 
recv``.
+Critical section handling functions modelled by this checker: ``lock, unlock, 
pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock, mtx_lock, 
mtx_timedlock, mtx_trylock, mtx_unlock, lock_guard, unique_lock``.

steakhal wrote:

```suggestion
Critical section handling functions modeled by this checker:
``lock, unlock, pthread_mutex_lock, pthread_mutex_trylock, 
pthread_mutex_unlock, mtx_lock, mtx_timedlock, mtx_trylock, mtx_unlock, 
lock_guard, unique_lock``.
```

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


[clang] [clang][analyzer] Move unix.BlockInCriticalSection out of alpha (PR #93815)

2024-06-01 Thread Balazs Benics via cfe-commits

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

LGTM. Minor typos/doc suggestions.

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


[clang] [clang][analyzer] Move unix.BlockInCriticalSection out of alpha (PR #93815)

2024-06-01 Thread Balazs Benics via cfe-commits


@@ -1235,6 +1235,49 @@ Check calls to various UNIX/Posix functions: ``open, 
pthread_once, calloc, mallo
 .. literalinclude:: checkers/unix_api_example.c
 :language: c
 
+.. _unix-BlockInCriticalSection:
+
+unix.BlockInCriticalSection (C)
+"

steakhal wrote:

```suggestion
unix.BlockInCriticalSection (C, C++)

```

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


[clang] [clang][analyzer] Move unix.BlockInCriticalSection out of alpha (PR #93815)

2024-06-01 Thread Balazs Benics via cfe-commits

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


[clang] [clang-repl] Support wasm execution (PR #86402)

2024-06-01 Thread Anubhab Ghosh via cfe-commits

https://github.com/argentite updated 
https://github.com/llvm/llvm-project/pull/86402

>From 4434ceeef152b95998ebd0a3b09a56d105490c4d Mon Sep 17 00:00:00 2001
From: Anubhab Ghosh 
Date: Sat, 23 Mar 2024 15:13:57 +
Subject: [PATCH 1/3] [clang-repl] Support wasm execution.

This commit introduces support for running clang-repl and executing C++ code
interactively inside a Javascript engine using WebAssembly when built with
Emscripten. This is achieved by producing WASM "shared libraries" that can be
loaded by the Emscripten runtime using dlopen()

More discussion is available in https://reviews.llvm.org/D158140
---
 clang/lib/Interpreter/CMakeLists.txt  |   1 +
 clang/lib/Interpreter/IncrementalExecutor.cpp |   2 +
 clang/lib/Interpreter/IncrementalExecutor.h   |  11 +-
 clang/lib/Interpreter/Interpreter.cpp |  11 ++
 clang/lib/Interpreter/WASM.cpp| 107 ++
 clang/lib/Interpreter/WASM.h  |  33 ++
 6 files changed, 161 insertions(+), 4 deletions(-)
 create mode 100644 clang/lib/Interpreter/WASM.cpp
 create mode 100644 clang/lib/Interpreter/WASM.h

diff --git a/clang/lib/Interpreter/CMakeLists.txt 
b/clang/lib/Interpreter/CMakeLists.txt
index 9065f998f73c4..a8a287edf5b04 100644
--- a/clang/lib/Interpreter/CMakeLists.txt
+++ b/clang/lib/Interpreter/CMakeLists.txt
@@ -20,6 +20,7 @@ add_clang_library(clangInterpreter
   Interpreter.cpp
   InterpreterUtils.cpp
   Value.cpp
+  WASM.cpp
 
   DEPENDS
   intrinsics_gen
diff --git a/clang/lib/Interpreter/IncrementalExecutor.cpp 
b/clang/lib/Interpreter/IncrementalExecutor.cpp
index 6f036107c14a9..1824a5b4570a9 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.cpp
+++ b/clang/lib/Interpreter/IncrementalExecutor.cpp
@@ -36,6 +36,8 @@ LLVM_ATTRIBUTE_USED void linkComponents() {
 }
 
 namespace clang {
+IncrementalExecutor::IncrementalExecutor(llvm::orc::ThreadSafeContext )
+: TSCtx(TSC) {}
 
 llvm::Expected>
 IncrementalExecutor::createDefaultJITBuilder(
diff --git a/clang/lib/Interpreter/IncrementalExecutor.h 
b/clang/lib/Interpreter/IncrementalExecutor.h
index b4347209e14fe..7954cde36588b 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.h
+++ b/clang/lib/Interpreter/IncrementalExecutor.h
@@ -43,16 +43,19 @@ class IncrementalExecutor {
   llvm::DenseMap
   ResourceTrackers;
 
+protected:
+  IncrementalExecutor(llvm::orc::ThreadSafeContext );
+
 public:
   enum SymbolNameKind { IRName, LinkerName };
 
   IncrementalExecutor(llvm::orc::ThreadSafeContext ,
   llvm::orc::LLJITBuilder , llvm::Error );
-  ~IncrementalExecutor();
+  virtual ~IncrementalExecutor();
 
-  llvm::Error addModule(PartialTranslationUnit );
-  llvm::Error removeModule(PartialTranslationUnit );
-  llvm::Error runCtors() const;
+  virtual llvm::Error addModule(PartialTranslationUnit );
+  virtual llvm::Error removeModule(PartialTranslationUnit );
+  virtual llvm::Error runCtors() const;
   llvm::Error cleanUp();
   llvm::Expected
   getSymbolAddress(llvm::StringRef Name, SymbolNameKind NameKind) const;
diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index cf31456b6950a..7d572b20cd828 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -15,6 +15,7 @@
 #include "IncrementalExecutor.h"
 #include "IncrementalParser.h"
 #include "InterpreterUtils.h"
+#include "WASM.h"
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Mangle.h"
@@ -183,6 +184,12 @@ IncrementalCompilerBuilder::CreateCpp() {
   std::vector Argv;
   Argv.reserve(5 + 1 + UserArgs.size());
   Argv.push_back("-xc++");
+#ifdef __EMSCRIPTEN__
+  Argv.push_back("-target");
+  Argv.push_back("wasm32-unknown-emscripten");
+  Argv.push_back("-pie");
+  Argv.push_back("-shared");
+#endif
   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
 
   std::string TT = TargetTriple ? *TargetTriple : 
llvm::sys::getProcessTriple();
@@ -400,7 +407,11 @@ llvm::Error Interpreter::CreateExecutor() {
   if (!JB)
 return JB.takeError();
   llvm::Error Err = llvm::Error::success();
+#ifdef __EMSCRIPTEN__
+  auto Executor = std::make_unique(*TSCtx, **JB, Err);
+#else
   auto Executor = std::make_unique(*TSCtx, **JB, Err);
+#endif
   if (!Err)
 IncrExecutor = std::move(Executor);
 
diff --git a/clang/lib/Interpreter/WASM.cpp b/clang/lib/Interpreter/WASM.cpp
new file mode 100644
index 0..d21d0ada1eafa
--- /dev/null
+++ b/clang/lib/Interpreter/WASM.cpp
@@ -0,0 +1,107 @@
+//===- WASM.cpp - WASM Interpreter --*- C++ 
-*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file implements interpreter support for code execution in WebAssembly.
+//

[clang] [clang][analyzer] Move unix.BlockInCriticalSection out of alpha (PR #93815)

2024-06-01 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer][NFC] Fix comparison to True/False (PR #94038)

2024-06-01 Thread via cfe-commits

github-actions[bot] wrote:



@e-kwsm Congratulations on having your first Pull Request (PR) merged into the 
LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested
by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with 
a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as
the builds can include changes from many authors. It is not uncommon for your
change to be included in a build that fails due to someone else's changes, or
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself.
This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang] [analyzer][NFC] Fix comparison to True/False (PR #94038)

2024-06-01 Thread Balazs Benics via cfe-commits

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


[clang] daaaf4e - [analyzer][NFC] Fix comparison to True/False (#94038)

2024-06-01 Thread via cfe-commits

Author: Eisuke Kawashima
Date: 2024-06-01T09:12:35+02:00
New Revision: daaaf4e9009edf38dfc3d01d3c30de0827ffd1b5

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

LOG: [analyzer][NFC] Fix comparison to True/False (#94038)

from PEP8
(https://peps.python.org/pep-0008/#programming-recommendations):

> Comparisons to singletons like None should always be done with is or
is not, never the equality operators.

Co-authored-by: Eisuke Kawashima 

Added: 


Modified: 
clang/tools/scan-build/bin/set-xcode-analyzer
clang/utils/check_cfc/check_cfc.py

Removed: 




diff  --git a/clang/tools/scan-build/bin/set-xcode-analyzer 
b/clang/tools/scan-build/bin/set-xcode-analyzer
index f8c3f775ef7de..8e4a5794594a6 100755
--- a/clang/tools/scan-build/bin/set-xcode-analyzer
+++ b/clang/tools/scan-build/bin/set-xcode-analyzer
@@ -107,7 +107,7 @@ def main():
 foundSpec = True
 ModifySpec(x, isBuiltinAnalyzer, path)
 
-  if foundSpec == False:
+  if not foundSpec:
   print "(-) No compiler configuration file was found.  Xcode's analyzer 
has not been updated."
 
 if __name__ == '__main__':

diff  --git a/clang/utils/check_cfc/check_cfc.py 
b/clang/utils/check_cfc/check_cfc.py
index 27d732d91030c..8d42ec532bbb7 100755
--- a/clang/utils/check_cfc/check_cfc.py
+++ b/clang/utils/check_cfc/check_cfc.py
@@ -156,7 +156,7 @@ def get_output_file(args):
 elif arg.startswith("-o"):
 # Specified conjoined with -o
 return arg[2:]
-assert grabnext == False
+assert not grabnext
 
 return None
 
@@ -182,7 +182,7 @@ def replace_output_file(args, new_name):
 if replaceidx is None:
 raise Exception
 replacement = new_name
-if attached == True:
+if attached:
 replacement = "-o" + new_name
 args[replaceidx] = replacement
 return args



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


[clang] [analyzer][NFC] Fix comparison to True/False (PR #94038)

2024-06-01 Thread Balazs Benics via cfe-commits

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


[clang] fix(clang/**.py): fix comparison to True/False (PR #94038)

2024-06-01 Thread Balazs Benics via cfe-commits

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

I'm not sure if llvm follows PEP8, but the change looks good regardless.

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


[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #94100)

2024-06-01 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 9261ab708e37c2d6499ac063045f816d25a5919c 
4841c8752abab8c5e05a97d8826cdca376f4ab0c -- 
clang/test/CodeGenCXX/debug-info-ptr-to-ptr.cpp 
clang/lib/CodeGen/CGDebugInfo.cpp clang/lib/CodeGen/CGDebugInfo.h 
clang/lib/CodeGen/CGExprScalar.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 6c332b2ae9c..2ed7dbe2854 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5706,9 +5706,9 @@ void CGDebugInfo::EmitPseudoVariable(CGBuilderTy ,
   // Emit debug info for materialized Value.
   unsigned Line = Builder.getCurrentDebugLocation().getLine();
   unsigned Column = Builder.getCurrentDebugLocation().getCol();
-  llvm::DILocalVariable *D = DBuilder.createAutoVariable(
-  LexicalBlockStack.back(), "", nullptr, 0, Type, false,
-  llvm::DINode::FlagArtificial);
+  llvm::DILocalVariable *D =
+  DBuilder.createAutoVariable(LexicalBlockStack.back(), "", nullptr, 0,
+  Type, false, llvm::DINode::FlagArtificial);
   llvm::DILocation *DIL =
   llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
 LexicalBlockStack.back(), CurInlinedAt);

``




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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-06-01 Thread via cfe-commits

https://github.com/trcrsired updated 
https://github.com/llvm/llvm-project/pull/79667

>From ba9b31041671099434570c6d3301782bc41c2c4a Mon Sep 17 00:00:00 2001
From: cqwrteur <100043421+trcrsi...@users.noreply.github.com>
Date: Sat, 1 Jun 2024 02:55:50 -0400
Subject: [PATCH] [libunwind][libcxx][libcxxabi] Fix Exception Handling build
 for wasm

The wasm unwind build appears to be dysfunctional, likely because the author 
has only supplied a customized LLVM build on request, rather than a fully 
functional patch.

This patch fixes the build

Apply formatting patch proposed by github bot

use "" to prevent CMAKE_SYSTEM_PROCESSOR not defined

[libunwind] logAPI functions should also be built

[libcxxabi] Fix function signatures for wasm

wasm does not define the function signatures correctly for cxxabi
Fix them

Fix formatting issues for libcxxabi's wasm eh change

Merge remote-tracking branch 'parent/main' into wasmlibunwindfix

remove unwanted changes in unwind-wasm.c

Make Unwind-wasm.c compile correctly without workaround in
CMakeLists.txt

using __wasm__ macro to guard against all wasm eh build

fix UnwindLevel.c's formatting issue

ISO C requires a translation unit to contain at least one declaration 
[-Werror,-Wempty-translation-unit]

compiler-rt does not define CMP_RESULT correct on wasm64
Fixed

Merge code
---
 compiler-rt/lib/builtins/fp_compare_impl.inc |   2 +-
 libcxx/include/__exception/exception_ptr.h   |  21 +-
 libcxxabi/include/cxxabi.h   | 179 ++---
 libcxxabi/src/cxa_exception.cpp  | 712 ---
 libcxxabi/src/cxa_exception.h|   7 +-
 libunwind/include/libunwind.h|   2 +
 libunwind/src/Unwind-wasm.c  |  13 +-
 libunwind/src/UnwindRegistersRestore.S   |   3 +-
 libunwind/src/UnwindRegistersSave.S  |   3 +
 libunwind/src/assembly.h |   2 +
 libunwind/src/cet_unwind.h   |   3 +
 libunwind/src/config.h   |  15 +-
 libunwind/src/libunwind.cpp  |   2 +
 libunwind/src/libunwind_ext.h|   2 +
 14 files changed, 423 insertions(+), 543 deletions(-)

diff --git a/compiler-rt/lib/builtins/fp_compare_impl.inc 
b/compiler-rt/lib/builtins/fp_compare_impl.inc
index a9a4f6fbf5dfe..83bdea46a45da 100644
--- a/compiler-rt/lib/builtins/fp_compare_impl.inc
+++ b/compiler-rt/lib/builtins/fp_compare_impl.inc
@@ -12,7 +12,7 @@
 // functions. We need to ensure that the return value is sign-extended in the
 // same way as GCC expects (since otherwise GCC-generated __builtin_isinf
 // returns true for finite 128-bit floating-point numbers).
-#ifdef __aarch64__
+#if defined(__aarch64__) || defined(__wasm__)
 // AArch64 GCC overrides libgcc_cmp_return to use int instead of long.
 typedef int CMP_RESULT;
 #elif __SIZEOF_POINTER__ == 8 && __SIZEOF_LONG__ == 4
diff --git a/libcxx/include/__exception/exception_ptr.h 
b/libcxx/include/__exception/exception_ptr.h
index 0a8337fa39de3..01f340a587ec3 100644
--- a/libcxx/include/__exception/exception_ptr.h
+++ b/libcxx/include/__exception/exception_ptr.h
@@ -29,22 +29,21 @@
 
 namespace __cxxabiv1 {
 
+#if defined(__wasm__)
+typedef void* (*__libcpp_exception_destructor_func)(void*);
+#elif defined(_WIN32)
+typedef void(__thiscall* __libcpp_exception_destructor_func)(void*);
+#else
+typedef void (*__libcpp_exception_destructor_func)(void*);
+#endif
+
 extern "C" {
 _LIBCPP_OVERRIDABLE_FUNC_VIS void* __cxa_allocate_exception(size_t) throw();
 _LIBCPP_OVERRIDABLE_FUNC_VIS void __cxa_free_exception(void*) throw();
 
 struct __cxa_exception;
-_LIBCPP_OVERRIDABLE_FUNC_VIS __cxa_exception* __cxa_init_primary_exception(
-void*,
-std::type_info*,
-#if defined(_WIN32)
-void(__thiscall*)(void*)) throw();
-#elif defined(__wasm__)
-// In Wasm, a destructor returns its argument
-void* (*)(void*)) throw();
-#else
-void (*)(void*)) throw();
-#endif
+_LIBCPP_OVERRIDABLE_FUNC_VIS __cxa_exception*
+__cxa_init_primary_exception(void*, std::type_info*, 
__libcpp_exception_destructor_func) throw();
 }
 
 } // namespace __cxxabiv1
diff --git a/libcxxabi/include/cxxabi.h b/libcxxabi/include/cxxabi.h
index 0e3969084e04f..4162fd7ec2ba7 100644
--- a/libcxxabi/include/cxxabi.h
+++ b/libcxxabi/include/cxxabi.h
@@ -20,62 +20,51 @@
 #include <__cxxabi_config.h>
 
 #define _LIBCPPABI_VERSION 15000
-#define _LIBCXXABI_NORETURN  __attribute__((noreturn))
+#define _LIBCXXABI_NORETURN __attribute__((noreturn))
 #define _LIBCXXABI_ALWAYS_COLD __attribute__((cold))
 
 #ifdef __cplusplus
 
 namespace std {
-#if defined(_WIN32)
+#  if defined(_WIN32)
 class _LIBCXXABI_TYPE_VIS type_info; // forward declaration
-#else
+#  else
 class type_info; // forward declaration
-#endif
-}
-
+#  endif
+} // namespace std
 
 // runtime routines use C calling conventions, but are in __cxxabiv1 namespace
 namespace __cxxabiv1 {
 
 struct __cxa_exception;
+#  if defined(__wasm__)
+typedef 

[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #94100)

2024-06-01 Thread David Blaikie via cfe-commits

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

Looks worth a shot. Please commit this at a time where you can respond to bot 
fail-mail for a while after the commit.

And ensure the commit message has most/all of the details of the original 
commit, plus the original commit and revert hashes, and a little detail on the 
updates to address the reason for the revert (adding the explicit triple to the 
test).

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


[clang] [llvm] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #94100)

2024-06-01 Thread William Junda Huang via cfe-commits

https://github.com/huangjd created 
https://github.com/llvm/llvm-project/pull/94100

This is another attempt to land #81545, which was reverted. 

Fixed test case so that it is consistent on all platforms. 

>From f2c82758e1cba7773e41d941d2812c829c339675 Mon Sep 17 00:00:00 2001
From: William Huang 
Date: Mon, 12 Feb 2024 02:27:13 -0500
Subject: [PATCH 01/14] Add option to generate additional info for expression
 containing pointer of pointers.

Such expression does correspond to a variable in the source code thus
does not have a debug location. However the user may want to collect
sampling counter for memory accesses to analyze usage frequency of class
members. By enabling -fdebug_info_for_pointer_type a psuedo variable and
its debug info is generated in place whenever there's an intermediate
expression with pointer access.
---
 clang/include/clang/Basic/DebugOptions.def |  4 ++
 clang/include/clang/Driver/Options.td  |  4 ++
 clang/lib/CodeGen/CGDebugInfo.cpp  | 16 +
 clang/lib/CodeGen/CGDebugInfo.h|  6 ++
 clang/lib/CodeGen/CGDecl.cpp   |  4 ++
 clang/lib/CodeGen/CGExpr.cpp   | 79 ++
 clang/lib/CodeGen/CodeGenFunction.h|  5 ++
 clang/lib/Driver/ToolChains/Clang.cpp  |  3 +
 8 files changed, 121 insertions(+)

diff --git a/clang/include/clang/Basic/DebugOptions.def 
b/clang/include/clang/Basic/DebugOptions.def
index 7cd3edf08a17e..6dd09f4684207 100644
--- a/clang/include/clang/Basic/DebugOptions.def
+++ b/clang/include/clang/Basic/DebugOptions.def
@@ -129,6 +129,10 @@ DEBUGOPT(CodeViewCommandLine, 1, 0)
 /// Whether emit extra debug info for sample pgo profile collection.
 DEBUGOPT(DebugInfoForProfiling, 1, 0)
 
+/// Whether to generate pseudo variables and their debug info for intermediate
+/// pointer accesses.
+DEBUGOPT(DebugInfoForPointerType, 1, 0)
+
 /// Whether to emit .debug_gnu_pubnames section instead of .debug_pubnames.
 DEBUGOPT(DebugNameTable, 2, 0)
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 7f4fa33748fac..96b22d3f7640d 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1675,6 +1675,10 @@ defm debug_info_for_profiling : 
BoolFOption<"debug-info-for-profiling",
   PosFlag,
   NegFlag>;
+def fdebug_info_for_pointer_type : Flag<["-"], "fdebug-info-for-pointer-type">,
+  Group, Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Generate pseudo variables and their debug info for intermediate 
pointer accesses">,
+  MarshallingInfoFlag>;
 def fprofile_instr_generate : Flag<["-"], "fprofile-instr-generate">,
 Group, Visibility<[ClangOption, CLOption]>,
 HelpText<"Generate instrumented code to collect execution counts into 
default.profraw file (overridden by '=' form of option or LLVM_PROFILE_FILE env 
var)">;
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 0f3f684d61dc9..6ce40da22dc97 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5636,6 +5636,22 @@ void 
CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
   Var->addDebugInfo(GVE);
 }
 
+void CGDebugInfo::EmitPseudoVariable(llvm::AllocaInst *Alloca, QualType Ty,
+ SourceLocation Loc) {
+  llvm::DIFile *Unit = getOrCreateFile(Loc);
+  unsigned Line = getLineNumber(Loc);
+  unsigned Column = getColumnNumber(Loc);
+  llvm::DILocalVariable *D = DBuilder.createAutoVariable(
+  LexicalBlockStack.back(), Alloca->getName(), getOrCreateFile(Loc), Line,
+  getOrCreateType(Ty, Unit));
+  llvm::DILocation *DIL =
+  llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
+LexicalBlockStack.back(), CurInlinedAt);
+  SmallVector Expr;
+  DBuilder.insertDeclare(Alloca, D, DBuilder.createExpression(Expr), DIL,
+ Alloca->getParent());
+}
+
 void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
   const GlobalDecl GD) {
 
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 7b60e94555d06..a2c484f50b2bc 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -529,6 +529,12 @@ class CGDebugInfo {
   /// Emit information about an external variable.
   void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
 
+  /// Emit debug information for a pseudo variable assigned to the value of an
+  /// intermediate expression, so that a performance counter can track the 
usage
+  /// of a specific expression of interest.
+  void EmitPseudoVariable(llvm::AllocaInst *Alloca, QualType Ty,
+  SourceLocation Loc);
+
   /// Emit information about global variable alias.
   void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl);
 
diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index bbe14ef4c1724..5f7b252917900 

[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-06-01 Thread via cfe-commits

https://github.com/trcrsired updated 
https://github.com/llvm/llvm-project/pull/79667

>From d73a87b47a549aeac7f4ea519037107a8f798df6 Mon Sep 17 00:00:00 2001
From: trcrsired 
Date: Fri, 26 Jan 2024 18:44:41 -0500
Subject: [PATCH] [libunwind][libcxx][libcxxabi] Fix Exception Handling build
 for wasm

The wasm unwind build appears to be dysfunctional, likely because the author 
has only supplied a customized LLVM build on request, rather than a fully 
functional patch.

This patch fixes the build

Apply formatting patch proposed by github bot

use "" to prevent CMAKE_SYSTEM_PROCESSOR not defined

[libunwind] logAPI functions should also be built

[libcxxabi] Fix function signatures for wasm

wasm does not define the function signatures correctly for cxxabi
Fix them

Fix formatting issues for libcxxabi's wasm eh change

Merge remote-tracking branch 'parent/main' into wasmlibunwindfix

remove unwanted changes in unwind-wasm.c

Make Unwind-wasm.c compile correctly without workaround in
CMakeLists.txt

using __wasm__ macro to guard against all wasm eh build

fix UnwindLevel.c's formatting issue

ISO C requires a translation unit to contain at least one declaration 
[-Werror,-Wempty-translation-unit]

compiler-rt does not define CMP_RESULT correct on wasm64
Fixed
---
 compiler-rt/lib/builtins/fp_compare_impl.inc |   2 +-
 libcxx/include/__exception/exception_ptr.h   |  18 +-
 libcxxabi/include/cxxabi.h   | 175 ++---
 libcxxabi/src/cxa_exception.cpp  | 707 ---
 libcxxabi/src/cxa_exception.h|   7 +-
 libunwind/include/__libunwind_config.h   |   1 +
 libunwind/include/libunwind.h|   2 +
 libunwind/src/Unwind-wasm.c  |  13 +-
 libunwind/src/UnwindLevel1.c |   3 +-
 libunwind/src/UnwindRegistersRestore.S   |   3 +-
 libunwind/src/UnwindRegistersSave.S  |   3 +
 libunwind/src/assembly.h |   2 +
 libunwind/src/cet_unwind.h   |   3 +
 libunwind/src/config.h   |  15 +-
 libunwind/src/libunwind.cpp  |   2 +
 libunwind/src/libunwind_ext.h|   2 +
 16 files changed, 426 insertions(+), 532 deletions(-)

diff --git a/compiler-rt/lib/builtins/fp_compare_impl.inc 
b/compiler-rt/lib/builtins/fp_compare_impl.inc
index a9a4f6fbf5dfe..83bdea46a45da 100644
--- a/compiler-rt/lib/builtins/fp_compare_impl.inc
+++ b/compiler-rt/lib/builtins/fp_compare_impl.inc
@@ -12,7 +12,7 @@
 // functions. We need to ensure that the return value is sign-extended in the
 // same way as GCC expects (since otherwise GCC-generated __builtin_isinf
 // returns true for finite 128-bit floating-point numbers).
-#ifdef __aarch64__
+#if defined(__aarch64__) || defined(__wasm__)
 // AArch64 GCC overrides libgcc_cmp_return to use int instead of long.
 typedef int CMP_RESULT;
 #elif __SIZEOF_POINTER__ == 8 && __SIZEOF_LONG__ == 4
diff --git a/libcxx/include/__exception/exception_ptr.h 
b/libcxx/include/__exception/exception_ptr.h
index c9027de9238cd..3324f832b7160 100644
--- a/libcxx/include/__exception/exception_ptr.h
+++ b/libcxx/include/__exception/exception_ptr.h
@@ -30,19 +30,21 @@
 
 namespace __cxxabiv1 {
 
+#if defined(__wasm__)
+typedef void* (*__libcpp_exception_destructor_func)(void*);
+#elif defined(_WIN32)
+typedef void(__thiscall* __libcpp_exception_destructor_func)(void*);
+#else
+typedef void (*__libcpp_exception_destructor_func)(void*);
+#endif
+
 extern "C" {
 _LIBCPP_OVERRIDABLE_FUNC_VIS void* __cxa_allocate_exception(size_t) throw();
 _LIBCPP_OVERRIDABLE_FUNC_VIS void __cxa_free_exception(void*) throw();
 
 struct __cxa_exception;
-_LIBCPP_OVERRIDABLE_FUNC_VIS __cxa_exception* __cxa_init_primary_exception(
-void*,
-std::type_info*,
-void(
-#if defined(_WIN32)
-__thiscall
-#endif
-*)(void*)) throw();
+_LIBCPP_OVERRIDABLE_FUNC_VIS __cxa_exception*
+__cxa_init_primary_exception(void*, std::type_info*, 
__libcpp_exception_destructor_func) throw();
 }
 
 } // namespace __cxxabiv1
diff --git a/libcxxabi/include/cxxabi.h b/libcxxabi/include/cxxabi.h
index d0701181751c5..4162fd7ec2ba7 100644
--- a/libcxxabi/include/cxxabi.h
+++ b/libcxxabi/include/cxxabi.h
@@ -20,58 +20,51 @@
 #include <__cxxabi_config.h>
 
 #define _LIBCPPABI_VERSION 15000
-#define _LIBCXXABI_NORETURN  __attribute__((noreturn))
+#define _LIBCXXABI_NORETURN __attribute__((noreturn))
 #define _LIBCXXABI_ALWAYS_COLD __attribute__((cold))
 
 #ifdef __cplusplus
 
 namespace std {
-#if defined(_WIN32)
+#  if defined(_WIN32)
 class _LIBCXXABI_TYPE_VIS type_info; // forward declaration
-#else
+#  else
 class type_info; // forward declaration
-#endif
-}
-
+#  endif
+} // namespace std
 
 // runtime routines use C calling conventions, but are in __cxxabiv1 namespace
 namespace __cxxabiv1 {
 
 struct __cxa_exception;
+#  if defined(__wasm__)
+typedef void* (*__libcxxabi_exception_destructor_func)(void*);
+#  else
+typedef 

[clang] [amdgpu] Pass variadic arguments without splitting (PR #94083)

2024-06-01 Thread Matt Arsenault via cfe-commits


@@ -197,12 +202,20 @@ ABIArgInfo 
AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
 }
 
-ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
+ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, bool Variadic,
unsigned ) const {
   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
 
   Ty = useFirstFieldIfTransparentUnion(Ty);
 
+  if (Variadic) {

arsenm wrote:

The bigger concern is using giant aggregate types is not great IR, and not all 
that well supported. a 65k element array will crash in SelectionDAG for example 

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


[clang] [amdgpu] Pass variadic arguments without splitting (PR #94083)

2024-06-01 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,293 @@
+// REQUIRES: amdgpu-registered-target
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --function-signature
+// RUN: %clang_cc1 -cc1 -std=c23 -triple amdgcn-amd-amdhsa -emit-llvm -O1 %s 
-o - | FileCheck %s
+
+void sink_0(...);
+void sink_1(int, ...);
+void sink_2(double, int, ...);
+
+// Simple scalar values
+
+// CHECK-LABEL: define {{[^@]+}}@zero_varargs
+// CHECK-SAME: (i32 noundef [[F0:%.*]], double noundef [[F1:%.*]]) 
local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void (...) @sink_0() #[[ATTR2:[0-9]+]]
+// CHECK-NEXT:tail call void (i32, ...) @sink_1(i32 noundef [[F0]]) 
#[[ATTR2]]
+// CHECK-NEXT:tail call void (double, i32, ...) @sink_2(double noundef 
[[F1]], i32 noundef [[F0]]) #[[ATTR2]]
+// CHECK-NEXT:ret void
+//
+void zero_varargs(int f0, double f1)
+{
+  sink_0();
+  sink_1(f0);
+  sink_2(f1, f0);
+}
+
+// CHECK-LABEL: define {{[^@]+}}@one_i32
+// CHECK-SAME: (i32 noundef [[F0:%.*]], double noundef [[F1:%.*]], i32 noundef 
[[V0:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void (...) @sink_0(i32 noundef [[V0]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (i32, ...) @sink_1(i32 noundef [[F0]], i32 
noundef [[V0]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (double, i32, ...) @sink_2(double noundef 
[[F1]], i32 noundef [[F0]], i32 noundef [[V0]]) #[[ATTR2]]
+// CHECK-NEXT:ret void
+//
+void one_i32(int f0, double f1, int v0)
+{
+  sink_0(v0);
+  sink_1(f0, v0);
+  sink_2(f1, f0, v0);
+}
+
+// CHECK-LABEL: define {{[^@]+}}@one_ptr
+// CHECK-SAME: (i32 noundef [[F0:%.*]], double noundef [[F1:%.*]], ptr noundef 
[[V0:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void (...) @sink_0(ptr noundef [[V0]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (i32, ...) @sink_1(i32 noundef [[F0]], ptr 
noundef [[V0]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (double, i32, ...) @sink_2(double noundef 
[[F1]], i32 noundef [[F0]], ptr noundef [[V0]]) #[[ATTR2]]
+// CHECK-NEXT:ret void
+//
+void one_ptr(int f0, double f1, void* v0)
+{
+  sink_0(v0);
+  sink_1(f0, v0);
+  sink_2(f1, f0, v0);
+}
+
+// CHECK-LABEL: define {{[^@]+}}@one_f64
+// CHECK-SAME: (i32 noundef [[F0:%.*]], double noundef [[F1:%.*]], double 
noundef [[V0:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void (...) @sink_0(double noundef [[V0]]) 
#[[ATTR2]]
+// CHECK-NEXT:tail call void (i32, ...) @sink_1(i32 noundef [[F0]], double 
noundef [[V0]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (double, i32, ...) @sink_2(double noundef 
[[F1]], i32 noundef [[F0]], double noundef [[V0]]) #[[ATTR2]]
+// CHECK-NEXT:ret void
+//
+void one_f64(int f0, double f1, double v0)
+{
+  sink_0(v0);
+  sink_1(f0, v0);
+  sink_2(f1, f0, v0);
+}
+
+
+// C has various type promotion rules for variadics
+
+// CHECK-LABEL: define {{[^@]+}}@one_i8
+// CHECK-SAME: (i32 noundef [[F0:%.*]], double noundef [[F1:%.*]], i8 noundef 
signext [[V0:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CONV:%.*]] = sext i8 [[V0]] to i32
+// CHECK-NEXT:tail call void (...) @sink_0(i32 noundef [[CONV]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (i32, ...) @sink_1(i32 noundef [[F0]], i32 
noundef [[CONV]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (double, i32, ...) @sink_2(double noundef 
[[F1]], i32 noundef [[F0]], i32 noundef [[CONV]]) #[[ATTR2]]
+// CHECK-NEXT:ret void
+//
+void one_i8(int f0, double f1, char v0)
+{
+  sink_0(v0);
+  sink_1(f0, v0);
+  sink_2(f1, f0, v0);
+}
+
+// CHECK-LABEL: define {{[^@]+}}@one_i16
+// CHECK-SAME: (i32 noundef [[F0:%.*]], double noundef [[F1:%.*]], i16 noundef 
signext [[V0:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CONV:%.*]] = sext i16 [[V0]] to i32
+// CHECK-NEXT:tail call void (...) @sink_0(i32 noundef [[CONV]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (i32, ...) @sink_1(i32 noundef [[F0]], i32 
noundef [[CONV]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (double, i32, ...) @sink_2(double noundef 
[[F1]], i32 noundef [[F0]], i32 noundef [[CONV]]) #[[ATTR2]]
+// CHECK-NEXT:ret void
+//
+void one_i16(int f0, double f1, short v0)
+{
+  sink_0(v0);
+  sink_1(f0, v0);
+  sink_2(f1, f0, v0);
+}
+
+// CHECK-LABEL: define {{[^@]+}}@one_f32
+// CHECK-SAME: (i32 noundef [[F0:%.*]], double noundef [[F1:%.*]], float 
noundef [[V0:%.*]]) local_unnamed_addr #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CONV:%.*]] = fpext float [[V0]] to double
+// CHECK-NEXT:tail call void (...) @sink_0(double noundef [[CONV]]) 
#[[ATTR2]]
+// CHECK-NEXT:tail call void (i32, ...) @sink_1(i32 noundef [[F0]], double 
noundef [[CONV]]) #[[ATTR2]]
+// CHECK-NEXT:tail call void (double, i32, ...) @sink_2(double noundef 
[[F1]], i32 noundef [[F0]], double noundef 

[clang] [amdgpu] Pass variadic arguments without splitting (PR #94083)

2024-06-01 Thread Matt Arsenault via cfe-commits


@@ -197,12 +202,20 @@ ABIArgInfo 
AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
 }
 
-ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
+ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, bool Variadic,
unsigned ) const {
   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
 
   Ty = useFirstFieldIfTransparentUnion(Ty);
 
+  if (Variadic) {

arsenm wrote:

Wouldn't we still want to follow the isAggregateTypeForABI rules? Large structs 
should still go through byref? 

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