[llvm-branch-commits] [clang] [Clang] Extend lifetime bound analysis to support assignments (PR #96475)

2024-06-26 Thread Haojian Wu via llvm-branch-commits

https://github.com/hokein edited https://github.com/llvm/llvm-project/pull/96475
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [Clang] Extend lifetime bound analysis to support assignments (PR #96475)

2024-06-26 Thread Haojian Wu via llvm-branch-commits

https://github.com/hokein edited https://github.com/llvm/llvm-project/pull/96475
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [Clang] Extend lifetime bound analysis to support assignments (PR #96475)

2024-06-26 Thread Haojian Wu via llvm-branch-commits

hokein wrote:

I have separated the refactoring change in #96758. This PR now only focuses on 
the assignment support.

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


[llvm-branch-commits] [clang] [Clang] Extend lifetime bound analysis to support assignments (PR #96475)

2024-06-27 Thread Haojian Wu via llvm-branch-commits

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

error: too big or took too long to generate
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang-tools-extra] release/18.x: [clangd] [HeuristicResolver] Protect against infinite recursion on DependentNameTypes (#83542) (PR #84117)

2024-03-15 Thread Haojian Wu via llvm-branch-commits

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

Backporting this change makes sense to me. I think it needs to be reviewed by 
the release manager.

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


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-03 Thread Haojian Wu via llvm-branch-commits

https://github.com/hokein created 
https://github.com/llvm/llvm-project/pull/90961

In the clang AST, constraint nodes are deliberately not instantiated unless 
they are actively being evaluated. Consequently, occurrences of template 
parameters in the require-clause expression have a subtle "depth" difference 
compared to normal occurrences in places, such as function parameters. When 
transforming the require-clause, we must take this distinction into account.

The existing implementation overlooks this consideration. This patch is to 
rewrite the implementation of the require-clause transformation to address this 
issue.

Fixes #90177

>From 94d5225d7eb6479cf4f91eb44ccdf253f7ae9a6d Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 3 May 2024 13:54:06 +0200
Subject: [PATCH] [clang] CTAD alias: refine the transformation for the
 require-clause expr.

In the clang AST, constraint nodes are deliberately not instantiated unless they
are actively being evaluated. Consequently, occurrences of template parameters
in the require-clause expression have a subtle "depth" difference compared to
normal occurrences in place contexts, such as function parameters. When
transforming the require-clause, we must take this distinction into account.

The existing implementation overlooks this consideration. This patch is
to rewrite the implementation of the require-clause transformation to
address this issue.
---
 clang/lib/Sema/SemaTemplate.cpp  | 151 +--
 clang/test/AST/ast-dump-ctad-alias.cpp   |  40 +
 clang/test/SemaCXX/cxx20-ctad-type-alias.cpp |  68 +
 3 files changed, 246 insertions(+), 13 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-ctad-alias.cpp

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 7f49acc36769e9..5f1a44d7850280 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return NTTP->getDepth();
+  llvm_unreachable("Unhandled template parameter types");
+}
+
 NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
   NamedDecl *TemplateParam,
   MultiLevelTemplateArgumentList &Args,
-  unsigned NewIndex) {
+  unsigned NewIndex, unsigned NewDepth) {
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
   NewIndex);
   if (auto *TTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
-  TTP->getDepth());
+  NewDepth);
   if (auto *NTTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
-  NTTP->getDepth());
+  NewDepth);
   llvm_unreachable("Unhandled template parameter types");
 }
 
-Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
- llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
+// Transform the require-clause of F if any.
+// The return result is expected to be the require-clause for the synthesized
+// alias deduction guide.
+Expr *transformRequireClause(
+Sema &SemaRef, FunctionTemplateDecl *F,
+TypeAliasTemplateDecl *AliasTemplate,
+ArrayRef DeduceResults) {
+  Expr *RC = F->getTemplateParameters()->getRequiresClause();
   if (!RC)
 return nullptr;
+
+  auto &Context = SemaRef.Context;
+  LocalInstantiationScope Scope(SemaRef);
+
+  // In the clang AST, constraint nodes are not instantiated at all unless they
+  // are being evaluated. This means that occurrences of template parameters
+  // in the require-clause expr have subtle differences compared to occurrences
+  // in other places, such as function parameters. When transforming the
+  // require-clause, we must respect these differences, particularly regarding
+  // the 'depth' information:
+  //   1) In the transformed require-clause, occurrences of template parameters
+  //   must use the "uninstantiated" depth;
+  //   2) When substituting on the require-clause expr of the underlying
+  //   deduction guide, we must use the entire set of template argument lists.
+  //
+  // It's important to note that we're performing this transformation on an
+  // *instantiated* AliasTemplate.
+
+  // For 1)

[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-07 Thread Haojian Wu via llvm-branch-commits

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

>From 5b70158f8eff30125c0bf0d675bab62497ac620f Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Fri, 3 May 2024 13:54:06 +0200
Subject: [PATCH 1/2] [clang] CTAD alias: refine the transformation for the
 require-clause expr.

In the clang AST, constraint nodes are deliberately not instantiated unless they
are actively being evaluated. Consequently, occurrences of template parameters
in the require-clause expression have a subtle "depth" difference compared to
normal occurrences in place contexts, such as function parameters. When
transforming the require-clause, we must take this distinction into account.

The existing implementation overlooks this consideration. This patch is
to rewrite the implementation of the require-clause transformation to
address this issue.
---
 clang/lib/Sema/SemaTemplate.cpp  | 147 +--
 clang/test/AST/ast-dump-ctad-alias.cpp   |  40 +
 clang/test/SemaCXX/cxx20-ctad-type-alias.cpp |  68 +
 3 files changed, 242 insertions(+), 13 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-ctad-alias.cpp

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 7f49acc36769e..1de0cfac8f1f7 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2744,31 +2744,151 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return NTTP->getDepth();
+  llvm_unreachable("Unhandled template parameter types");
+}
+
 NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
   NamedDecl *TemplateParam,
   MultiLevelTemplateArgumentList &Args,
-  unsigned NewIndex) {
+  unsigned NewIndex, unsigned NewDepth) {
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
   NewIndex);
   if (auto *TTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
-  TTP->getDepth());
+  NewDepth);
   if (auto *NTTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
-  NTTP->getDepth());
+  NewDepth);
   llvm_unreachable("Unhandled template parameter types");
 }
 
-Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
- llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
+// Transform the require-clause of F if any.
+// The return result is expected to be the require-clause for the synthesized
+// alias deduction guide.
+Expr *transformRequireClause(
+Sema &SemaRef, FunctionTemplateDecl *F,
+TypeAliasTemplateDecl *AliasTemplate,
+ArrayRef DeduceResults) {
+  Expr *RC = F->getTemplateParameters()->getRequiresClause();
   if (!RC)
 return nullptr;
+
+  auto &Context = SemaRef.Context;
+  LocalInstantiationScope Scope(SemaRef);
+
+  // In the clang AST, constraint nodes are deliberately not instantiated 
unless
+  // they are actively being evaluated. Consequently, occurrences of template
+  // parameters in the require-clause expression have a subtle "depth"
+  // difference compared to normal occurrences in places, such as function
+  // parameters. When transforming the require-clause, we must take this
+  // distinction into account:
+  //
+  //   1) In the transformed require-clause, occurrences of template parameters
+  //   must use the "uninstantiated" depth;
+  //   2) When substituting on the require-clause expr of the underlying
+  //   deduction guide, we must use the entire set of template argument lists;
+  //
+  // It's important to note that we're performing this transformation on an
+  // *instantiated* AliasTemplate.
+
+  // For 1), if the alias template is nested within a class template, we
+  // calcualte the 'uninstantiated' depth by adding the substitution level 
back.
+  unsigned AdjustDepth = 0;
+  if (auto *PrimaryTemplate = 
AliasTemplate->getInstantiatedFromMemberTemplate())
+AdjustDepth = PrimaryTemplate->getTemplateDepth();
+  
+  // We rebuild all template parameters with the uninstantiated depth, and
+  // build template arguments refer to them.
+  SmallVector AdjustedAliasTemplateArgs;
+
+  for (auto *TP : *AliasTemplate->getTemplateParameters()) {
+// Rebuild an

[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-07 Thread Haojian Wu via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {

hokein wrote:

Renamed to `getTemplateParameterDepth` per your suggestion.

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


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-07 Thread Haojian Wu via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return NTTP->getDepth();
+  llvm_unreachable("Unhandled template parameter types");
+}
+
 NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
   NamedDecl *TemplateParam,
   MultiLevelTemplateArgumentList &Args,
-  unsigned NewIndex) {
+  unsigned NewIndex, unsigned NewDepth) {
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
   NewIndex);
   if (auto *TTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
-  TTP->getDepth());
+  NewDepth);
   if (auto *NTTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
-  NTTP->getDepth());
+  NewDepth);
   llvm_unreachable("Unhandled template parameter types");
 }
 
-Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
- llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
+// Transform the require-clause of F if any.
+// The return result is expected to be the require-clause for the synthesized
+// alias deduction guide.
+Expr *transformRequireClause(

hokein wrote:

We're in an anonymous namespace.

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


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-07 Thread Haojian Wu via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {

hokein wrote:

Done.

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


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-07 Thread Haojian Wu via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {

hokein wrote:

Yeah, we're in an anonymous namespace.

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


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-07 Thread Haojian Wu via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return NTTP->getDepth();
+  llvm_unreachable("Unhandled template parameter types");
+}
+
 NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
   NamedDecl *TemplateParam,
   MultiLevelTemplateArgumentList &Args,
-  unsigned NewIndex) {
+  unsigned NewIndex, unsigned NewDepth) {
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
   NewIndex);
   if (auto *TTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
-  TTP->getDepth());
+  NewDepth);
   if (auto *NTTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
-  NTTP->getDepth());
+  NewDepth);
   llvm_unreachable("Unhandled template parameter types");
 }
 
-Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
- llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
+// Transform the require-clause of F if any.
+// The return result is expected to be the require-clause for the synthesized
+// alias deduction guide.
+Expr *transformRequireClause(
+Sema &SemaRef, FunctionTemplateDecl *F,
+TypeAliasTemplateDecl *AliasTemplate,
+ArrayRef DeduceResults) {
+  Expr *RC = F->getTemplateParameters()->getRequiresClause();
   if (!RC)
 return nullptr;
+
+  auto &Context = SemaRef.Context;
+  LocalInstantiationScope Scope(SemaRef);
+
+  // In the clang AST, constraint nodes are not instantiated at all unless they
+  // are being evaluated. This means that occurrences of template parameters
+  // in the require-clause expr have subtle differences compared to occurrences
+  // in other places, such as function parameters. When transforming the
+  // require-clause, we must respect these differences, particularly regarding
+  // the 'depth' information:
+  //   1) In the transformed require-clause, occurrences of template parameters
+  //   must use the "uninstantiated" depth;
+  //   2) When substituting on the require-clause expr of the underlying
+  //   deduction guide, we must use the entire set of template argument lists.
+  //
+  // It's important to note that we're performing this transformation on an
+  // *instantiated* AliasTemplate.
+
+  // For 1), if the alias template is nested within a class template, we
+  // calcualte the 'uninstantiated' depth by adding the substitution level 
back.
+  unsigned AdjustDepth = 0;
+  if (auto *PrimaryTemplate = 
AliasTemplate->getInstantiatedFromMemberTemplate())
+AdjustDepth = PrimaryTemplate->getTemplateDepth();
+  
+  // We rebuild all template parameters with the uninstantiated depth, and
+  // build template arguments refer to them.
+  SmallVector AdjustedAliasTemplateArgs;
+
+  for (auto *TP : *AliasTemplate->getTemplateParameters()) {
+// Rebuild any internal references to earlier parameters and reindex
+// as we go.
+MultiLevelTemplateArgumentList Args;
+Args.setKind(TemplateSubstitutionKind::Rewrite);
+Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
+NamedDecl *NewParam = transformTemplateParameter(
+SemaRef, AliasTemplate->getDeclContext(), TP, Args,
+/*NewIndex=*/AdjustedAliasTemplateArgs.size(),
+getTemplateDepth(TP) + AdjustDepth);
+
+auto NewTemplateArgument = Context.getCanonicalTemplateArgument(

hokein wrote:

Probably not needed, and I think avoiding the use of canonical types can lead 
to a more optimal AST, see #79798. We've already used this pattern in the 
`ConvertConstructorToDeductionGuideTransform`, and the current implementation 
here simply follows it.

However, addressing this issue is not the primary focus of this PR. It might be 
more appropriate to address it in a separate patch.

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


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-07 Thread Haojian Wu via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return NTTP->getDepth();
+  llvm_unreachable("Unhandled template parameter types");
+}
+
 NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
   NamedDecl *TemplateParam,
   MultiLevelTemplateArgumentList &Args,
-  unsigned NewIndex) {
+  unsigned NewIndex, unsigned NewDepth) {
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
   NewIndex);
   if (auto *TTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
-  TTP->getDepth());
+  NewDepth);
   if (auto *NTTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
-  NTTP->getDepth());
+  NewDepth);
   llvm_unreachable("Unhandled template parameter types");
 }
 
-Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
- llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
+// Transform the require-clause of F if any.
+// The return result is expected to be the require-clause for the synthesized
+// alias deduction guide.
+Expr *transformRequireClause(
+Sema &SemaRef, FunctionTemplateDecl *F,
+TypeAliasTemplateDecl *AliasTemplate,
+ArrayRef DeduceResults) {
+  Expr *RC = F->getTemplateParameters()->getRequiresClause();
   if (!RC)
 return nullptr;
+
+  auto &Context = SemaRef.Context;
+  LocalInstantiationScope Scope(SemaRef);
+
+  // In the clang AST, constraint nodes are not instantiated at all unless they
+  // are being evaluated. This means that occurrences of template parameters
+  // in the require-clause expr have subtle differences compared to occurrences
+  // in other places, such as function parameters. When transforming the
+  // require-clause, we must respect these differences, particularly regarding
+  // the 'depth' information:
+  //   1) In the transformed require-clause, occurrences of template parameters
+  //   must use the "uninstantiated" depth;
+  //   2) When substituting on the require-clause expr of the underlying
+  //   deduction guide, we must use the entire set of template argument lists.
+  //
+  // It's important to note that we're performing this transformation on an
+  // *instantiated* AliasTemplate.
+
+  // For 1), if the alias template is nested within a class template, we
+  // calcualte the 'uninstantiated' depth by adding the substitution level 
back.
+  unsigned AdjustDepth = 0;
+  if (auto *PrimaryTemplate = 
AliasTemplate->getInstantiatedFromMemberTemplate())

hokein wrote:

I've noticed that there are several places 
(e.g.,[1](https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaTemplate.cpp#L2374),
 
[2](https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/DeclCXX.cpp#L1943),
 
[3](https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/Decl.cpp#L4149))
 where we use a while-loop to retrieve the primary template. However, I'm not 
entirely clear on the rationale behind it. It appears that using 
`getInstantiatedFromMemberTemplate()` consistently provides the correct result 
for all cases I came up with. Interestingly, removing the while-loop from all 
occurrences [1], [2], [3] doesn't trigger any test failures on `check-clang`.

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


[llvm-branch-commits] [clang-tools-extra] [clangd] Add clangd 19 release notes (PR #105975)

2024-08-26 Thread Haojian Wu via llvm-branch-commits

https://github.com/hokein commented:

Thanks. I’ll leave the final approval to @kadircet.

Should we mention the module support, even though it’s still in the initial 
stages?



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


[llvm-branch-commits] [clang] c6bd660 - Fix a build-bot failure.

2021-01-25 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-25T09:46:29+01:00
New Revision: c6bd6607bf8abfe259fef6a41e695581a88c88f0

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

LOG: Fix a build-bot failure.

The test ms-lookup-template-base-classes.cpp added in 
d972d4c749048531953a16b815e07c67e8455a3b
is failing on some builtbot that don't include x86.

This patch should fix that (following the patterns in the test directory).

Added: 


Modified: 
clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp 
b/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp
index fbc211aca17a..41a4ee8b5bb8 100644
--- a/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp
+++ b/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-obj -fms-compatibility %s 
-o -
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm -fms-compatibility 
%s -o -
 // CHECK that we don't crash.
 
 struct Base {



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


[llvm-branch-commits] [clang-tools-extra] 42830f8 - [clangd] Extend find-refs to include overrides.

2021-01-20 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-20T13:23:20+01:00
New Revision: 42830f8bdc8f064fee648541f79f8e8d66072cce

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

LOG: [clangd] Extend find-refs to include overrides.

find-references on `virtual void meth^od() = 0` will include override 
references.

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/unittests/XRefsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index 8027e0564126..d4dc6212553f 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -879,11 +879,8 @@ class ReferenceFinder : public index::IndexDataConsumer {
   };
 
   ReferenceFinder(const ParsedAST &AST,
-  const std::vector &TargetDecls)
-  : AST(AST) {
-for (const NamedDecl *D : TargetDecls)
-  CanonicalTargets.insert(D->getCanonicalDecl());
-  }
+  const llvm::DenseSet &TargetIDs)
+  : AST(AST), TargetIDs(TargetIDs) {}
 
   std::vector take() && {
 llvm::sort(References, [](const Reference &L, const Reference &R) {
@@ -908,9 +905,9 @@ class ReferenceFinder : public index::IndexDataConsumer {
llvm::ArrayRef Relations,
SourceLocation Loc,
index::IndexDataConsumer::ASTNodeInfo ASTNode) override 
{
-assert(D->isCanonicalDecl() && "expect D to be a canonical declaration");
 const SourceManager &SM = AST.getSourceManager();
-if (!CanonicalTargets.count(D) || !isInsideMainFile(Loc, SM))
+if (!isInsideMainFile(Loc, SM) ||
+TargetIDs.find(getSymbolID(D)) == TargetIDs.end())
   return true;
 const auto &TB = AST.getTokens();
 Loc = SM.getFileLoc(Loc);
@@ -920,14 +917,14 @@ class ReferenceFinder : public index::IndexDataConsumer {
   }
 
 private:
-  llvm::SmallSet CanonicalTargets;
   std::vector References;
   const ParsedAST *
+  const llvm::DenseSet &TargetIDs;
 };
 
 std::vector
-findRefs(const std::vector &Decls, ParsedAST &AST) {
-  ReferenceFinder RefFinder(AST, Decls);
+findRefs(const llvm::DenseSet &IDs, ParsedAST &AST) {
+  ReferenceFinder RefFinder(AST, IDs);
   index::IndexingOptions IndexOpts;
   IndexOpts.SystemSymbolFilter =
   index::IndexingOptions::SystemSymbolFilterKind::All;
@@ -1217,7 +1214,11 @@ std::vector 
findDocumentHighlights(ParsedAST &AST,
   if (!Decls.empty()) {
 // FIXME: we may get multiple DocumentHighlights with the same location
 // and 
diff erent kinds, deduplicate them.
-for (const auto &Ref : findRefs({Decls.begin(), Decls.end()}, AST))
+llvm::DenseSet Targets;
+for (const NamedDecl *ND : Decls)
+  if (auto ID = getSymbolID(ND))
+Targets.insert(ID);
+for (const auto &Ref : findRefs(Targets, AST))
   Result.push_back(toHighlight(Ref, SM));
 return true;
   }
@@ -1295,13 +1296,14 @@ ReferencesResult findReferences(ParsedAST &AST, 
Position Pos, uint32_t Limit,
 llvm::consumeError(CurLoc.takeError());
 return {};
   }
-  llvm::Optional Macro;
-  if (const auto *IdentifierAtCursor =
-  syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens())) {
-Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor());
-  }
 
   RefsRequest Req;
+
+  const auto *IdentifierAtCursor =
+  syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
+  llvm::Optional Macro;
+  if (IdentifierAtCursor)
+Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor());
   if (Macro) {
 // Handle references to macro.
 if (auto MacroSID = getSymbolID(Macro->Name, Macro->Info, SM)) {
@@ -1325,9 +1327,35 @@ ReferencesResult findReferences(ParsedAST &AST, Position 
Pos, uint32_t Limit,
 DeclRelation::TemplatePattern | DeclRelation::Alias;
 std::vector Decls =
 getDeclAtPosition(AST, *CurLoc, Relations);
+llvm::DenseSet Targets;
+for (const NamedDecl *D : Decls)
+  if (auto ID = getSymbolID(D))
+Targets.insert(ID);
+
+llvm::DenseSet Overrides;
+if (Index) {
+  RelationsRequest FindOverrides;
+  FindOverrides.Predicate = RelationKind::OverriddenBy;
+  for (const NamedDecl *ND : Decls) {
+// Special case: virtual void meth^od() = 0 includes refs of overrides.
+if (const auto *CMD = llvm::dyn_cast(ND)) {
+  if (CMD->isPure())
+if (IdentifierAtCursor && SM.getSpellingLoc(CMD->getLocation()) ==
+  IdentifierAtCursor->location())
+  if (auto ID = getSymbolID(CMD))
+FindOverrides.Subjects.insert(ID);
+}
+  }
+

[llvm-branch-commits] [clang-tools-extra] facea4a - [clangd] Fix a missing override keyword, NFC.

2021-01-21 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-21T11:06:43+01:00
New Revision: facea4a2d4fa543da2241fb4268c34e9c019fca6

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

LOG: [clangd] Fix a missing override keyword, NFC.

Added: 


Modified: 
clang-tools-extra/clangd/index/remote/Client.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/remote/Client.cpp 
b/clang-tools-extra/clangd/index/remote/Client.cpp
index b09dbf915e46..a153a8812baf 100644
--- a/clang-tools-extra/clangd/index/remote/Client.cpp
+++ b/clang-tools-extra/clangd/index/remote/Client.cpp
@@ -152,7 +152,8 @@ class IndexClient : public clangd::SymbolIndex {
   });
   }
 
-  llvm::unique_function indexedFiles() const {
+  llvm::unique_function
+  indexedFiles() const override {
 // FIXME: For now we always return "false" regardless of whether the file
 //was indexed or not. A possible implementation could be based on
 //the idea that we do not want to send a request at every



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


[llvm-branch-commits] [clang] d972d4c - Revert "[clang] Suppress "follow-up" diagnostics on recovery call expressions."

2021-01-22 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-22T13:04:37+01:00
New Revision: d972d4c749048531953a16b815e07c67e8455a3b

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

LOG: Revert "[clang] Suppress "follow-up" diagnostics on recovery call 
expressions."

This reverts commit efa9aaad703e6b150980ed1a74b4e7c9da7d85a2 and adds a
crash test.

The commit caused a crash in CodeGen with -fms-compatibility, see
https://bugs.llvm.org/show_bug.cgi?id=48690.

Added: 
clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp

Modified: 
clang/lib/Sema/SemaOverload.cpp
clang/test/AST/ast-dump-recovery.cpp
clang/test/SemaCXX/typo-correction-delayed.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 13d2125d1a28..2bef37b76763 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -12923,7 +12923,7 @@ BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
 return ExprError();
   }
 
-  // Build an implicit member access expression if appropriate. Just drop the
+  // Build an implicit member call if appropriate.  Just drop the
   // casts and such from the call, we don't really care.
   ExprResult NewFn = ExprError();
   if ((*R.begin())->isCXXClassMember())
@@ -12938,19 +12938,12 @@ BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr 
*Fn,
   if (NewFn.isInvalid())
 return ExprError();
 
-  auto CallE =
-  SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
-MultiExprArg(Args.data(), Args.size()), RParenLoc);
-  if (CallE.isInvalid())
-return ExprError();
-  // We now have recovered a callee. However, building a real call may lead to
-  // incorrect secondary diagnostics if our recovery wasn't correct.
-  // We keep the recovery behavior but suppress all following diagnostics by
-  // using RecoveryExpr. We deliberately drop the return type of the recovery
-  // function, and rely on clang's dependent mechanism to suppress following
-  // diagnostics.
-  return SemaRef.CreateRecoveryExpr(CallE.get()->getBeginLoc(),
-CallE.get()->getEndLoc(), {CallE.get()});
+  // This shouldn't cause an infinite loop because we're giving it
+  // an expression with viable lookup results, which should never
+  // end up here.
+  return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
+   MultiExprArg(Args.data(), Args.size()),
+   RParenLoc);
 }
 
 /// Constructs and populates an OverloadedCandidateSet from

diff  --git a/clang/test/AST/ast-dump-recovery.cpp 
b/clang/test/AST/ast-dump-recovery.cpp
index a8da2b8ad449..b6d7ac1d0a8e 100644
--- a/clang/test/AST/ast-dump-recovery.cpp
+++ b/clang/test/AST/ast-dump-recovery.cpp
@@ -296,14 +296,3 @@ void InvalidCondition() {
   // CHECK-NEXT: `-IntegerLiteral {{.*}} 'int' 2
   invalid() ? 1 : 2;
 }
-
-void abcc();
-void TypoCorrection() {
-  // RecoveryExpr is always dependent-type in this case in order to suppress
-  // following diagnostics.
-  // CHECK:  RecoveryExpr {{.*}} ''
-  // CHECK-NEXT: `-CallExpr {{.*}} 'void'
-  // CHECK-NEXT:   `-ImplicitCastExpr
-  // CHECK-NEXT: `-DeclRefExpr {{.*}} 'abcc'
-  abc();
-}

diff  --git a/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp 
b/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp
new file mode 100644
index ..fbc211aca17a
--- /dev/null
+++ b/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-obj -fms-compatibility %s 
-o -
+// CHECK that we don't crash.
+
+struct Base {
+  void b(int, int);
+};
+
+template  struct Derived : Base {
+  void d() { b(1, 2); }
+};
+
+void use() {
+  Derived d;
+  d.d();
+}

diff  --git a/clang/test/SemaCXX/typo-correction-delayed.cpp 
b/clang/test/SemaCXX/typo-correction-delayed.cpp
index aa136a08be4f..66d19daf66fd 100644
--- a/clang/test/SemaCXX/typo-correction-delayed.cpp
+++ b/clang/test/SemaCXX/typo-correction-delayed.cpp
@@ -209,15 +209,6 @@ int z = 1 ? N : ;  // expected-error {{expected 
expression}}
 // expected-error-re@-1 {{use of undeclared identifier 'N'{{$
 }
 
-namespace noSecondaryDiags {
-void abcc(); // expected-note {{'abcc' declared here}}
-
-void test() {
-  // Verify the secondary diagnostic ".. convertible to 'bool'" is suppressed.
-  if (abc()) {} // expected-error {{use of undeclared identifier 'abc'; did 
you mean 'abcc'?}}
-}
-}
-
 // PR 23285. This test must be at the end of the file to avoid additional,
 // unwanted diagnostics.
 // expected-error-re@+2 {{use of undeclared identifier 'uintmax_t'{{$



___
llvm-branch-commits mailing list
llvm-bran

[llvm-branch-commits] [clang-tools-extra] b83b7d0 - [clangd] NFC, avoid potential ODR violation.

2021-01-08 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-08T13:29:11+01:00
New Revision: b83b7d08730e2b67d911653f59091b1b311c0213

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

LOG: [clangd] NFC, avoid potential ODR violation.

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Merge.cpp 
b/clang-tools-extra/clangd/index/Merge.cpp
index 29174ff0d354..0dd0d9e01518 100644
--- a/clang-tools-extra/clangd/index/Merge.cpp
+++ b/clang-tools-extra/clangd/index/Merge.cpp
@@ -164,7 +164,7 @@ void MergedIndex::relations(
 
 // Returns true if \p L is (strictly) preferred to \p R (e.g. by file paths). 
If
 // neither is preferred, this returns false.
-bool prefer(const SymbolLocation &L, const SymbolLocation &R) {
+static bool prefer(const SymbolLocation &L, const SymbolLocation &R) {
   if (!L)
 return false;
   if (!R)



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


[llvm-branch-commits] [clang-tools-extra] c909512 - [clangd] Cleanup a remaining Optional usage, NFC.

2021-01-08 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-08T13:44:20+01:00
New Revision: c909512fdb9ed63081b0578410430117811b86e8

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

LOG: [clangd] Cleanup a remaining Optional usage, NFC.

Added: 


Modified: 
clang-tools-extra/clangd/CodeComplete.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index ebdbd56c286a..1a8474f6c53d 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -828,9 +828,9 @@ struct CompletionRecorder : public CodeCompleteConsumer {
 };
 
 struct ScoredSignature {
-  // When set, requires documentation to be requested from the index with this
-  // ID.
-  llvm::Optional IDForDoc;
+  // When not null, requires documentation to be requested from the index with
+  // this ID.
+  SymbolID IDForDoc;
   SignatureInformation Signature;
   SignatureQualitySignals Quality;
 };
@@ -894,7 +894,7 @@ class SignatureHelpCollector final : public 
CodeCompleteConsumer {
   for (const auto &S : ScoredSignatures) {
 if (!S.IDForDoc)
   continue;
-IndexRequest.IDs.insert(*S.IDForDoc);
+IndexRequest.IDs.insert(S.IDForDoc);
   }
   Index->lookup(IndexRequest, [&](const Symbol &S) {
 if (!S.Documentation.empty())
@@ -939,7 +939,7 @@ class SignatureHelpCollector final : public 
CodeCompleteConsumer {
 
 for (auto &SS : ScoredSignatures) {
   auto IndexDocIt =
-  SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end();
+  SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
   if (IndexDocIt != FetchedDocs.end())
 SS.Signature.documentation = IndexDocIt->second;
 



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


[llvm-branch-commits] [clang-tools-extra] ed3b1f9 - [clangd] go-to-implementation on a base class jumps to all subclasses.

2021-01-08 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-08T13:50:57+01:00
New Revision: ed3b1f906115a0dcd2542fa294d0382a42eb177d

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

LOG: [clangd] go-to-implementation on a base class jumps to all subclasses.

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/XRefs.h
clang-tools-extra/clangd/unittests/XRefsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index c7ec401c6479..ebe03e74a4a7 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -292,13 +292,14 @@ const NamedDecl *getPreferredDecl(const NamedDecl *D) {
   return D;
 }
 
-std::vector findOverrides(llvm::DenseSet IDs,
- const SymbolIndex *Index,
- llvm::StringRef MainFilePath) {
+std::vector findImplementors(llvm::DenseSet IDs,
+RelationKind Predicate,
+const SymbolIndex *Index,
+llvm::StringRef MainFilePath) {
   if (IDs.empty())
 return {};
   RelationsRequest Req;
-  Req.Predicate = RelationKind::OverriddenBy;
+  Req.Predicate = Predicate;
   Req.Subjects = std::move(IDs);
   std::vector Results;
   Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
@@ -458,7 +459,8 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
 });
   }
 
-  auto Overrides = findOverrides(VirtualMethods, Index, MainFilePath);
+  auto Overrides = findImplementors(VirtualMethods, RelationKind::OverriddenBy,
+Index, MainFilePath);
   Result.insert(Result.end(), Overrides.begin(), Overrides.end());
   return Result;
 }
@@ -1239,12 +1241,20 @@ std::vector 
findImplementations(ParsedAST &AST, Position Pos,
   }
   DeclRelationSet Relations =
   DeclRelation::TemplatePattern | DeclRelation::Alias;
-  llvm::DenseSet VirtualMethods;
-  for (const NamedDecl *ND : getDeclAtPosition(AST, *CurLoc, Relations))
-if (const CXXMethodDecl *CXXMD = llvm::dyn_cast(ND))
-  if (CXXMD->isVirtual())
-VirtualMethods.insert(getSymbolID(ND));
-  return findOverrides(std::move(VirtualMethods), Index, *MainFilePath);
+  llvm::DenseSet IDs;
+  RelationKind QueryKind;
+  for (const NamedDecl *ND : getDeclAtPosition(AST, *CurLoc, Relations)) {
+if (const auto *CXXMD = llvm::dyn_cast(ND)) {
+  if (CXXMD->isVirtual()) {
+IDs.insert(getSymbolID(ND));
+QueryKind = RelationKind::OverriddenBy;
+  }
+} else if (const auto *RD = dyn_cast(ND)) {
+  IDs.insert(getSymbolID(RD));
+  QueryKind = RelationKind::BaseOf;
+}
+  }
+  return findImplementors(std::move(IDs), QueryKind, Index, *MainFilePath);
 }
 
 ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit,

diff  --git a/clang-tools-extra/clangd/XRefs.h 
b/clang-tools-extra/clangd/XRefs.h
index eca174f59096..4c745eb9bc51 100644
--- a/clang-tools-extra/clangd/XRefs.h
+++ b/clang-tools-extra/clangd/XRefs.h
@@ -83,7 +83,9 @@ struct ReferencesResult {
   bool HasMore = false;
 };
 
-/// Returns implementations of the virtual function at a specified \p Pos.
+/// Returns implementations at a specified \p Pos:
+///   - overrides for a virtual method;
+///   - subclasses for a base class;
 std::vector findImplementations(ParsedAST &AST, Position Pos,
const SymbolIndex *Index);
 

diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 26e06dad9250..508634ec908a 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -1611,11 +1611,11 @@ TEST(LocateSymbol, NearbyIdentifier) {
 
 TEST(FindImplementations, Inheritance) {
   llvm::StringRef Test = R"cpp(
-struct Base {
+struct $0^Base {
   virtual void F$1^oo();
   void C$4^oncrete();
 };
-struct Child1 : Base {
+struct $0[[Child1]] : Base {
   void $1[[Fo$3^o]]() override;
   virtual void B$2^ar();
   void Concrete();  // No implementations for concrete methods.
@@ -1625,7 +1625,7 @@ TEST(FindImplementations, Inheritance) {
   void $2[[Bar]]() override;
 };
 void FromReference() {
-  Base* B;
+  $0^Base* B;
   B->Fo$1^o();
   B->C$4^oncrete();
   &Base::Fo$1^o;
@@ -1633,12 +1633,16 @@ TEST(FindImplementations, Inheritance) {
   C1->B$2^ar();
   C1->Fo$3^o();
 }
+// CRTP should work.
+template
+struct $5^TemplateBas

[llvm-branch-commits] [clang-tools-extra] 8e36d21 - [clangd] Add go-to-def metric.

2021-01-08 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-08T21:03:59+01:00
New Revision: 8e36d21fabcd23835d17855025d06946eb0dfb9b

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

LOG: [clangd] Add go-to-def metric.

to track the number of different "special" go-to-def request.

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index ebe03e74a4a7..667a90aa2efb 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -336,6 +336,8 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
   // Keep track of SymbolID -> index mapping, to fill in index data later.
   llvm::DenseMap ResultIndex;
 
+  static constexpr trace::Metric LocateASTReferentMetric(
+  "locate_ast_referent", trace::Metric::Counter, "case");
   auto AddResultDecl = [&](const NamedDecl *D) {
 D = getPreferredDecl(D);
 auto Loc =
@@ -369,8 +371,10 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
   // saved in the AST.
   if (CMD->isPure()) {
 if (TouchedIdentifier && SM.getSpellingLoc(CMD->getLocation()) ==
- TouchedIdentifier->location())
+ TouchedIdentifier->location()) {
   VirtualMethods.insert(getSymbolID(CMD));
+  LocateASTReferentMetric.record(1, "method-to-override");
+}
   }
   // Special case: void foo() ^override: jump to the overridden method.
   const InheritableAttr *Attr = D->getAttr();
@@ -379,6 +383,7 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
   if (Attr && TouchedIdentifier &&
   SM.getSpellingLoc(Attr->getLocation()) ==
   TouchedIdentifier->location()) {
+LocateASTReferentMetric.record(1, "method-to-base");
 // We may be overridding multiple methods - offer them all.
 for (const NamedDecl *ND : CMD->overridden_methods())
   AddResultDecl(ND);
@@ -403,6 +408,7 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
 if (auto *CTSD = dyn_cast(D)) {
   if (TouchedIdentifier &&
   D->getLocation() == TouchedIdentifier->location()) {
+LocateASTReferentMetric.record(1, 
"template-specialization-to-primary");
 AddResultDecl(CTSD->getSpecializedTemplate());
 continue;
   }
@@ -418,9 +424,12 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
   if (const auto *ID = CD->getClassInterface())
 if (TouchedIdentifier &&
 (CD->getLocation() == TouchedIdentifier->location() ||
- ID->getName() == TouchedIdentifier->text(SM)))
+ ID->getName() == TouchedIdentifier->text(SM))) {
+  LocateASTReferentMetric.record(1, "objc-category-to-class");
   AddResultDecl(ID);
+}
 
+LocateASTReferentMetric.record(1, "regular");
 // Otherwise the target declaration is the right one.
 AddResultDecl(D);
   }



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


[llvm-branch-commits] [clang-tools-extra] 1677c86 - [clangd] Add metrics for go-to-implementation.

2021-01-11 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-11T10:26:50+01:00
New Revision: 1677c86124e5b82a8dbf991f2d5fc450d06db4ad

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

LOG: [clangd] Add metrics for go-to-implementation.

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index 667a90aa2efb..8bb74ed7ae43 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -298,6 +298,17 @@ std::vector 
findImplementors(llvm::DenseSet IDs,
 llvm::StringRef MainFilePath) {
   if (IDs.empty())
 return {};
+  static constexpr trace::Metric FindImplementorsMetric(
+  "find_implementors", trace::Metric::Counter, "case");
+  switch (Predicate) {
+  case RelationKind::BaseOf:
+FindImplementorsMetric.record(1, "find-base");
+break;
+  case RelationKind::OverriddenBy:
+FindImplementorsMetric.record(1, "find-override");
+break;
+  }
+
   RelationsRequest Req;
   Req.Predicate = Predicate;
   Req.Subjects = std::move(IDs);



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


[llvm-branch-commits] [clang-tools-extra] a2dbf34 - [clangd] Fix -check mode doesn't respect any tidy configs.

2021-01-11 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2021-01-11T16:43:33+01:00
New Revision: a2dbf3443af79426c80e8a808821236c5a2b305e

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

LOG: [clangd] Fix -check mode doesn't respect any tidy configs.

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

Added: 


Modified: 
clang-tools-extra/clangd/tool/Check.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/tool/Check.cpp 
b/clang-tools-extra/clangd/tool/Check.cpp
index 18d2837b89c2..e42596bb4bf4 100644
--- a/clang-tools-extra/clangd/tool/Check.cpp
+++ b/clang-tools-extra/clangd/tool/Check.cpp
@@ -123,6 +123,7 @@ class Checker {
 std::vector CC1Args;
 Inputs.CompileCommand = Cmd;
 Inputs.TFS = &TFS;
+Inputs.ClangTidyProvider = Opts.ClangTidyProvider;
 if (Contents.hasValue()) {
   Inputs.Contents = *Contents;
   log("Imaginary source file contents:\n{0}", Inputs.Contents);



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


[llvm-branch-commits] [clang] 5d21aed - Add release note for RecoveryExpr.

2020-08-28 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-08-28T09:56:52+02:00
New Revision: 5d21aedfdbf0b85d65bad08b7b89913205de4b33

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

LOG: Add release note for RecoveryExpr.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7b1df2ed9c3f..83877d0d95a2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -48,6 +48,46 @@ Major New Features
 
 - ...
 
+Recovery AST
+
+
+clang's AST now improves support for representing broken C++ code. This 
improves
+the quality of subsequent diagnostics after an error is encountered. It also
+exposes more information to tools like clang-tidy and clangd that consume
+clang’s AST, allowing them to be more accurate on broken code.
+
+A RecoveryExpr is introduced in clang's AST, marking an expression containing
+semantic errors. This preserves the source range and subexpressions of the
+broken expression in the AST (rather than discarding the whole expression).
+
+For the following invalid code:
+
+  .. code-block:: c++
+
+ int NoArg(); // Line 1
+ int x = NoArg(42); // oops!
+
+clang-10 produces the minimal placeholder:
+
+  .. code-block:: c++
+
+ // VarDecl  col:5 x 'int'
+
+clang-11 produces a richer AST:
+
+  .. code-block:: c++
+
+ // VarDecl  col:5 x 'int' cinit
+ // `-RecoveryExpr  '' contains-errors 
lvalue
+ //`-UnresolvedLookupExpr  '' lvalue (ADL) 
= 'NoArg'
+ //`-IntegerLiteral  'int' 42
+
+Note that error-dependent types and values may now occur outside a template
+context. Tools may need to adjust assumptions about dependent code.
+
+This feature is on by default for C++ code, and can be explicitly controlled
+with `-Xclang -f[no-]recovery-ast`.
+
 Improvements to Clang's diagnostics
 ^^^
 



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


[llvm-branch-commits] [clang] b1444ed - [AST] Build recovery expression by default for all language.

2020-11-23 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-11-23T11:08:28+01:00
New Revision: b1444edbf41c1fe9f7e676df6e873e9c9318283e

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

LOG: [AST] Build recovery expression by default for all language.

The dependency mechanism for C has been implemented, and we have rolled out
this to all internal users, didn't see crashy issues, we consider it is stable
enough.

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

Added: 


Modified: 
clang/include/clang/AST/Expr.h
clang/include/clang/Basic/LangOptions.def
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/CodeGen/SystemZ/builtins-systemz-zvector-error.c
clang/test/CodeGen/SystemZ/builtins-systemz-zvector2-error.c
clang/test/CodeGen/SystemZ/builtins-systemz-zvector3-error.c
clang/test/CodeGen/builtins-ppc-error.c
clang/test/Index/complete-switch.c
clang/test/OpenMP/begin_declare_variant_messages.c
clang/test/OpenMP/declare_variant_messages.c
clang/test/Parser/objc-foreach-syntax.m
clang/test/Sema/__try.c
clang/test/Sema/enum.c
clang/test/Sema/typo-correction.c

Removed: 




diff  --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 11b05ce7a5f5e..3ea2817f1926c 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -6330,9 +6330,6 @@ class TypoExpr : public Expr {
 ///
 /// One can also reliably suppress all bogus errors on expressions containing
 /// recovery expressions by examining results of Expr::containsErrors().
-///
-/// FIXME: RecoveryExpr is currently generated by default in C++ mode only, as
-/// dependence isn't handled properly on several C-only codepaths.
 class RecoveryExpr final : public Expr,
private llvm::TrailingObjects 
{
 public:

diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 9c573b43049c7..e4113789f07ce 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -148,8 +148,8 @@ LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed 
matching of template t
 
 LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for 
all language standard modes")
 
-COMPATIBLE_LANGOPT(RecoveryAST, 1, 0, "Preserve expressions in AST when 
encountering errors")
-COMPATIBLE_LANGOPT(RecoveryASTType, 1, 0, "Preserve the type in recovery 
expressions")
+COMPATIBLE_LANGOPT(RecoveryAST, 1, 1, "Preserve expressions in AST when 
encountering errors")
+COMPATIBLE_LANGOPT(RecoveryASTType, 1, 1, "Preserve the type in recovery 
expressions")
 
 BENIGN_LANGOPT(ThreadsafeStatics , 1, 1, "thread-safe static initializers")
 LANGOPT(POSIXThreads  , 1, 0, "POSIX thread support")

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index f6753b5b91a03..35025a9829ef8 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -3020,11 +3020,9 @@ static void ParseLangArgs(LangOptions &Opts, ArgList 
&Args, InputKind IK,
   !Args.hasArg(OPT_fno_concept_satisfaction_caching);
   if (Args.hasArg(OPT_fconcepts_ts))
 Diags.Report(diag::warn_fe_concepts_ts_flag);
-  // Recovery AST still heavily relies on dependent-type machinery.
-  Opts.RecoveryAST =
-  Args.hasFlag(OPT_frecovery_ast, OPT_fno_recovery_ast, Opts.CPlusPlus);
-  Opts.RecoveryASTType = Args.hasFlag(
-  OPT_frecovery_ast_type, OPT_fno_recovery_ast_type, Opts.CPlusPlus);
+  Opts.RecoveryAST = Args.hasFlag(OPT_frecovery_ast, OPT_fno_recovery_ast);
+  Opts.RecoveryASTType =
+  Args.hasFlag(OPT_frecovery_ast_type, OPT_fno_recovery_ast_type);
   Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
   Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
   Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);

diff  --git a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector-error.c 
b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector-error.c
index 5fdcb4061850f..77e90b5ad4b84 100644
--- a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector-error.c
+++ b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector-error.c
@@ -67,7 +67,7 @@ void test_core(void) {
   len = __lcbb(cptr, 8192);  // expected-error {{no matching function}}
  // expected-note@vecintrin.h:* {{must be a 
constant power of 2 from 64 to 4096}}
 
-  vsl = vec_permi(vsl, vsl, idx); // expected-error {{no matching function}}
+  vsl = vec_permi(vsl, vsl, idx); // expected-error {{no matching function}} 
expected-error {{argument to '__builtin_s390_vpdi' must be a constant integer}}
   // expected-note@vecintrin.h:* 3 {{candidate 
function

[llvm-branch-commits] [clang-tools-extra] fb6f425 - [clangd] Add metrics for invalid name.

2020-11-25 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-11-25T10:50:43+01:00
New Revision: fb6f425d1b06480f4e61109852b1761cc15c81c1

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

LOG: [clangd] Add metrics for invalid name.

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/Rename.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index e7924b4add09..78aaa9930cd4 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -341,6 +341,15 @@ struct InvalidName {
   Kind K;
   std::string Details;
 };
+std::string toString(InvalidName::Kind K) {
+  switch (K) {
+  case InvalidName::Keywords:
+return "Keywords";
+  case InvalidName::Conflict:
+return "Conflict";
+  }
+  llvm_unreachable("unhandled InvalidName kind");
+}
 
 llvm::Error makeError(InvalidName Reason) {
   auto Message = [](InvalidName Reason) {
@@ -361,18 +370,25 @@ llvm::Error makeError(InvalidName Reason) {
 llvm::Optional checkName(const NamedDecl &RenameDecl,
   llvm::StringRef NewName) {
   trace::Span Tracer("CheckName");
+  static constexpr trace::Metric InvalidNameMetric(
+  "rename_name_invalid", trace::Metric::Counter, "invalid_kind");
   auto &ASTCtx = RenameDecl.getASTContext();
+  llvm::Optional Result;
   if (isKeyword(NewName, ASTCtx.getLangOpts()))
-return InvalidName{InvalidName::Keywords, NewName.str()};
-  // Name conflict detection.
-  // Function conflicts are subtle (overloading), so ignore them.
-  if (RenameDecl.getKind() != Decl::Function) {
-if (auto *Conflict = lookupSiblingWithName(ASTCtx, RenameDecl, NewName))
-  return InvalidName{
-  InvalidName::Conflict,
-  Conflict->getLocation().printToString(ASTCtx.getSourceManager())};
+Result = InvalidName{InvalidName::Keywords, NewName.str()};
+  else {
+// Name conflict detection.
+// Function conflicts are subtle (overloading), so ignore them.
+if (RenameDecl.getKind() != Decl::Function) {
+  if (auto *Conflict = lookupSiblingWithName(ASTCtx, RenameDecl, NewName))
+Result = InvalidName{
+InvalidName::Conflict,
+Conflict->getLocation().printToString(ASTCtx.getSourceManager())};
+}
   }
-  return llvm::None;
+  if (Result)
+InvalidNameMetric.record(1, toString(Result->K));
+  return Result;
 }
 
 // AST-based rename, it renames all occurrences in the main file.

diff  --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index 68a6a666a895..d109b5139b2e 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1031,6 +1031,7 @@ TEST(RenameTest, PrepareRename) {
   EXPECT_THAT(FooCC.ranges(),
   testing::UnorderedElementsAreArray(Results->LocalChanges));
 
+  trace::TestTracer Tracer;
   // Name validation.
   Results =
   runPrepareRename(Server, FooCCPath, FooCC.point(),
@@ -1038,6 +1039,8 @@ TEST(RenameTest, PrepareRename) {
   EXPECT_FALSE(Results);
   EXPECT_THAT(llvm::toString(Results.takeError()),
   testing::HasSubstr("keyword"));
+  EXPECT_THAT(Tracer.takeMetric("rename_name_invalid", "Keywords"),
+  ElementsAre(1));
 
   // Single-file rename on global symbols, we should report an error.
   Results = runPrepareRename(Server, FooCCPath, FooCC.point(),



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


[llvm-branch-commits] [clang-tools-extra] 0cb3869 - [clangd] Fix a tsan failure.

2020-11-25 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-11-25T11:47:44+01:00
New Revision: 0cb38699a09d859dd40da0e4216b6066c63035f6

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

LOG: [clangd] Fix a tsan failure.

Tracer must be set up before calling any clangd-specific functions.

Added: 


Modified: 
clang-tools-extra/clangd/unittests/RenameTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index d109b5139b2e..c67339ff2be4 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1016,6 +1016,7 @@ TEST(RenameTest, PrepareRename) {
   auto ServerOpts = ClangdServer::optsForTest();
   ServerOpts.BuildDynamicSymbolIndex = true;
 
+  trace::TestTracer Tracer;
   MockCompilationDatabase CDB;
   ClangdServer Server(CDB, FS, ServerOpts);
   runAddDocument(Server, FooHPath, FooH.code());
@@ -1031,7 +1032,6 @@ TEST(RenameTest, PrepareRename) {
   EXPECT_THAT(FooCC.ranges(),
   testing::UnorderedElementsAreArray(Results->LocalChanges));
 
-  trace::TestTracer Tracer;
   // Name validation.
   Results =
   runPrepareRename(Server, FooCCPath, FooCC.point(),



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


[llvm-branch-commits] [clang] ec6c5e9 - [clang] Improve diagnostics for auto-return-type function if the return expr had an error.

2020-11-30 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-11-30T09:19:15+01:00
New Revision: ec6c5e920a89db0e1c5f73b8349ee0b84192072d

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

LOG: [clang] Improve diagnostics for auto-return-type function if the return 
expr had an error.

Given the following case:

```
auto k() {
  return undef();
  return 1;
}
```

Prior to the patch, clang emits an `cannot initialize return object of type
'auto' with an rvalue of type 'int'` diagnostic on the second return
(because the return type of the function cannot be deduced from the first 
contain-errors return).

This patch suppresses this error.

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

Added: 


Modified: 
clang/lib/Sema/SemaStmt.cpp
clang/test/SemaCXX/attr-target-mv.cpp
clang/test/SemaCXX/cxx1y-deduced-return-type.cpp
clang/test/SemaCXX/lambda-expressions.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 195121e1e256..f5bf889b3878 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3327,9 +3327,14 @@ Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, 
Expr *RetValExp) {
   }
 
   if (HasDeducedReturnType) {
+FunctionDecl *FD = CurLambda->CallOperator;
+// If we've already decided this lambda is invalid, e.g. because
+// we saw a `return` whose expression had an error, don't keep
+// trying to deduce its return type.
+if (FD->isInvalidDecl())
+  return StmtError();
 // In C++1y, the return type may involve 'auto'.
 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
-FunctionDecl *FD = CurLambda->CallOperator;
 if (CurCap->ReturnType.isNull())
   CurCap->ReturnType = FD->getReturnType();
 
@@ -3709,6 +3714,11 @@ StmtResult Sema::BuildReturnStmt(SourceLocation 
ReturnLoc, Expr *RetValExp) {
   if (getLangOpts().CPlusPlus14) {
 if (AutoType *AT = FnRetType->getContainedAutoType()) {
   FunctionDecl *FD = cast(CurContext);
+  // If we've already decided this function is invalid, e.g. because
+  // we saw a `return` whose expression had an error, don't keep
+  // trying to deduce its return type.
+  if (FD->isInvalidDecl())
+return StmtError();
   if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
 FD->setInvalidDecl();
 return StmtError();

diff  --git a/clang/test/SemaCXX/attr-target-mv.cpp 
b/clang/test/SemaCXX/attr-target-mv.cpp
index 11f3a276c7c7..5ef1d398d2d8 100644
--- a/clang/test/SemaCXX/attr-target-mv.cpp
+++ b/clang/test/SemaCXX/attr-target-mv.cpp
@@ -107,7 +107,6 @@ int __attribute__((target("arch=sandybridge"))) 
diff _mangle(void) { return 0; }
 
 // expected-error@+1 {{multiversioned functions do not yet support deduced 
return types}}
 auto __attribute__((target("default"))) deduced_return(void) { return 0; }
-// expected-error@-1 {{cannot initialize return object of type 'auto' with an 
rvalue of type 'int'}}
 
 auto __attribute__((target("default"))) trailing_return(void)-> int { return 
0; }
 

diff  --git a/clang/test/SemaCXX/cxx1y-deduced-return-type.cpp 
b/clang/test/SemaCXX/cxx1y-deduced-return-type.cpp
index 958728b10487..3e544c300884 100644
--- a/clang/test/SemaCXX/cxx1y-deduced-return-type.cpp
+++ b/clang/test/SemaCXX/cxx1y-deduced-return-type.cpp
@@ -22,7 +22,7 @@ int conv1d = conv1.operator int(); // expected-error {{no 
member named 'operator
 
 struct Conv2 {
   operator auto() { return 0; }  // expected-note {{previous}}
-  operator auto() { return 0.; } // expected-error {{cannot be redeclared}} 
expected-error {{cannot initialize return object of type 'auto' with an rvalue 
of type 'double'}}
+  operator auto() { return 0.; } // expected-error {{cannot be redeclared}}
 };
 
 struct Conv3 {
@@ -100,7 +100,7 @@ auto fac(int n) {
 auto fac_2(int n) { // expected-note {{declared here}}
   if (n > 2)
 return n * fac_2(n-1); // expected-error {{cannot be used before it is 
defined}}
-  return n; // expected-error {{cannot initialize return object of type 
'auto'}}
+  return n;
 }
 
 auto void_ret() {}
@@ -617,7 +617,6 @@ namespace PR33222 {
   };
   template<> auto *B::q() { return (int*)0; }
   template<> auto B::q() { return (int*)0; } // expected-error 
{{return type}}
-  // FIXME: suppress this follow-on error: expected-error@-1 {{cannot 
initialize}}
   template<> int B::q() { return 0; } // expected-error {{return 
type}}
 }
 

diff  --git a/clang/test/SemaCXX/lambda-expressions.cpp 
b/clang/test/SemaCXX/lambda-expressions.cpp
index 7f7f9c570487..22e0939379f5 100644
--- a/clang/test/SemaCXX/lambda-expressions.cpp
+++ b/clang/test/SemaCXX/lambda-expressions.cpp
@@ -521,6 +521,10 @@ void foo() {
   return undeclared_error; // expected-error {{us

[llvm-branch-commits] [clang] c219282 - [AST][RecoveryAST] Preseve more invalid return stmt.

2020-11-30 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-11-30T09:26:41+01:00
New Revision: c21928285430cc25905f774a89cb948867ae55b6

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

LOG: [AST][RecoveryAST] Preseve more invalid return stmt.

suppress the diagnostics for missing return stmt in constexpr func.

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

Added: 


Modified: 
clang/lib/Sema/SemaStmt.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaCXX/typo-correction-crash.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index f5bf889b3878..d89dfaf78a9c 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3629,7 +3629,8 @@ Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr 
*RetValExp,
   Scope *CurScope) {
   // Correct typos, in case the containing function returns 'auto' and
   // RetValExp should determine the deduced type.
-  ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
+  ExprResult RetVal = CorrectDelayedTyposInExpr(
+  RetValExp, nullptr, /*RecoverUncorrectedTypos=*/true);
   if (RetVal.isInvalid())
 return StmtError();
   StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());

diff  --git a/clang/test/SemaCXX/constant-expression-cxx11.cpp 
b/clang/test/SemaCXX/constant-expression-cxx11.cpp
index 8b80f5438d8e..67c5e78b8791 100644
--- a/clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1807,11 +1807,10 @@ namespace PR15884 {
 }
 
 namespace AfterError {
-  // FIXME: Suppress the 'no return statements' diagnostic if the body is 
invalid.
-  constexpr int error() { // expected-error {{no return statement}}
+  constexpr int error() {
 return foobar; // expected-error {{undeclared identifier}}
   }
-  constexpr int k = error();
+  constexpr int k = error(); // expected-error {{constexpr variable 'k' must 
be initialized by a constant expression}}
 }
 
 namespace std {

diff  --git a/clang/test/SemaCXX/typo-correction-crash.cpp 
b/clang/test/SemaCXX/typo-correction-crash.cpp
index 10c0c11aaa6b..49ea4c1bf16c 100644
--- a/clang/test/SemaCXX/typo-correction-crash.cpp
+++ b/clang/test/SemaCXX/typo-correction-crash.cpp
@@ -16,7 +16,8 @@ template  struct is_same { static constexpr 
bool value = true; };
 
 auto L1 = [] { return s; }; // expected-error {{use of undeclared identifier 
's'}}
 using T1 = decltype(L1());
-static_assert(is_same::value, "Return statement should be 
discarded");
+// FIXME: Suppress the 'undeclared identifier T1' diagnostic, the UsingDecl T1 
is discarded because of an invalid L1().
+static_assert(is_same::value, "Return statement should be 
discarded"); // expected-error {{use of undeclared identifier 'T1'}}
 auto L2 = [] { return tes; }; // expected-error {{use of undeclared identifier 
'tes'; did you mean 'test'?}}
 using T2 = decltype(L2());
 static_assert(is_same::value, "Return statement was corrected");



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


[llvm-branch-commits] [clang-tools-extra] a59e504 - [clangd] Fix a nullptr-access crash in canonicalRenameDecl.

2020-12-03 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-03T12:59:00+01:00
New Revision: a59e504a61a580e7b7d9af0b0380b573cee21a1c

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

LOG: [clangd] Fix a nullptr-access crash in canonicalRenameDecl.

Added: 


Modified: 
clang-tools-extra/clangd/refactor/Rename.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index 946daaf6d158..0af8a98427c7 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -129,7 +129,8 @@ const NamedDecl *canonicalRenameDecl(const NamedDecl *D) {
 // CXXMethodDecl::getInstantiatedFromMemberFunction for the field because
 // Clang AST does not store relevant information about the field that is
 // instantiated.
-const auto *FieldParent = dyn_cast(Field->getParent());
+const auto *FieldParent =
+dyn_cast_or_null(Field->getParent());
 if (!FieldParent)
   return Field->getCanonicalDecl();
 FieldParent = FieldParent->getTemplateInstantiationPattern();

diff  --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index 2382dba19659..306909892509 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -816,6 +816,13 @@ TEST(RenameTest, WithinFileRename) {
   [[F^oo]] foo = static_cast<[[F^oo]]>(boo);
 }
   )cpp",
+
+  // ObjC, should not crash.
+  R"cpp(
+@interface ObjC {
+  char [[da^ta]];
+} @end
+  )cpp",
   };
   llvm::StringRef NewName = "NewName";
   for (llvm::StringRef T : Tests) {
@@ -823,6 +830,7 @@ TEST(RenameTest, WithinFileRename) {
 Annotations Code(T);
 auto TU = TestTU::withCode(Code.code());
 TU.ExtraArgs.push_back("-fno-delayed-template-parsing");
+TU.ExtraArgs.push_back("-xobjective-c++");
 auto AST = TU.build();
 for (const auto &RenamePos : Code.points()) {
   auto RenameResult =



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


[llvm-branch-commits] [clang] 5b9fc44 - [clang] Add a C++17 deduction guide testcase.

2020-12-04 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-04T09:02:50+01:00
New Revision: 5b9fc44d8128717ef2f219b061c018abb85c717f

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

LOG: [clang] Add a C++17 deduction guide testcase.

>From https://bugs.llvm.org/show_bug.cgi?id=47219.

It was crashing before the commit 1e14588d0f68.

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

Added: 
clang/test/PCH/cxx17-deduction-guide-decl.cpp

Modified: 


Removed: 




diff  --git a/clang/test/PCH/cxx17-deduction-guide-decl.cpp 
b/clang/test/PCH/cxx17-deduction-guide-decl.cpp
new file mode 100644
index ..93ab82c02403
--- /dev/null
+++ b/clang/test/PCH/cxx17-deduction-guide-decl.cpp
@@ -0,0 +1,24 @@
+// Test with pch.
+// RUN: %clang_cc1 -emit-pch -std=c++17  -o %t %s
+// RUN: %clang_cc1 -include-pch %t -emit-llvm -std=c++17 -o - %s
+
+#ifndef HEADER
+#define HEADER
+
+namespace RP47219 {
+typedef int MyInt;
+template 
+class Some {
+ public:
+  explicit Some(T, MyInt) {}
+};
+
+struct Foo {};
+void ParseNatural() {
+  Some(Foo(), 1);
+}
+}
+
+#else
+
+#endif



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


[llvm-branch-commits] [clang-tools-extra] 445289a - [clangd] Fix an assertion violation in rename.

2020-12-04 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-04T12:23:26+01:00
New Revision: 445289aa63e1b82b9eea6497fb2d0443813a9d4e

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

LOG: [clangd] Fix an assertion violation in rename.

NamedDecl::getName() asserts the name must be an identifier.

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/Rename.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index 0af8a98427c7..8ed5811c88b2 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -637,7 +637,10 @@ llvm::Expected rename(const RenameInputs 
&RInputs) {
   if (DeclsUnderCursor.size() > 1)
 return makeError(ReasonToReject::AmbiguousSymbol);
   const auto &RenameDecl = **DeclsUnderCursor.begin();
-  if (RenameDecl.getName() == RInputs.NewName)
+  const auto *ID = RenameDecl.getIdentifier();
+  if (!ID)
+return makeError(ReasonToReject::UnsupportedSymbol);
+  if (ID->getName() == RInputs.NewName)
 return makeError(ReasonToReject::SameName);
   auto Invalid = checkName(RenameDecl, RInputs.NewName);
   if (Invalid)

diff  --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index 306909892509..0aa87c61baeb 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -946,6 +946,13 @@ TEST(RenameTest, Renameable) {
)cpp",
"not a supported kind", !HeaderFile, Index},
 
+  {R"cpp(// disallow rename on non-normal identifiers.
+ @interface Foo {}
+ -(int) fo^o:(int)x; // Token is an identifier, but declaration name 
isn't a simple identifier.
+ @end
+   )cpp",
+   "not a supported kind", HeaderFile, Index},
+
   {R"cpp(
  void foo(int);
  void foo(char);



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


[llvm-branch-commits] [clang-tools-extra] 1df0677 - [clangd] Add language metrics for recovery AST usage.

2020-12-07 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-07T10:52:05+01:00
New Revision: 1df0677e6ac65e18da54b1dd5c391bf17a4c2737

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

LOG: [clangd] Add language metrics for recovery AST usage.

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

Added: 


Modified: 
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index fbd72be320a7..9f84b4729182 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -38,21 +38,24 @@ using Node = SelectionTree::Node;
 using ast_type_traits::DynTypedNode;
 
 // Measure the fraction of selections that were enabled by recovery AST.
-void recordMetrics(const SelectionTree &S) {
+void recordMetrics(const SelectionTree &S, const LangOptions &Lang) {
+  if (!trace::enabled())
+return;
+  const char *LanguageLabel = Lang.CPlusPlus ? "C++" : Lang.ObjC ? "ObjC" : 
"C";
   static constexpr trace::Metric SelectionUsedRecovery(
-  "selection_recovery", trace::Metric::Distribution);
-  static constexpr trace::Metric RecoveryType("selection_recovery_type",
-  trace::Metric::Distribution);
+  "selection_recovery", trace::Metric::Distribution, "language");
+  static constexpr trace::Metric RecoveryType(
+  "selection_recovery_type", trace::Metric::Distribution, "language");
   const auto *Common = S.commonAncestor();
   for (const auto *N = Common; N; N = N->Parent) {
 if (const auto *RE = N->ASTNode.get()) {
-  SelectionUsedRecovery.record(1); // used recovery ast.
-  RecoveryType.record(RE->isTypeDependent() ? 0 : 1);
+  SelectionUsedRecovery.record(1, LanguageLabel); // used recovery ast.
+  RecoveryType.record(RE->isTypeDependent() ? 0 : 1, LanguageLabel);
   return;
 }
   }
   if (Common)
-SelectionUsedRecovery.record(0); // unused.
+SelectionUsedRecovery.record(0, LanguageLabel); // unused.
 }
 
 // An IntervalSet maintains a set of disjoint subranges of an array.
@@ -834,7 +837,7 @@ SelectionTree::SelectionTree(ASTContext &AST, const 
syntax::TokenBuffer &Tokens,
.printToString(SM));
   Nodes = SelectionVisitor::collect(AST, Tokens, PrintPolicy, Begin, End, FID);
   Root = Nodes.empty() ? nullptr : &Nodes.front();
-  recordMetrics(*this);
+  recordMetrics(*this, AST.getLangOpts());
   dlog("Built selection tree\n{0}", *this);
 }
 

diff  --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 55b05ebe11ab..efe06383b04a 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -18,6 +18,7 @@
 namespace clang {
 namespace clangd {
 namespace {
+using ::testing::ElementsAreArray;
 using ::testing::UnorderedElementsAreArray;
 
 // Create a selection tree corresponding to a point or pair of points.
@@ -452,7 +453,8 @@ TEST(SelectionTest, CommonAncestor) {
 if (Test.ranges().empty()) {
   // If no [[range]] is marked in the example, there should be no 
selection.
   EXPECT_FALSE(T.commonAncestor()) << C.Code << "\n" << T;
-  EXPECT_THAT(Tracer.takeMetric("selection_recovery"), testing::IsEmpty());
+  EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
+  testing::IsEmpty());
 } else {
   // If there is an expected selection, common ancestor should exist
   // with the appropriate node type.
@@ -468,8 +470,8 @@ TEST(SelectionTest, CommonAncestor) {
   // and no nodes outside it are selected.
   EXPECT_TRUE(verifyCommonAncestor(T.root(), T.commonAncestor(), C.Code))
   << C.Code;
-  EXPECT_THAT(Tracer.takeMetric("selection_recovery"),
-  testing::ElementsAreArray({0}));
+  EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
+  ElementsAreArray({0}));
 }
   }
 }
@@ -494,10 +496,10 @@ TEST(SelectionTree, Metrics) {
   auto AST = TestTU::withCode(Annotations(Code).code()).build();
   trace::TestTracer Tracer;
   auto T = makeSelectionTree(Code, AST);
-  EXPECT_THAT(Tracer.takeMetric("selection_recovery"),
-  testing::ElementsAreArray({1}));
-  EXPECT_THAT(Tracer.takeMetric("selection_recovery_type"),
-  testing::ElementsAreArray({1}));
+  EXPECT_THAT(Tracer.takeMetric("selection_recovery", "C++"),
+  ElementsAreArray({1}));
+  EXPECT_THAT(Tracer.takeMetric("selection_recovery_type", "C++"),
+  ElementsAreArray({1}));
 }
 
 // FIXME: Doesn't select the binary operator node in



__

[llvm-branch-commits] [llvm] ecaff13 - [MemProf] Fix a potential "permission denied" test failure on some systems.

2020-12-07 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-07T14:04:23+01:00
New Revision: ecaff13fc0bc1105ad910a72a5d0dcd164b35191

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

LOG: [MemProf] Fix a potential "permission denied" test failure on some systems.

NFC, to make the test more robost.

Added: 


Modified: 
llvm/test/Instrumentation/HeapProfiler/shadow.ll

Removed: 




diff  --git a/llvm/test/Instrumentation/HeapProfiler/shadow.ll 
b/llvm/test/Instrumentation/HeapProfiler/shadow.ll
index 4472f3d33a0f..6aa3a33aa91a 100644
--- a/llvm/test/Instrumentation/HeapProfiler/shadow.ll
+++ b/llvm/test/Instrumentation/HeapProfiler/shadow.ll
@@ -1,6 +1,6 @@
 ; RUN: opt < %s -passes='function(memprof),module(memprof-module)' -S | 
FileCheck --check-prefixes=STATIC %s
 
-; RUN: cp %s %t.pic.ll
+; RUN: cat %s > %t.pic.ll
 ; RUN: echo -e '!llvm.module.flags = !{!0}\n!0 = !{i32 7, !"PIC Level", i32 
1}' >> %t.pic.ll
 ; RUN: opt < %t.pic.ll -passes='function(memprof),module(memprof-module)' -S | 
FileCheck --check-prefixes=PIC %s
 



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


[llvm-branch-commits] [lldb] ce14ffa - [lldb] Fix a failure test after 843f2dbf003f2a51d0d4ab8cf40647c99ded2e93.

2020-12-09 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-09T09:32:13+01:00
New Revision: ce14ffa1bba2b609eaba81186c51cf26e9cd60ac

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

LOG: [lldb] Fix a failure test after 843f2dbf003f2a51d0d4ab8cf40647c99ded2e93.

The behavior of -gsplit-dwarf is changed because of the new commit.

Restore the old behavior by replacing -gsplit-dwarf with -gsplit-dwarf -g.

Added: 


Modified: 
lldb/test/Shell/SymbolFile/DWARF/split-dwarf-inlining.cpp

Removed: 




diff  --git a/lldb/test/Shell/SymbolFile/DWARF/split-dwarf-inlining.cpp 
b/lldb/test/Shell/SymbolFile/DWARF/split-dwarf-inlining.cpp
index 5873d896b19a..39c3fd643349 100644
--- a/lldb/test/Shell/SymbolFile/DWARF/split-dwarf-inlining.cpp
+++ b/lldb/test/Shell/SymbolFile/DWARF/split-dwarf-inlining.cpp
@@ -1,4 +1,4 @@
-// RUN: %clangxx -target x86_64-pc-linux -gsplit-dwarf -fsplit-dwarf-inlining \
+// RUN: %clangxx -target x86_64-pc-linux -gsplit-dwarf -g 
-fsplit-dwarf-inlining \
 // RUN:   -c %s -o %t
 // RUN: %lldb %t -o "breakpoint set -n foo" -b | FileCheck %s
 



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


[llvm-branch-commits] [lldb] 6883042 - [lldb] Fix one more failure test after 843f2dbf003f2a51d0d4ab8cf40647c99ded2e93.

2020-12-09 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-09T10:43:52+01:00
New Revision: 6883042528d0338b776bb2316e58999650e94892

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

LOG: [lldb] Fix one more failure test after 
843f2dbf003f2a51d0d4ab8cf40647c99ded2e93.

Added: 


Modified: 
lldb/test/Shell/SymbolFile/DWARF/split-dwarf-expression-eval-bug.cpp

Removed: 




diff  --git 
a/lldb/test/Shell/SymbolFile/DWARF/split-dwarf-expression-eval-bug.cpp 
b/lldb/test/Shell/SymbolFile/DWARF/split-dwarf-expression-eval-bug.cpp
index dcdc81b3e7eb..ef1aa257665d 100644
--- a/lldb/test/Shell/SymbolFile/DWARF/split-dwarf-expression-eval-bug.cpp
+++ b/lldb/test/Shell/SymbolFile/DWARF/split-dwarf-expression-eval-bug.cpp
@@ -7,9 +7,9 @@
 
 // UNSUPPORTED: system-darwin, system-windows
 
-// RUN: %clang_host -c -gsplit-dwarf %s -o %t1.o -DONE
-// RUN: %clang_host -c -gsplit-dwarf %s -o %t2.o -DTWO
-// RUN: %clang_host -c -gsplit-dwarf %s -o %t3.o -DTHREE
+// RUN: %clang_host -c -gsplit-dwarf -g %s -o %t1.o -DONE
+// RUN: %clang_host -c -gsplit-dwarf -g %s -o %t2.o -DTWO
+// RUN: %clang_host -c -gsplit-dwarf -g %s -o %t3.o -DTHREE
 // RUN: %clang_host %t1.o %t2.o %t3.o -o %t
 // RUN: %lldb %t -o "br set -n foo" -o run -o "p bool_in_first_cu" -o exit \
 // RUN:   | FileCheck %s



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


[llvm-branch-commits] [clang] a053929 - [AST] Fix a constexpr-evaluator crash on error-dependent returnstmt.

2020-12-10 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-10T10:12:15+01:00
New Revision: a0539298540e49cb734c7b82f93572ab46bf9b00

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

LOG: [AST] Fix a constexpr-evaluator crash on error-dependent returnstmt.

When the evaluator encounters an error-dependent returnstmt, before this patch
it returned a ESR_Returned without setting the result, the callsides think this
is a successful execution, and try to access the Result which causes the crash.

The fix is to always return failed as we don't know the result of the
error-dependent return stmt.

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/constexpr-function-recovery-crash.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index fc1d2cd7757e..0865b8b85138 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -5142,8 +5142,11 @@ static EvalStmtResult EvaluateStmt(StmtResult &Result, 
EvalInfo &Info,
   case Stmt::ReturnStmtClass: {
 const Expr *RetExpr = cast(S)->getRetValue();
 FullExpressionRAII Scope(Info);
-if (RetExpr && RetExpr->isValueDependent())
-  return EvaluateDependentExpr(RetExpr, Info) ? ESR_Returned : ESR_Failed;
+if (RetExpr && RetExpr->isValueDependent()) {
+  EvaluateDependentExpr(RetExpr, Info);
+  // We know we returned, but we don't know what the value is.
+  return ESR_Failed;
+}
 if (RetExpr &&
 !(Result.Slot
   ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)

diff  --git a/clang/test/SemaCXX/constexpr-function-recovery-crash.cpp 
b/clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
index 48a0d97619e4..94be9a12bc66 100644
--- a/clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
+++ b/clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
@@ -66,3 +66,6 @@ template constexpr int f(int y) { // expected-note 
{{candidate template i
 constexpr int test9(int x) {
   return f<1>(f(1)); // expected-error {{no matching function for call to 
'f'}}
 }
+
+constexpr int test10() { return undef(); } // expected-error {{use of 
undeclared identifier 'undef'}}
+static_assert(test10() <= 1, "should not crash"); // expected-error 
{{static_assert expression is not an integral constant expression}}



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


[llvm-branch-commits] [llvm] 2fc4afd - Fix a -Wunused-variable warning in release build.

2020-12-10 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-10T14:52:45+01:00
New Revision: 2fc4afda0f57d6c99b591c1f71f6da933d5e7b31

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

LOG: Fix a -Wunused-variable warning in release build.

Added: 


Modified: 
llvm/lib/Target/ARM/MVEVPTOptimisationsPass.cpp

Removed: 




diff  --git a/llvm/lib/Target/ARM/MVEVPTOptimisationsPass.cpp 
b/llvm/lib/Target/ARM/MVEVPTOptimisationsPass.cpp
index 909d478a95ca..62f23cf49073 100644
--- a/llvm/lib/Target/ARM/MVEVPTOptimisationsPass.cpp
+++ b/llvm/lib/Target/ARM/MVEVPTOptimisationsPass.cpp
@@ -257,6 +257,7 @@ bool MVEVPTOptimisations::MergeLoopEnd(MachineLoop *ML) {
   TII->get(ARM::t2LoopEndDec), DecReg)
   .addReg(PhiReg)
   .add(LoopEnd->getOperand(1));
+  (void)MI;
   LLVM_DEBUG(dbgs() << "Merged LoopDec and End into: " << *MI.getInstr());
 
   LoopDec->eraseFromParent();



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


[llvm-branch-commits] [clang] 5663bf2 - Revert "[analyzer] NFC: Move path diagnostic consumer implementations to libAnalysis."

2020-12-11 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-11T10:16:13+01:00
New Revision: 5663bf201f5c444d6fb56fb1bd471bc53c17d837

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

LOG: Revert "[analyzer] NFC: Move path diagnostic consumer implementations to 
libAnalysis."

The patch introduced a cycle dependency:

clangAnalysis -> clangFrontend -> clangSema -> clangAnalysis

This reverts commit 00ffea77ad887b576e9db82d98c97a31fee172cb.
This reverts commit ea6641085d025ca0a5cef940465ef14d0ccace02.

Added: 
clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp

Modified: 
clang/include/clang/CrossTU/CrossTranslationUnit.h
clang/include/clang/StaticAnalyzer/Core/Analyses.def
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
clang/include/clang/module.modulemap
clang/lib/Analysis/CMakeLists.txt
clang/lib/CrossTU/CrossTranslationUnit.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/StaticAnalyzer/Core/CMakeLists.txt
clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Removed: 
clang/include/clang/Analysis/CrossTUAnalysisHelper.h
clang/include/clang/Analysis/PathDiagnosticConsumers.def
clang/include/clang/Analysis/PathDiagnosticConsumers.h
clang/lib/Analysis/HTMLPathDiagnosticConsumer.cpp
clang/lib/Analysis/PlistHTMLPathDiagnosticConsumer.cpp
clang/lib/Analysis/PlistPathDiagnosticConsumer.cpp
clang/lib/Analysis/SarifPathDiagnosticConsumer.cpp
clang/lib/Analysis/TextPathDiagnosticConsumer.cpp



diff  --git a/clang/include/clang/Analysis/CrossTUAnalysisHelper.h 
b/clang/include/clang/Analysis/CrossTUAnalysisHelper.h
deleted file mode 100644
index ba2562b43055..
--- a/clang/include/clang/Analysis/CrossTUAnalysisHelper.h
+++ /dev/null
@@ -1,41 +0,0 @@
-//===- CrossTUAnalysisHelper.h - Abstraction layer for CTU --*- C++ 
-*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-#ifndef LLVM_CLANG_ANALYSIS_CROSS_TU_HELPER_H
-#define LLVM_CLANG_ANALYSIS_CROSS_TU_HELPER_H
-
-#include "llvm/ADT/Optional.h"
-#include "clang/Basic/SourceManager.h"
-
-namespace clang {
-
-class ASTUnit;
-
-/// This class is an abstract interface acting as a bridge between
-/// an analysis that requires lookups across translation units (a user
-/// of that interface) and the facility that implements such lookups
-/// (an implementation of that interface). This is useful to break direct
-/// link-time dependencies between the (possibly shared) libraries in which
-/// the user and the implementation live.
-class CrossTUAnalysisHelper {
-public:
-  /// Determine the original source location in the original TU for an
-  /// imported source location.
-  /// \p ToLoc Source location in the imported-to AST.
-  /// \return Source location in the imported-from AST and the corresponding
-  /// ASTUnit object (the AST was loaded from a file using an internal ASTUnit
-  /// object that is returned here).
-  /// If any error happens (ToLoc is a non-imported source location) empty is
-  /// returned.
-  virtual llvm::Optional>
-  getImportedFromSourceLocation(SourceLocation ToLoc) const = 0;
-
-  virtual ~CrossTUAnalysisHelper() {}
-};
-} // namespace clang
-
-#endif // LLVM_CLANG_ANALYSIS_CROSS_TU_HELPER_H

diff  --git a/clang/include/clang/Analysis/PathDiagnosticConsumers.def 
b/clang/include/clang/Analysis/PathDiagnosticConsumers.def
deleted file mode 100644
index 33d2072fcf31..
--- a/clang/include/clang/Analysis/PathDiagnosticConsumers.def
+++ /dev/null
@@ -1,50 +0,0 @@
-//===-- PathDiagnosticConsumers.def - Visualizing warnings --*- C++ 
-*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-// This file defines the set of path diagnostic consumers - objects that
-// implement 
diff erent representations of static analysis results.
-//
-//===--===//
-
-#ifndef ANALYSIS_DIAGNOSTICS
-#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN)
-#endif
-
-ANALYSIS_DIAGNOSTICS(HTML,

[llvm-branch-commits] [clang] 556e4eb - [AST][RecoveryAST] Preserve type for member call expr if argments are not matched.

2020-12-11 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-11T10:38:03+01:00
New Revision: 556e4eba4404acdc003ce344a62de846c0661be2

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

LOG: [AST][RecoveryAST] Preserve type for member call expr if argments are not 
matched.

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaOverload.cpp
clang/test/AST/ast-dump-recovery.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 9c838e574283..04e2b9553f4c 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3723,11 +3723,11 @@ class Sema final {
 SourceLocation RLoc,
 Expr *Base,Expr *Idx);
 
-  ExprResult
-  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
-SourceLocation LParenLoc,
-MultiExprArg Args,
-SourceLocation RParenLoc);
+  ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
+   SourceLocation LParenLoc,
+   MultiExprArg Args,
+   SourceLocation RParenLoc,
+   bool AllowRecovery = false);
   ExprResult
   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation 
LParenLoc,
MultiExprArg Args,
@@ -5238,7 +5238,8 @@ class Sema final {
   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
-   bool IsExecConfig = false);
+   bool IsExecConfig = false,
+   bool AllowRecovery = false);
   enum class AtomicArgumentOrder { API, AST };
   ExprResult
   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 859960d13007..0e829230d6a8 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6309,7 +6309,8 @@ ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, 
SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig) {
   ExprResult Call =
-  BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
+  BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
+/*IsExecConfig=*/false, /*AllowRecovery=*/true);
   if (Call.isInvalid())
 return Call;
 
@@ -6337,7 +6338,8 @@ ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, 
SourceLocation LParenLoc,
 /// locations.
 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation 
LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
-   Expr *ExecConfig, bool IsExecConfig) {
+   Expr *ExecConfig, bool IsExecConfig,
+   bool AllowRecovery) {
   // Since this might be a postfix expression, get rid of ParenListExprs.
   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
   if (Result.isInvalid()) return ExprError();
@@ -6397,7 +6399,7 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, 
SourceLocation LParenLoc,
 
 if (Fn->getType() == Context.BoundMemberTy) {
   return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
-   RParenLoc);
+   RParenLoc, AllowRecovery);
 }
   }
 
@@ -6416,7 +6418,7 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, 
SourceLocation LParenLoc,
 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
   return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
-   RParenLoc);
+   RParenLoc, AllowRecovery);
 }
   }
 

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index ff010fd6e4df..5689efe578fa 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -14154,11 +14154,11 @@ 
Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
 /// parameter). The caller needs to validate that the member
 /// expression refers to a non-static member function or an overloaded
 /// member function.
-ExprResult
-Sema::BuildCal

[llvm-branch-commits] [clang-tools-extra] 38d32e4 - [clangd] Reorder the class field to avoid -Wreorder-ctor warning, NFC.

2020-12-11 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-11T10:46:54+01:00
New Revision: 38d32e4fd70cc2b1f6ec10b578a56e631e8ed658

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

LOG: [clangd] Reorder the class field to avoid -Wreorder-ctor warning, NFC.

Added: 


Modified: 
clang-tools-extra/clangd/index/remote/Client.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/remote/Client.cpp 
b/clang-tools-extra/clangd/index/remote/Client.cpp
index bb19be54f6d2..0387e65db7d0 100644
--- a/clang-tools-extra/clangd/index/remote/Client.cpp
+++ b/clang-tools-extra/clangd/index/remote/Client.cpp
@@ -128,8 +128,8 @@ class IndexClient : public clangd::SymbolIndex {
 
 private:
   std::unique_ptr Stub;
-  llvm::SmallString<256> ServerAddress;
   std::unique_ptr ProtobufMarshaller;
+  llvm::SmallString<256> ServerAddress;
   // Each request will be terminated if it takes too long.
   std::chrono::milliseconds DeadlineWaitingTime;
 };



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


[llvm-branch-commits] [clang] 6326b09 - [AST][RecoveryExpr] Preserve type for broken overrload member call expr.

2020-12-13 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-14T08:50:41+01:00
New Revision: 6326b098852bea51debe415a85eebd1753151cd0

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

LOG: [AST][RecoveryExpr] Preserve type for broken overrload member call expr.

Reviewed By: sammccall

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

Added: 


Modified: 
clang/lib/Sema/SemaOverload.cpp
clang/test/AST/ast-dump-recovery.cpp
clang/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p12.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 5689efe578fa..13d2125d1a28 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -14300,6 +14300,7 @@ ExprResult Sema::BuildCallToMemberFunction(Scope *S, 
Expr *MemExprE,
 UnbridgedCasts.restore();
 
 OverloadCandidateSet::iterator Best;
+bool Succeeded = false;
 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
 Best)) {
 case OR_Success:
@@ -14307,7 +14308,7 @@ ExprResult Sema::BuildCallToMemberFunction(Scope *S, 
Expr *MemExprE,
   FoundDecl = Best->FoundDecl;
   CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
   if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
-return ExprError();
+break;
   // If FoundDecl is 
diff erent from Method (such as if one is a template
   // and the other a specialization), make sure DiagnoseUseOfDecl is
   // called on both.
@@ -14316,7 +14317,8 @@ ExprResult Sema::BuildCallToMemberFunction(Scope *S, 
Expr *MemExprE,
   // being used.
   if (Method != FoundDecl.getDecl() &&
   DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
-return ExprError();
+break;
+  Succeeded = true;
   break;
 
 case OR_No_Viable_Function:
@@ -14326,27 +14328,25 @@ ExprResult Sema::BuildCallToMemberFunction(Scope *S, 
Expr *MemExprE,
   PDiag(diag::err_ovl_no_viable_member_function_in_call)
   << DeclName << MemExprE->getSourceRange()),
   *this, OCD_AllCandidates, Args);
-  // FIXME: Leaking incoming expressions!
-  return ExprError();
-
+  break;
 case OR_Ambiguous:
   CandidateSet.NoteCandidates(
   PartialDiagnosticAt(UnresExpr->getMemberLoc(),
   PDiag(diag::err_ovl_ambiguous_member_call)
   << DeclName << MemExprE->getSourceRange()),
   *this, OCD_AmbiguousCandidates, Args);
-  // FIXME: Leaking incoming expressions!
-  return ExprError();
-
+  break;
 case OR_Deleted:
   CandidateSet.NoteCandidates(
   PartialDiagnosticAt(UnresExpr->getMemberLoc(),
   PDiag(diag::err_ovl_deleted_member_call)
   << DeclName << MemExprE->getSourceRange()),
   *this, OCD_AllCandidates, Args);
-  // FIXME: Leaking incoming expressions!
-  return ExprError();
+  break;
 }
+// Overload resolution fails, try to recover.
+if (!Succeeded)
+  return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
 
 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
 

diff  --git a/clang/test/AST/ast-dump-recovery.cpp 
b/clang/test/AST/ast-dump-recovery.cpp
index 2a8346eb0d15..a8da2b8ad449 100644
--- a/clang/test/AST/ast-dump-recovery.cpp
+++ b/clang/test/AST/ast-dump-recovery.cpp
@@ -125,6 +125,9 @@ struct Foo2 {
   double func();
   class ForwardClass;
   ForwardClass createFwd();
+
+  int overload();
+  int overload(int, int);
 };
 void test2(Foo2 f) {
   // CHECK:  RecoveryExpr {{.*}} 'double'
@@ -136,6 +139,11 @@ void test2(Foo2 f) {
   // CHECK-NEXT: `-MemberExpr {{.*}} '' .createFwd
   // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'f'
   f.createFwd();
+  // CHECK:  RecoveryExpr {{.*}} 'int' contains-errors
+  // CHECK-NEXT: |-UnresolvedMemberExpr
+  // CHECK-NEXT:`-DeclRefExpr {{.*}} 'Foo2'
+  // CHECK-NEXT: `-IntegerLiteral {{.*}} 'int' 1
+  f.overload(1);
 }
 
 // CHECK: |-AlignedAttr {{.*}} alignas

diff  --git a/clang/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p12.cpp 
b/clang/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p12.cpp
index ce43720cb2d3..f12e0083fb0c 100644
--- a/clang/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p12.cpp
+++ b/clang/test/CXX/dcl.dcl/basic.namespace/namespace.udecl/p12.cpp
@@ -9,7 +9,7 @@
 //   parameter types in a base class (rather than conflicting).
 
 template  struct Opaque {};
-template  void expect(Opaque _) {}
+template  void expect(Opaque _) {} // expected-note 4 
{{candidate function template not viable}}
 
 // PR5727
 // This just shouldn't cr

[llvm-branch-commits] [clang-tools-extra] 63ec9e4 - [clangd] Go-to-definition on pure virtual method decls jumps to all overrides.

2020-12-14 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-12-14T08:56:24+01:00
New Revision: 63ec9e40d10056b0f85605d585e7db0b4146851e

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

LOG: [clangd] Go-to-definition on pure virtual method decls jumps to all 
overrides.

Reviewed By: usaxena95

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/unittests/XRefsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index 8a85507ff14c..ac4543026a9f 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -292,6 +292,35 @@ const NamedDecl *getPreferredDecl(const NamedDecl *D) {
   return D;
 }
 
+std::vector findOverrides(llvm::DenseSet IDs,
+ const SymbolIndex *Index,
+ llvm::StringRef MainFilePath) {
+  if (IDs.empty())
+return {};
+  RelationsRequest Req;
+  Req.Predicate = RelationKind::OverriddenBy;
+  Req.Subjects = std::move(IDs);
+  std::vector Results;
+  Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
+auto DeclLoc =
+indexToLSPLocation(Object.CanonicalDeclaration, MainFilePath);
+if (!DeclLoc) {
+  elog("Find overrides: {0}", DeclLoc.takeError());
+  return;
+}
+Results.emplace_back();
+Results.back().Name = Object.Name.str();
+Results.back().PreferredDeclaration = *DeclLoc;
+auto DefLoc = indexToLSPLocation(Object.Definition, MainFilePath);
+if (!DefLoc) {
+  elog("Failed to convert location: {0}", DefLoc.takeError());
+  return;
+}
+Results.back().Definition = *DefLoc;
+  });
+  return Results;
+}
+
 // Decls are more complicated.
 // The AST contains at least a declaration, maybe a definition.
 // These are up-to-date, and so generally preferred over index results.
@@ -330,10 +359,19 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
   DeclRelation::TemplatePattern | DeclRelation::Alias;
   auto Candidates =
   getDeclAtPositionWithRelations(AST, CurLoc, Relations, NodeKind);
+  llvm::DenseSet VirtualMethods;
   for (const auto &E : Candidates) {
 const NamedDecl *D = E.first;
-// Special case: void foo() ^override: jump to the overridden method.
 if (const auto *CMD = llvm::dyn_cast(D)) {
+  // Special case: virtual void ^method() = 0: jump to all overrides.
+  // FIXME: extend it to ^virtual, unfortunately, virtual location is not
+  // saved in the AST.
+  if (CMD->isPure()) {
+if (TouchedIdentifier && SM.getSpellingLoc(CMD->getLocation()) ==
+ TouchedIdentifier->location())
+  VirtualMethods.insert(getSymbolID(CMD));
+  }
+  // Special case: void foo() ^override: jump to the overridden method.
   const InheritableAttr *Attr = D->getAttr();
   if (!Attr)
 Attr = D->getAttr();
@@ -420,6 +458,8 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
 });
   }
 
+  auto Overrides = findOverrides(VirtualMethods, Index, MainFilePath);
+  Result.insert(Result.end(), Overrides.begin(), Overrides.end());
   return Result;
 }
 
@@ -1145,36 +1185,14 @@ std::vector 
findImplementations(ParsedAST &AST, Position Pos,
  CurLoc.takeError());
 return {};
   }
-  std::vector Results;
   DeclRelationSet Relations =
   DeclRelation::TemplatePattern | DeclRelation::Alias;
-  RelationsRequest Req;
-  Req.Predicate = RelationKind::OverriddenBy;
+  llvm::DenseSet VirtualMethods;
   for (const NamedDecl *ND : getDeclAtPosition(AST, *CurLoc, Relations))
 if (const CXXMethodDecl *CXXMD = llvm::dyn_cast(ND))
   if (CXXMD->isVirtual())
-Req.Subjects.insert(getSymbolID(ND));
-
-  if (Req.Subjects.empty())
-return Results;
-  Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
-auto DeclLoc =
-indexToLSPLocation(Object.CanonicalDeclaration, *MainFilePath);
-if (!DeclLoc) {
-  elog("Find implementation: {0}", DeclLoc.takeError());
-  return;
-}
-LocatedSymbol Loc;
-Loc.Name = Object.Name.str();
-Loc.PreferredDeclaration = *DeclLoc;
-auto DefLoc = indexToLSPLocation(Object.Definition, *MainFilePath);
-if (DefLoc)
-  Loc.Definition = *DefLoc;
-else
-  llvm::consumeError(DefLoc.takeError());
-Results.push_back(Loc);
-  });
-  return Results;
+VirtualMethods.insert(getSymbolID(ND));
+  return findOverrides(std::move(VirtualMethods), Index, *MainFilePath);
 }
 
 ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit,

diff  --git a/clang-tools-extra/cla

[llvm-branch-commits] [clang-tools-extra] 2378a6e - [clangd] Fix null check in FindTarget.

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Sam McCall
Date: 2020-06-10T10:28:44+02:00
New Revision: 2378a6e4f136d574c294da72f2dde0225ba05e89

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

LOG: [clangd] Fix null check in FindTarget.

I've hit this stack trace a few times but don't have a good reproducer.
The code is unsafe by inspection, though.

(cherry picked from commit 9a5c448a31bacc08e73fcae4636094f9b6e2be6a)

Added: 


Modified: 
clang-tools-extra/clangd/FindTarget.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index 82a2e8c27d56..71bb9d3d5066 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -229,7 +229,7 @@ struct TargetFinder {
   }
 
   void add(const Decl *Dcl, RelSet Flags) {
-const NamedDecl *D = llvm::dyn_cast(Dcl);
+const NamedDecl *D = llvm::dyn_cast_or_null(Dcl);
 if (!D)
   return;
 debug(*D, Flags);



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


[llvm-branch-commits] [clang-tools-extra] 85a2d23 - [clangd] Add the missing elaborated types in FindTarget.

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-06-10T10:43:50+02:00
New Revision: 85a2d23d963a5bd537a447378c6fc19b6a8b224a

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

LOG: [clangd] Add the missing elaborated types in FindTarget.

Reviewers: sammccall

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, kadircet, usaxena95, 
cfe-commits

Tags: #clang

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

(cherry picked from commit eaf0c89ec5f866b6cef296c542c030bb2cf8481d)

Added: 


Modified: 
clang-tools-extra/clangd/FindTarget.cpp
clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index 5bdb1a63b87c..5912464b0ed0 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -374,6 +374,10 @@ struct TargetFinder {
 Outer.add(TT->getAsTagDecl(), Flags);
   }
 
+  void VisitElaboratedType(const ElaboratedType *ET) {
+Outer.add(ET->desugar(), Flags);
+  }
+
   void VisitInjectedClassNameType(const InjectedClassNameType *ICNT) {
 Outer.add(ICNT->getDecl(), Flags);
   }

diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index bbba007d242a..9c1020b7a189 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -242,6 +242,13 @@ TEST_F(TargetDeclTest, Types) {
   )cpp";
   EXPECT_DECLS("TypedefTypeLoc", {"typedef S X", Rel::Alias},
{"struct S", Rel::Underlying});
+  Code = R"cpp(
+namespace ns { struct S{}; }
+typedef ns::S X;
+[[X]] x;
+  )cpp";
+  EXPECT_DECLS("TypedefTypeLoc", {"typedef ns::S X", Rel::Alias},
+   {"struct S", Rel::Underlying});
 
   // FIXME: Auto-completion in a template requires disabling delayed template
   // parsing.



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


[llvm-branch-commits] [clang-tools-extra] 7918dbd - [clangd] Handle the missing injectedClassNameType in targetDecl.

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-06-10T10:40:34+02:00
New Revision: 7918dbda298871cd4f7f622c4d880e9251986ffd

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

LOG: [clangd] Handle the missing injectedClassNameType in targetDecl.

Reviewers: sammccall

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, kadircet, usaxena95, 
cfe-commits

Tags: #clang

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

(cherry picked from commit 5d4e89975714875a86cb8e62b60d93eebefa4029)

Added: 


Modified: 
clang-tools-extra/clangd/FindTarget.cpp
clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index 71bb9d3d5066..5bdb1a63b87c 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -373,6 +373,11 @@ struct TargetFinder {
   void VisitTagType(const TagType *TT) {
 Outer.add(TT->getAsTagDecl(), Flags);
   }
+
+  void VisitInjectedClassNameType(const InjectedClassNameType *ICNT) {
+Outer.add(ICNT->getDecl(), Flags);
+  }
+
   void VisitDecltypeType(const DecltypeType *DTT) {
 Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying);
   }

diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 408ebe24e773..bbba007d242a 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -286,6 +286,14 @@ TEST_F(TargetDeclTest, Types) {
   )cpp";
   // FIXME: We don't do a good job printing TemplateTypeParmDecls, apparently!
   EXPECT_DECLS("SizeOfPackExpr", "");
+
+  Code = R"cpp(
+template 
+class Foo {
+  void f([[Foo]] x);
+};
+  )cpp";
+  EXPECT_DECLS("InjectedClassNameTypeLoc", "class Foo");
 }
 
 TEST_F(TargetDeclTest, ClassTemplate) {



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


[llvm-branch-commits] [clang-tools-extra] cd477e7 - [clangd] Fix modernize-loop-convert "multiple diag in flight" crash.

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-06-10T10:57:46+02:00
New Revision: cd477e7fdbf75642caa58b55b498a62f82a88bf7

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

LOG: [clangd] Fix modernize-loop-convert "multiple diag in flight" crash.

Summary:
this maybe not ideal, but it is trivial and does fix the crash.

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

Reviewers: sammccall

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, kadircet, usaxena95, 
cfe-commits

Tags: #clang

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

(cherry picked from commit a466e4be3831848d7ff6ffbe4f57d99de8fb66af)

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index f359702b3f50..01a6ca74898b 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -522,13 +522,11 @@ void LoopConvertCheck::doConversion(
 const ValueDecl *MaybeContainer, const UsageResult &Usages,
 const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit,
 const ForStmt *Loop, RangeDescriptor Descriptor) {
-  auto Diag = diag(Loop->getForLoc(), "use range-based for loop instead");
-
   std::string VarName;
   bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
   bool AliasVarIsRef = false;
   bool CanCopy = true;
-
+  std::vector FixIts;
   if (VarNameFromAlias) {
 const auto *AliasVar = cast(AliasDecl->getSingleDecl());
 VarName = AliasVar->getName().str();
@@ -560,8 +558,8 @@ void LoopConvertCheck::doConversion(
   getAliasRange(Context->getSourceManager(), ReplaceRange);
 }
 
-Diag << FixItHint::CreateReplacement(
-CharSourceRange::getTokenRange(ReplaceRange), ReplacementText);
+FixIts.push_back(FixItHint::CreateReplacement(
+CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
 // No further replacements are made to the loop, since the iterator or 
index
 // was used exactly once - in the initialization of AliasVar.
   } else {
@@ -606,8 +604,8 @@ void LoopConvertCheck::doConversion(
 Usage.Kind == Usage::UK_CaptureByCopy ? "&" + VarName : VarName;
   }
   TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
-  Diag << FixItHint::CreateReplacement(
-  CharSourceRange::getTokenRange(Range), ReplaceText);
+  FixIts.push_back(FixItHint::CreateReplacement(
+  CharSourceRange::getTokenRange(Range), ReplaceText));
 }
   }
 
@@ -645,8 +643,9 @@ void LoopConvertCheck::doConversion(
   std::string Range = ("(" + TypeString + " " + VarName + " : " +
MaybeDereference + Descriptor.ContainerString + ")")
   .str();
-  Diag << FixItHint::CreateReplacement(
-  CharSourceRange::getTokenRange(ParenRange), Range);
+  FixIts.push_back(FixItHint::CreateReplacement(
+  CharSourceRange::getTokenRange(ParenRange), Range));
+  diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts;
   TUInfo->getGeneratedDecls().insert(make_pair(Loop, VarName));
 }
 

diff  --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp 
b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
index ef73519ef138..1fdd54888149 100644
--- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -266,6 +266,33 @@ TEST(DiagnosticsTest, ClangTidy) {
   ));
 }
 
+TEST(DiagnosticTest, NoMultipleDiagnosticInFlight) {
+  Annotations Main(R"cpp(
+template  struct Foo {
+  T *begin();
+  T *end();
+};
+struct LabelInfo {
+  int a;
+  bool b;
+};
+
+void f() {
+  Foo label_info_map;
+  [[for]] (auto it = label_info_map.begin(); it != label_info_map.end(); 
++it) {
+auto S = *it;
+  }
+}
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.ClangTidyChecks = "modernize-loop-convert";
+  EXPECT_THAT(
+  TU.build().getDiagnostics(),
+  UnorderedElementsAre(::testing::AllOf(
+  Diag(Main.range(), "use range-based for loop instead"),
+  DiagSource(Diag::ClangTidy), DiagName("modernize-loop-convert";
+}
+
 TEST(DiagnosticTest, ClangTidySuppressionComment) {
   Annotations Main(R"cpp(
 int main() {



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


[llvm-branch-commits] [clang-tools-extra] 38f995e - [clangd] Don't assert when completing a lambda variable inside the lambda.

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Sam McCall
Date: 2020-06-10T11:15:14+02:00
New Revision: 38f995e4cb4c77c4a64cd1fedc1aeae91d8281cc

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

LOG: [clangd] Don't assert when completing a lambda variable inside the lambda.

Summary:
This is a fairly ugly hack - we back off several features for any variable
whose type isn't deduced, to avoid computing/caching linkage.
Better suggestions welcome.

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

Reviewers: kadircet, kbobyrev

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits

Tags: #clang

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

(cherry picked from commit 2629035a009095f62f48413e175437261165ecd7)

Added: 


Modified: 
clang-tools-extra/clangd/AST.cpp
clang-tools-extra/clangd/AST.h
clang-tools-extra/clangd/CodeComplete.cpp
clang-tools-extra/clangd/Quality.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/AST.cpp 
b/clang-tools-extra/clangd/AST.cpp
index c800ee870dc9..836eb6a36459 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -473,5 +473,12 @@ std::string getQualification(ASTContext &Context,
   });
 }
 
+bool hasUnstableLinkage(const Decl *D) {
+  // Linkage of a ValueDecl depends on the type.
+  // If that's not deduced yet, deducing it may change the linkage.
+  auto *VD = llvm::dyn_cast_or_null(D);
+  return VD && !VD->getType().isNull() && VD->getType()->isUndeducedType();
+}
+
 } // namespace clangd
 } // namespace clang

diff  --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index 6cae719986a0..a40aeaf32a77 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -148,6 +148,21 @@ std::string getQualification(ASTContext &Context,
  const NamedDecl *ND,
  llvm::ArrayRef VisibleNamespaces);
 
+/// Whether we must avoid computing linkage for D during code completion.
+/// Clang aggressively caches linkage computation, which is stable after the 
AST
+/// is built. Unfortunately the AST is incomplete during code completion, so
+/// linkage may still change.
+///
+/// Example: `auto x = []{^}` at file scope.
+/// During code completion, the initializer for x hasn't been parsed yet.
+/// x has type `undeduced auto`, and external linkage.
+/// If we compute linkage at this point, the external linkage will be cached.
+///
+/// After code completion the initializer is attached, and x has a lambda type.
+/// This means x has "unique external" linkage. If we computed linkage above,
+/// the cached value is incorrect. (clang catches this with an assertion).
+bool hasUnstableLinkage(const Decl *D);
+
 } // namespace clangd
 } // namespace clang
 

diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 86268b6c25ec..275b7cc832dc 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -489,6 +489,9 @@ llvm::Optional getSymbolID(const 
CodeCompletionResult &R,
   switch (R.Kind) {
   case CodeCompletionResult::RK_Declaration:
   case CodeCompletionResult::RK_Pattern: {
+// Computing USR caches linkage, which may change after code completion.
+if (hasUnstableLinkage(R.Declaration))
+  return llvm::None;
 return clang::clangd::getSymbolID(R.Declaration);
   }
   case CodeCompletionResult::RK_Macro:
@@ -1001,10 +1004,12 @@ class SignatureHelpCollector final : public 
CodeCompleteConsumer {
 ScoredSignature Result;
 Result.Signature = std::move(Signature);
 Result.Quality = Signal;
-Result.IDForDoc =
-Result.Signature.documentation.empty() && Candidate.getFunction()
-? clangd::getSymbolID(Candidate.getFunction())
-: None;
+const FunctionDecl *Func = Candidate.getFunction();
+if (Func && Result.Signature.documentation.empty()) {
+  // Computing USR caches linkage, which may change after code completion.
+  if (!hasUnstableLinkage(Func))
+Result.IDForDoc = clangd::getSymbolID(Func);
+}
 return Result;
   }
 

diff  --git a/clang-tools-extra/clangd/Quality.cpp 
b/clang-tools-extra/clangd/Quality.cpp
index bd25256904cd..d80790fc9808 100644
--- a/clang-tools-extra/clangd/Quality.cpp
+++ b/clang-tools-extra/clangd/Quality.cpp
@@ -275,8 +275,9 @@ computeScope(const NamedDecl *D) {
   }
   if (InClass)
 return SymbolRelevanceSignals::ClassScope;
-  // This threshold could be tweaked, e.g. to treat module-visible as global.
-  if (D->getLinkageInternal() < ExternalLinkage)
+  // ExternalLinkage threshold could be tweaked, e.g. module-visible as global.
+  // Avoid cach

[llvm-branch-commits] [clang] cbc9b92 - [clang] Persist Attr::IsPackExpansion into the PCH

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Nathan Ridge
Date: 2020-06-10T11:34:30+02:00
New Revision: cbc9b92df4582617314b08d1ecef41d355733874

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

LOG: [clang] Persist Attr::IsPackExpansion into the PCH

Summary: Fixes https://github.com/clangd/clangd/issues/309

Subscribers: ilya-biryukov, kadircet, usaxena95, cfe-commits

Tags: #clang

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

(cherry picked from commit 8b3b7556e9ab6084e9fd337d64dac1c165867d32)

Added: 
clang/test/PCH/cxx-attrs-packexpansion.cpp

Modified: 
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/test/PCH/cxx-attrs-packexpansion.cpp 
b/clang/test/PCH/cxx-attrs-packexpansion.cpp
new file mode 100644
index ..6d292ec1e3e0
--- /dev/null
+++ b/clang/test/PCH/cxx-attrs-packexpansion.cpp
@@ -0,0 +1,25 @@
+// Test this without pch.
+// RUN: %clang_cc1 -include %s -emit-llvm -o - %s
+
+// Test with pch.
+// RUN: %clang_cc1 -emit-pch -o %t %s
+// RUN: %clang_cc1 -include-pch %t -emit-llvm -o - %s
+
+#ifndef HEADER
+#define HEADER
+
+template
+struct static_variant {
+alignas(Types...) T storage[10];
+};
+
+#else
+
+struct A {
+static_variant a;
+};
+struct B {
+static_variant _b;
+};
+
+#endif

diff  --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 4c3742c8e339..2fce9d428137 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2825,6 +2825,7 @@ void EmitClangAttrPCHRead(RecordKeeper &Records, 
raw_ostream &OS) {
 if (R.isSubClassOf(InhClass))
   OS << "bool isInherited = Record.readInt();\n";
 OS << "bool isImplicit = Record.readInt();\n";
+OS << "bool isPackExpansion = Record.readInt();\n";
 ArgRecords = R.getValueAsListOfDefs("Args");
 Args.clear();
 for (const auto *Arg : ArgRecords) {
@@ -2840,6 +2841,7 @@ void EmitClangAttrPCHRead(RecordKeeper &Records, 
raw_ostream &OS) {
 if (R.isSubClassOf(InhClass))
   OS << "cast(New)->setInherited(isInherited);\n";
 OS << "New->setImplicit(isImplicit);\n";
+OS << "New->setPackExpansion(isPackExpansion);\n";
 OS << "break;\n";
 OS << "  }\n";
   }
@@ -2866,6 +2868,7 @@ void EmitClangAttrPCHWrite(RecordKeeper &Records, 
raw_ostream &OS) {
 if (R.isSubClassOf(InhClass))
   OS << "Record.push_back(SA->isInherited());\n";
 OS << "Record.push_back(A->isImplicit());\n";
+OS << "Record.push_back(A->isPackExpansion());\n";
 
 for (const auto *Arg : Args)
   createArgument(*Arg, R.getName())->writePCHWrite(OS);



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


[llvm-branch-commits] [clang] d942a81 - PR45063: Fix crash on invalid processing an elaborated class template-id

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Richard Smith
Date: 2020-06-10T11:46:25+02:00
New Revision: d942a81c71a3f970857e92e98cc6503b61b589b0

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

LOG: PR45063: Fix crash on invalid processing an elaborated class template-id
with an invalid scope specifier.

(cherry picked from commit 44c3a63c74dddeef17e424ec76bd90c8582d8a3c)

Added: 


Modified: 
clang/lib/Sema/SemaTemplate.cpp
clang/test/Parser/cxx-template-decl.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index c38c724ed9b0..943e8f422a70 100755
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3817,6 +3817,9 @@ TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
 SourceLocation LAngleLoc,
 ASTTemplateArgsPtr TemplateArgsIn,
 SourceLocation RAngleLoc) {
+  if (SS.isInvalid())
+return TypeResult(true);
+
   TemplateName Template = TemplateD.get();
 
   // Translate the parser's template argument list in our AST format.

diff  --git a/clang/test/Parser/cxx-template-decl.cpp 
b/clang/test/Parser/cxx-template-decl.cpp
index cb8a93fdecb1..3d7a3dc14f4c 100644
--- a/clang/test/Parser/cxx-template-decl.cpp
+++ b/clang/test/Parser/cxx-template-decl.cpp
@@ -269,3 +269,7 @@ namespace AnnotateAfterInvalidTemplateId {
 
   void f() { A<0, 0>::f(); } // expected-error {{ambiguous partial 
specializations}}
 }
+
+namespace PR45063 {
+  template> struct X {}; // expected-error 
{{undeclared identifier 'a'}}
+}



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


[llvm-branch-commits] [clang] 3f4a753 - [clang] Fix crash on visiting null nestedNameSpecifier.

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Haojian Wu
Date: 2020-06-10T11:46:53+02:00
New Revision: 3f4a753f597357db77fe395561234a50daa451b3

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

LOG: [clang] Fix crash on visiting null nestedNameSpecifier.

Summary: Fix https://github.com/clangd/clangd/issues/293

Reviewers: sammccall

Subscribers: ilya-biryukov, kadircet, usaxena95, cfe-commits

Tags: #clang

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

(cherry picked from commit bd763e2cf7c1d84bab95064cc5cbe542b227b025)

Added: 


Modified: 
clang/lib/Sema/SemaTemplate.cpp
clang/test/Parser/cxx-template-decl.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 943e8f422a70..264c903209af 100755
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5928,7 +5928,9 @@ bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
 
 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
  const DependentTemplateSpecializationType* T) 
{
-  return VisitNestedNameSpecifier(T->getQualifier());
+  if (auto *Q = T->getQualifier())
+return VisitNestedNameSpecifier(Q);
+  return false;
 }
 
 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
@@ -5982,6 +5984,7 @@ bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const 
TagDecl *Tag) {
 
 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
 NestedNameSpecifier *NNS) {
+  assert(NNS);
   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
 return true;
 

diff  --git a/clang/test/Parser/cxx-template-decl.cpp 
b/clang/test/Parser/cxx-template-decl.cpp
index 3d7a3dc14f4c..0d52ad8fb50f 100644
--- a/clang/test/Parser/cxx-template-decl.cpp
+++ b/clang/test/Parser/cxx-template-decl.cpp
@@ -273,3 +273,9 @@ namespace AnnotateAfterInvalidTemplateId {
 namespace PR45063 {
   template> struct X {}; // expected-error 
{{undeclared identifier 'a'}}
 }
+
+namespace NoCrashOnEmptyNestedNameSpecifier {
+  template ::template arg_t<0>> // 
expected-error {{no template named 'ABC'}}
+  void foo(FnT) {}
+}



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


[llvm-branch-commits] [clang] 41c5efc - [Syntax] Simplify TokenCollector::Builder, use captured expansion bounds. NFC

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Sam McCall
Date: 2020-06-10T14:21:44+02:00
New Revision: 41c5efc3f2f22475bf3290309c90e84713511711

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

LOG: [Syntax] Simplify TokenCollector::Builder, use captured expansion bounds. 
NFC

Summary:
The motivation here is fixing https://bugs.llvm.org/show_bug.cgi?id=45428, see
D77507. The fundamental problem is that a "top-level" expansion wasn't precisely
defined. Repairing this concept means that TokenBuffer's "top-level expansion"
may not correspond to a single macro expansion. Example:

```
M(2); // expands to 1+2
```

The expansions overlap, but neither expansion alone yields all the tokens.
We need a TokenBuffer::Mapping that corresponds to their union.

This is fairly easy to fix in CollectPPExpansions, but the current design of
TokenCollector::Builder needs a fix too as it relies on the macro's expansion
range rather than the captured expansion bounds. This fix is hard to make due
to the way code is reused within Builder. And honestly, I found that code pretty
hard to reason about too.

The new approach doesn't use the expansion range, but only the expansion
location: it assumes an expansion is the contiguous set of expanded tokens with
the same expansion location, which seems like a reasonable formalization of
the "top-level" notion.

And hopefully the control flow is easier to follow too, it's considerably
shorter even with more documentation.

Reviewers: kadircet

Subscribers: cfe-commits

Tags: #clang

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

(cherry picked from commit ec0b9908952a9f4a19c3eb92ba0fc01cffcb8614)

Added: 


Modified: 
clang/lib/Tooling/Syntax/Tokens.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/Tokens.cpp 
b/clang/lib/Tooling/Syntax/Tokens.cpp
index 3df1c064923a..77cc9295757b 100644
--- a/clang/lib/Tooling/Syntax/Tokens.cpp
+++ b/clang/lib/Tooling/Syntax/Tokens.cpp
@@ -399,197 +399,167 @@ class TokenCollector::Builder {
   }
 
   TokenBuffer build() && {
-buildSpelledTokens();
-
-// Walk over expanded tokens and spelled tokens in parallel, building the
-// mappings between those using source locations.
-// To correctly recover empty macro expansions, we also take locations
-// reported to PPCallbacks::MacroExpands into account as we do not have any
-// expanded tokens with source locations to guide us.
-
-// The 'eof' token is special, it is not part of spelled token stream. We
-// handle it separately at the end.
 assert(!Result.ExpandedTokens.empty());
 assert(Result.ExpandedTokens.back().kind() == tok::eof);
-for (unsigned I = 0; I < Result.ExpandedTokens.size() - 1; ++I) {
-  // (!) I might be updated by the following call.
-  processExpandedToken(I);
-}
 
-// 'eof' not handled in the loop, do it here.
-assert(SM.getMainFileID() ==
-   SM.getFileID(Result.ExpandedTokens.back().location()));
-fillGapUntil(Result.Files[SM.getMainFileID()],
- Result.ExpandedTokens.back().location(),
- Result.ExpandedTokens.size() - 1);
-Result.Files[SM.getMainFileID()].EndExpanded = 
Result.ExpandedTokens.size();
+// Tokenize every file that contributed tokens to the expanded stream.
+buildSpelledTokens();
 
-// Some files might have unaccounted spelled tokens at the end, add an 
empty
-// mapping for those as they did not have expanded counterparts.
-fillGapsAtEndOfFiles();
+// The expanded token stream consists of runs of tokens that came from
+// the same source (a macro expansion, part of a file etc).
+// Between these runs are the logical positions of spelled tokens that
+// didn't expand to anything.
+while (NextExpanded < Result.ExpandedTokens.size() - 1 /* eof */) {
+  // Create empty mappings for spelled tokens that expanded to nothing 
here.
+  // May advance NextSpelled, but NextExpanded is unchanged.
+  discard();
+  // Create mapping for a contiguous run of expanded tokens.
+  // Advances NextExpanded past the run, and NextSpelled accordingly.
+  unsigned OldPosition = NextExpanded;
+  advance();
+  if (NextExpanded == OldPosition)
+diagnoseAdvanceFailure();
+}
+// If any tokens remain in any of the files, they didn't expand to 
anything.
+// Create empty mappings up until the end of the file.
+for (const auto &File : Result.Files)
+  discard(File.first);
 
 return std::move(Result);
   }
 
 private:
-  /// Process the next token in an expanded stream and move corresponding
-  /// spelled tokens, record any mapping if needed.
-  /// (!) \p I will be updated if this had to skip tokens, e.g. for macros.
-  void processExpandedToken(unsigned &I) {
-auto L = Result.E

[llvm-branch-commits] [clang] 0530e2a - [Syntax] Merge overlapping top-level macros in TokenBuffer

2020-06-10 Thread Haojian Wu via llvm-branch-commits

Author: Sam McCall
Date: 2020-06-10T14:21:44+02:00
New Revision: 0530e2a811b08f13e8137c29f047ad6bd11967fa

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

LOG: [Syntax] Merge overlapping top-level macros in TokenBuffer

Summary:
Our previous definition of "top-level" was too informal, and didn't
allow for overlapping macros that each directly produce expanded tokens.
See D77507 for previous discussion.

Fixes http://bugs.llvm.org/show_bug.cgi?id=45428

Reviewers: kadircet, vabridgers

Subscribers: cfe-commits

Tags: #clang

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

(cherry picked from commit d66afd6dde542dc373f87e07fe764c071fe20d76)

Added: 


Modified: 
clang/lib/Tooling/Syntax/Tokens.cpp
clang/unittests/Tooling/Syntax/TokensTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/Tokens.cpp 
b/clang/lib/Tooling/Syntax/Tokens.cpp
index 77cc9295757b..35a35f904069 100644
--- a/clang/lib/Tooling/Syntax/Tokens.cpp
+++ b/clang/lib/Tooling/Syntax/Tokens.cpp
@@ -335,14 +335,38 @@ class TokenCollector::CollectPPExpansions : public 
PPCallbacks {
 SourceRange Range, const MacroArgs *Args) override {
 if (!Collector)
   return;
-// Only record top-level expansions, not those where:
+const auto &SM = Collector->PP.getSourceManager();
+// Only record top-level expansions that directly produce expanded tokens.
+// This excludes those where:
 //   - the macro use is inside a macro body,
 //   - the macro appears in an argument to another macro.
-if (!MacroNameTok.getLocation().isFileID() ||
-(LastExpansionEnd.isValid() &&
- Collector->PP.getSourceManager().isBeforeInTranslationUnit(
- Range.getBegin(), LastExpansionEnd)))
+// However macro expansion isn't really a tree, it's token rewrite rules,
+// so there are other cases, e.g.
+//   #define B(X) X
+//   #define A 1 + B
+//   A(2)
+// Both A and B produce expanded tokens, though the macro name 'B' comes
+// from an expansion. The best we can do is merge the mappings for both.
+
+// The *last* token of any top-level macro expansion must be in a file.
+// (In the example above, see the closing paren of the expansion of B).
+if (!Range.getEnd().isFileID())
   return;
+// If there's a current expansion that encloses this one, this one can't be
+// top-level.
+if (LastExpansionEnd.isValid() &&
+!SM.isBeforeInTranslationUnit(LastExpansionEnd, Range.getEnd()))
+  return;
+
+// If the macro invocation (B) starts in a macro (A) but ends in a file,
+// we'll create a merged mapping for A + B by overwriting the endpoint for
+// A's startpoint.
+if (!Range.getBegin().isFileID()) {
+  Range.setBegin(SM.getExpansionLoc(Range.getBegin()));
+  assert(Collector->Expansions.count(Range.getBegin().getRawEncoding()) &&
+ "Overlapping macros should have same expansion location");
+}
+
 Collector->Expansions[Range.getBegin().getRawEncoding()] = Range.getEnd();
 LastExpansionEnd = Range.getEnd();
   }

diff  --git a/clang/unittests/Tooling/Syntax/TokensTest.cpp 
b/clang/unittests/Tooling/Syntax/TokensTest.cpp
index b2ad3859104a..f1e2dda963cb 100644
--- a/clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ b/clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -470,11 +470,28 @@ file './input.cpp'
   mappings:
 ['#'_0, 'int'_7) => ['int'_0, 'int'_0)
 ['FOO'_10, ''_11) => ['10'_3, ''_7)
-)"}};
+)"},
+  {R"cpp(
+ #define NUM 42
+ #define ID(a) a
+ #define M 1 + ID
+ M(NUM)
+   )cpp",
+   R"(expanded tokens:
+  1 + 42
+file './input.cpp'
+  spelled tokens:
+# define NUM 42 # define ID ( a ) a # define M 1 + ID M ( NUM )
+  mappings:
+['#'_0, 'M'_17) => ['1'_0, '1'_0)
+['M'_17, ''_21) => ['1'_0, ''_3)
+)"},
+  };
 
-  for (auto &Test : TestCases)
-EXPECT_EQ(Test.second, collectAndDump(Test.first))
-<< collectAndDump(Test.first);
+  for (auto &Test : TestCases) {
+std::string Dump = collectAndDump(Test.first);
+EXPECT_EQ(Test.second, Dump) << Dump;
+  }
 }
 
 TEST_F(TokenCollectorTest, SpecialTokens) {



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


[llvm-branch-commits] [clang-tools-extra] release/19.x: [clang-tidy] Avoid capturing a local variable in a static lambda in UseRangesCheck (#111282) (PR #111318)

2024-10-08 Thread Haojian Wu via llvm-branch-commits

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


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


[llvm-branch-commits] [clang] release/20.x: [Clang] Remove the PackExpansion restrictions for rewrite substitution (PR #127174)

2025-02-13 Thread Haojian Wu via llvm-branch-commits

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


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


[llvm-branch-commits] [clang] release/20.x: Fix false positive of [[clang::require_explicit_initialization]] on copy/move constructors (#126553) (PR #126767)

2025-02-11 Thread Haojian Wu via llvm-branch-commits

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

It looks good to me. This is an important fix.

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


[llvm-branch-commits] [clang] [clang-tools-extra] [clang][HeuristicResolver] Default argument heuristic for template parameters (PR #131074)

2025-03-19 Thread Haojian Wu via llvm-branch-commits


@@ -125,6 +126,20 @@ TagDecl 
*HeuristicResolverImpl::resolveTypeToTagDecl(QualType QT) {
   if (!T)
 return nullptr;
 
+  // If T is the type of a template parameter, we can't get a useful TagDecl
+  // out of it. However, if the template parameter has a default argument,
+  // as a heuristic we can replace T with the default argument type.
+  if (const auto *TTPT = dyn_cast(T)) {
+if (const auto *TTPD = TTPT->getDecl()) {
+  if (TTPD->hasDefaultArgument()) {
+const auto &DefaultArg = TTPD->getDefaultArgument().getArgument();
+if (DefaultArg.getKind() == TemplateArgument::Type) {
+  T = DefaultArg.getAsType().getTypePtrOrNull();

hokein wrote:

the code doesn't look safe -- `getTypePtrOrNull` could return a nullptr, then 
we have a null-reference on Line144. Move this new code block before line 126?

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


[llvm-branch-commits] [clang] release/20.x: [Clang] Fix an integer overflow issue in computing CTAD's parameter depth (PR #128845)

2025-02-26 Thread Haojian Wu via llvm-branch-commits

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


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