[clang] [coroutines] Introduce [[clang::coro_disable_lifetimebound]] (PR #76818)

2024-01-05 Thread Chuanqi Xu via cfe-commits

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

I feel good with this. We can do other improvements in other patches.

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


[llvm] [clang] [clang-tools-extra] [AMDGPU][GFX12] Default component broadcast store (PR #76212)

2024-01-05 Thread Mariusz Sikora via cfe-commits

https://github.com/mariusz-sikora-at-amd updated 
https://github.com/llvm/llvm-project/pull/76212

>From 06117c6124e94953f62eff3b1b87d98146f9e25e Mon Sep 17 00:00:00 2001
From: Mateja Marjanovic 
Date: Wed, 10 May 2023 16:24:38 +0200
Subject: [PATCH 1/2] [AMDGPU][GFX12] Default component broadcast store

For image and buffer stores the default behaviour on GFX12
is to set all unset components to the value of the first component.
So if we pass only X component, it will be the same as , or XY same as XYXX.

This patch simplifies the passed vector of components in InstCombine
by removing components from the end that are equal to the first component.

For image stores it also trims DMask if necessary.
---
 .../AMDGPU/AMDGPUInstCombineIntrinsic.cpp | 36 +--
 .../amdgcn-simplify-image-buffer-stores.ll| 32 -
 2 files changed, 49 insertions(+), 19 deletions(-)

diff --git a/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp
index 2bb7b6bd0674a2..da2f862308558b 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUInstCombineIntrinsic.cpp
@@ -402,6 +402,35 @@ static APInt trimTrailingZerosInVector(InstCombiner &IC, 
Value *UseV,
   return DemandedElts;
 }
 
+// Trim elements of the end of the vector \p V, if they are
+// equal to the first element of the vector.
+static APInt defaultComponentBroadcast(Value *V) {
+  auto *VTy = cast(V->getType());
+  unsigned VWidth = VTy->getNumElements();
+  APInt DemandedElts = APInt::getAllOnes(VWidth);
+  Value *FirstComponent = findScalarElement(V, 0);
+
+  SmallVector ShuffleMask;
+  if (auto *SVI = dyn_cast(V))
+SVI->getShuffleMask(ShuffleMask);
+
+  for (int I = VWidth - 1; I > 0; --I) {
+if (ShuffleMask.empty()) {
+  auto *Elt = findScalarElement(V, I);
+  if (!Elt || (Elt != FirstComponent && !isa(Elt)))
+break;
+} else {
+  // Detect identical elements in the shufflevector result, even though
+  // findScalarElement cannot tell us what that element is.
+  if (ShuffleMask[I] != ShuffleMask[0] && ShuffleMask[I] != PoisonMaskElem)
+break;
+}
+DemandedElts.clearBit(I);
+  }
+
+  return DemandedElts;
+}
+
 static Value *simplifyAMDGCNMemoryIntrinsicDemanded(InstCombiner &IC,
 IntrinsicInst &II,
 APInt DemandedElts,
@@ -1140,8 +1169,11 @@ GCNTTIImpl::instCombineIntrinsic(InstCombiner &IC, 
IntrinsicInst &II) const {
 if (!isa(II.getArgOperand(0)->getType()))
   break;
 
-APInt DemandedElts =
-trimTrailingZerosInVector(IC, II.getArgOperand(0), &II);
+APInt DemandedElts;
+if (AMDGPU::isGFX12Plus(*ST))
+  DemandedElts = defaultComponentBroadcast(II.getArgOperand(0));
+else
+  DemandedElts = trimTrailingZerosInVector(IC, II.getArgOperand(0), &II);
 
 int DMaskIdx = getAMDGPUImageDMaskIntrinsic(II.getIntrinsicID()) ? 1 : -1;
 if (simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts, DMaskIdx,
diff --git 
a/llvm/test/Transforms/InstCombine/AMDGPU/amdgcn-simplify-image-buffer-stores.ll
 
b/llvm/test/Transforms/InstCombine/AMDGPU/amdgcn-simplify-image-buffer-stores.ll
index f2d904cce7f00d..95b1d09bbd6036 100644
--- 
a/llvm/test/Transforms/InstCombine/AMDGPU/amdgcn-simplify-image-buffer-stores.ll
+++ 
b/llvm/test/Transforms/InstCombine/AMDGPU/amdgcn-simplify-image-buffer-stores.ll
@@ -23,7 +23,8 @@ define amdgpu_ps void 
@image_store_1d_store_insert_zeros_at_end(<8 x i32> inreg
 ; GCN-NEXT:ret void
 ;
 ; GFX12-LABEL: @image_store_1d_store_insert_zeros_at_end(
-; GFX12-NEXT:call void @llvm.amdgcn.image.store.1d.f32.i32(float 
[[VDATA1:%.*]], i32 1, i32 [[S:%.*]], <8 x i32> [[RSRC:%.*]], i32 0, i32 0)
+; GFX12-NEXT:[[NEWVDATA4:%.*]] = insertelement <4 x float> , float 
[[VDATA1:%.*]], i64 0
+; GFX12-NEXT:call void @llvm.amdgcn.image.store.1d.v4f32.i32(<4 x float> 
[[NEWVDATA4]], i32 15, i32 [[S:%.*]], <8 x i32> [[RSRC:%.*]], i32 0, i32 0)
 ; GFX12-NEXT:ret void
 ;
   %newvdata1 = insertelement <4 x float> undef, float %vdata1, i32 0
@@ -63,9 +64,9 @@ define amdgpu_ps void 
@buffer_store_format_insert_zeros_at_end(<4 x i32> inreg %
 ; GCN-NEXT:ret void
 ;
 ; GFX12-LABEL: @buffer_store_format_insert_zeros_at_end(
-; GFX12-NEXT:[[TMP1:%.*]] = insertelement <2 x float> poison, float 
[[VDATA1:%.*]], i64 0
-; GFX12-NEXT:[[TMP2:%.*]] = shufflevector <2 x float> [[TMP1]], <2 x 
float> poison, <2 x i32> zeroinitializer
-; GFX12-NEXT:call void @llvm.amdgcn.buffer.store.format.v2f32(<2 x float> 
[[TMP2]], <4 x i32> [[A:%.*]], i32 [[B:%.*]], i32 0, i1 false, i1 false)
+; GFX12-NEXT:[[TMP1:%.*]] = insertelement <4 x float> , float [[VDATA1:%.*]], i64 0
+; GFX12-NEXT:[[NEWVDATA4:%.*]] = insertelement <4 x float> [[TMP1]], float 
[[VDATA1]], i64 1
+; GFX12-NEXT:call void @llvm.amdgcn.buffer.st

[llvm] [clang] [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs (PR #76777)

2024-01-05 Thread Wang Pengcheng via cfe-commits

wangpc-pp wrote:

> > As for your diffs, it seems that you only handle the 
> > `__riscv_save/restore_[2|1|0]`, which is incomplete. And the code is not 
> > different with non-rve cases?
> 
> Yes, I mostly copy-pasted the existing code and removed all of the code 
> dealing with registers not available on RV32E, so having only 
> `__riscv_save/restore_[2|1|0]` is intended I suppose because there are only 
> this many saved registers on RV32E. (There's probably a better way of doing 
> it, and it looks like I screwed up the RV64E part of the patch.)
> 
> If I remember correctly I think I did this because otherwise compiling 
> `compiler-rt` was not possible for RV32E and the compilation was spewing out 
> errors about the unavailable registers? But I need to check this again once I 
> finish porting this newest version of the patch to the most recent version of 
> Rust.

Oh, I see. My previous comment was wrong.
I just checked GCC implementation, we do need to handle RVE cases (but GCC 
still lacks of RV64E handling). LLVM hasn't handled this mainly because we 
haven't support RVE now, I think.
Can you fire a PR for these changes? I think we should support it in 
compiler-rt once we have merge this PR.

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


[llvm] [clang] [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs (PR #76777)

2024-01-05 Thread via cfe-commits

koute wrote:

> Can you fire a PR for these changes? I think we should support it in 
> compiler-rt once we have merged this PR.

Once this PR is merged, sure, I can make a PR.

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


[clang-tools-extra] [include-cleaner] Fix a race issue when editing multiple files. (PR #76960)

2024-01-05 Thread kadir çetinkaya via cfe-commits

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


[clang-tools-extra] [include-cleaner] Fix a race issue when editing multiple files. (PR #76960)

2024-01-05 Thread kadir çetinkaya via cfe-commits

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

thanks, lgtm!

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


[clang-tools-extra] [include-cleaner] Fix a race issue when editing multiple files. (PR #76960)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -215,11 +208,15 @@ class ActionFactory : public 
tooling::FrontendActionFactory {
   : HeaderFilter(HeaderFilter) {}
 
   std::unique_ptr create() override {
-return std::make_unique(HeaderFilter);
+return std::make_unique(HeaderFilter, EditFiles);
   }
 
+  const llvm::StringMap &getEditFiles() const { return EditFiles; 
}

kadircet wrote:

s/getEditFiles/editedFiles

https://github.com/llvm/llvm-project/pull/76960
___
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 false positive in cppcoreguidelines-missing-std-forward (PR #77056)

2024-01-05 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky created 
https://github.com/llvm/llvm-project/pull/77056

Parameter variable which is forwarded in lambda capture list or in body by 
reference is reasonable and current version of this check produces false 
positive on these cases. This patch try to fix the 
[issue](https://github.com/llvm/llvm-project/issues/68105)

>From 799efba6c8fd3acfc96db8b5b2185bcd93aecb84 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 3 Jan 2024 09:44:26 +0800
Subject: [PATCH] [clang-tidy] fix false positive in
 cppcoreguidelines-missing-std-forward

---
 .../MissingStdForwardCheck.cpp| 73 +--
 .../cppcoreguidelines/missing-std-forward.cpp | 26 ++-
 2 files changed, 89 insertions(+), 10 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
index 0b85ea19735eef..f0e021039f094d 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
@@ -53,18 +53,76 @@ AST_MATCHER(ParmVarDecl, isTemplateTypeParameter) {
  FuncTemplate->getTemplateParameters()->getDepth();
 }
 
+AST_MATCHER_P(NamedDecl, hasSameNameAsBoundNode, std::string, BindingID) {
+  const auto &Name = Node.getNameAsString();
+
+  return Builder->removeBindings(
+  [this, Name](const ast_matchers::internal::BoundNodesMap &Nodes) {
+const auto &BN = Nodes.getNode(this->BindingID);
+if (const auto *ND = BN.get()) {
+  if (!isa(ND))
+return true;
+  return ND->getName() != Name;
+}
+return true;
+  });
+}
+
+AST_MATCHER_P(LambdaCapture, hasCaptureKind, LambdaCaptureKind, Kind) {
+  return Node.getCaptureKind() == Kind;
+}
+
+AST_MATCHER_P(LambdaExpr, hasCaptureDefaultKind, LambdaCaptureDefault, Kind) {
+  return Node.getCaptureDefault() == Kind;
+}
+
+AST_MATCHER(LambdaExpr, hasCaptureToParm) {
+  auto RefToParm = capturesVar(varDecl(hasSameNameAsBoundNode("param")));
+  auto HasRefToParm = hasAnyCapture(RefToParm);
+
+  auto CaptureInRef =
+  allOf(hasCaptureDefaultKind(LambdaCaptureDefault::LCD_ByRef),
+unless(HasRefToParm));
+  auto CaptureInCopy = allOf(
+  hasCaptureDefaultKind(LambdaCaptureDefault::LCD_ByCopy), HasRefToParm);
+  auto CaptureByRefExplicit = hasAnyCapture(
+  allOf(hasCaptureKind(LambdaCaptureKind::LCK_ByRef), RefToParm));
+
+  auto Captured =
+  lambdaExpr(anyOf(CaptureInRef, CaptureInCopy, CaptureByRefExplicit));
+  if (Captured.matches(Node, Finder, Builder))
+return true;
+
+  return false;
+}
+
+AST_MATCHER(CallExpr, forCallableNode) {
+  auto InvokeInCaptureList = hasAnyCapture(capturesVar(
+  varDecl(hasInitializer(ignoringParenImpCasts(equalsNode(&Node));
+  auto InvokeInLambda = hasDeclContext(cxxRecordDecl(
+  isLambda(),
+  hasParent(lambdaExpr(forCallable(equalsBoundNode("func")),
+   anyOf(InvokeInCaptureList, hasCaptureToParm());
+
+  if (forCallable(anyOf(equalsBoundNode("func"), InvokeInLambda))
+  .matches(Node, Finder, Builder))
+return true;
+
+  return false;
+}
+
 } // namespace
 
 void MissingStdForwardCheck::registerMatchers(MatchFinder *Finder) {
   auto ToParam = hasAnyParameter(parmVarDecl(equalsBoundNode("param")));
 
-  auto ForwardCallMatcher = callExpr(
-  forCallable(equalsBoundNode("func")), argumentCountIs(1),
-  callee(unresolvedLookupExpr(hasAnyDeclaration(
-  namedDecl(hasUnderlyingDecl(hasName("::std::forward")),
-  hasArgument(0, declRefExpr(to(equalsBoundNode("param"))).bind("ref")),
-  unless(anyOf(hasAncestor(typeLoc()),
-   hasAncestor(expr(hasUnevaluatedContext());
+  auto ForwardCallMatcher =
+  callExpr(forCallableNode(), argumentCountIs(1),
+   callee(unresolvedLookupExpr(hasAnyDeclaration(
+   namedDecl(hasUnderlyingDecl(hasName("::std::forward")),
+   hasArgument(0, declRefExpr(to(equalsBoundNode("param",
+   unless(anyOf(hasAncestor(typeLoc()),
+hasAncestor(expr(hasUnevaluatedContext());
 
   Finder->addMatcher(
   parmVarDecl(parmVarDecl().bind("param"), isTemplateTypeParameter(),
@@ -76,6 +134,7 @@ void MissingStdForwardCheck::registerMatchers(MatchFinder 
*Finder) {
 }
 
 void MissingStdForwardCheck::check(const MatchFinder::MatchResult &Result) {
+
   const auto *Param = Result.Nodes.getNodeAs("param");
 
   if (!Param)
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
index b9720db272e406..55d6be743c22ab 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/m

[clang-tools-extra] [clang-tidy] fix false positive in cppcoreguidelines-missing-std-forward (PR #77056)

2024-01-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Qizhi Hu (jcsxky)


Changes

Parameter variable which is forwarded in lambda capture list or in body by 
reference is reasonable and current version of this check produces false 
positive on these cases. This patch try to fix the 
[issue](https://github.com/llvm/llvm-project/issues/68105)

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


2 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp 
(+66-7) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
 (+23-3) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
index 0b85ea19735eef..f0e021039f094d 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
@@ -53,18 +53,76 @@ AST_MATCHER(ParmVarDecl, isTemplateTypeParameter) {
  FuncTemplate->getTemplateParameters()->getDepth();
 }
 
+AST_MATCHER_P(NamedDecl, hasSameNameAsBoundNode, std::string, BindingID) {
+  const auto &Name = Node.getNameAsString();
+
+  return Builder->removeBindings(
+  [this, Name](const ast_matchers::internal::BoundNodesMap &Nodes) {
+const auto &BN = Nodes.getNode(this->BindingID);
+if (const auto *ND = BN.get()) {
+  if (!isa(ND))
+return true;
+  return ND->getName() != Name;
+}
+return true;
+  });
+}
+
+AST_MATCHER_P(LambdaCapture, hasCaptureKind, LambdaCaptureKind, Kind) {
+  return Node.getCaptureKind() == Kind;
+}
+
+AST_MATCHER_P(LambdaExpr, hasCaptureDefaultKind, LambdaCaptureDefault, Kind) {
+  return Node.getCaptureDefault() == Kind;
+}
+
+AST_MATCHER(LambdaExpr, hasCaptureToParm) {
+  auto RefToParm = capturesVar(varDecl(hasSameNameAsBoundNode("param")));
+  auto HasRefToParm = hasAnyCapture(RefToParm);
+
+  auto CaptureInRef =
+  allOf(hasCaptureDefaultKind(LambdaCaptureDefault::LCD_ByRef),
+unless(HasRefToParm));
+  auto CaptureInCopy = allOf(
+  hasCaptureDefaultKind(LambdaCaptureDefault::LCD_ByCopy), HasRefToParm);
+  auto CaptureByRefExplicit = hasAnyCapture(
+  allOf(hasCaptureKind(LambdaCaptureKind::LCK_ByRef), RefToParm));
+
+  auto Captured =
+  lambdaExpr(anyOf(CaptureInRef, CaptureInCopy, CaptureByRefExplicit));
+  if (Captured.matches(Node, Finder, Builder))
+return true;
+
+  return false;
+}
+
+AST_MATCHER(CallExpr, forCallableNode) {
+  auto InvokeInCaptureList = hasAnyCapture(capturesVar(
+  varDecl(hasInitializer(ignoringParenImpCasts(equalsNode(&Node));
+  auto InvokeInLambda = hasDeclContext(cxxRecordDecl(
+  isLambda(),
+  hasParent(lambdaExpr(forCallable(equalsBoundNode("func")),
+   anyOf(InvokeInCaptureList, hasCaptureToParm());
+
+  if (forCallable(anyOf(equalsBoundNode("func"), InvokeInLambda))
+  .matches(Node, Finder, Builder))
+return true;
+
+  return false;
+}
+
 } // namespace
 
 void MissingStdForwardCheck::registerMatchers(MatchFinder *Finder) {
   auto ToParam = hasAnyParameter(parmVarDecl(equalsBoundNode("param")));
 
-  auto ForwardCallMatcher = callExpr(
-  forCallable(equalsBoundNode("func")), argumentCountIs(1),
-  callee(unresolvedLookupExpr(hasAnyDeclaration(
-  namedDecl(hasUnderlyingDecl(hasName("::std::forward")),
-  hasArgument(0, declRefExpr(to(equalsBoundNode("param"))).bind("ref")),
-  unless(anyOf(hasAncestor(typeLoc()),
-   hasAncestor(expr(hasUnevaluatedContext());
+  auto ForwardCallMatcher =
+  callExpr(forCallableNode(), argumentCountIs(1),
+   callee(unresolvedLookupExpr(hasAnyDeclaration(
+   namedDecl(hasUnderlyingDecl(hasName("::std::forward")),
+   hasArgument(0, declRefExpr(to(equalsBoundNode("param",
+   unless(anyOf(hasAncestor(typeLoc()),
+hasAncestor(expr(hasUnevaluatedContext());
 
   Finder->addMatcher(
   parmVarDecl(parmVarDecl().bind("param"), isTemplateTypeParameter(),
@@ -76,6 +134,7 @@ void MissingStdForwardCheck::registerMatchers(MatchFinder 
*Finder) {
 }
 
 void MissingStdForwardCheck::check(const MatchFinder::MatchResult &Result) {
+
   const auto *Param = Result.Nodes.getNodeAs("param");
 
   if (!Param)
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
index b9720db272e406..55d6be743c22ab 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
@@ -90,9 +90,9 @@ void lambda_value_capture(T&& t) {
 }
 
 templ

[clang-tools-extra] [clang-tidy] fix false positive in cppcoreguidelines-missing-std-forward (PR #77056)

2024-01-05 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/77056

>From 043fc62485293f5cdc41ed8e4afd056671b0ea06 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 3 Jan 2024 09:44:26 +0800
Subject: [PATCH] [clang-tidy] fix false positive in
 cppcoreguidelines-missing-std-forward

---
 .../MissingStdForwardCheck.cpp| 72 +--
 .../cppcoreguidelines/missing-std-forward.cpp | 26 ++-
 2 files changed, 88 insertions(+), 10 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
index 0b85ea19735eef..ae31ce13f8def9 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/MissingStdForwardCheck.cpp
@@ -53,18 +53,76 @@ AST_MATCHER(ParmVarDecl, isTemplateTypeParameter) {
  FuncTemplate->getTemplateParameters()->getDepth();
 }
 
+AST_MATCHER_P(NamedDecl, hasSameNameAsBoundNode, std::string, BindingID) {
+  const auto &Name = Node.getNameAsString();
+
+  return Builder->removeBindings(
+  [this, Name](const ast_matchers::internal::BoundNodesMap &Nodes) {
+const auto &BN = Nodes.getNode(this->BindingID);
+if (const auto *ND = BN.get()) {
+  if (!isa(ND))
+return true;
+  return ND->getName() != Name;
+}
+return true;
+  });
+}
+
+AST_MATCHER_P(LambdaCapture, hasCaptureKind, LambdaCaptureKind, Kind) {
+  return Node.getCaptureKind() == Kind;
+}
+
+AST_MATCHER_P(LambdaExpr, hasCaptureDefaultKind, LambdaCaptureDefault, Kind) {
+  return Node.getCaptureDefault() == Kind;
+}
+
+AST_MATCHER(LambdaExpr, hasCaptureToParm) {
+  auto RefToParm = capturesVar(varDecl(hasSameNameAsBoundNode("param")));
+  auto HasRefToParm = hasAnyCapture(RefToParm);
+
+  auto CaptureInRef =
+  allOf(hasCaptureDefaultKind(LambdaCaptureDefault::LCD_ByRef),
+unless(HasRefToParm));
+  auto CaptureInCopy = allOf(
+  hasCaptureDefaultKind(LambdaCaptureDefault::LCD_ByCopy), HasRefToParm);
+  auto CaptureByRefExplicit = hasAnyCapture(
+  allOf(hasCaptureKind(LambdaCaptureKind::LCK_ByRef), RefToParm));
+
+  auto Captured =
+  lambdaExpr(anyOf(CaptureInRef, CaptureInCopy, CaptureByRefExplicit));
+  if (Captured.matches(Node, Finder, Builder))
+return true;
+
+  return false;
+}
+
+AST_MATCHER(CallExpr, forCallableNode) {
+  auto InvokeInCaptureList = hasAnyCapture(capturesVar(
+  varDecl(hasInitializer(ignoringParenImpCasts(equalsNode(&Node));
+  auto InvokeInLambda = hasDeclContext(cxxRecordDecl(
+  isLambda(),
+  hasParent(lambdaExpr(forCallable(equalsBoundNode("func")),
+   anyOf(InvokeInCaptureList, hasCaptureToParm());
+
+  if (forCallable(anyOf(equalsBoundNode("func"), InvokeInLambda))
+  .matches(Node, Finder, Builder))
+return true;
+
+  return false;
+}
+
 } // namespace
 
 void MissingStdForwardCheck::registerMatchers(MatchFinder *Finder) {
   auto ToParam = hasAnyParameter(parmVarDecl(equalsBoundNode("param")));
 
-  auto ForwardCallMatcher = callExpr(
-  forCallable(equalsBoundNode("func")), argumentCountIs(1),
-  callee(unresolvedLookupExpr(hasAnyDeclaration(
-  namedDecl(hasUnderlyingDecl(hasName("::std::forward")),
-  hasArgument(0, declRefExpr(to(equalsBoundNode("param"))).bind("ref")),
-  unless(anyOf(hasAncestor(typeLoc()),
-   hasAncestor(expr(hasUnevaluatedContext());
+  auto ForwardCallMatcher =
+  callExpr(forCallableNode(), argumentCountIs(1),
+   callee(unresolvedLookupExpr(hasAnyDeclaration(
+   namedDecl(hasUnderlyingDecl(hasName("::std::forward")),
+   hasArgument(0, declRefExpr(to(equalsBoundNode("param",
+   unless(anyOf(hasAncestor(typeLoc()),
+hasAncestor(expr(hasUnevaluatedContext());
 
   Finder->addMatcher(
   parmVarDecl(parmVarDecl().bind("param"), isTemplateTypeParameter(),
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
index b9720db272e406..55d6be743c22ab 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/missing-std-forward.cpp
@@ -90,9 +90,9 @@ void lambda_value_capture(T&& t) {
 }
 
 template 
-void lambda_value_reference(T&& t) {
-  // CHECK-MESSAGES: :[[@LINE-1]]:33: warning: forwarding reference parameter 
't' is never forwarded inside the function body 
[cppcoreguidelines-missing-std-forward]
-  [&]() { T other = std::forward(t); };
+void lambda_value_capture_copy(T&& t) {
+  // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: forwarding reference parameter 
't' is never forwarded inside the function body 

[libcxx] [lldb] [openmp] [llvm] [mlir] [clang] [clang-tools-extra] [SEH] Fix register liveness verification for EHa (PR #76933)

2024-01-05 Thread Phoebe Wang via cfe-commits


@@ -3347,10 +3348,37 @@ void MachineVerifier::verifyLiveRangeSegment(const 
LiveRange &LR,
 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
   }
 
+  bool IsEHa = MF->getMMI().getModule()->getModuleFlag("eh-asynch");
   while (true) {
 assert(LiveInts->isLiveInToMBB(LR, &*MFI));
-// We don't know how to track physregs into a landing pad.
-if (!Reg.isVirtual() && MFI->isEHPad()) {
+auto IsSEHHandler = [](const MachineBasicBlock &Handler) -> bool {
+  if (!Handler.isMachineBlockAddressTaken())
+return false;
+
+  for (const User *U : Handler.getBasicBlock()->users()) {
+if (!isa(U))
+  continue;
+const Function *Fn = cast(U)->getCalledFunction();
+if (!Fn || !Fn->isIntrinsic())
+  continue;
+
+switch (Fn->getIntrinsicID()) {
+default:
+  continue;
+case Intrinsic::seh_scope_begin:
+case Intrinsic::seh_scope_end:
+case Intrinsic::seh_try_begin:
+case Intrinsic::seh_try_end:
+  return true;
+}
+  }
+  return false;
+};
+
+// TODO: we don't know how to track physregs into a landing pad. For async
+// EH, the virtual reg lives before scope begin, but we don't know seh 
scope

phoebewang wrote:

Can we get the scope through `seh_scope_begin/seh_scope_end` etc.?

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


[clang] [clang][analyzer] Add missing stream related functions to StdCLibraryFunctionsChecker. (PR #76979)

2024-01-05 Thread Balázs Kéri via cfe-commits

https://github.com/balazske updated 
https://github.com/llvm/llvm-project/pull/76979

From e24b90eebfff7a352dd2c0df7f948ffef26ea3b3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Thu, 4 Jan 2024 18:16:12 +0100
Subject: [PATCH 1/2] [clang][analyzer] Add missing stream related functions to
 StdCLibraryFunctionsChecker.

Some stream functions were recently added to StreamChecker that were not 
modeled by
StdCLibraryFunctionsChecker. To ensure consistency these functions are added
to the other checker too.
Some of the related tests are re-organized.
---
 .../Checkers/StdLibraryFunctionsChecker.cpp   | 88 +++
 clang/test/Analysis/std-c-library-functions.c |  4 +-
 clang/test/Analysis/stream-error.c| 26 --
 clang/test/Analysis/stream-noopen.c   | 68 ++
 clang/test/Analysis/stream-note.c |  1 +
 clang/test/Analysis/stream.c  | 25 +-
 6 files changed, 166 insertions(+), 46 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 20068653d530a3..f4bf68c3147fd1 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2023,13 +2023,6 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
{{EOFv, EOFv}, {0, UCharRangeMax}},
"an unsigned char value or EOF")));
 
-  // The getc() family of functions that returns either a char or an EOF.
-  addToFunctionSummaryMap(
-  {"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
-  Summary(NoEvalCall)
-  .Case({ReturnValueCondition(WithinRange,
-  {{EOFv, EOFv}, {0, UCharRangeMax}})},
-ErrnoIrrelevant));
   addToFunctionSummaryMap(
   "getchar", Signature(ArgTypes{}, RetType{IntTy}),
   Summary(NoEvalCall)
@@ -2139,7 +2132,17 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 std::move(GetenvSummary));
   }
 
-  if (ModelPOSIX) {
+  if (!ModelPOSIX) {
+// Without POSIX use of 'errno' is not specified (in these cases).
+// Add these functions without 'errno' checks.
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange,
+{{EOFv, EOFv}, {0, UCharRangeMax}})},
+  ErrnoIrrelevant)
+.ArgConstraint(NotNull(ArgNo(0;
+  } else {
 const auto ReturnsZeroOrMinusOne =
 ConstraintSet{ReturnValueCondition(WithinRange, Range(-1, 0))};
 const auto ReturnsZero =
@@ -2192,6 +2195,16 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(1)))
 .ArgConstraint(NotNull(ArgNo(2;
 
+// FILE *fdopen(int fd, const char *mode);
+addToFunctionSummaryMap(
+"fdopen",
+Signature(ArgTypes{IntTy, ConstCharPtrTy}, RetType{FilePtrTy}),
+Summary(NoEvalCall)
+.Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(ArgumentCondition(0, WithinRange, Range(0, IntMax)))
+.ArgConstraint(NotNull(ArgNo(1;
+
 // int fclose(FILE *stream);
 addToFunctionSummaryMap(
 "fclose", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
@@ -2201,6 +2214,56 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// int fgetc(FILE *stream);
+// 'getc' is the same as 'fgetc' but may be a macro
+addToFunctionSummaryMap(
+{"getc", "fgetc"}, Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, {{0, UCharRangeMax}})},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;
+
+// int fputc(int c, FILE *stream);
+// 'putc' is the same as 'fputc' but may be a macro
+addToFunctionSummaryMap(
+{"putc", "fputc"},
+Signature(ArgTypes{IntTy, FilePtrTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+  ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(1)))
+.ArgConstraint(
+ArgumentCond

[clang] [clang][analyzer] Add missing stream related functions to StdCLibraryFunctionsChecker. (PR #76979)

2024-01-05 Thread Balázs Kéri via cfe-commits

balazske wrote:

Next step is to add all functions to the non-POSIX part that exist in the C 
standard (at least the stream functions), and change `fread` and `fwrite` too 
(currently `errno` is always modeled but should be only in POSIX mode).

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


[clang] [Clang] Correctly construct template arguments for file-scope template template parameters (PR #76811)

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

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

>From 1164c705a8515d39bc9d4404e8523da8876d81cf Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 3 Jan 2024 19:33:01 +0800
Subject: [PATCH 1/2] [Clang] Correctly construct template arguments for
 file-scope template template parameters

This fixes the bug introduced by
https://github.com/llvm/llvm-project/commit/6db007a0654ed7a6ed5c3aa3b61a937c19a6bc6b.

We construct placeholder template arguments for template-template parameters to
avoid mismatching argument substitution since they have different depths
with their corresponding template arguments. In this case,

```cpp
template  class T> void foo(T);
```

T lies at the depth 0, and C lies at 1. The corresponding argument, of which
there is exactly one, int, is at depth 0. If we consider the
argument as the outermost one, then we would end up substituting 'int'
into the wrong parameter T.

We used to perform such placeholder construction during the context walk-up.
In the previous patch, we slipped through that inadvertently because we would
walk up to the parent, which is precisely a FileContext for template-template
parameters, after adding innermost arguments.

Besides, this patch moves the sanity check up to the context switch.
That way, we avoid dereferencing null pointers if ND is unspecified.

Closes https://github.com/llvm/llvm-project/issues/57410.
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 12 ++---
 .../temp/temp.arg/temp.arg.template/p3-2a.cpp | 25 +++
 3 files changed, 36 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0c8fec691bf3c9..7193d711333780 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -843,6 +843,9 @@ Bug Fixes to C++ Support
 - Fix crash when parsing nested requirement. Fixes:
   (`#73112 `_)
 
+- Fix a regression where clang forgets how to substitute into constraints on 
template-template
+  parameters. Fixes: (`#57410 
`_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index df6b40999e645c..4420280efebb86 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -345,15 +345,19 @@ MultiLevelTemplateArgumentList 
Sema::getTemplateInstantiationArgs(
 
   using namespace TemplateInstArgsHelpers;
   const Decl *CurDecl = ND;
+
+  if (!ND)
+CurDecl = Decl::castFromDeclContext(DC);
+
   if (Innermost) {
 Result.addOuterTemplateArguments(const_cast(ND),
  Innermost->asArray(), Final);
-CurDecl = Response::UseNextDecl(ND).NextDecl;
+if (CurDecl->getDeclContext()->isFileContext())
+  if (const auto *TTP = dyn_cast(CurDecl))
+HandleDefaultTempArgIntoTempTempParam(TTP, Result);
+CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
   }
 
-  if (!ND)
-CurDecl = Decl::castFromDeclContext(DC);
-
   while (!CurDecl->isFileContextDecl()) {
 Response R;
 if (const auto *VarTemplSpec =
diff --git a/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp 
b/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
index 449b6232542e24..277935f6b3b2f0 100644
--- a/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
+++ b/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
@@ -59,3 +59,28 @@ struct Nothing {};
 
 // FIXME: Wait the standard to clarify the intent.
 template<> template<> Z S5::V;
+
+namespace GH57410 {
+
+template
+concept True = true;
+
+template
+concept False = false; // #False
+
+template typename Wrapper>
+using Test = Wrapper;
+
+template typename Wrapper> // #TTP-Wrapper
+using Test = Wrapper; // expected-error {{constraints not satisfied for 
template template parameter 'Wrapper' [with T = int]}}
+
+// expected-note@#TTP-Wrapper {{'int' does not satisfy 'False'}}
+// expected-note@#False {{evaluated to false}}
+
+template  typename T> // #TTP-foo
+void foo(T); // expected-error {{constraints not satisfied for template 
template parameter 'T' [with $0 = int]}}
+
+// expected-note@#TTP-foo {{'int' does not satisfy 'False'}}
+// expected-note@#False {{evaluated to false}}
+
+}

>From 8d5a7cdb39b0e64d350b8e4540738ef6eae7dc5c Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Fri, 5 Jan 2024 16:37:05 +0800
Subject: [PATCH 2/2] Address comments and poke the CI

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 22 ---
 .../temp/temp.arg/temp.arg.template/p3-2a.cpp | 12 ++
 2 files changed, 22 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 4420280ef

[clang] [Clang] Correctly construct template arguments for template template parameters (PR #76811)

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

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


[clang] [Clang] Correctly construct template arguments for template template parameters (PR #76811)

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

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Freddy Ye via cfe-commits

FreddyLeaf wrote:

ping for review

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


[clang-tools-extra] [include-cleaner] Fix a race issue when editing multiple files. (PR #76960)

2024-01-05 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/76960

>From 6cc7141f1f182763ccec8a4801d3b866cc839324 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Thu, 4 Jan 2024 14:59:22 +0100
Subject: [PATCH 1/2] [include-cleaner] Fix a race issue when editing multiple
 files.

We have a previous fix 
https://github.com/llvm/llvm-project/commit/be861b64d94198230d8f9889b17280e3cd215a0a,
which snapshots all processing files.

It works most of times, the snapshot (InMemoryFileSystem) is based on
the file path. The file-path-based lookup can fail in a subtle way for
some tricky cases (we encounter it internally), which will result in
reading a corrupted header.

This is a different fix, we don't modify files on the fly, instead,
we write files when the tool finishes analysises for all files.
---
 .../include-cleaner/tool/IncludeCleaner.cpp   | 54 +--
 1 file changed, 27 insertions(+), 27 deletions(-)

diff --git a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp 
b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
index 30aaee29b9a397..eacdfab57b74f0 100644
--- a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -16,10 +16,10 @@
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
-#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/raw_ostream.h"
@@ -110,14 +110,16 @@ format::FormatStyle getStyle(llvm::StringRef Filename) {
 
 class Action : public clang::ASTFrontendAction {
 public:
-  Action(llvm::function_ref HeaderFilter)
-  : HeaderFilter(HeaderFilter){};
+  Action(llvm::function_ref HeaderFilter,
+ llvm::StringMap &FileEdits)
+  : HeaderFilter(HeaderFilter), EditFiles(FileEdits) {}
 
 private:
   RecordedAST AST;
   RecordedPP PP;
   PragmaIncludes PI;
   llvm::function_ref HeaderFilter;
+  llvm::StringMap& EditFiles;
 
   bool BeginInvocation(CompilerInstance &CI) override {
 // We only perform include-cleaner analysis. So we disable diagnostics that
@@ -181,17 +183,8 @@ class Action : public clang::ASTFrontendAction {
   }
 }
 
-if (Edit && (!Results.Missing.empty() || !Results.Unused.empty())) {
-  if (auto Err = llvm::writeToOutput(
-  Path, [&](llvm::raw_ostream &OS) -> llvm::Error {
-OS << Final;
-return llvm::Error::success();
-  })) {
-llvm::errs() << "Failed to apply edits to " << Path << ": "
- << toString(std::move(Err)) << "\n";
-++Errors;
-  }
-}
+if (!Results.Missing.empty() || !Results.Unused.empty())
+  EditFiles.try_emplace(Path, Final);
   }
 
   void writeHTML() {
@@ -215,11 +208,15 @@ class ActionFactory : public 
tooling::FrontendActionFactory {
   : HeaderFilter(HeaderFilter) {}
 
   std::unique_ptr create() override {
-return std::make_unique(HeaderFilter);
+return std::make_unique(HeaderFilter, EditFiles);
   }
 
+  const llvm::StringMap &getEditFiles() const { return EditFiles; 
}
+
 private:
   llvm::function_ref HeaderFilter;
+  // Map from file name to final code with the include edits applied.
+  llvm::StringMap EditFiles;
 };
 
 std::function headerFilter() {
@@ -274,21 +271,24 @@ int main(int argc, const char **argv) {
 
   clang::tooling::ClangTool Tool(OptionsParser->getCompilations(),
  OptionsParser->getSourcePathList());
-  std::vector> Buffers;
-  for (const auto &File : OptionsParser->getSourcePathList()) {
-auto Content = llvm::MemoryBuffer::getFile(File);
-if (!Content) {
-  llvm::errs() << "Error: can't read file '" << File
-   << "': " << Content.getError().message() << "\n";
-  return 1;
-}
-Buffers.push_back(std::move(Content.get()));
-Tool.mapVirtualFile(File, Buffers.back()->getBuffer());
-  }
 
   auto HeaderFilter = headerFilter();
   if (!HeaderFilter)
 return 1; // error already reported.
   ActionFactory Factory(HeaderFilter);
-  return Tool.run(&Factory) || Errors != 0;
+  auto ErrorCode = Tool.run(&Factory);
+  if (Edit) {
+for (const auto &[FileName, FinalCode] : Factory.getEditFiles()) {
+  if (auto Err = llvm::writeToOutput(
+  FileName, [&](llvm::raw_ostream &OS) -> llvm::Error {
+OS << FinalCode;
+return llvm::Error::success();
+  })) {
+llvm::errs() << "Failed to apply edits to " << FileName << ": "
+ << toString(std::move(Err)) << "\n";
+++Errors;
+  }
+}
+  }
+  return ErrorCode || Errors != 0;
 }

>From acace9a6753e8f95a718b8ec7464c465c7687d72 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 5

[clang] [Clang] Correctly construct template arguments for template template parameters (PR #76811)

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

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

>From 1164c705a8515d39bc9d4404e8523da8876d81cf Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 3 Jan 2024 19:33:01 +0800
Subject: [PATCH 1/3] [Clang] Correctly construct template arguments for
 file-scope template template parameters

This fixes the bug introduced by
https://github.com/llvm/llvm-project/commit/6db007a0654ed7a6ed5c3aa3b61a937c19a6bc6b.

We construct placeholder template arguments for template-template parameters to
avoid mismatching argument substitution since they have different depths
with their corresponding template arguments. In this case,

```cpp
template  class T> void foo(T);
```

T lies at the depth 0, and C lies at 1. The corresponding argument, of which
there is exactly one, int, is at depth 0. If we consider the
argument as the outermost one, then we would end up substituting 'int'
into the wrong parameter T.

We used to perform such placeholder construction during the context walk-up.
In the previous patch, we slipped through that inadvertently because we would
walk up to the parent, which is precisely a FileContext for template-template
parameters, after adding innermost arguments.

Besides, this patch moves the sanity check up to the context switch.
That way, we avoid dereferencing null pointers if ND is unspecified.

Closes https://github.com/llvm/llvm-project/issues/57410.
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 12 ++---
 .../temp/temp.arg/temp.arg.template/p3-2a.cpp | 25 +++
 3 files changed, 36 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0c8fec691bf3c9..7193d711333780 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -843,6 +843,9 @@ Bug Fixes to C++ Support
 - Fix crash when parsing nested requirement. Fixes:
   (`#73112 `_)
 
+- Fix a regression where clang forgets how to substitute into constraints on 
template-template
+  parameters. Fixes: (`#57410 
`_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index df6b40999e645c..4420280efebb86 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -345,15 +345,19 @@ MultiLevelTemplateArgumentList 
Sema::getTemplateInstantiationArgs(
 
   using namespace TemplateInstArgsHelpers;
   const Decl *CurDecl = ND;
+
+  if (!ND)
+CurDecl = Decl::castFromDeclContext(DC);
+
   if (Innermost) {
 Result.addOuterTemplateArguments(const_cast(ND),
  Innermost->asArray(), Final);
-CurDecl = Response::UseNextDecl(ND).NextDecl;
+if (CurDecl->getDeclContext()->isFileContext())
+  if (const auto *TTP = dyn_cast(CurDecl))
+HandleDefaultTempArgIntoTempTempParam(TTP, Result);
+CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
   }
 
-  if (!ND)
-CurDecl = Decl::castFromDeclContext(DC);
-
   while (!CurDecl->isFileContextDecl()) {
 Response R;
 if (const auto *VarTemplSpec =
diff --git a/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp 
b/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
index 449b6232542e24..277935f6b3b2f0 100644
--- a/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
+++ b/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
@@ -59,3 +59,28 @@ struct Nothing {};
 
 // FIXME: Wait the standard to clarify the intent.
 template<> template<> Z S5::V;
+
+namespace GH57410 {
+
+template
+concept True = true;
+
+template
+concept False = false; // #False
+
+template typename Wrapper>
+using Test = Wrapper;
+
+template typename Wrapper> // #TTP-Wrapper
+using Test = Wrapper; // expected-error {{constraints not satisfied for 
template template parameter 'Wrapper' [with T = int]}}
+
+// expected-note@#TTP-Wrapper {{'int' does not satisfy 'False'}}
+// expected-note@#False {{evaluated to false}}
+
+template  typename T> // #TTP-foo
+void foo(T); // expected-error {{constraints not satisfied for template 
template parameter 'T' [with $0 = int]}}
+
+// expected-note@#TTP-foo {{'int' does not satisfy 'False'}}
+// expected-note@#False {{evaluated to false}}
+
+}

>From 8d5a7cdb39b0e64d350b8e4540738ef6eae7dc5c Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Fri, 5 Jan 2024 16:37:05 +0800
Subject: [PATCH 2/3] Address comments and poke the CI

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 22 ---
 .../temp/temp.arg/temp.arg.template/p3-2a.cpp | 12 ++
 2 files changed, 22 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 4420280ef

[clang-tools-extra] [include-cleaner] Fix a race issue when editing multiple files. (PR #76960)

2024-01-05 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/76960

>From 6cc7141f1f182763ccec8a4801d3b866cc839324 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Thu, 4 Jan 2024 14:59:22 +0100
Subject: [PATCH 1/3] [include-cleaner] Fix a race issue when editing multiple
 files.

We have a previous fix 
https://github.com/llvm/llvm-project/commit/be861b64d94198230d8f9889b17280e3cd215a0a,
which snapshots all processing files.

It works most of times, the snapshot (InMemoryFileSystem) is based on
the file path. The file-path-based lookup can fail in a subtle way for
some tricky cases (we encounter it internally), which will result in
reading a corrupted header.

This is a different fix, we don't modify files on the fly, instead,
we write files when the tool finishes analysises for all files.
---
 .../include-cleaner/tool/IncludeCleaner.cpp   | 54 +--
 1 file changed, 27 insertions(+), 27 deletions(-)

diff --git a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp 
b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
index 30aaee29b9a397..eacdfab57b74f0 100644
--- a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -16,10 +16,10 @@
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
-#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/raw_ostream.h"
@@ -110,14 +110,16 @@ format::FormatStyle getStyle(llvm::StringRef Filename) {
 
 class Action : public clang::ASTFrontendAction {
 public:
-  Action(llvm::function_ref HeaderFilter)
-  : HeaderFilter(HeaderFilter){};
+  Action(llvm::function_ref HeaderFilter,
+ llvm::StringMap &FileEdits)
+  : HeaderFilter(HeaderFilter), EditFiles(FileEdits) {}
 
 private:
   RecordedAST AST;
   RecordedPP PP;
   PragmaIncludes PI;
   llvm::function_ref HeaderFilter;
+  llvm::StringMap& EditFiles;
 
   bool BeginInvocation(CompilerInstance &CI) override {
 // We only perform include-cleaner analysis. So we disable diagnostics that
@@ -181,17 +183,8 @@ class Action : public clang::ASTFrontendAction {
   }
 }
 
-if (Edit && (!Results.Missing.empty() || !Results.Unused.empty())) {
-  if (auto Err = llvm::writeToOutput(
-  Path, [&](llvm::raw_ostream &OS) -> llvm::Error {
-OS << Final;
-return llvm::Error::success();
-  })) {
-llvm::errs() << "Failed to apply edits to " << Path << ": "
- << toString(std::move(Err)) << "\n";
-++Errors;
-  }
-}
+if (!Results.Missing.empty() || !Results.Unused.empty())
+  EditFiles.try_emplace(Path, Final);
   }
 
   void writeHTML() {
@@ -215,11 +208,15 @@ class ActionFactory : public 
tooling::FrontendActionFactory {
   : HeaderFilter(HeaderFilter) {}
 
   std::unique_ptr create() override {
-return std::make_unique(HeaderFilter);
+return std::make_unique(HeaderFilter, EditFiles);
   }
 
+  const llvm::StringMap &getEditFiles() const { return EditFiles; 
}
+
 private:
   llvm::function_ref HeaderFilter;
+  // Map from file name to final code with the include edits applied.
+  llvm::StringMap EditFiles;
 };
 
 std::function headerFilter() {
@@ -274,21 +271,24 @@ int main(int argc, const char **argv) {
 
   clang::tooling::ClangTool Tool(OptionsParser->getCompilations(),
  OptionsParser->getSourcePathList());
-  std::vector> Buffers;
-  for (const auto &File : OptionsParser->getSourcePathList()) {
-auto Content = llvm::MemoryBuffer::getFile(File);
-if (!Content) {
-  llvm::errs() << "Error: can't read file '" << File
-   << "': " << Content.getError().message() << "\n";
-  return 1;
-}
-Buffers.push_back(std::move(Content.get()));
-Tool.mapVirtualFile(File, Buffers.back()->getBuffer());
-  }
 
   auto HeaderFilter = headerFilter();
   if (!HeaderFilter)
 return 1; // error already reported.
   ActionFactory Factory(HeaderFilter);
-  return Tool.run(&Factory) || Errors != 0;
+  auto ErrorCode = Tool.run(&Factory);
+  if (Edit) {
+for (const auto &[FileName, FinalCode] : Factory.getEditFiles()) {
+  if (auto Err = llvm::writeToOutput(
+  FileName, [&](llvm::raw_ostream &OS) -> llvm::Error {
+OS << FinalCode;
+return llvm::Error::success();
+  })) {
+llvm::errs() << "Failed to apply edits to " << FileName << ": "
+ << toString(std::move(Err)) << "\n";
+++Errors;
+  }
+}
+  }
+  return ErrorCode || Errors != 0;
 }

>From acace9a6753e8f95a718b8ec7464c465c7687d72 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 5

[clang-tools-extra] [clang] [llvm] [clang] Disable missing definition warning on pure virtual functions (PR #74510)

2024-01-05 Thread Charalampos Mitrodimas via cfe-commits

https://github.com/charmitro updated 
https://github.com/llvm/llvm-project/pull/74510

>From 83d29e896b7ae0b5b259cbf179143e526dc37b1c Mon Sep 17 00:00:00 2001
From: Charalampos Mitrodimas 
Date: Tue, 5 Dec 2023 11:46:56 +0200
Subject: [PATCH] [clang] Disable missing definition warning on pure virtual
 functions

Warning '-Wundefined-func-template' incorrectly indicates that no
definition is available for a pure virtual function. However, a
definition is not needed for a pure virtual function.

Fixes #74016

Signed-off-by: Charalampos Mitrodimas 
---
 clang/docs/ReleaseNotes.rst   |  3 ++
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  3 +-
 .../instantiate-pure-virtual-function.cpp | 48 +++
 3 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 
clang/test/SemaTemplate/instantiate-pure-virtual-function.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 828dd10e3d6db9..10dce199b9fd16 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -514,6 +514,9 @@ Improvements to Clang's time-trace
 
 Bug Fixes in This Version
 -
+- Clang's ``-Wundefined-func-template`` no longer warns on pure virtual
+  functions.
+  (`#74016 `_)
 - Fixed an issue where a class template specialization whose declaration is
   instantiated in one module and whose definition is instantiated in another
   module may end up with members associated with the wrong declaration of the
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index d768bb72e07c09..a034de0697b2b7 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4952,7 +4952,8 @@ void Sema::InstantiateFunctionDefinition(SourceLocation 
PointOfInstantiation,
 std::make_pair(Function, PointOfInstantiation));
 } else if (TSK == TSK_ImplicitInstantiation) {
   if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
-  !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
+  !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc()) &&
+  !Function->isPure()) {
 Diag(PointOfInstantiation, diag::warn_func_template_missing)
   << Function;
 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
diff --git a/clang/test/SemaTemplate/instantiate-pure-virtual-function.cpp 
b/clang/test/SemaTemplate/instantiate-pure-virtual-function.cpp
new file mode 100644
index 00..d188adc9ed034e
--- /dev/null
+++ b/clang/test/SemaTemplate/instantiate-pure-virtual-function.cpp
@@ -0,0 +1,48 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wundefined-func-template %s
+
+namespace GH74016 {
+  template  class B {
+  public:
+constexpr void foo(const T &) { bar(1); }
+virtual constexpr void bar(unsigned int) = 0;
+  };
+
+  template  class D : public B {
+  public:
+constexpr void bar(unsigned int) override {}
+  };
+
+  void test() {
+auto t = D();
+t.foo(0);
+  }
+};
+
+namespace non_pure_virtual_function {
+  template  class B {
+  public:
+constexpr void foo(const T &) { bar(1); }
+
+virtual constexpr void bar(unsigned int); // expected-warning {{inline 
function 'non_pure_virtual_function::B::bar' is not defined}}
+// expected-note@-1 {{forward declaration of template entity is here}}
+// expected-note@-2 {{forward declaration of template entity is here}}
+// expected-note@-3 {{forward declaration of template entity is here}}
+  };
+
+  template  class D : public B { // expected-warning 
{{instantiation of function 'non_pure_virtual_function::B::bar' required 
here, but no definition is available}}
+// expected-warning@-1 {{instantiation of function 
'non_pure_virtual_function::B::bar' required here, but no definition is 
available}}
+// expected-warning@-2 {{instantiation of function 
'non_pure_virtual_function::B::bar' required here, but no definition is 
available}}
+// expected-note@-3 {{add an explicit instantiation declaration to suppress 
this warning if 'non_pure_virtual_function::B::bar' is explicitly 
instantiated in another translation unit}}
+// expected-note@-4 {{add an explicit instantiation declaration to suppress 
this warning if 'non_pure_virtual_function::B::bar' is explicitly 
instantiated in another translation unit}}
+// expected-note@-5 {{add an explicit instantiation declaration to suppress 
this warning if 'non_pure_virtual_function::B::bar' is explicitly 
instantiated in another translation unit}}
+// expected-note@-6 {{used here}}
+
+  public:
+constexpr void bar(unsigned int) override { }
+  };
+
+  void test() {
+auto t = D();
+t.foo(0);
+  }
+};

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


[clang] [clang-format] Fix crash involving array designators and dangling comma (PR #77045)

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


@@ -21084,6 +21084,12 @@ TEST_F(FormatTest, 
CatchAlignArrayOfStructuresLeftAlignment) {
   "};",
   Style);
 
+  verifyNoCrash("Foo f[] = {\n"
+"[0] = { 1, },\n"
+"[1] { 1, },\n"
+"};",
+Style);

owenca wrote:

We should also add it to `CatchAlignArrayOfStructuresRightAlignment`.

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


[clang] [clang-format] Fix crash involving array designators and dangling comma (PR #77045)

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


@@ -1444,7 +1444,8 @@ WhitespaceManager::CellDescriptions 
WhitespaceManager::getCells(unsigned Start,
   } else if (C.Tok->is(tok::comma)) {
 if (!Cells.empty())
   Cells.back().EndIndex = i;
-if (C.Tok->getNextNonComment()->isNot(tok::r_brace)) // dangling comma
+const FormatToken *Next = C.Tok->getNextNonComment();
+if (Next && Next->isNot(tok::r_brace)) // dangling comma
   ++Cell;

owenca wrote:

```suggestion
if (const auto *Next = C.Tok->getNextNonComment();
Next && Next->isNot(tok::r_brace)) { // dangling comma
  ++Cell;
}
```

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


[clang] Improve modeling of 'getcwd' in the StdLibraryFunctionsChecker (PR #77040)

2024-01-05 Thread Balázs Kéri via cfe-commits


@@ -2516,12 +2516,15 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(0;
 
 // char *getcwd(char *buf, size_t size);
-// FIXME: Improve for errno modeling.
 addToFunctionSummaryMap(
 "getcwd", Signature(ArgTypes{CharPtrTy, SizeTy}, RetType{CharPtrTy}),
 Summary(NoEvalCall)
+.Case({ReturnValueCondition(BO_EQ, ArgNo(0))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0)))
 .ArgConstraint(
-ArgumentCondition(1, WithinRange, Range(0, SizeMax;
+ArgumentCondition(1, WithinRange, Range(1, SizeMax;

balazske wrote:

Here a `BufferSize` type of constraint can be used additionally. See `readlink` 
for example.
Value 0 is allowed for the size. Passing 0 is not undefined behavior, the 
function shall fail and set `errno`. A new case can be added (like at 
`readlink`).

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


[clang-tools-extra] [include-cleaner] Fix a race issue when editing multiple files. (PR #76960)

2024-01-05 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/76960

>From 6cc7141f1f182763ccec8a4801d3b866cc839324 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Thu, 4 Jan 2024 14:59:22 +0100
Subject: [PATCH 1/4] [include-cleaner] Fix a race issue when editing multiple
 files.

We have a previous fix 
https://github.com/llvm/llvm-project/commit/be861b64d94198230d8f9889b17280e3cd215a0a,
which snapshots all processing files.

It works most of times, the snapshot (InMemoryFileSystem) is based on
the file path. The file-path-based lookup can fail in a subtle way for
some tricky cases (we encounter it internally), which will result in
reading a corrupted header.

This is a different fix, we don't modify files on the fly, instead,
we write files when the tool finishes analysises for all files.
---
 .../include-cleaner/tool/IncludeCleaner.cpp   | 54 +--
 1 file changed, 27 insertions(+), 27 deletions(-)

diff --git a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp 
b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
index 30aaee29b9a397..eacdfab57b74f0 100644
--- a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -16,10 +16,10 @@
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
-#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/raw_ostream.h"
@@ -110,14 +110,16 @@ format::FormatStyle getStyle(llvm::StringRef Filename) {
 
 class Action : public clang::ASTFrontendAction {
 public:
-  Action(llvm::function_ref HeaderFilter)
-  : HeaderFilter(HeaderFilter){};
+  Action(llvm::function_ref HeaderFilter,
+ llvm::StringMap &FileEdits)
+  : HeaderFilter(HeaderFilter), EditFiles(FileEdits) {}
 
 private:
   RecordedAST AST;
   RecordedPP PP;
   PragmaIncludes PI;
   llvm::function_ref HeaderFilter;
+  llvm::StringMap& EditFiles;
 
   bool BeginInvocation(CompilerInstance &CI) override {
 // We only perform include-cleaner analysis. So we disable diagnostics that
@@ -181,17 +183,8 @@ class Action : public clang::ASTFrontendAction {
   }
 }
 
-if (Edit && (!Results.Missing.empty() || !Results.Unused.empty())) {
-  if (auto Err = llvm::writeToOutput(
-  Path, [&](llvm::raw_ostream &OS) -> llvm::Error {
-OS << Final;
-return llvm::Error::success();
-  })) {
-llvm::errs() << "Failed to apply edits to " << Path << ": "
- << toString(std::move(Err)) << "\n";
-++Errors;
-  }
-}
+if (!Results.Missing.empty() || !Results.Unused.empty())
+  EditFiles.try_emplace(Path, Final);
   }
 
   void writeHTML() {
@@ -215,11 +208,15 @@ class ActionFactory : public 
tooling::FrontendActionFactory {
   : HeaderFilter(HeaderFilter) {}
 
   std::unique_ptr create() override {
-return std::make_unique(HeaderFilter);
+return std::make_unique(HeaderFilter, EditFiles);
   }
 
+  const llvm::StringMap &getEditFiles() const { return EditFiles; 
}
+
 private:
   llvm::function_ref HeaderFilter;
+  // Map from file name to final code with the include edits applied.
+  llvm::StringMap EditFiles;
 };
 
 std::function headerFilter() {
@@ -274,21 +271,24 @@ int main(int argc, const char **argv) {
 
   clang::tooling::ClangTool Tool(OptionsParser->getCompilations(),
  OptionsParser->getSourcePathList());
-  std::vector> Buffers;
-  for (const auto &File : OptionsParser->getSourcePathList()) {
-auto Content = llvm::MemoryBuffer::getFile(File);
-if (!Content) {
-  llvm::errs() << "Error: can't read file '" << File
-   << "': " << Content.getError().message() << "\n";
-  return 1;
-}
-Buffers.push_back(std::move(Content.get()));
-Tool.mapVirtualFile(File, Buffers.back()->getBuffer());
-  }
 
   auto HeaderFilter = headerFilter();
   if (!HeaderFilter)
 return 1; // error already reported.
   ActionFactory Factory(HeaderFilter);
-  return Tool.run(&Factory) || Errors != 0;
+  auto ErrorCode = Tool.run(&Factory);
+  if (Edit) {
+for (const auto &[FileName, FinalCode] : Factory.getEditFiles()) {
+  if (auto Err = llvm::writeToOutput(
+  FileName, [&](llvm::raw_ostream &OS) -> llvm::Error {
+OS << FinalCode;
+return llvm::Error::success();
+  })) {
+llvm::errs() << "Failed to apply edits to " << FileName << ": "
+ << toString(std::move(Err)) << "\n";
+++Errors;
+  }
+}
+  }
+  return ErrorCode || Errors != 0;
 }

>From acace9a6753e8f95a718b8ec7464c465c7687d72 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 5

[clang] [Clang] Correctly construct template arguments for template template parameters (PR #76811)

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

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

>From 1164c705a8515d39bc9d4404e8523da8876d81cf Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 3 Jan 2024 19:33:01 +0800
Subject: [PATCH 1/3] [Clang] Correctly construct template arguments for
 file-scope template template parameters

This fixes the bug introduced by
https://github.com/llvm/llvm-project/commit/6db007a0654ed7a6ed5c3aa3b61a937c19a6bc6b.

We construct placeholder template arguments for template-template parameters to
avoid mismatching argument substitution since they have different depths
with their corresponding template arguments. In this case,

```cpp
template  class T> void foo(T);
```

T lies at the depth 0, and C lies at 1. The corresponding argument, of which
there is exactly one, int, is at depth 0. If we consider the
argument as the outermost one, then we would end up substituting 'int'
into the wrong parameter T.

We used to perform such placeholder construction during the context walk-up.
In the previous patch, we slipped through that inadvertently because we would
walk up to the parent, which is precisely a FileContext for template-template
parameters, after adding innermost arguments.

Besides, this patch moves the sanity check up to the context switch.
That way, we avoid dereferencing null pointers if ND is unspecified.

Closes https://github.com/llvm/llvm-project/issues/57410.
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 12 ++---
 .../temp/temp.arg/temp.arg.template/p3-2a.cpp | 25 +++
 3 files changed, 36 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0c8fec691bf3c9..7193d711333780 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -843,6 +843,9 @@ Bug Fixes to C++ Support
 - Fix crash when parsing nested requirement. Fixes:
   (`#73112 `_)
 
+- Fix a regression where clang forgets how to substitute into constraints on 
template-template
+  parameters. Fixes: (`#57410 
`_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index df6b40999e645c..4420280efebb86 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -345,15 +345,19 @@ MultiLevelTemplateArgumentList 
Sema::getTemplateInstantiationArgs(
 
   using namespace TemplateInstArgsHelpers;
   const Decl *CurDecl = ND;
+
+  if (!ND)
+CurDecl = Decl::castFromDeclContext(DC);
+
   if (Innermost) {
 Result.addOuterTemplateArguments(const_cast(ND),
  Innermost->asArray(), Final);
-CurDecl = Response::UseNextDecl(ND).NextDecl;
+if (CurDecl->getDeclContext()->isFileContext())
+  if (const auto *TTP = dyn_cast(CurDecl))
+HandleDefaultTempArgIntoTempTempParam(TTP, Result);
+CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
   }
 
-  if (!ND)
-CurDecl = Decl::castFromDeclContext(DC);
-
   while (!CurDecl->isFileContextDecl()) {
 Response R;
 if (const auto *VarTemplSpec =
diff --git a/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp 
b/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
index 449b6232542e24..277935f6b3b2f0 100644
--- a/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
+++ b/clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
@@ -59,3 +59,28 @@ struct Nothing {};
 
 // FIXME: Wait the standard to clarify the intent.
 template<> template<> Z S5::V;
+
+namespace GH57410 {
+
+template
+concept True = true;
+
+template
+concept False = false; // #False
+
+template typename Wrapper>
+using Test = Wrapper;
+
+template typename Wrapper> // #TTP-Wrapper
+using Test = Wrapper; // expected-error {{constraints not satisfied for 
template template parameter 'Wrapper' [with T = int]}}
+
+// expected-note@#TTP-Wrapper {{'int' does not satisfy 'False'}}
+// expected-note@#False {{evaluated to false}}
+
+template  typename T> // #TTP-foo
+void foo(T); // expected-error {{constraints not satisfied for template 
template parameter 'T' [with $0 = int]}}
+
+// expected-note@#TTP-foo {{'int' does not satisfy 'False'}}
+// expected-note@#False {{evaluated to false}}
+
+}

>From 8d5a7cdb39b0e64d350b8e4540738ef6eae7dc5c Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Fri, 5 Jan 2024 16:37:05 +0800
Subject: [PATCH 2/3] Address comments and poke the CI

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 22 ---
 .../temp/temp.arg/temp.arg.template/p3-2a.cpp | 12 ++
 2 files changed, 22 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 4420280ef

[clang] [clang][analyzer] Support 'fdopen' in the StreamChecker (PR #76776)

2024-01-05 Thread Balázs Kéri via cfe-commits

balazske wrote:

Documentation is in **checkers.rst** but not accurate now. It must be updated 
with more information.

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


[clang] [coroutines] Introduce [[clang::coro_disable_lifetimebound]] (PR #76818)

2024-01-05 Thread Ilya Biryukov via cfe-commits

https://github.com/ilya-biryukov approved this pull request.

I agree we could add parameter attributes later! LGTM!

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


[lldb] [clang] [llvm] [libcxx] [clang-tools-extra] [mlir] [openmp] [SEH] Fix register liveness verification for EHa (PR #76933)

2024-01-05 Thread via cfe-commits


@@ -3347,10 +3348,37 @@ void MachineVerifier::verifyLiveRangeSegment(const 
LiveRange &LR,
 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
   }
 
+  bool IsEHa = MF->getMMI().getModule()->getModuleFlag("eh-asynch");
   while (true) {
 assert(LiveInts->isLiveInToMBB(LR, &*MFI));
-// We don't know how to track physregs into a landing pad.
-if (!Reg.isVirtual() && MFI->isEHPad()) {
+auto IsSEHHandler = [](const MachineBasicBlock &Handler) -> bool {
+  if (!Handler.isMachineBlockAddressTaken())
+return false;
+
+  for (const User *U : Handler.getBasicBlock()->users()) {
+if (!isa(U))
+  continue;
+const Function *Fn = cast(U)->getCalledFunction();
+if (!Fn || !Fn->isIntrinsic())
+  continue;
+
+switch (Fn->getIntrinsicID()) {
+default:
+  continue;
+case Intrinsic::seh_scope_begin:
+case Intrinsic::seh_scope_end:
+case Intrinsic::seh_try_begin:
+case Intrinsic::seh_try_end:
+  return true;
+}
+  }
+  return false;
+};
+
+// TODO: we don't know how to track physregs into a landing pad. For async
+// EH, the virtual reg lives before scope begin, but we don't know seh 
scope

HaohaiWen wrote:

seh_scope_begin/seh_scope_end is lowered to fall through jmp which can be 
eliminated.
e.g.
```
BB0:
  instA
  jmp BB1:
BB1:
  invoke llvm.seh.scope.begin to BB2
BB2:
  instB
```

Those BB0, BB1, BB2 can be optimized to
```
MBB0:
   EH_LABEL
   instA
   EH_LABEL
   EH_LABEL
   instB
   EH_LABEL
```

We don't know which MBB the BB2 is mapped to. We also don't know which EH_LABEL 
the llvm.seh.scope.begin was located.


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


[lldb] [clang] [llvm] [libcxx] [clang-tools-extra] [mlir] [openmp] [SEH] Fix register liveness verification for EHa (PR #76933)

2024-01-05 Thread via cfe-commits

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


[clang] 190a75b - [coroutines] Introduce [[clang::coro_disable_lifetimebound]] (#76818)

2024-01-05 Thread via cfe-commits

Author: Utkarsh Saxena
Date: 2024-01-05T10:07:04+01:00
New Revision: 190a75b5f12d3872a5a26d6079d62adae40f147d

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

LOG: [coroutines] Introduce [[clang::coro_disable_lifetimebound]] (#76818)

Lifetime-bound analysis of reference parameters of coroutines and
coroutine wrappers is helpful in surfacing memory bugs associated with
using temporaries and stack variables in call expressions in plain
return statements.

This is the default semantics of `[[clang::coro_lifetimebound]]`. But it
should be okay to relax the requirements for a function when the
reference arguments are not lifetime bound. For example:

A coroutine wrapper accepts a reference parameter but does not pass it
to the underlying coroutine call.
```cpp
[[clang::coro_wrapper]] Task wrapper(const Request& req) {
  return req.shouldCallA() ? coroA() : coroB();
}
```
Or passes it the coroutine by value
```cpp
Task coro(std::string s) { co_return s.size(); }
[[clang::coro_wrapper]] wrapper(const std::string& s) { return coro(s); }
```

This patch allows functions to be annotated with
`[[clang::coro_disable_lifetime_bound]]` to disable lifetime bound
analysis for all calls to this function.

---
One missing piece here is a note suggesting using this annotation in
cases of lifetime warnings. This would require some more tweaks in the
lifetimebound analysis to recognize violations involving coroutines only
and produce this note only in those cases.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/lib/Sema/SemaInit.cpp
clang/test/Misc/pragma-attribute-supported-attributes-list.test
clang/test/SemaCXX/coro-lifetimebound.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ce7599ad34beaf..903a50a4d4d3a4 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -357,6 +357,7 @@ Attribute Changes in Clang
 - Clang now introduced ``[[clang::coro_lifetimebound]]`` attribute.
   All parameters of a function are considered to be lifetime bound if the 
function
   returns a type annotated with ``[[clang::coro_lifetimebound]]`` and 
``[[clang::coro_return_type]]``.
+  This analysis can be disabled for a function by annotating the function with 
``[[clang::coro_disable_lifetimebound]]``.
 
 Improvements to Clang's diagnostics
 ---

diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index db17211747b17d..fda62aaae22c78 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1121,6 +1121,14 @@ def CoroLifetimeBound : InheritableAttr {
   let SimpleHandler = 1;
 }
 
+def CoroDisableLifetimeBound : InheritableAttr {
+  let Spellings = [Clang<"coro_disable_lifetimebound">];
+  let Subjects = SubjectList<[Function]>;
+  let LangOpts = [CPlusPlus];
+  let Documentation = [CoroLifetimeBoundDoc];
+  let SimpleHandler = 1;
+}
+
 // OSObject-based attributes.
 def OSConsumed : InheritableParamAttr {
   let Spellings = [Clang<"os_consumed">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 98a7ecc7fd7df3..cd3dcf2ccf4411 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7671,9 +7671,12 @@ The ``[[clang::coro_lifetimebound]]`` is a class 
attribute which can be applied
 to a coroutine return type (`CRT`_) (i.e.
 it should also be annotated with ``[[clang::coro_return_type]]``).
 
-All parameters of a function are considered to be lifetime bound. See 
`documentation`_
-of ``[[clang::lifetimebound]]`` for more details.
-if the function returns a coroutine return type (CRT) annotated with 
``[[clang::coro_lifetimebound]]``.
+All parameters of a function are considered to be lifetime bound if the 
function returns a
+coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
+This lifetime bound analysis can be disabled for a coroutine wrapper or a 
coroutine by annotating the function
+with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
+See `documentation`_ of ``[[clang::lifetimebound]]`` for details about 
lifetime bound analysis.
+
 
 Reference parameters of a coroutine are susceptible to capturing references to 
temporaries or local variables.
 
@@ -7703,7 +7706,7 @@ Both coroutines and coroutine wrappers are part of this 
analysis.
   };
 
   Task coro(const int& a) { co_return a + 1; }
-  Task [[clang::coro_wrapper]] coro_wrapper(const int& a, const int& b) {
+  [[clang::coro_wrapper]] Task coro_wrapper(const int& a, const int& b) {
 return a > b ? coro(a) : coro(b);
   }
   Task temporary_reference() {
@@ 

[clang] [coroutines] Introduce [[clang::coro_disable_lifetimebound]] (PR #76818)

2024-01-05 Thread Utkarsh Saxena via cfe-commits

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Phoebe Wang via cfe-commits


@@ -69,7 +69,10 @@
 // RUN: %clang_cl -m32 -arch:avx2 --target=i386-pc-windows -### -- 2>&1 %s | 
FileCheck -check-prefix=avx2 %s
 // avx2: invalid /arch: argument
 
-// RUN: %clang_cl -m32 -arch:AVX512F --target=i386-pc-windows /c /Fo%t.obj 
-Xclang -verify -DTEST_32_ARCH_AVX512F -- %s
+// RUN: %clang_cl -m32 -arch:AVX512F --target=i386-pc-windows /c /Fo%t.obj 
-Xclang -verify=KNL1 -DTEST_32_ARCH_AVX512F -- %s

phoebewang wrote:

Why we emit warnings given no KNL/KNM feature specified?

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Phoebe Wang via cfe-commits


@@ -18,7 +18,7 @@ This test serves two purposes:
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (65):

phoebewang wrote:

The comment says we should not increase it.

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Freddy Ye via cfe-commits


@@ -69,7 +69,10 @@
 // RUN: %clang_cl -m32 -arch:avx2 --target=i386-pc-windows -### -- 2>&1 %s | 
FileCheck -check-prefix=avx2 %s
 // avx2: invalid /arch: argument
 
-// RUN: %clang_cl -m32 -arch:AVX512F --target=i386-pc-windows /c /Fo%t.obj 
-Xclang -verify -DTEST_32_ARCH_AVX512F -- %s
+// RUN: %clang_cl -m32 -arch:AVX512F --target=i386-pc-windows /c /Fo%t.obj 
-Xclang -verify=KNL1 -DTEST_32_ARCH_AVX512F -- %s

FreddyLeaf wrote:

AVX512F will be handled as "knl" in driver

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


[clang-tools-extra] 67963d3 - [include-cleaner] Fix a race issue when editing multiple files. (#76960)

2024-01-05 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-01-05T10:13:33+01:00
New Revision: 67963d384b23a2d46967b8f39ec2df3375731f4f

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

LOG: [include-cleaner] Fix a race issue when editing multiple files. (#76960)

We have a previous fix
https://github.com/llvm/llvm-project/commit/be861b64d94198230d8f9889b17280e3cd215a0a,
which snapshots all processing files.

It works most of times, the snapshot (InMemoryFileSystem) is based on
the file path. The file-path-based lookup can fail in a subtle way for
some tricky cases (we encounter it internally), which will result in
reading a corrupted file.

This is a different fix, we don't modify files on the fly, instead, we
write files when the tool finishes for all files.

Added: 


Modified: 
clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp 
b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
index 30aaee29b9a397..e078bfae66c3b5 100644
--- a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -16,10 +16,10 @@
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
-#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/raw_ostream.h"
@@ -110,14 +110,16 @@ format::FormatStyle getStyle(llvm::StringRef Filename) {
 
 class Action : public clang::ASTFrontendAction {
 public:
-  Action(llvm::function_ref HeaderFilter)
-  : HeaderFilter(HeaderFilter){};
+  Action(llvm::function_ref HeaderFilter,
+ llvm::StringMap &EditedFiles)
+  : HeaderFilter(HeaderFilter), EditedFiles(EditedFiles) {}
 
 private:
   RecordedAST AST;
   RecordedPP PP;
   PragmaIncludes PI;
   llvm::function_ref HeaderFilter;
+  llvm::StringMap &EditedFiles;
 
   bool BeginInvocation(CompilerInstance &CI) override {
 // We only perform include-cleaner analysis. So we disable diagnostics that
@@ -181,17 +183,8 @@ class Action : public clang::ASTFrontendAction {
   }
 }
 
-if (Edit && (!Results.Missing.empty() || !Results.Unused.empty())) {
-  if (auto Err = llvm::writeToOutput(
-  Path, [&](llvm::raw_ostream &OS) -> llvm::Error {
-OS << Final;
-return llvm::Error::success();
-  })) {
-llvm::errs() << "Failed to apply edits to " << Path << ": "
- << toString(std::move(Err)) << "\n";
-++Errors;
-  }
-}
+if (!Results.Missing.empty() || !Results.Unused.empty())
+  EditedFiles.try_emplace(Path, Final);
   }
 
   void writeHTML() {
@@ -215,11 +208,17 @@ class ActionFactory : public 
tooling::FrontendActionFactory {
   : HeaderFilter(HeaderFilter) {}
 
   std::unique_ptr create() override {
-return std::make_unique(HeaderFilter);
+return std::make_unique(HeaderFilter, EditedFiles);
+  }
+
+  const llvm::StringMap &editedFiles() const {
+return EditedFiles;
   }
 
 private:
   llvm::function_ref HeaderFilter;
+  // Map from file name to final code with the include edits applied.
+  llvm::StringMap EditedFiles;
 };
 
 std::function headerFilter() {
@@ -274,21 +273,26 @@ int main(int argc, const char **argv) {
 
   clang::tooling::ClangTool Tool(OptionsParser->getCompilations(),
  OptionsParser->getSourcePathList());
-  std::vector> Buffers;
-  for (const auto &File : OptionsParser->getSourcePathList()) {
-auto Content = llvm::MemoryBuffer::getFile(File);
-if (!Content) {
-  llvm::errs() << "Error: can't read file '" << File
-   << "': " << Content.getError().message() << "\n";
-  return 1;
-}
-Buffers.push_back(std::move(Content.get()));
-Tool.mapVirtualFile(File, Buffers.back()->getBuffer());
-  }
 
   auto HeaderFilter = headerFilter();
   if (!HeaderFilter)
 return 1; // error already reported.
   ActionFactory Factory(HeaderFilter);
-  return Tool.run(&Factory) || Errors != 0;
+  auto ErrorCode = Tool.run(&Factory);
+  if (Edit) {
+for (const auto &NameAndContent : Factory.editedFiles()) {
+  llvm::StringRef FileName = NameAndContent.first();
+  const std::string &FinalCode = NameAndContent.second;
+  if (auto Err = llvm::writeToOutput(
+  FileName, [&](llvm::raw_ostream &OS) -> llvm::Error {
+OS << FinalCode;
+return llvm::Error::success();
+  })) {
+llvm::errs() << "Failed to apply edits to " << Fi

[clang-tools-extra] [include-cleaner] Fix a race issue when editing multiple files. (PR #76960)

2024-01-05 Thread Haojian Wu via cfe-commits

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Freddy Ye via cfe-commits


@@ -18,7 +18,7 @@ This test serves two purposes:
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (65):

FreddyLeaf wrote:

Emm, seems like increased six months ago: https://reviews.llvm.org/D154251.

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


[lldb] [clang] [llvm] [libcxx] [clang-tools-extra] [mlir] [openmp] [SEH] Fix register liveness verification for EHa (PR #76933)

2024-01-05 Thread Phoebe Wang via cfe-commits


@@ -3347,10 +3348,37 @@ void MachineVerifier::verifyLiveRangeSegment(const 
LiveRange &LR,
 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
   }
 
+  bool IsEHa = MF->getMMI().getModule()->getModuleFlag("eh-asynch");
   while (true) {
 assert(LiveInts->isLiveInToMBB(LR, &*MFI));
-// We don't know how to track physregs into a landing pad.
-if (!Reg.isVirtual() && MFI->isEHPad()) {
+auto IsSEHHandler = [](const MachineBasicBlock &Handler) -> bool {
+  if (!Handler.isMachineBlockAddressTaken())
+return false;
+
+  for (const User *U : Handler.getBasicBlock()->users()) {
+if (!isa(U))
+  continue;
+const Function *Fn = cast(U)->getCalledFunction();
+if (!Fn || !Fn->isIntrinsic())
+  continue;
+
+switch (Fn->getIntrinsicID()) {
+default:
+  continue;
+case Intrinsic::seh_scope_begin:
+case Intrinsic::seh_scope_end:
+case Intrinsic::seh_try_begin:
+case Intrinsic::seh_try_end:
+  return true;
+}
+  }
+  return false;
+};
+
+// TODO: we don't know how to track physregs into a landing pad. For async
+// EH, the virtual reg lives before scope begin, but we don't know seh 
scope

phoebewang wrote:

I once had an idea to lower them into pseudo instructions. But maybe need more 
work to do.

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Freddy Ye via cfe-commits


@@ -18,7 +18,7 @@ This test serves two purposes:
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (65):

FreddyLeaf wrote:

Will fix

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Phoebe Wang via cfe-commits


@@ -18,7 +18,7 @@ This test serves two purposes:
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (65):

phoebewang wrote:

Maybe it's not a good example. The test is to prevent adding warnings without 
-W flags. I think we also need the flag here for user to mask the warning.

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Freddy Ye via cfe-commits


@@ -18,7 +18,7 @@ This test serves two purposes:
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (65):

FreddyLeaf wrote:

agree. Will add a warning group. sorry for misleading info above.

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


[clang] [X86] Emit Warnings for frontend options to enable knl/knm specific ISAs. (PR #75580)

2024-01-05 Thread Freddy Ye via cfe-commits

https://github.com/FreddyLeaf updated 
https://github.com/llvm/llvm-project/pull/75580

>From e16afbdc9f0c04bad0e8f80f90c0eb26c13d3326 Mon Sep 17 00:00:00 2001
From: Freddy Ye 
Date: Fri, 15 Dec 2023 16:50:23 +0800
Subject: [PATCH 1/7] [X86] Emit Warnings for frontend options to enable
 knl/knm.

Since Knight Landing and Knight Mill microarchitectures are EOL, we
would like to remove its support in LLVM 19. In LLVM 18, we will first
emit a warning for the usage.
---
 clang/include/clang/Basic/DiagnosticCommonKinds.td |  2 ++
 clang/lib/Basic/Targets/X86.cpp|  3 +++
 clang/test/CodeGen/X86/avx512er-builtins.c |  2 +-
 clang/test/CodeGen/X86/avx512pf-builtins.c |  2 +-
 clang/test/Driver/cl-x86-flags.c   | 10 --
 clang/test/Frontend/x86-target-cpu.c   | 10 --
 clang/test/Misc/warning-flags.c|  3 ++-
 7 files changed, 25 insertions(+), 7 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index 65a33f61a6948a..40841e9df547bc 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -349,6 +349,8 @@ def warn_invalid_feature_combination : Warning<
 def warn_target_unrecognized_env : Warning<
   "mismatch between architecture and environment in target triple '%0'; did 
you mean '%1'?">,
   InGroup;
+def warn_knl_knm_target_supports_remove : Warning<
+  "KNL/KNM's feature support will be removed in LLVM 19.">;
 
 // Source manager
 def err_cannot_open_file : Error<"cannot open file '%0': %1">, DefaultFatal;
diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index b97f88647fa49f..dc56524d378104 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -295,11 +295,13 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasAVX512BF16 = true;
 } else if (Feature == "+avx512er") {
   HasAVX512ER = true;
+  Diags.Report(diag::warn_knl_knm_target_supports_remove);
 } else if (Feature == "+avx512fp16") {
   HasAVX512FP16 = true;
   HasLegalHalfType = true;
 } else if (Feature == "+avx512pf") {
   HasAVX512PF = true;
+  Diags.Report(diag::warn_knl_knm_target_supports_remove);
 } else if (Feature == "+avx512dq") {
   HasAVX512DQ = true;
 } else if (Feature == "+avx512bitalg") {
@@ -358,6 +360,7 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector &Features,
   HasPREFETCHI = true;
 } else if (Feature == "+prefetchwt1") {
   HasPREFETCHWT1 = true;
+  Diags.Report(diag::warn_knl_knm_target_supports_remove);
 } else if (Feature == "+clzero") {
   HasCLZERO = true;
 } else if (Feature == "+cldemote") {
diff --git a/clang/test/CodeGen/X86/avx512er-builtins.c 
b/clang/test/CodeGen/X86/avx512er-builtins.c
index ee31236a3c01aa..11ec6aabec1e3f 100644
--- a/clang/test/CodeGen/X86/avx512er-builtins.c
+++ b/clang/test/CodeGen/X86/avx512er-builtins.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -flax-vector-conversions=none -ffreestanding %s 
-triple=x86_64-apple-darwin -target-feature +avx512f -target-feature +avx512er 
-emit-llvm -o - -Wall -Werror | FileCheck %s
+// RUN: %clang_cc1 -flax-vector-conversions=none -ffreestanding %s 
-triple=x86_64-apple-darwin -target-feature +avx512f -target-feature +avx512er 
-emit-llvm -o - -Wall | FileCheck %s
 
 
 #include 
diff --git a/clang/test/CodeGen/X86/avx512pf-builtins.c 
b/clang/test/CodeGen/X86/avx512pf-builtins.c
index 4ca70f5787968b..3a117ed6a9460e 100644
--- a/clang/test/CodeGen/X86/avx512pf-builtins.c
+++ b/clang/test/CodeGen/X86/avx512pf-builtins.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -flax-vector-conversions=none -ffreestanding %s 
-triple=x86_64-apple-darwin -target-feature +avx512pf -emit-llvm -o - -Wall 
-Werror | FileCheck %s
+// RUN: %clang_cc1 -flax-vector-conversions=none -ffreestanding %s 
-triple=x86_64-apple-darwin -target-feature +avx512pf -emit-llvm -o - -Wall | 
FileCheck %s
 
 
 #include 
diff --git a/clang/test/Driver/cl-x86-flags.c b/clang/test/Driver/cl-x86-flags.c
index 51b16f0ce35463..ae35a312fe8a4b 100644
--- a/clang/test/Driver/cl-x86-flags.c
+++ b/clang/test/Driver/cl-x86-flags.c
@@ -69,7 +69,10 @@
 // RUN: %clang_cl -m32 -arch:avx2 --target=i386-pc-windows -### -- 2>&1 %s | 
FileCheck -check-prefix=avx2 %s
 // avx2: invalid /arch: argument
 
-// RUN: %clang_cl -m32 -arch:AVX512F --target=i386-pc-windows /c /Fo%t.obj 
-Xclang -verify -DTEST_32_ARCH_AVX512F -- %s
+// RUN: %clang_cl -m32 -arch:AVX512F --target=i386-pc-windows /c /Fo%t.obj 
-Xclang -verify=KNL1 -DTEST_32_ARCH_AVX512F -- %s
+// KNL1-warning@*:* {{KNL/KNM's feature support will be removed in LLVM 19.}}
+// KNL1-warning@*:* {{KNL/KNM's feature support will be removed in LLVM 19.}}
+// KNL1-warning@*:* {{KNL/KNM's feature support will be removed in LLVM 19.}}
 #if defined(TEST_32_ARCH_AVX512F)
 #if _M_IX86_FP !=

[lldb] [openmp] [compiler-rt] [libcxx] [llvm] [libc] [flang] [clang-tools-extra] [mlir] [clang] [libc++][span] P2821R5: `span.at()` (PR #74994)

2024-01-05 Thread Hristo Hristov via cfe-commits

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


[lldb] [openmp] [compiler-rt] [libcxx] [llvm] [libc] [flang] [lld] [clang-tools-extra] [mlir] [clang] [libc++][streams] P1759R6: Native handles and file streams (PR #76632)

2024-01-05 Thread Hristo Hristov via cfe-commits

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


[clang] [clang-format] Break after string literals with trailing line breaks (PR #76795)

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


@@ -5151,6 +5151,14 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 return true;
   if (Left.IsUnterminatedLiteral)
 return true;
+  // FIXME: Breaking after newlines seems useful in general. Turn this into an
+  // option and Recognize more cases like endl etc, and break independent of
+  // what comes after operator lessless.
+  if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) &&
+  Right.Next->is(tok::string_literal) &&

owenca wrote:

```suggestion
  // option and recognize more cases like endl etc, and break independent of
  // what comes after operator lessless.
  if (Right.is(tok::lessless) && Right.Next &&
  Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) &&
```

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


[clang] [clang-format] Break after string literals with trailing line breaks (PR #76795)

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


@@ -2499,6 +2499,15 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
   EXPECT_BRACE_KIND(Tokens[6], BK_Block);
 }
 
+TEST_F(TokenAnnotatorTest, StreamOperator) {
+  auto Tokens = annotate("\"foo\\n\" << aux << \"foo\\n\" << \"foo\";");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_FALSE(Tokens[1]->MustBreakBefore);
+  EXPECT_FALSE(Tokens[3]->MustBreakBefore);
+  // Only break between string literals if the former ends with \n.
+  EXPECT_TRUE(Tokens[5]->MustBreakBefore);
+}
+

owenca wrote:

Can you delete this test or move it to FormatTest.cpp?

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-05 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 created https://github.com/llvm/llvm-project/pull/77066

This came up in the discussion with seastar folks on RFC
Fixes https://github.com/llvm/llvm-project/issues/76995

>From 3e0d0ab6c4fc6cba68285816a95e423bc18e8e55 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 5 Jan 2024 10:11:20 +0100
Subject: [PATCH] [coroutines] Detect lifetime issues with coroutine lambda
 captures

---
 clang/lib/Sema/SemaInit.cpp   | 20 +--
 clang/test/SemaCXX/coro-lifetimebound.cpp | 64 +--
 2 files changed, 76 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 60c0e3e74204ec..c100bf11454786 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -12,6 +12,7 @@
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
@@ -33,6 +34,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -7575,15 +7577,27 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
 Path.pop_back();
   };
 
-  if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
-VisitLifetimeBoundArg(Callee, ObjectArg);
-
   bool CheckCoroCall = false;
   if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
 CheckCoroCall = RD->hasAttr() &&
 RD->hasAttr() &&
 !Callee->hasAttr();
   }
+
+  if (ObjectArg) {
+bool CheckCoroObjArg = CheckCoroCall;
+// Ignore `__promise.get_return_object()` as it not lifetimebound.
+if (Callee->getDeclName().isIdentifier() &&
+Callee->getName() == "get_return_object")
+  CheckCoroObjArg = false;
+// Coroutine lambda objects with empty capture list are not lifetimebound.
+if (auto *LE = dyn_cast(ObjectArg->IgnoreImplicit());
+LE && LE->captures().empty())
+  CheckCoroObjArg = false;
+if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
+  VisitLifetimeBoundArg(Callee, ObjectArg);
+  }
+
   for (unsigned I = 0,
 N = std::min(Callee->getNumParams(), Args.size());
I != N; ++I) {
diff --git a/clang/test/SemaCXX/coro-lifetimebound.cpp 
b/clang/test/SemaCXX/coro-lifetimebound.cpp
index 3fc7ca70a14a12..319134450e4b6f 100644
--- a/clang/test/SemaCXX/coro-lifetimebound.cpp
+++ b/clang/test/SemaCXX/coro-lifetimebound.cpp
@@ -64,6 +64,10 @@ Co bar_coro(const int &b, int c) {
   : bar_coro(0, 1); // expected-warning {{returning address of local 
temporary object}}
 }
 
+// 
=
+// Lambdas
+// 
=
+namespace lambdas {
 void lambdas() {
   auto unsafe_lambda = [] [[clang::coro_wrapper]] (int b) {
 return foo_coro(b); // expected-warning {{address of stack memory 
associated with parameter}}
@@ -84,15 +88,47 @@ void lambdas() {
 co_return x + co_await foo_coro(b);
   };
 }
+
+Co lambda_captures() {
+  int a = 1;
+  // Temporary lambda object dies.
+  auto lamb = [a](int x, const int& y) -> Co { // expected-warning 
{{temporary whose address is used as value of local variable 'lamb'}}
+co_return x + y + a;
+  }(1, a);
+  // Object dies but it has no capture.
+  auto no_capture = []() -> Co { co_return 1; }();
+  auto bad_no_capture = [](const int& a) -> Co { co_return a; }(1); // 
expected-warning {{temporary}}
+  // Temporary lambda object with lifetime extension under co_await.
+  int res = co_await [a](int x, const int& y) -> Co {
+co_return x + y + a;
+  }(1, a);
+  co_return 1;
+}
+} // namespace lambdas
+
 // 
=
-// Safe usage when parameters are value
+// Member coroutines
 // 
=
-namespace by_value {
-Co value_coro(int b) { co_return co_await foo_coro(b); }
-[[clang::coro_wrapper]] Co wrapper1(int b) { return value_coro(b); }
-[[clang::coro_wrapper]] Co wrapper2(const int& b) { return value_coro(b); 
}
+namespace member_coroutines{
+struct S {
+  Co member(const int& a) { co_return a; }  
+};
+
+Co use() {
+  S s;
+  int a = 1;
+  auto test1 = s.member(1);  // expected-warning {{temporary whose address is 
used as value of local variable}}
+  auto test2 = s.member(a);
+  auto test3 = S{}.member(a);  // expected-warning {{temporary whose address 
is used as value of local variable}}
+  co_return 1;
 }
 
+[[clang::coro_wrapper]] Co wrapper(const int& a) {
+  S s;
+  return s.member(a); // expected-warning {{address of stack memory}}
+}
+} // member_coroutines
+
 // 

[clang] [clang-scan-deps] Fix check for empty `Compilation` (PR #75545)

2024-01-05 Thread via cfe-commits

Yaraslaut wrote:

ping

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


[clang] 0eefcaf - [Clang][SME] Add IsStreamingOrSVE2p1 (#76975)

2024-01-05 Thread via cfe-commits

Author: Sam Tebbs
Date: 2024-01-05T09:55:50Z
New Revision: 0eefcaf96d2900a4f3009026a3673ed3b7793fcc

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

LOG: [Clang][SME] Add IsStreamingOrSVE2p1 (#76975)

This patch adds IsStreamingOrSVE2p1 to the applicable builtins and a
warning for when those builtins are not used in a streaming or sve2p1
function.

Added: 
clang/test/Sema/aarch64-sme2-sve2p1-diagnostics.c

Modified: 
clang/include/clang/Basic/arm_sve.td
clang/include/clang/Basic/arm_sve_sme_incl.td
clang/lib/Basic/Targets/AArch64.h
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_bfmlsl.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_cntp.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_fclamp.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_ld1.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_pext.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_pfalse.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_psel.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_sclamp.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_stnt1.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_uclamp.c
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_while_pn.c
clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_imm.cpp
clang/utils/TableGen/SveEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 91f62c4c76339d..7f80fb0386cc77 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1976,39 +1976,37 @@ def SVFMINQV: SInst<"svminqv[_{d}]", "{Pd", "hfd", 
MergeNone, "aarch64_sve_fminq
 }
 
 let TargetGuard = "sve2p1|sme2" in {
-//FIXME: Replace IsStreamingCompatible with IsStreamingOrHasSVE2p1 when 
available
-def SVPEXT_SINGLE : SInst<"svpext_lane_{d}", "P}i", "QcQsQiQl", MergeNone, 
"aarch64_sve_pext", [IsStreamingCompatible], [ImmCheck<1, ImmCheck0_3>]>;
-def SVPEXT_X2 : SInst<"svpext_lane_{d}_x2", "2.P}i", "QcQsQiQl", 
MergeNone, "aarch64_sve_pext_x2", [IsStreamingCompatible], [ImmCheck<1, 
ImmCheck0_1>]>;
+def SVPEXT_SINGLE : SInst<"svpext_lane_{d}", "P}i", "QcQsQiQl", MergeNone, 
"aarch64_sve_pext", [IsStreamingOrSVE2p1], [ImmCheck<1, ImmCheck0_3>]>;
+def SVPEXT_X2 : SInst<"svpext_lane_{d}_x2", "2.P}i", "QcQsQiQl", 
MergeNone, "aarch64_sve_pext_x2", [IsStreamingOrSVE2p1], [ImmCheck<1, 
ImmCheck0_1>]>;
 
-def SVWHILEGE_COUNT  : SInst<"svwhilege_{d}[_{1}]",  "}lli", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilege_{d}", [IsOverloadNone], [ImmCheck<2, 
ImmCheck2_4_Mul2>]>;
-def SVWHILEGT_COUNT  : SInst<"svwhilegt_{d}[_{1}]",  "}lli", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilegt_{d}", [IsOverloadNone], [ImmCheck<2, 
ImmCheck2_4_Mul2>]>;
-def SVWHILELE_COUNT  : SInst<"svwhilele_{d}[_{1}]",  "}lli", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilele_{d}", [IsOverloadNone], [ImmCheck<2, 
ImmCheck2_4_Mul2>]>;
-def SVWHILELT_COUNT  : SInst<"svwhilelt_{d}[_{1}]",  "}lli", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilelt_{d}", [IsOverloadNone], [ImmCheck<2, 
ImmCheck2_4_Mul2>]>;
-def SVWHILELO_COUNT  : SInst<"svwhilelt_{d}[_{1}]",  "}nni", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilelo_{d}", [IsOverloadNone], [ImmCheck<2, 
ImmCheck2_4_Mul2>]>;
-def SVWHILELS_COUNT  : SInst<"svwhilele_{d}[_{1}]",  "}nni", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilels_{d}", [IsOverloadNone], [ImmCheck<2, 
ImmCheck2_4_Mul2>]>;
-def SVWHILEHI_COUNT  : SInst<"svwhilegt_{d}[_{1}]",  "}nni", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilehi_{d}", [IsOverloadNone], [ImmCheck<2, 
ImmCheck2_4_Mul2>]>;
-def SVWHILEHS_COUNT  : SInst<"svwhilege_{d}[_{1}]",  "}nni", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilehs_{d}", [IsOverloadNone], [ImmCheck<2, 
ImmCheck2_4_Mul2>]>;
+def SVWHILEGE_COUNT  : SInst<"svwhilege_{d}[_{1}]",  "}lli", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilege_{d}", [IsOverloadNone, IsStreamingOrSVE2p1], 
[ImmCheck<2, ImmCheck2_4_Mul2>]>;
+def SVWHILEGT_COUNT  : SInst<"svwhilegt_{d}[_{1}]",  "}lli", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilegt_{d}", [IsOverloadNone, IsStreamingOrSVE2p1], 
[ImmCheck<2, ImmCheck2_4_Mul2>]>;
+def SVWHILELE_COUNT  : SInst<"svwhilele_{d}[_{1}]",  "}lli", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilele_{d}", [IsOverloadNone, IsStreamingOrSVE2p1], 
[ImmCheck<2, ImmCheck2_4_Mul2>]>;
+def SVWHILELT_COUNT  : SInst<"svwhilelt_{d}[_{1}]",  "}lli", "QcQsQiQl", 
MergeNone, "aarch64_sve_whilelt_{d}", [IsOverloadNone, IsStreamingOrSVE2p1], 
[ImmCheck<2, ImmCheck2_4_Mul2>]>;
+def SVWHILELO_COUNT  : SInst<"svwhilelt_{d}[_{1}]",  "}nni", "QcQsQiQl", 
MergeNone, "aar

[clang] [Clang][SME] Add IsStreamingOrSVE2p1 (PR #76975)

2024-01-05 Thread Sam Tebbs via cfe-commits

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


[libcxxabi] [lldb] [compiler-rt] [mlir] [flang] [libc] [clang-tools-extra] [llvm] [libcxx] [lld] [clang] [libc++][ranges] Implement ranges::contains_subrange (PR #66963)

2024-01-05 Thread Hristo Hristov via cfe-commits

H-G-Hristov wrote:

Just a gentle reminder. You should probably also update the release notes, the 
status page and the feature test macro: `#define __cpp_lib_ranges_contains 
20L // also in `

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-05 Thread Utkarsh Saxena via cfe-commits

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


[clang] [NFC][clang][test][asan] Make `instantiation-depth-default.cpp` a valid test case under `asan` and `ubsan` configs (PR #75254)

2024-01-05 Thread via cfe-commits

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

LGTM!

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-05 Thread Utkarsh Saxena via cfe-commits

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


[clang] c458f92 - [NFC][clang][test][asan] Make `instantiation-depth-default.cpp` a valid test case under `asan` and `ubsan` configs (#75254)

2024-01-05 Thread via cfe-commits

Author: Duo Wang
Date: 2024-01-05T09:59:26Z
New Revision: c458f928fad7bbcf08ab1da9949eb2969fc9f89c

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

LOG: [NFC][clang][test][asan] Make `instantiation-depth-default.cpp` a valid 
test case under `asan` and `ubsan` configs (#75254)

Clang test `instantiation-depth-default.cpp` fails on Windows when built
with `ubsan` due to extra warnings printed by the compiler:
```console
File instantiation-depth-default.cpp Line 11: stack nearly exhausted; 
compilation time may suffer, and crashes due to stack overflow are likely
```
The test case was disabled for `asan` in 571a647 because of the extra
stack usage. Since `ubsan` also increases stack usage, seems like the
two configs should be treated uniformly.

On the other hand, we might be able to re-enable this test case for
`asan`. During some preliminary testing on Windows, Linux, and macOS
with the host compiler being as old as clang-10, the test case exited
successfully if the `stack-exhausted` warnings are suppressed, though I
haven't done exhaustive testing across platforms and clang versions. Any
insights into whether this change will introduce any risks to existing
buildbots is appreciated.

Enabling this test case for `asan` helps to improve our test coverage,
but if it causes problems on any buildbot, marking it as unsupported for
`ubsan` is also a viable solution.

Added: 


Modified: 
clang/test/SemaTemplate/instantiation-depth-default.cpp

Removed: 




diff  --git a/clang/test/SemaTemplate/instantiation-depth-default.cpp 
b/clang/test/SemaTemplate/instantiation-depth-default.cpp
index f5835b86b3a385..430d042d7e0f49 100644
--- a/clang/test/SemaTemplate/instantiation-depth-default.cpp
+++ b/clang/test/SemaTemplate/instantiation-depth-default.cpp
@@ -1,18 +1,12 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-backtrace-limit=2 %s
-//
-// FIXME: Disable this test when Clang was built with ASan, because ASan
-// increases our per-frame stack usage enough that this test no longer fits
-// within our normal stack space allocation.
-// UNSUPPORTED: asan
-//
+// RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-backtrace-limit=2 %if 
{{asan|ubsan}} %{ -Wno-stack-exhausted %} %s
 // The default stack size on NetBSD is too small for this test.
 // UNSUPPORTED: system-netbsd
 
 template struct X : X {};
-// expected-error-re@11 {{recursive template instantiation exceeded maximum 
depth of 1024{{$
-// expected-note@11 {{instantiation of template class}}
-// expected-note@11 {{skipping 1023 contexts in backtrace}}
-// expected-note@11 {{use -ftemplate-depth=N to increase recursive template 
instantiation depth}}
+// expected-error-re@5 {{recursive template instantiation exceeded maximum 
depth of 1024{{$
+// expected-note@5 {{instantiation of template class}}
+// expected-note@5 {{skipping 1023 contexts in backtrace}}
+// expected-note@5 {{use -ftemplate-depth=N to increase recursive template 
instantiation depth}}
 
 X<0, int> x; // expected-note {{in instantiation of}}
 



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


[clang] [NFC][clang][test][asan] Make `instantiation-depth-default.cpp` a valid test case under `asan` and `ubsan` configs (PR #75254)

2024-01-05 Thread via cfe-commits

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


[clang] [clang] Correctly implement CWG 2672 (PR #75001)

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

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

>From 8681b3c9f5e19b6ae977321d5d4154113273c2a0 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 12 Nov 2023 13:21:03 +0800
Subject: [PATCH 1/2] [clang] Correctly implement CWG 2672

This is a follow-up patch for [D156993](https://reviews.llvm.org/D156993),
that marks only the lambda body as non-immediate context.

Fixes https://github.com/llvm/llvm-project/issues/71684
---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 11 +---
 clang/lib/Sema/TreeTransform.h|  7 +
 clang/test/CXX/drs/dr26xx.cpp |  2 +-
 .../expr.prim.lambda/default-arguments.cpp|  6 ++--
 .../expr.prim/expr.prim.lambda/p11-1y.cpp |  2 --
 .../expr/expr.prim/expr.prim.lambda/p23.cpp   |  1 -
 .../expr/expr.prim/expr.prim.lambda/p4.cpp|  3 +-
 clang/test/CXX/temp/temp.deduct/p9.cpp|  8 ++
 clang/test/SemaCXX/cxx1y-init-captures.cpp|  8 +++---
 clang/test/SemaCXX/cxx1z-lambda-star-this.cpp |  4 +--
 clang/test/SemaCXX/lambda-expressions.cpp |  4 +--
 clang/test/SemaCXX/lambda-pack-expansion.cpp  |  1 -
 clang/test/SemaCXX/vartemplate-lambda.cpp |  1 -
 .../SemaCXX/warn-unused-lambda-capture.cpp| 28 +--
 .../SemaTemplate/instantiate-local-class.cpp  |  4 +--
 15 files changed, 37 insertions(+), 53 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index df6b40999e645c..88bd44f7d6934d 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -35,7 +35,6 @@
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateDeduction.h"
 #include "clang/Sema/TemplateInstCallback.h"
-#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TimeProfiler.h"
@@ -1142,8 +1141,7 @@ std::optional 
Sema::isSFINAEContext() const {
 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
   // We're either substituting explicitly-specified template arguments,
   // deduced template arguments. SFINAE applies unless we are in a lambda
-  // expression, see [temp.deduct]p9.
-  [[fallthrough]];
+  // body, see [temp.deduct]p9.
 case CodeSynthesisContext::ConstraintSubstitution:
 case CodeSynthesisContext::RequirementInstantiation:
 case CodeSynthesisContext::RequirementParameterInstantiation:
@@ -1444,13 +1442,6 @@ namespace {
   LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
   Sema::ConstraintEvalRAII RAII(*this);
 
-  Sema::CodeSynthesisContext C;
-  C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
-  C.PointOfInstantiation = E->getBeginLoc();
-  SemaRef.pushCodeSynthesisContext(C);
-  auto PopCtx =
-  llvm::make_scope_exit([this] { SemaRef.popCodeSynthesisContext(); });
-
   ExprResult Result = inherited::TransformLambdaExpr(E);
   if (Result.isInvalid())
 return Result;
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 1ad843d0bf4e0c..55e5c3c9dedc56 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -13648,10 +13648,17 @@ 
TreeTransform::TransformLambdaExpr(LambdaExpr *E) {
   getSema().PushExpressionEvaluationContext(
   Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
 
+  Sema::CodeSynthesisContext C;
+  C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
+  C.PointOfInstantiation = E->getBody()->getBeginLoc();
+  getSema().pushCodeSynthesisContext(C);
+
   // Instantiate the body of the lambda expression.
   StmtResult Body =
   Invalid ? StmtError() : getDerived().TransformLambdaBody(E, 
E->getBody());
 
+  getSema().popCodeSynthesisContext();
+
   // ActOnLambda* will pop the function scope for us.
   FuncScopeCleanup.disable();
 
diff --git a/clang/test/CXX/drs/dr26xx.cpp b/clang/test/CXX/drs/dr26xx.cpp
index dd4bb1ff6ae2e1..8a22dbeb98a3d5 100644
--- a/clang/test/CXX/drs/dr26xx.cpp
+++ b/clang/test/CXX/drs/dr26xx.cpp
@@ -211,7 +211,7 @@ void f(...);
 
 template 
 void bar(T) requires requires {
-   decltype([]() -> T {})::foo();
+   []() -> decltype(T::foo()) {};
 };
 void bar(...);
 
diff --git 
a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp 
b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
index c5d08ec404a7c3..72265d77700aaf 100644
--- a/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
+++ b/clang/test/CXX/expr/expr.prim/expr.prim.lambda/default-arguments.cpp
@@ -35,8 +35,7 @@ struct NoDefaultCtor {
 template
 void defargs_in_template_unused(T t) {
   auto l1 = [](const T& value = T()) { };  // expected-error{{no matching 
constructor for initialization of 'NoDefaultCtor'}} \
-   // expected-note {{in instantiation 
of defa

[clang] [clang] Correctly implement CWG 2672 (PR #75001)

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

zyn0217 wrote:

Thank you folks!

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


[clang] [X86] Add ABI handling for __float128 (PR #75156)

2024-01-05 Thread Simon Pilgrim via cfe-commits

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

LGTM - please mention in the commit message + release notes that this matches 
GCC behaviour

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


[libc] [compiler-rt] [clang] [llvm] [clang-tools-extra] [flang] [libcxx] [clang] Accept recursive non-dependent calls to functions with deduced return type (PR #75456)

2024-01-05 Thread Mariya Podchishchaeva via cfe-commits

https://github.com/Fznamznon updated 
https://github.com/llvm/llvm-project/pull/75456

>From 0e190f131862dd8f4b07891c3ee712a0a163f936 Mon Sep 17 00:00:00 2001
From: "Podchishchaeva, Mariya" 
Date: Thu, 14 Dec 2023 01:33:17 -0800
Subject: [PATCH 1/2] [clang] Accept recursive non-dependent calls to functions
 with deduced return type

Treat such calls as dependent since it is much easier to implement.

Fixes https://github.com/llvm/llvm-project/issues/71015
---
 clang/docs/ReleaseNotes.rst   |  3 ++
 clang/lib/AST/ComputeDependence.cpp   |  2 ++
 clang/lib/Sema/SemaOverload.cpp   | 18 ++
 .../SemaCXX/deduced-return-type-cxx14.cpp | 33 +++
 4 files changed, 56 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 05d59d0da264f3..9ffc7500414981 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -688,6 +688,9 @@ Bug Fixes in This Version
 - Fixed false positive error emitted when templated alias inside a class
   used private members of the same class.
   Fixes (`#41693 `_)
+- Clang now accepts recursive non-dependent calls to functions with deduced 
return
+  type.
+  Fixes (`#71015 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/AST/ComputeDependence.cpp 
b/clang/lib/AST/ComputeDependence.cpp
index 097753fd3267b5..584b58473294be 100644
--- a/clang/lib/AST/ComputeDependence.cpp
+++ b/clang/lib/AST/ComputeDependence.cpp
@@ -603,6 +603,8 @@ ExprDependence clang::computeDependence(PredefinedExpr *E) {
 ExprDependence clang::computeDependence(CallExpr *E,
 llvm::ArrayRef PreArgs) {
   auto D = E->getCallee()->getDependence();
+  if (E->getType()->isDependentType())
+D |= ExprDependence::Type;
   for (auto *A : llvm::ArrayRef(E->getArgs(), E->getNumArgs())) {
 if (A)
   D |= A->getDependence();
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 5026e1d603e5ee..9fb767101e1eb7 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -13994,6 +13994,24 @@ ExprResult Sema::BuildOverloadedCallExpr(Scope *S, 
Expr *Fn,
   OverloadCandidateSet::iterator Best;
   OverloadingResult OverloadResult =
   CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
+  FunctionDecl *FDecl = Best->Function;
+
+  // Model the case with a call to a templated function whose definition
+  // encloses the call and whose return type contains a placeholder type as if
+  // the UnresolvedLookupExpr was type-dependent.
+  if (OverloadResult == OR_Success && FDecl &&
+  FDecl->isTemplateInstantiation() &&
+  FDecl->getReturnType()->isUndeducedType()) {
+if (auto TP = FDecl->getTemplateInstantiationPattern(false)) {
+  if (TP->willHaveBody()) {
+CallExpr *CE =
+CallExpr::Create(Context, Fn, Args, Context.DependentTy, 
VK_PRValue,
+ RParenLoc, CurFPFeatureOverrides());
+result = CE;
+return result;
+  }
+}
+  }
 
   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 
RParenLoc,
   ExecConfig, &CandidateSet, &Best,
diff --git a/clang/test/SemaCXX/deduced-return-type-cxx14.cpp 
b/clang/test/SemaCXX/deduced-return-type-cxx14.cpp
index 6344d1df3fbaeb..1da597499d34f5 100644
--- a/clang/test/SemaCXX/deduced-return-type-cxx14.cpp
+++ b/clang/test/SemaCXX/deduced-return-type-cxx14.cpp
@@ -640,3 +640,36 @@ namespace PR46637 {
   template struct Y { T x; };
   Y auto> y; // expected-error {{'auto' not allowed in template 
argument}}
 }
+
+namespace GH71015 {
+
+// Check that there is no error in case a templated function is recursive and
+// has a placeholder return type.
+struct Node {
+  int value;
+  Node* left;
+  Node* right;
+};
+
+bool parse(const char*);
+Node* parsePrimaryExpr();
+
+auto parseMulExpr(auto node) { // cxx14-error {{'auto' not allowed in function 
prototype}}
+  if (node == nullptr) node = parsePrimaryExpr();
+  if (!parse("*")) return node;
+  return parseMulExpr(new Node{.left = node, .right = parsePrimaryExpr()});
+}
+
+template 
+auto parseMulExpr2(T node) {
+  if (node == nullptr) node = parsePrimaryExpr();
+  if (!parse("*")) return node;
+  return parseMulExpr2(new Node{.left = node, .right = parsePrimaryExpr()});
+}
+
+auto f(auto x) { // cxx14-error {{'auto' not allowed in function prototype}}
+  if (x == 0) return 0;
+  return f(1) + 1;
+}
+
+}

>From 9981ec5663fd039cb2ddfc00ae8f1468f2b56d61 Mon Sep 17 00:00:00 2001
From: "Podchishchaeva, Mariya" 
Date: Thu, 4 Jan 2024 02:23:33 -0800
Subject: [PATCH 2/2] Add a testcase

---
 clang/test/SemaCXX/deduced-return-type-cxx14.cpp | 15 ++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/clang/test/SemaCXX/deduced-return-typ

[clang] [clang][analyzer] Add missing stream related functions to StdCLibraryFunctionsChecker. (PR #76979)

2024-01-05 Thread Balazs Benics via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 


steakhal wrote:

Why do we need to keep these two checkers in-sync?

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


[clang] [clang]Transform uninstantiated ExceptionSpec in `TemplateInstantiator` (PR #77073)

2024-01-05 Thread Congcong Cai via cfe-commits

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

Fixes: #77071
`SubstituteDeducedTypeTransform` will transform type and it will visit 
uninstantiated `ExceptionSpecInfo`, which will cause odd behavior

>From 04ef8fd566491024c8163ad3b901f8c4cebaf890 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 5 Jan 2024 18:15:24 +0800
Subject: [PATCH] [clang]Transform uninstantiated ExceptionSpec in
 TemplateInstantiator

Fixes: #77071
SubstituteDeducedTypeTransform will transform type and it will visit 
uninstantiated ExceptionSpecInfo which will odd behavior
---
 clang/docs/ReleaseNotes.rst   |  3 ++-
 clang/include/clang/AST/Type.h|  2 ++
 clang/lib/AST/Type.cpp|  7 +++
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 11 +++
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  4 +---
 .../SemaCXX/dependent-noexcept-uninstantiated.cpp |  4 +++-
 6 files changed, 26 insertions(+), 5 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ee211c16a48ac8..f750587ad12271 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -607,7 +607,8 @@ Bug Fixes in This Version
 - Clang will correctly evaluate ``noexcept`` expression for template functions
   of template classes. Fixes
   (`#68543 `_,
-  `#42496 `_)
+  `#42496 `_,
+  `#77071 `_)
 - Fixed an issue when a shift count larger than ``__INT64_MAX__``, in a right
   shift operation, could result in missing warnings about
   ``shift count >= width of type`` or internal compiler error.
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index b3ae66e6e769d0..0fcf331dd79bc6 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -4228,6 +4228,8 @@ class FunctionProtoType final
 ExceptionSpecInfo() = default;
 
 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
+
+void instantiate();
   };
 
   /// Extra information about a function prototype. ExtProtoInfo is not
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 160a725939ccd4..a894d3289eb185 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -3414,6 +3414,13 @@ StringRef FunctionType::getNameForCallConv(CallingConv 
CC) {
   llvm_unreachable("Invalid calling convention.");
 }
 
+void FunctionProtoType::ExceptionSpecInfo::instantiate() {
+  assert(Type == EST_Uninstantiated);
+  NoexceptExpr =
+  cast(SourceTemplate->getType())->getNoexceptExpr();
+  Type = EST_DependentNoexcept;
+}
+
 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef 
params,
  QualType canonical,
  const ExtProtoInfo &epi)
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 699e0985e595b6..015b0abaf0e5ee 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -4737,6 +4737,7 @@ namespace {
 QualType Replacement;
 bool ReplacementIsPack;
 bool UseTypeSugar;
+using inherited = TreeTransform;
 
   public:
 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
@@ -4797,6 +4798,16 @@ namespace {
   // Lambdas never need to be transformed.
   return E;
 }
+bool TransformExceptionSpec(SourceLocation Loc,
+FunctionProtoType::ExceptionSpecInfo &ESI,
+SmallVectorImpl &Exceptions,
+bool &Changed) {
+  if (ESI.Type == EST_Uninstantiated) {
+ESI.instantiate();
+Changed = true;
+  }
+  return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
+}
 
 QualType Apply(TypeLoc TL) {
   // Create some scratch storage for the transformed type locations.
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index df6b40999e645c..2c452404459a5d 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1630,9 +1630,7 @@ bool TemplateInstantiator::TransformExceptionSpec(
 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
 SmallVectorImpl &Exceptions, bool &Changed) {
   if (ESI.Type == EST_Uninstantiated) {
-ESI.NoexceptExpr = cast(ESI.SourceTemplate->getType())
-   ->getNoexceptExpr();
-ESI.Type = EST_DependentNoexcept;
+ESI.instantiate();
 Changed = true;
   }
   return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
diff --git a/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp 
b/clang/test/SemaC

[clang] [clang]Transform uninstantiated ExceptionSpec in `TemplateInstantiator` (PR #77073)

2024-01-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #77071
`SubstituteDeducedTypeTransform` will transform type and it will visit 
uninstantiated `ExceptionSpecInfo`, which will cause odd behavior

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


6 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2-1) 
- (modified) clang/include/clang/AST/Type.h (+2) 
- (modified) clang/lib/AST/Type.cpp (+7) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+11) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+1-3) 
- (modified) clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp (+3-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ee211c16a48ac8..f750587ad12271 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -607,7 +607,8 @@ Bug Fixes in This Version
 - Clang will correctly evaluate ``noexcept`` expression for template functions
   of template classes. Fixes
   (`#68543 `_,
-  `#42496 `_)
+  `#42496 `_,
+  `#77071 `_)
 - Fixed an issue when a shift count larger than ``__INT64_MAX__``, in a right
   shift operation, could result in missing warnings about
   ``shift count >= width of type`` or internal compiler error.
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index b3ae66e6e769d0..0fcf331dd79bc6 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -4228,6 +4228,8 @@ class FunctionProtoType final
 ExceptionSpecInfo() = default;
 
 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
+
+void instantiate();
   };
 
   /// Extra information about a function prototype. ExtProtoInfo is not
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 160a725939ccd4..a894d3289eb185 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -3414,6 +3414,13 @@ StringRef FunctionType::getNameForCallConv(CallingConv 
CC) {
   llvm_unreachable("Invalid calling convention.");
 }
 
+void FunctionProtoType::ExceptionSpecInfo::instantiate() {
+  assert(Type == EST_Uninstantiated);
+  NoexceptExpr =
+  cast(SourceTemplate->getType())->getNoexceptExpr();
+  Type = EST_DependentNoexcept;
+}
+
 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef 
params,
  QualType canonical,
  const ExtProtoInfo &epi)
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 699e0985e595b6..015b0abaf0e5ee 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -4737,6 +4737,7 @@ namespace {
 QualType Replacement;
 bool ReplacementIsPack;
 bool UseTypeSugar;
+using inherited = TreeTransform;
 
   public:
 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
@@ -4797,6 +4798,16 @@ namespace {
   // Lambdas never need to be transformed.
   return E;
 }
+bool TransformExceptionSpec(SourceLocation Loc,
+FunctionProtoType::ExceptionSpecInfo &ESI,
+SmallVectorImpl &Exceptions,
+bool &Changed) {
+  if (ESI.Type == EST_Uninstantiated) {
+ESI.instantiate();
+Changed = true;
+  }
+  return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
+}
 
 QualType Apply(TypeLoc TL) {
   // Create some scratch storage for the transformed type locations.
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index df6b40999e645c..2c452404459a5d 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1630,9 +1630,7 @@ bool TemplateInstantiator::TransformExceptionSpec(
 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
 SmallVectorImpl &Exceptions, bool &Changed) {
   if (ESI.Type == EST_Uninstantiated) {
-ESI.NoexceptExpr = cast(ESI.SourceTemplate->getType())
-   ->getNoexceptExpr();
-ESI.Type = EST_DependentNoexcept;
+ESI.instantiate();
 Changed = true;
   }
   return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
diff --git a/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp 
b/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp
index ddb26989022753..3821f18e7bf276 100644
--- a/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp
+++ b/clang/test/SemaCXX/dependent-noexcept-uninstantiated.cpp
@@ -6,6 +6,8 @@ using B = char;
 
 template  struct C {
   template  void f0() noexcept(sizeof(T) == sizeof(A) && sizeof(V) == 
sizeof(B)) {}
+  te

[clang] [llvm] [libcxx] "Reapply "[Sema] Fix crash on invalid code with parenthesized aggrega… (PR #76833)

2024-01-05 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

> It's not ideal, but I can't think of a better solution. Typically nightly apt 
> builds are built nightly so then we can update the Docker CI quickly. If the 
> nightly builds are red it might take a bit longer.
> The patch is in draft since I wanted to test with the bootstrap build which 
> required temporary disabling other builds (the second commit). When the CI is 
> green I'll do a final review and publish the patch.

It's been 2 days, maybe we should just submit this and see if anything goes 
wrong?
Besides, the CI seems green now, so hopefully everything has already been 
checked.

> > In the long-term, how should people land changes like this? Compiler 
> > diagnostics are expected to change sometimes, so we should figure out some 
> > way that allows landing these without reverts. Any thoughts?
> 
> Typically we work together with whom changes the tests. When there are libc++ 
> changes it is visible in our review queue. For changes in diagnostics it's 
> often possible to use a regex matcher. For example, the messages of 
> `static_asserts` changed a while back. In general we prefer to minimize the 
> tests depending on the compiler diagnostics.

This use-case is different, we need a way to change the set of reported 
diagnostics in Clang even if the diagnostic is produced in libc++ tests. 
Blocking changes to Clang because libc++ tests against nightly and head builds 
looks too harsh.

I think we need to find some alternative solution that works here. The obvious 
solution that I see is to run the nightly Clang as post-submits and allow them 
to be broken for this reasons (as it will fix itself after nightly Clang gets 
rebuilt).

@AaronBallman, @cor3ntin what are your thoughts as Clang maintainers? TLDR; is 
that libc++ runs tests in CI with both head Clang and nightly Clang builds. 
Therefore, if we happen to change the set of reported diagnostics in Clang (in 
this case it was a spurious error in initialization of invalid classes that got 
silenced with a Clang change), we cannot land this change without breaking the 
libc++ CI.

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


[clang] [clang]Transform uninstantiated ExceptionSpec in `TemplateInstantiator` (PR #77073)

2024-01-05 Thread Congcong Cai via cfe-commits

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


[clang] [CLANG][NFC] Modify test cases to suit assigned default sysroot path (PR #77075)

2024-01-05 Thread via cfe-commits

https://github.com/Yunzezhu94 created 
https://github.com/llvm/llvm-project/pull/77075

When using cmake with option -DDEFAULT_SYSROOT, a default sysroot path is 
assigned. 
However, some test cases use a relative path to indicate sysroot path, but the 
path goes wrong with default sysroot path assigned. 
This patch modified test cases to make them use correct sysroot path.

>From e04fa94a98b71e729885b0544add053127180f7d Mon Sep 17 00:00:00 2001
From: Yunze Zhu 
Date: Fri, 5 Jan 2024 17:11:26 +0800
Subject: [PATCH] [CLANG][NFC] Modify test cases to suit assigned default
 sysroot path

When using cmake with option -DDEFAULT_SYSROOT, a default sysroot path is 
assigned.
However, some test cases use a relative path to indicate sysroot path,
but the path goes wrong with default sysroot path assigned.
This patch modified test cases to make them use correct sysroot path.
---
 clang/test/Driver/baremetal.cpp | 10 +-
 clang/test/Driver/csky-toolchain.c  |  4 ++--
 clang/test/Driver/freebsd-include-paths.c   |  4 ++--
 clang/test/Driver/haiku.c   |  2 +-
 clang/test/Driver/hexagon-toolchain-linux.c |  2 ++
 clang/test/Driver/riscv32-toolchain-extra.c |  1 +
 clang/test/Driver/riscv64-toolchain-extra.c |  1 +
 clang/test/Driver/solaris-ld.c  |  2 +-
 8 files changed, 15 insertions(+), 11 deletions(-)

diff --git a/clang/test/Driver/baremetal.cpp b/clang/test/Driver/baremetal.cpp
index c04f4506a0994d..03d0fbcc76fd1c 100644
--- a/clang/test/Driver/baremetal.cpp
+++ b/clang/test/Driver/baremetal.cpp
@@ -157,7 +157,7 @@
 // RUN: %clang -### %s --target=aarch64_be-none-elf -mlittle-endian 
--sysroot=%S/Inputs/baremetal_arm 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-AARCH64LE %s
 
-// RUN: %clang -no-canonical-prefixes %s -### --target=aarch64-none-elf 2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=aarch64-none-elf 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-AARCH64-NO-HOST-INC %s
 // Verify that the bare metal driver does not include any host system paths:
 // CHECK-AARCH64-NO-HOST-INC: InstalledDir: [[INSTALLEDDIR:.+]]
@@ -385,7 +385,7 @@
 // CHECK-RV32IMAFC-SAME: 
"-L[[SYSROOT:[^"]+]]{{[/\\]+}}rv32imafc{{[/\\]+}}ilp32f{{[/\\]+}}lib"
 // CHECK-RV32IMAFC-SAME: 
"-L[[RESOURCE_DIR:[^"]+]]{{[/\\]+}}lib{{[/\\]+}}baremetal{{[/\\]+}}rv32imafc{{[/\\]+}}ilp32f"
 
-// RUN: %clang -no-canonical-prefixes %s -### --target=powerpc-unknown-eabi 
2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=powerpc-unknown-eabi 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPCEABI %s
 // CHECK-PPCEABI: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-PPCEABI: "-nostdsysteminc"
@@ -398,7 +398,7 @@
 // CHECK-PPCEABI-SAME: "-L[[RESOURCE]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-PPCEABI-SAME: "-lc" "-lm" "-lclang_rt.builtins-powerpc" "-o" "a.out"
 
-// RUN: %clang -no-canonical-prefixes %s -### --target=powerpc64-unknown-eabi 
2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=powerpc64-unknown-eabi 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPC64EABI %s
 // CHECK-PPC64EABI: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-PPC64EABI: "-nostdsysteminc"
@@ -411,7 +411,7 @@
 // CHECK-PPC64EABI-SAME: "-L[[RESOURCE]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-PPC64EABI-SAME: "-lc" "-lm" "-lclang_rt.builtins-powerpc64" "-o" 
"a.out"
 
-// RUN: %clang -no-canonical-prefixes %s -### --target=powerpcle-unknown-eabi 
2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=powerpcle-unknown-eabi 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPCLEEABI %s
 // CHECK-PPCLEEABI: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-PPCLEEABI: "-nostdsysteminc"
@@ -424,7 +424,7 @@
 // CHECK-PPCLEEABI-SAME: "-L[[RESOURCE]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-PPCLEEABI-SAME: "-lc" "-lm" "-lclang_rt.builtins-powerpcle" "-o" 
"a.out"
 
-// RUN: %clang -no-canonical-prefixes %s -### 
--target=powerpc64le-unknown-eabi 2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=powerpc64le-unknown-eabi 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPC64LEEABI %s
 // CHECK-PPC64LEEABI: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-PPC64LEEABI: "-nostdsysteminc"
diff --git a/clang/test/Driver/csky-toolchain.c 
b/clang/test/Driver/csky-toolchain.c
index 66485464652ac8..557feeeb1d1d38 100644
--- a/clang/test/Driver/csky-toolchain.c
+++ b/clang/test/Driver/csky-toolchain.c
@@ -7,7 +7,7 @@
 // In the below tests, --rtlib=platform is used so that the driver ignores
 // the configure-time CLANG_DEFAULT_RTLIB option when choosing the runtime lib
 
-// RUN: %clang -### %s -fuse-ld=ld -no-pie --target=csky-unknown-linux-gnu 
--rtlib=platform --unwindlib=platform \
+// RUN: %clang -### %s -fuse-ld=ld -no-pie --target=csky-unknown-linux-gnu 
--rtlib=platform --sysroot="" --unwindlib=platform \
 // RUN:   --gcc-toolchain=%S/Inputs/multilib_csky_linux_sdk  2>&1 | FileCheck 
-check-prefix=C

[clang] [CLANG][NFC] Modify test cases to suit assigned default sysroot path (PR #77075)

2024-01-05 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-backend-risc-v

Author: None (Yunzezhu94)


Changes

When using cmake with option -DDEFAULT_SYSROOT, a default sysroot path is 
assigned. 
However, some test cases use a relative path to indicate sysroot path, but the 
path goes wrong with default sysroot path assigned. 
This patch modified test cases to make them use correct sysroot path.

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


8 Files Affected:

- (modified) clang/test/Driver/baremetal.cpp (+5-5) 
- (modified) clang/test/Driver/csky-toolchain.c (+2-2) 
- (modified) clang/test/Driver/freebsd-include-paths.c (+2-2) 
- (modified) clang/test/Driver/haiku.c (+1-1) 
- (modified) clang/test/Driver/hexagon-toolchain-linux.c (+2) 
- (modified) clang/test/Driver/riscv32-toolchain-extra.c (+1) 
- (modified) clang/test/Driver/riscv64-toolchain-extra.c (+1) 
- (modified) clang/test/Driver/solaris-ld.c (+1-1) 


``diff
diff --git a/clang/test/Driver/baremetal.cpp b/clang/test/Driver/baremetal.cpp
index c04f4506a0994d..03d0fbcc76fd1c 100644
--- a/clang/test/Driver/baremetal.cpp
+++ b/clang/test/Driver/baremetal.cpp
@@ -157,7 +157,7 @@
 // RUN: %clang -### %s --target=aarch64_be-none-elf -mlittle-endian 
--sysroot=%S/Inputs/baremetal_arm 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-AARCH64LE %s
 
-// RUN: %clang -no-canonical-prefixes %s -### --target=aarch64-none-elf 2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=aarch64-none-elf 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-AARCH64-NO-HOST-INC %s
 // Verify that the bare metal driver does not include any host system paths:
 // CHECK-AARCH64-NO-HOST-INC: InstalledDir: [[INSTALLEDDIR:.+]]
@@ -385,7 +385,7 @@
 // CHECK-RV32IMAFC-SAME: 
"-L[[SYSROOT:[^"]+]]{{[/\\]+}}rv32imafc{{[/\\]+}}ilp32f{{[/\\]+}}lib"
 // CHECK-RV32IMAFC-SAME: 
"-L[[RESOURCE_DIR:[^"]+]]{{[/\\]+}}lib{{[/\\]+}}baremetal{{[/\\]+}}rv32imafc{{[/\\]+}}ilp32f"
 
-// RUN: %clang -no-canonical-prefixes %s -### --target=powerpc-unknown-eabi 
2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=powerpc-unknown-eabi 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPCEABI %s
 // CHECK-PPCEABI: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-PPCEABI: "-nostdsysteminc"
@@ -398,7 +398,7 @@
 // CHECK-PPCEABI-SAME: "-L[[RESOURCE]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-PPCEABI-SAME: "-lc" "-lm" "-lclang_rt.builtins-powerpc" "-o" "a.out"
 
-// RUN: %clang -no-canonical-prefixes %s -### --target=powerpc64-unknown-eabi 
2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=powerpc64-unknown-eabi 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPC64EABI %s
 // CHECK-PPC64EABI: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-PPC64EABI: "-nostdsysteminc"
@@ -411,7 +411,7 @@
 // CHECK-PPC64EABI-SAME: "-L[[RESOURCE]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-PPC64EABI-SAME: "-lc" "-lm" "-lclang_rt.builtins-powerpc64" "-o" 
"a.out"
 
-// RUN: %clang -no-canonical-prefixes %s -### --target=powerpcle-unknown-eabi 
2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=powerpcle-unknown-eabi 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPCLEEABI %s
 // CHECK-PPCLEEABI: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-PPCLEEABI: "-nostdsysteminc"
@@ -424,7 +424,7 @@
 // CHECK-PPCLEEABI-SAME: "-L[[RESOURCE]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-PPCLEEABI-SAME: "-lc" "-lm" "-lclang_rt.builtins-powerpcle" "-o" 
"a.out"
 
-// RUN: %clang -no-canonical-prefixes %s -### 
--target=powerpc64le-unknown-eabi 2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --sysroot="" 
--target=powerpc64le-unknown-eabi 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPC64LEEABI %s
 // CHECK-PPC64LEEABI: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-PPC64LEEABI: "-nostdsysteminc"
diff --git a/clang/test/Driver/csky-toolchain.c 
b/clang/test/Driver/csky-toolchain.c
index 66485464652ac8..557feeeb1d1d38 100644
--- a/clang/test/Driver/csky-toolchain.c
+++ b/clang/test/Driver/csky-toolchain.c
@@ -7,7 +7,7 @@
 // In the below tests, --rtlib=platform is used so that the driver ignores
 // the configure-time CLANG_DEFAULT_RTLIB option when choosing the runtime lib
 
-// RUN: %clang -### %s -fuse-ld=ld -no-pie --target=csky-unknown-linux-gnu 
--rtlib=platform --unwindlib=platform \
+// RUN: %clang -### %s -fuse-ld=ld -no-pie --target=csky-unknown-linux-gnu 
--rtlib=platform --sysroot="" --unwindlib=platform \
 // RUN:   --gcc-toolchain=%S/Inputs/multilib_csky_linux_sdk  2>&1 | FileCheck 
-check-prefix=C-CSKY-LINUX-MULTI %s
 
 // C-CSKY-LINUX-MULTI: 
"{{.*}}/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/../../..{{/|}}..{{/|}}csky-linux-gnuabiv2/bin{{/|}}ld"
@@ -23,7 +23,7 @@
 // C-CSKY-LINUX-MULTI: 
"-L{{.*}}/Inputs/multilib_csky_linux_sdk/lib/gcc/csky-linux-gnuabiv2/6.3.0/../../..{{/|}}..{{/|}}csky-linux-gnuabiv2/libc/lib"
 // C-CSKY-LINUX-MULTI: 
"-

[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-05 Thread Utkarsh Saxena via cfe-commits

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-05 Thread Utkarsh Saxena via cfe-commits

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Utkarsh Saxena (usx95)


Changes

### Problem

```cpp
co_task coro() {
int a = 1;
auto lamb = [a]() -> co_task {
co_return a; // 'a' in the lambda object dies after the iniital_suspend 
in the lambda coroutine.
}();
co_return co_await lamb;
}
```
[use-after-free](https://godbolt.org/z/GWPEovWWc)

Lambda captures (even by value) are prone to use-after-free once the lambda 
object dies. In the above example, the lambda object appears only as a 
temporary in the call expression. It dies after the first suspension 
(`initial_suspend`) in the lambda.
On resumption in `co_await lamb`, the lambda accesses `a` which is part of the 
already-dead lambda object.

---

### Solution

This problem can be formulated by saying that the `this` parameter of the 
lambda call operator is a lifetimebound parameter. The lambda object argument 
should therefore live atleast as long as the return object.
That said, this requirement does not hold if the lambda does not have a capture 
list. In principle, the coroutine frame still has a reference to a dead lambda 
object, but it is easy to see that the object would not be used in the 
lambda-coroutine body due to no capture list.

Using this pattern inside a`co_await` expression due to the lifetime extension 
of temporaries. Example:

```cpp
co_task coro() {
int a = 1;
int res = co_await [a]() -> co_task { co_return a; }();
co_return res;
}
```
---
### Background

This came up in the discussion with seastar folks on 
[RFC](https://discourse.llvm.org/t/rfc-lifetime-bound-check-for-parameters-of-coroutines/74253/19?u=usx95).
 This is a fairly common pattern in continuation-style-passing (CSP) async 
programming involving futures and continuations. Document ["Lambda coroutine 
fiasco"](https://github.com/scylladb/seastar/blob/master/doc/lambda-coroutine-fiasco.md)
 by Seastar captures the problem.
This pattern makes the migration from CSP-style async programming to coroutines 
very bugprone.


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

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaInit.cpp (+17-3) 
- (modified) clang/test/SemaCXX/coro-lifetimebound.cpp (+59-5) 


``diff
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 60c0e3e74204ec..c100bf11454786 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -12,6 +12,7 @@
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
@@ -33,6 +34,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -7575,15 +7577,27 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
 Path.pop_back();
   };
 
-  if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
-VisitLifetimeBoundArg(Callee, ObjectArg);
-
   bool CheckCoroCall = false;
   if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
 CheckCoroCall = RD->hasAttr() &&
 RD->hasAttr() &&
 !Callee->hasAttr();
   }
+
+  if (ObjectArg) {
+bool CheckCoroObjArg = CheckCoroCall;
+// Ignore `__promise.get_return_object()` as it not lifetimebound.
+if (Callee->getDeclName().isIdentifier() &&
+Callee->getName() == "get_return_object")
+  CheckCoroObjArg = false;
+// Coroutine lambda objects with empty capture list are not lifetimebound.
+if (auto *LE = dyn_cast(ObjectArg->IgnoreImplicit());
+LE && LE->captures().empty())
+  CheckCoroObjArg = false;
+if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
+  VisitLifetimeBoundArg(Callee, ObjectArg);
+  }
+
   for (unsigned I = 0,
 N = std::min(Callee->getNumParams(), Args.size());
I != N; ++I) {
diff --git a/clang/test/SemaCXX/coro-lifetimebound.cpp 
b/clang/test/SemaCXX/coro-lifetimebound.cpp
index 3fc7ca70a14a12..319134450e4b6f 100644
--- a/clang/test/SemaCXX/coro-lifetimebound.cpp
+++ b/clang/test/SemaCXX/coro-lifetimebound.cpp
@@ -64,6 +64,10 @@ Co bar_coro(const int &b, int c) {
   : bar_coro(0, 1); // expected-warning {{returning address of local 
temporary object}}
 }
 
+// 
=
+// Lambdas
+// 
=
+namespace lambdas {
 void lambdas() {
   auto unsafe_lambda = [] [[clang::coro_wrapper]] (int b) {
 return foo_coro(b); // expected-warning {{address of stack memory 
associated with parameter}}
@@ -84,15 +88,47 @@ void lambdas() {
 co_return x + co

[clang] [clang-tools-extra] [libunwind] [lldb] [libc] [compiler-rt] [libcxx] [flang] [llvm] [libc++] Implement ranges::iota (PR #68494)

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


@@ -0,0 +1,123 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// Testing std::ranges::iota
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+#include "test_iterators.h"
+#include "almost_satisfies_types.h"
+
+// Concepts to check different overloads of std::ranges::iota
+template 
+concept HasIotaIter = requires(Iter&& iter, Sent&& sent, Value&& val) {
+  std::ranges::iota(std::forward(iter), std::forward(sent), 
std::forward(val));
+};
+
+template 
+concept HasIotaRange =
+requires(Range&& range, Value&& val) { 
std::ranges::iota(std::forward(range), std::forward(val)); };
+
+constexpr void test_constraints() {
+  // Test constraints of the iterator/sentinel overload
+  // ==
+  static_assert(HasIotaIter);
+
+  // !input_or_output_iterator
+  static_assert(!HasIotaIter);
+
+  // !sentinel_for
+  static_assert(!HasIotaIter);
+  static_assert(!HasIotaIter);
+
+  // !weakly_incrementable
+  static_assert(!HasIotaIter);
+
+  // !indirectly writable 
+  static_assert(!HasIotaIter);
+
+  // Test constraints for the range overload
+  // ===
+  static_assert(HasIotaRange, int>);
+
+  // !weakly_incrementable
+  static_assert(!HasIotaRange, 
WeaklyIncrementableNotMovable>);
+
+  // !ranges::output_range
+  static_assert(!HasIotaRange, 
OutputIteratorNotIndirectlyWritable>);
+}
+
+template 
+constexpr void test_result(std::array input, int starting_value, 
std::array const expected) {
+  { // (iterator, sentinel) overload
+auto in_begin = Iter(input.data());
+auto in_end   = Sent(Iter(input.data() + input.size()));
+std::same_as> decltype(auto) 
result =
+std::ranges::iota(std::move(in_begin), std::move(in_end), 
starting_value);
+assert(result.out == in_end);
+if constexpr (expected.size() > 0) {
+  assert(result.value == expected.back() + 1);
+} else {
+  assert(result.value == starting_value);
+}
+assert(std::ranges::equal(input, expected));
+  }
+
+  // The range overload adds the additional constraint that it must be an 
outputrange
+  // so skip this for the input iterators we test
+  if constexpr (!std::is_same_v> &&
+!std::is_same_v>) { // 
(range) overload

philnik777 wrote:

I don't think this is required. They should both qualify as output iterators.

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


[compiler-rt] [clang] [libc] [llvm] [libcxx] [clang-tools-extra] [lldb] [flang] [libunwind] [libc++] Implement ranges::iota (PR #68494)

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


@@ -0,0 +1,123 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// Testing std::ranges::iota
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+#include "test_iterators.h"
+#include "almost_satisfies_types.h"
+
+// Concepts to check different overloads of std::ranges::iota
+template 
+concept HasIotaIter = requires(Iter&& iter, Sent&& sent, Value&& val) {
+  std::ranges::iota(std::forward(iter), std::forward(sent), 
std::forward(val));
+};
+
+template 
+concept HasIotaRange =
+requires(Range&& range, Value&& val) { 
std::ranges::iota(std::forward(range), std::forward(val)); };
+
+constexpr void test_constraints() {
+  // Test constraints of the iterator/sentinel overload
+  // ==
+  static_assert(HasIotaIter);
+
+  // !input_or_output_iterator
+  static_assert(!HasIotaIter);
+
+  // !sentinel_for
+  static_assert(!HasIotaIter);
+  static_assert(!HasIotaIter);
+
+  // !weakly_incrementable
+  static_assert(!HasIotaIter);
+
+  // !indirectly writable 
+  static_assert(!HasIotaIter);
+
+  // Test constraints for the range overload
+  // ===
+  static_assert(HasIotaRange, int>);
+
+  // !weakly_incrementable
+  static_assert(!HasIotaRange, 
WeaklyIncrementableNotMovable>);
+
+  // !ranges::output_range
+  static_assert(!HasIotaRange, 
OutputIteratorNotIndirectlyWritable>);
+}
+
+template 
+constexpr void test_result(std::array input, int starting_value, 
std::array const expected) {
+  { // (iterator, sentinel) overload
+auto in_begin = Iter(input.data());
+auto in_end   = Sent(Iter(input.data() + input.size()));
+std::same_as> decltype(auto) 
result =
+std::ranges::iota(std::move(in_begin), std::move(in_end), 
starting_value);
+assert(result.out == in_end);
+if constexpr (expected.size() > 0) {
+  assert(result.value == expected.back() + 1);
+} else {
+  assert(result.value == starting_value);
+}
+assert(std::ranges::equal(input, expected));
+  }
+
+  // The range overload adds the additional constraint that it must be an 
outputrange
+  // so skip this for the input iterators we test
+  if constexpr (!std::is_same_v> &&
+!std::is_same_v>) { // 
(range) overload
+auto in_begin = Iter(input.data());
+auto in_end   = Sent(Iter(input.data() + input.size()));
+auto range= std::ranges::subrange(std::move(in_begin), 
std::move(in_end));
+
+std::same_as> decltype(auto) 
result =
+std::ranges::iota(range, starting_value);
+assert(result.out == in_end);
+if constexpr (expected.size() > 0) {
+  assert(result.value == expected.back() + 1);
+} else {
+  assert(result.value == starting_value);
+}
+assert(std::ranges::equal(input, expected));
+  }
+}
+
+template >
+constexpr void test_results() {
+  // Empty
+  test_result({}, 0, {});
+  // 1-element sequence
+  test_result({1}, 0, {0});
+  // Longer sequence
+  test_result({1, 2, 3, 4, 5}, 0, {0, 1, 2, 3, 4});
+}
+
+void test_results() {
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results();
+}
+

philnik777 wrote:

I'd also like to see a test with a non-fundamental type, and especially one 
that behaves differently when it's `const` to test the `std::as_const` in the 
loop.

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


[libunwind] [libc] [compiler-rt] [llvm] [clang] [lldb] [clang-tools-extra] [flang] [libcxx] [libc++] Implement ranges::iota (PR #68494)

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


@@ -46,7 +46,7 @@
 "`P2255R2 `__","LWG","A type trait to detect 
reference binding to temporary","February 2022","",""
 "`P2273R3 `__","LWG","Making ``std::unique_ptr`` 
constexpr","February 2022","|Complete|","16.0"
 "`P2387R3 `__","LWG","Pipe support for user-defined 
range adaptors","February 2022","","","|ranges|"
-"`P2440R1 `__","LWG","``ranges::iota``, 
``ranges::shift_left`` and ``ranges::shift_right``","February 
2022","","","|ranges|"
+"`P2440R1 `__","LWG","``ranges::iota``, 
``ranges::shift_left`` and ``ranges::shift_right``","February 2022","|In 
progress|","","|ranges|"

philnik777 wrote:

Please also add a note in `libcxx/docs/Status/Cxx23.rst` which states what 
parts are currently implemented.

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


[clang] [compiler-rt] [libunwind] [flang] [llvm] [libcxx] [libc] [lldb] [clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

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


@@ -0,0 +1,123 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// Testing std::ranges::iota
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+#include "test_iterators.h"
+#include "almost_satisfies_types.h"
+
+// Concepts to check different overloads of std::ranges::iota
+template 
+concept HasIotaIter = requires(Iter&& iter, Sent&& sent, Value&& val) {
+  std::ranges::iota(std::forward(iter), std::forward(sent), 
std::forward(val));
+};
+
+template 
+concept HasIotaRange =
+requires(Range&& range, Value&& val) { 
std::ranges::iota(std::forward(range), std::forward(val)); };
+
+constexpr void test_constraints() {
+  // Test constraints of the iterator/sentinel overload
+  // ==
+  static_assert(HasIotaIter);
+
+  // !input_or_output_iterator
+  static_assert(!HasIotaIter);
+
+  // !sentinel_for
+  static_assert(!HasIotaIter);
+  static_assert(!HasIotaIter);
+
+  // !weakly_incrementable
+  static_assert(!HasIotaIter);
+
+  // !indirectly writable 
+  static_assert(!HasIotaIter);
+
+  // Test constraints for the range overload
+  // ===
+  static_assert(HasIotaRange, int>);
+
+  // !weakly_incrementable
+  static_assert(!HasIotaRange, 
WeaklyIncrementableNotMovable>);
+
+  // !ranges::output_range
+  static_assert(!HasIotaRange, 
OutputIteratorNotIndirectlyWritable>);
+}
+
+template 
+constexpr void test_result(std::array input, int starting_value, 
std::array const expected) {
+  { // (iterator, sentinel) overload
+auto in_begin = Iter(input.data());
+auto in_end   = Sent(Iter(input.data() + input.size()));
+std::same_as> decltype(auto) 
result =
+std::ranges::iota(std::move(in_begin), std::move(in_end), 
starting_value);
+assert(result.out == in_end);
+if constexpr (expected.size() > 0) {
+  assert(result.value == expected.back() + 1);
+} else {
+  assert(result.value == starting_value);
+}
+assert(std::ranges::equal(input, expected));
+  }
+
+  // The range overload adds the additional constraint that it must be an 
outputrange
+  // so skip this for the input iterators we test
+  if constexpr (!std::is_same_v> &&
+!std::is_same_v>) { // 
(range) overload
+auto in_begin = Iter(input.data());
+auto in_end   = Sent(Iter(input.data() + input.size()));
+auto range= std::ranges::subrange(std::move(in_begin), 
std::move(in_end));
+
+std::same_as> decltype(auto) 
result =
+std::ranges::iota(range, starting_value);
+assert(result.out == in_end);
+if constexpr (expected.size() > 0) {
+  assert(result.value == expected.back() + 1);
+} else {
+  assert(result.value == starting_value);
+}
+assert(std::ranges::equal(input, expected));
+  }
+}
+
+template >
+constexpr void test_results() {
+  // Empty
+  test_result({}, 0, {});
+  // 1-element sequence
+  test_result({1}, 0, {0});
+  // Longer sequence
+  test_result({1, 2, 3, 4, 5}, 0, {0, 1, 2, 3, 4});
+}
+
+void test_results() {
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results>();
+  test_results();

philnik777 wrote:

```suggestion
  types::for_each(types::cpp20_input_iterator_list{}, [] { 
test_results(); });
  test_results>();
  test_results>();
```
You should also test with different sentinel types.

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


[clang-tools-extra] [libcxx] [libunwind] [lldb] [clang] [compiler-rt] [libc] [flang] [llvm] [libc++] Implement ranges::iota (PR #68494)

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


@@ -0,0 +1,123 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// Testing std::ranges::iota
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+#include "test_iterators.h"
+#include "almost_satisfies_types.h"
+
+// Concepts to check different overloads of std::ranges::iota
+template 
+concept HasIotaIter = requires(Iter&& iter, Sent&& sent, Value&& val) {
+  std::ranges::iota(std::forward(iter), std::forward(sent), 
std::forward(val));
+};
+
+template 
+concept HasIotaRange =
+requires(Range&& range, Value&& val) { 
std::ranges::iota(std::forward(range), std::forward(val)); };
+
+constexpr void test_constraints() {

philnik777 wrote:

These test don't need to be inside a function. You can just put them at global 
scope. Otherwise they look really nice.

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


[compiler-rt] [clang] [flang] [libunwind] [libc] [clang-tools-extra] [llvm] [libcxx] [lldb] [libc++] Implement ranges::iota (PR #68494)

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


@@ -13,7 +13,7 @@
 // Range algorithms should return `std::ranges::dangling` when given a 
dangling range.
 

philnik777 wrote:

The formatting changes in here are nice, but would be better handled in a 
separate PR, just to make it clear what actually changed.

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


[lldb] [libunwind] [libcxx] [llvm] [libc] [compiler-rt] [clang-tools-extra] [flang] [clang] [libc++] Implement ranges::iota (PR #68494)

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


@@ -0,0 +1,123 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// Testing std::ranges::iota
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+#include 
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+#include "test_iterators.h"
+#include "almost_satisfies_types.h"
+
+// Concepts to check different overloads of std::ranges::iota
+template 
+concept HasIotaIter = requires(Iter&& iter, Sent&& sent, Value&& val) {
+  std::ranges::iota(std::forward(iter), std::forward(sent), 
std::forward(val));
+};
+
+template 
+concept HasIotaRange =
+requires(Range&& range, Value&& val) { 
std::ranges::iota(std::forward(range), std::forward(val)); };
+
+constexpr void test_constraints() {
+  // Test constraints of the iterator/sentinel overload
+  // ==
+  static_assert(HasIotaIter);
+
+  // !input_or_output_iterator
+  static_assert(!HasIotaIter);
+
+  // !sentinel_for
+  static_assert(!HasIotaIter);
+  static_assert(!HasIotaIter);
+
+  // !weakly_incrementable
+  static_assert(!HasIotaIter);
+
+  // !indirectly writable 
+  static_assert(!HasIotaIter);
+
+  // Test constraints for the range overload
+  // ===
+  static_assert(HasIotaRange, int>);
+
+  // !weakly_incrementable
+  static_assert(!HasIotaRange, 
WeaklyIncrementableNotMovable>);
+
+  // !ranges::output_range
+  static_assert(!HasIotaRange, 
OutputIteratorNotIndirectlyWritable>);
+}
+
+template 
+constexpr void test_result(std::array input, int starting_value, 
std::array const expected) {
+  { // (iterator, sentinel) overload
+auto in_begin = Iter(input.data());
+auto in_end   = Sent(Iter(input.data() + input.size()));
+std::same_as> decltype(auto) 
result =
+std::ranges::iota(std::move(in_begin), std::move(in_end), 
starting_value);
+assert(result.out == in_end);
+if constexpr (expected.size() > 0) {
+  assert(result.value == expected.back() + 1);
+} else {
+  assert(result.value == starting_value);
+}
+assert(std::ranges::equal(input, expected));
+  }
+
+  // The range overload adds the additional constraint that it must be an 
outputrange
+  // so skip this for the input iterators we test
+  if constexpr (!std::is_same_v> &&
+!std::is_same_v>) { // 
(range) overload
+auto in_begin = Iter(input.data());
+auto in_end   = Sent(Iter(input.data() + input.size()));
+auto range= std::ranges::subrange(std::move(in_begin), 
std::move(in_end));
+
+std::same_as> decltype(auto) 
result =
+std::ranges::iota(range, starting_value);
+assert(result.out == in_end);
+if constexpr (expected.size() > 0) {
+  assert(result.value == expected.back() + 1);
+} else {
+  assert(result.value == starting_value);
+}

philnik777 wrote:

```suggestion
assert(result.value == starting_value + N);
```
I think this should be equivalent.

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-05 Thread Utkarsh Saxena via cfe-commits

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


[llvm] [clang-tools-extra] [clang] [AMDGPU][GFX12] Default component broadcast store (PR #76212)

2024-01-05 Thread Jay Foad via cfe-commits

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

LGTM. @arsenm does this address your concerns?

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


[clang] [clang] Disable missing definition warning on pure virtual functions (PR #74510)

2024-01-05 Thread Charalampos Mitrodimas via cfe-commits

https://github.com/charmitro updated 
https://github.com/llvm/llvm-project/pull/74510

>From f60f12f8e4e8b70a8fdf2aa9398b94849a863fff Mon Sep 17 00:00:00 2001
From: Charalampos Mitrodimas 
Date: Tue, 5 Dec 2023 11:46:56 +0200
Subject: [PATCH] [clang] Disable missing definition warning on pure virtual
 functions

Warning '-Wundefined-func-template' incorrectly indicates that no
definition is available for a pure virtual function. However, a
definition is not needed for a pure virtual function.

Fixes #74016

Signed-off-by: Charalampos Mitrodimas 
---
 clang/docs/ReleaseNotes.rst   |  3 +
 clang/lib/Sema/SemaExpr.cpp   |  2 +-
 .../instantiate-pure-virtual-function.cpp | 67 +++
 3 files changed, 71 insertions(+), 1 deletion(-)
 create mode 100644 
clang/test/SemaTemplate/instantiate-pure-virtual-function.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ce7599ad34beaf..858248f3cce896 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -531,6 +531,9 @@ Improvements to Clang's time-trace
 
 Bug Fixes in This Version
 -
+- Clang's ``-Wundefined-func-template`` no longer warns on pure virtual
+  functions.
+  (`#74016 `_)
 - Fixed an issue where a class template specialization whose declaration is
   instantiated in one module and whose definition is instantiated in another
   module may end up with members associated with the wrong declaration of the
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 960f513db2..43b266ec07dd35 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18931,7 +18931,7 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
   //   constant evaluated
   bool NeededForConstantEvaluation =
   isPotentiallyConstantEvaluatedContext(*this) &&
-  isImplicitlyDefinableConstexprFunction(Func);
+  isImplicitlyDefinableConstexprFunction(Func) && !Func->isPure();
 
   // Determine whether we require a function definition to exist, per
   // C++11 [temp.inst]p3:
diff --git a/clang/test/SemaTemplate/instantiate-pure-virtual-function.cpp 
b/clang/test/SemaTemplate/instantiate-pure-virtual-function.cpp
new file mode 100644
index 00..caec42b6b77f95
--- /dev/null
+++ b/clang/test/SemaTemplate/instantiate-pure-virtual-function.cpp
@@ -0,0 +1,67 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wundefined-func-template %s
+
+namespace GH74016 {
+  template  class B {
+  public:
+constexpr void foo(const T &) { bar(1); }
+virtual constexpr void bar(unsigned int) = 0;
+  };
+
+  template  class D : public B {
+  public:
+constexpr void bar(unsigned int) override {}
+  };
+
+  void test() {
+auto t = D();
+t.foo(0);
+  }
+};
+
+namespace call_pure_virtual_function_from_virtual {
+  template  class B {
+  public:
+const void foo(const T &) { B::bar(1); } // expected-warning 
{{instantiation of function 
'call_pure_virtual_function_from_virtual::B::bar' required here, but no 
definition is available}}
+// expected-note@-1 {{add an explicit instantiation declaration to 
suppress this warning if 'call_pure_virtual_function_from_virtual::B::bar' 
is explicitly instantiated in another translation unit}}
+virtual const void bar(unsigned int) = 0; // expected-note {{forward 
declaration of template entity is here}}
+  };
+
+  template  class D : public B {
+  public:
+const void bar(unsigned int) override {}
+  };
+
+  void test() {
+auto t = D();
+t.foo(0); // expected-note {{in instantiation of member function 
'call_pure_virtual_function_from_virtual::B::foo' requested here}}
+  }
+};
+
+namespace non_pure_virtual_function {
+  template  class B {
+  public:
+constexpr void foo(const T &) { bar(1); }
+
+virtual constexpr void bar(unsigned int); // expected-warning {{inline 
function 'non_pure_virtual_function::B::bar' is not defined}}
+// expected-note@-1 {{forward declaration of template entity is here}}
+// expected-note@-2 {{forward declaration of template entity is here}}
+// expected-note@-3 {{forward declaration of template entity is here}}
+  };
+
+  template  class D : public B { // expected-warning 
{{instantiation of function 'non_pure_virtual_function::B::bar' required 
here, but no definition is available}}
+// expected-warning@-1 {{instantiation of function 
'non_pure_virtual_function::B::bar' required here, but no definition is 
available}}
+// expected-warning@-2 {{instantiation of function 
'non_pure_virtual_function::B::bar' required here, but no definition is 
available}}
+// expected-note@-3 {{add an explicit instantiation declaration to suppress 
this warning if 'non_pure_virtual_function::B::bar' is explicitly 
instantiated in another translation unit}}
+// expected-note@-4 {{add an explicit instantiation declaration to suppress 
this warning if 'no

[clang] [Serialization] Load Specializations Lazily (1/2) (PR #76774)

2024-01-05 Thread Jonas Hahnfeld via cfe-commits


@@ -1249,3 +1249,5 @@ void ODRHash::AddQualType(QualType T) {
 void ODRHash::AddBoolean(bool Value) {
   Bools.push_back(Value);
 }
+
+void ODRHash::AddInteger(unsigned Value) { ID.AddInteger(Value); }

hahnjo wrote:

The review related to `ODRHash` is this one: https://reviews.llvm.org/D153003

In short, my understanding is that `ODRHash` gives the following guarantee: If 
the hashes are different, there is guaranteed to be a ODR violation. In the 
other direction, if two hashes are the same, the declarations have to be 
compared in more detail, ie there may or may not be an ODR violation.

For the specializations, we need the opposite: If two template arguments are 
semantically the same (*), they *must* hash to the same value or otherwise we 
will not find the correct bucket. On the other hand, two different 
specialization arguments may have the same hash, that's fine for the map data 
structure.

Now the additional caveat (*) is that "semantically the same" is not the same 
congruence as "no ODR violation". In https://reviews.llvm.org/D153003 we 
discuss `using` declarations, but IIRC it's also possible to construct 
problematic cases with (nested) namespaces, top-level `::` prefixes, and 
template template parameters. Taken together, my conclusion from the discussion 
above is that `ODRHash` is simply not the right method to find template 
specialization parameters in a map.

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet commented:

thanks, this LG in direction. only reviewed the pieces leading to in-file 
rename so far.

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -1187,6 +1187,16 @@ bool fromJSON(const llvm::json::Value &Params, 
RenameParams &R,
  O.map("position", R.position) && O.map("newName", R.newName);
 }
 
+llvm::json::Value toJSON(const PrepareRenameResult &PRR) {
+  if (!PRR.placeholder) {

kadircet wrote:

nit: braces

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -1436,6 +1436,14 @@ struct RenameParams {
 };
 bool fromJSON(const llvm::json::Value &, RenameParams &, llvm::json::Path);
 
+struct PrepareRenameResult {
+  /// Range of the string to rename.
+  Range range;
+  /// Placeholder text to use in the editor, if set.
+  std::optional placeholder;

kadircet wrote:

let's drop `optional` to prevent confusion here, there isn't any difference 
between an empty placeholder and nullopt, right?

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -53,13 +55,38 @@ struct RenameInputs {
 struct RenameResult {
   // The range of the symbol that the user can attempt to rename.
   Range Target;
+  // Placeholder text for the rename operation, if set.
+  std::optional Placeholder;
   // Rename occurrences for the current main file.
   std::vector LocalChanges;
   // Complete edits for the rename, including LocalChanges.
   // If the full set of changes is unknown, this field is empty.
   FileEdits GlobalChanges;
 };
 
+/// Represents a symbol range where the symbol can potentially have multiple
+/// tokens.
+struct SymbolRange {
+  /// All ranges. If multiple, corresponds to an ObjC selector.

kadircet wrote:

maybe also talk about the general case?
```
Ranges for the tokens that make up the symbol's name.
Usually a single range, there can be multiple ranges if the tokens for symbol 
are split, e.g. ObjC selectors.
```

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -183,6 +185,8 @@ bool isSpelled(SourceLocation Loc, const NamedDecl &ND) {
   if (clang::Lexer::getRawToken(Loc, Tok, SM, LO))
 return false;
   auto StrName = Name.getAsString();
+  if (const auto *MD = dyn_cast(&ND))
+StrName = MD->getSelector().getNameForSlot(0).str();

kadircet wrote:

nit: we can rewrite as:
```
auto TokSpelling = clang::Lexer::getSpelling(Tok, SM, LO);
if (const auto *MD = dyn_cast(&ND))
  return TokSpelling == MD->getSelector().getNameForSlot(0);
return TokSpelling == Name.getAsString();
```

(to prevent a string construction)

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -569,8 +571,43 @@ renameWithinFile(ParsedAST &AST, const NamedDecl 
&RenameDecl,
 //   }
 if (!isInsideMainFile(RenameLoc, SM))
   continue;
+Locs.push_back(RenameLoc);
+  }
+  if (const auto *MD = dyn_cast(&RenameDecl)) {

kadircet wrote:

let's extract this branch into a separate function?

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -134,7 +134,7 @@ class ClangdLSPServer : private ClangdServer::Callbacks,
   void onWorkspaceSymbol(const WorkspaceSymbolParams &,
  Callback>);
   void onPrepareRename(const TextDocumentPositionParams &,
-   Callback>);
+   Callback>);

kadircet wrote:

you can drop the optional now, we either return an Error or PrepareRenameResult

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -508,7 +508,8 @@ static bool mayBeValidIdentifier(llvm::StringRef Ident) {
   !isAsciiIdentifierStart(Ident.front(), AllowDollar))
 return false;
   for (char C : Ident) {
-if (llvm::isASCII(C) && !isAsciiIdentifierContinue(C, AllowDollar))
+if (llvm::isASCII(C) && !isAsciiIdentifierContinue(C, AllowDollar) &&

kadircet wrote:

nit:
```cpp
if (AllowColon && C == ':')
  continue;
if (llvm::isASCII ...)
```

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -338,6 +338,10 @@ inline bool isReservedName(llvm::StringRef Name) {
 SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
   const SourceManager &SM);
 
+clangd::Range tokenRangeForLoc(SourceLocation TokLoc,

kadircet wrote:

this isn't used outside rename.cpp, let's move it there?

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -53,13 +55,38 @@ struct RenameInputs {
 struct RenameResult {
   // The range of the symbol that the user can attempt to rename.
   Range Target;
+  // Placeholder text for the rename operation, if set.
+  std::optional Placeholder;

kadircet wrote:

same here, let's drop optional

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -71,8 +98,8 @@ llvm::Expected rename(const RenameInputs 
&RInputs);
 /// REQUIRED: Occurrences is sorted and doesn't have duplicated ranges.
 llvm::Expected buildRenameEdit(llvm::StringRef AbsFilePath,
  llvm::StringRef InitialCode,
- std::vector Occurrences,
- llvm::StringRef NewName);
+ std::vector Occurrences,
+ llvm::SmallVectorImpl 
&NewNames);

kadircet wrote:

why not `llvm::ArrayRef NewNames` ?

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -569,8 +571,43 @@ renameWithinFile(ParsedAST &AST, const NamedDecl 
&RenameDecl,
 //   }
 if (!isInsideMainFile(RenameLoc, SM))
   continue;
+Locs.push_back(RenameLoc);
+  }
+  if (const auto *MD = dyn_cast(&RenameDecl)) {
+auto Code = SM.getBufferData(SM.getMainFileID());
+auto RenameIdentifier = MD->getSelector().getNameForSlot(0).str();
+llvm::SmallVector NewNames;
+NewName.split(NewNames, ":");
+if (NewNames.empty())
+  NewNames.push_back(NewName);
+std::vector Ranges;
+const auto &LangOpts = RenameDecl.getASTContext().getLangOpts();
+for (const auto &Loc : Locs)
+  Ranges.push_back(tokenRangeForLoc(Loc, SM, LangOpts));
+auto FilePath = AST.tuPath();
+auto RenameRanges =
+adjustRenameRanges(Code, RenameIdentifier,

kadircet wrote:

we don't need to adjust ranges again in here. we're already using ranges from 
the AST (not from index)

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -893,22 +964,36 @@ llvm::Expected buildRenameEdit(llvm::StringRef 
AbsFilePath,
 return LastOffset;
   };
 
-  std::vector> OccurrencesOffsets;
-  for (const auto &R : Occurrences) {
-auto StartOffset = Offset(R.start);
-if (!StartOffset)
-  return StartOffset.takeError();
-auto EndOffset = Offset(R.end);
-if (!EndOffset)
-  return EndOffset.takeError();
-OccurrencesOffsets.push_back({*StartOffset, *EndOffset});
+  struct OccurrenceOffset {
+size_t Start;
+size_t End;
+llvm::StringRef NewName;
+
+OccurrenceOffset(size_t Start, size_t End, llvm::StringRef NewName) :
+  Start(Start), End(End), NewName(NewName) {}
+  };
+
+  std::vector OccurrencesOffsets;
+  for (const auto &SR : Occurrences) {
+for (auto It = SR.Ranges.begin(); It != SR.Ranges.end(); ++It) {

kadircet wrote:

nit: `for (auto [Range, NewName] : llvm::zip(SR.Ranges, NewNames))`

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -53,13 +55,38 @@ struct RenameInputs {
 struct RenameResult {
   // The range of the symbol that the user can attempt to rename.
   Range Target;
+  // Placeholder text for the rename operation, if set.
+  std::optional Placeholder;
   // Rename occurrences for the current main file.
   std::vector LocalChanges;
   // Complete edits for the rename, including LocalChanges.
   // If the full set of changes is unknown, this field is empty.
   FileEdits GlobalChanges;
 };
 
+/// Represents a symbol range where the symbol can potentially have multiple
+/// tokens.
+struct SymbolRange {
+  /// All ranges. If multiple, corresponds to an ObjC selector.
+  std::vector Ranges;
+
+  /// Returns the first range.
+  Range range() const { return Ranges.front(); }
+
+  SymbolRange(Range R) : Ranges({R}) {}
+  SymbolRange(std::vector Ranges) : Ranges(std::move(Ranges)) {}
+
+  friend bool operator==(const SymbolRange &LHS, const SymbolRange &RHS) {
+return LHS.Ranges == RHS.Ranges;
+  }
+  friend bool operator!=(const SymbolRange &LHS, const SymbolRange &RHS) {
+return !(LHS == RHS);
+  }
+  friend bool operator<(const SymbolRange &LHS, const SymbolRange &RHS) {
+return LHS.range() < RHS.range();
+  }
+};

kadircet wrote:

can you move function definitions to implementation file?

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-01-05 Thread kadir çetinkaya via cfe-commits


@@ -569,8 +571,43 @@ renameWithinFile(ParsedAST &AST, const NamedDecl 
&RenameDecl,
 //   }
 if (!isInsideMainFile(RenameLoc, SM))
   continue;
+Locs.push_back(RenameLoc);
+  }
+  if (const auto *MD = dyn_cast(&RenameDecl)) {
+auto Code = SM.getBufferData(SM.getMainFileID());
+auto RenameIdentifier = MD->getSelector().getNameForSlot(0).str();
+llvm::SmallVector NewNames;
+NewName.split(NewNames, ":");
+if (NewNames.empty())
+  NewNames.push_back(NewName);
+std::vector Ranges;
+const auto &LangOpts = RenameDecl.getASTContext().getLangOpts();
+for (const auto &Loc : Locs)
+  Ranges.push_back(tokenRangeForLoc(Loc, SM, LangOpts));

kadircet wrote:

instead of re-lexing, you can use tokenbuffer inside AST and call 
`spelledTokenAt`, then convert it into a range

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


[clang] [coroutines] Detect lifetime issues with coroutine lambda captures (PR #77066)

2024-01-05 Thread Utkarsh Saxena via cfe-commits

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

>From 3e0d0ab6c4fc6cba68285816a95e423bc18e8e55 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 5 Jan 2024 10:11:20 +0100
Subject: [PATCH 1/2] [coroutines] Detect lifetime issues with coroutine lambda
 captures

---
 clang/lib/Sema/SemaInit.cpp   | 20 +--
 clang/test/SemaCXX/coro-lifetimebound.cpp | 64 +--
 2 files changed, 76 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 60c0e3e74204ec..c100bf11454786 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -12,6 +12,7 @@
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
@@ -33,6 +34,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -7575,15 +7577,27 @@ static void 
visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
 Path.pop_back();
   };
 
-  if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
-VisitLifetimeBoundArg(Callee, ObjectArg);
-
   bool CheckCoroCall = false;
   if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
 CheckCoroCall = RD->hasAttr() &&
 RD->hasAttr() &&
 !Callee->hasAttr();
   }
+
+  if (ObjectArg) {
+bool CheckCoroObjArg = CheckCoroCall;
+// Ignore `__promise.get_return_object()` as it not lifetimebound.
+if (Callee->getDeclName().isIdentifier() &&
+Callee->getName() == "get_return_object")
+  CheckCoroObjArg = false;
+// Coroutine lambda objects with empty capture list are not lifetimebound.
+if (auto *LE = dyn_cast(ObjectArg->IgnoreImplicit());
+LE && LE->captures().empty())
+  CheckCoroObjArg = false;
+if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
+  VisitLifetimeBoundArg(Callee, ObjectArg);
+  }
+
   for (unsigned I = 0,
 N = std::min(Callee->getNumParams(), Args.size());
I != N; ++I) {
diff --git a/clang/test/SemaCXX/coro-lifetimebound.cpp 
b/clang/test/SemaCXX/coro-lifetimebound.cpp
index 3fc7ca70a14a12..319134450e4b6f 100644
--- a/clang/test/SemaCXX/coro-lifetimebound.cpp
+++ b/clang/test/SemaCXX/coro-lifetimebound.cpp
@@ -64,6 +64,10 @@ Co bar_coro(const int &b, int c) {
   : bar_coro(0, 1); // expected-warning {{returning address of local 
temporary object}}
 }
 
+// 
=
+// Lambdas
+// 
=
+namespace lambdas {
 void lambdas() {
   auto unsafe_lambda = [] [[clang::coro_wrapper]] (int b) {
 return foo_coro(b); // expected-warning {{address of stack memory 
associated with parameter}}
@@ -84,15 +88,47 @@ void lambdas() {
 co_return x + co_await foo_coro(b);
   };
 }
+
+Co lambda_captures() {
+  int a = 1;
+  // Temporary lambda object dies.
+  auto lamb = [a](int x, const int& y) -> Co { // expected-warning 
{{temporary whose address is used as value of local variable 'lamb'}}
+co_return x + y + a;
+  }(1, a);
+  // Object dies but it has no capture.
+  auto no_capture = []() -> Co { co_return 1; }();
+  auto bad_no_capture = [](const int& a) -> Co { co_return a; }(1); // 
expected-warning {{temporary}}
+  // Temporary lambda object with lifetime extension under co_await.
+  int res = co_await [a](int x, const int& y) -> Co {
+co_return x + y + a;
+  }(1, a);
+  co_return 1;
+}
+} // namespace lambdas
+
 // 
=
-// Safe usage when parameters are value
+// Member coroutines
 // 
=
-namespace by_value {
-Co value_coro(int b) { co_return co_await foo_coro(b); }
-[[clang::coro_wrapper]] Co wrapper1(int b) { return value_coro(b); }
-[[clang::coro_wrapper]] Co wrapper2(const int& b) { return value_coro(b); 
}
+namespace member_coroutines{
+struct S {
+  Co member(const int& a) { co_return a; }  
+};
+
+Co use() {
+  S s;
+  int a = 1;
+  auto test1 = s.member(1);  // expected-warning {{temporary whose address is 
used as value of local variable}}
+  auto test2 = s.member(a);
+  auto test3 = S{}.member(a);  // expected-warning {{temporary whose address 
is used as value of local variable}}
+  co_return 1;
 }
 
+[[clang::coro_wrapper]] Co wrapper(const int& a) {
+  S s;
+  return s.member(a); // expected-warning {{address of stack memory}}
+}
+} // member_coroutines
+
 // 
=
 // Lifetime bound but not a Coroutine Return Type: No a

[clang] [Clang][SME] Add IsStreamingOrSVE2p1 (PR #76975)

2024-01-05 Thread David Spickett via cfe-commits


@@ -50,6 +50,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasMatMul = false;
   bool HasBFloat16 = false;
   bool HasSVE2 = false;
+  bool HasSVE2p1 = false;

DavidSpickett wrote:

FYI
```
/home/david.spickett/llvm-project/clang/lib/Basic/Targets/AArch64.h:53:8: 
warning: private field 'HasSVE2p1' is not used [-Wunused-private-field]
  bool HasSVE2p1 = false;
   ^
1 warning generated.
```


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


  1   2   3   4   5   >