[PATCH] D95782: [Syntax] Support condition for IfStmt.

2021-02-04 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:803
 
+  bool TraverseIfStmt(IfStmt *S) {
+bool Result = [&, this]() {

sammccall wrote:
> is it clear to you what all this code is doing?
> It does seem to fit the pattern used elsewhere, it just looks pretty 
> different than the RAVs I've seen in the pass (e.g. overriding WalkUp 
> functions).
> 
> It seems correct, but I think I'll need to study later.
this is also my first time to see the pattern of overriding WalkUp function 
etc. 

The purpose of overriding the `TraverseIfStmt` is that the default 
implementation (which traverses the implicit condition expression which has the 
same location of the condition variable decl) seems to violate the invariant of 
foldNode (`fold should not crosses boundaries of existing subtrees`).

I think the `TraverseCXXForRangeStmt` below follows the same patten :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95782

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


[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-04 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321334.
kbobyrev marked 5 inline comments as done and an inline comment as not done.
kbobyrev added a comment.

Fix a couple problems pointed out during the review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,69 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
-  int Conflict;
-  int [[V^ar]];
+  bool Whatever;
+  int V^ar;
+  char Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,101 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  // Store Parents list outside of GetSingleParent, so that returned pointer is
+  // not invalidated.
+  DynTypedNodeList Storage(DynTypedNode::create(RenamedDecl));
+  auto GetSingleParent = [&](DynTypedNode Node) -> const DynTypedNode * {
+Storage = Ctx.getParents(Node);
+return (Storage.size() == 1) ? Storage.begin() : nullptr;
+  };
+
+  // We need to get to the enclosing scope: NamedDecl's parent is typically
+  // DeclStmt, so enclosing scope would be the second order parent.
+  const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
+  if (!Parent || !Parent->get())
+return nullptr;
+  Parent = GetSingleParent(*Parent);
+
+  // The following helpers check corresponding AST nodes for variable
+  // declarations with the name collision.
+  auto CheckDeclStmt = [&](const DeclStmt *DS,
+   StringRef Name) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == Name)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const Stmt *S,
+   StringRef Name) -> const NamedDecl * {
+if (const auto *CS = dyn_cast_or_null(S))
+  for (const auto *Node : CS->children())
+if (const auto *Result = CheckDeclStmt(dyn_cast(Node), Name))
+  return Result;

[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-04 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:334
+  DynTypedNodeList Parents(DynTypedNode::create(RenamedDecl));
+  auto GetSingleParent = [&](DynTypedNode Node) -> const DynTypedNode * {
+Parents = Ctx.getParents(Node);

hokein wrote:
> `const DynTypedNode &`
Sorry, I'm a bit confused: this can return nullptr when there are _no parents_. 
Is there any way I can return the reference safely?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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


[clang] 6c1a233 - [Syntax] Support condition for IfStmt.

2021-02-04 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2021-02-04T09:15:30+01:00
New Revision: 6c1a23303de9d957cf45ebd04daba862519e393d

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

LOG: [Syntax] Support condition for IfStmt.

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

Added: 


Modified: 
clang/lib/Tooling/Syntax/BuildTree.cpp
clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
clang/unittests/Tooling/Syntax/SynthesisTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/BuildTree.cpp 
b/clang/lib/Tooling/Syntax/BuildTree.cpp
index 7654e3dfaa01..62573b6c95b2 100644
--- a/clang/lib/Tooling/Syntax/BuildTree.cpp
+++ b/clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -800,6 +800,30 @@ class BuildTreeVisitor : public 
RecursiveASTVisitor {
 return true;
   }
 
+  bool TraverseIfStmt(IfStmt *S) {
+bool Result = [&, this]() {
+  if (S->getInit() && !TraverseStmt(S->getInit())) {
+return false;
+  }
+  // In cases where the condition is an initialized declaration in a
+  // statement, we want to preserve the declaration and ignore the
+  // implicit condition expression in the syntax tree.
+  if (S->hasVarStorage()) {
+if (!TraverseStmt(S->getConditionVariableDeclStmt()))
+  return false;
+  } else if (S->getCond() && !TraverseStmt(S->getCond()))
+return false;
+
+  if (S->getThen() && !TraverseStmt(S->getThen()))
+return false;
+  if (S->getElse() && !TraverseStmt(S->getElse()))
+return false;
+  return true;
+}();
+WalkUpFromIfStmt(S);
+return Result;
+  }
+
   bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
 // We override to traverse range initializer as VarDecl.
 // RAV traverses it as a statement, we produce invalid node kinds in that
@@ -1426,6 +1450,10 @@ class BuildTreeVisitor : public 
RecursiveASTVisitor {
 
   bool WalkUpFromIfStmt(IfStmt *S) {
 Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword);
+Stmt *ConditionStatement = S->getCond();
+if (S->hasVarStorage())
+  ConditionStatement = S->getConditionVariableDeclStmt();
+Builder.markStmtChild(ConditionStatement, syntax::NodeRole::Condition);
 Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement);
 Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword);
 Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement);

diff  --git a/clang/unittests/Tooling/Syntax/BuildTreeTest.cpp 
b/clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
index 17e1bbe102df..1f950b05e3f1 100644
--- a/clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ b/clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -204,8 +204,9 @@ void test() {
 IfStatement Statement
 |-'if' IntroducerKeyword
 |-'('
-|-IntegerLiteralExpression
-| `-'1' LiteralToken
+|-ExpressionStatement Condition
+| `-IntegerLiteralExpression Expression
+|   `-'1' LiteralToken
 |-')'
 `-CompoundStatement ThenStatement
   |-'{' OpenParen
@@ -215,8 +216,9 @@ IfStatement Statement
 IfStatement Statement
 |-'if' IntroducerKeyword
 |-'('
-|-IntegerLiteralExpression
-| `-'1' LiteralToken
+|-ExpressionStatement Condition
+| `-IntegerLiteralExpression Expression
+|   `-'1' LiteralToken
 |-')'
 |-CompoundStatement ThenStatement
 | |-'{' OpenParen
@@ -225,8 +227,9 @@ IfStatement Statement
 `-IfStatement ElseStatement
   |-'if' IntroducerKeyword
   |-'('
-  |-IntegerLiteralExpression
-  | `-'0' LiteralToken
+  |-ExpressionStatement Condition
+  | `-IntegerLiteralExpression Expression
+  |   `-'0' LiteralToken
   |-')'
   `-CompoundStatement ThenStatement
 |-'{' OpenParen
@@ -234,6 +237,61 @@ IfStatement Statement
 )txt"}));
 }
 
+TEST_P(BuildSyntaxTreeTest, IfDecl) {
+  if (!GetParam().isCXX17OrLater()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+void test() {
+  [[if (int a = 5) {}]]
+  [[if (int a; a == 5) {}]]
+}
+)cpp",
+  {R"txt(
+IfStatement Statement
+|-'if' IntroducerKeyword
+|-'('
+|-DeclarationStatement Condition
+| `-SimpleDeclaration
+|   |-'int'
+|   `-DeclaratorList Declarators
+| `-SimpleDeclarator ListElement
+|   |-'a'
+|   |-'='
+|   `-IntegerLiteralExpression
+| `-'5' LiteralToken
+|-')'
+`-CompoundStatement ThenStatement
+  |-'{' OpenParen
+  `-'}' CloseParen
+  )txt",
+   R"txt(
+IfStatement Statement
+|-'if' IntroducerKeyword
+|-'('
+|-DeclarationStatement
+| |-SimpleDeclaration
+| | |-'int'
+| | `-DeclaratorList Declarators
+| |   `-SimpleDeclarator ListElement
+| | `-'a'
+| `-';'
+|-ExpressionStatement Condition
+| `-BinaryOperatorExpression Expression
+|   |-IdExpression LeftHandSide
+|   | `-UnqualifiedId UnqualifiedId
+|   |   `-'a'
+|   |-'==' OperatorToken
+|   `-IntegerLiteralExpression RightH

[PATCH] D95782: [Syntax] Support condition for IfStmt.

2021-02-04 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6c1a23303de9: [Syntax] Support condition for IfStmt. 
(authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95782

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
  clang/unittests/Tooling/Syntax/SynthesisTest.cpp

Index: clang/unittests/Tooling/Syntax/SynthesisTest.cpp
===
--- clang/unittests/Tooling/Syntax/SynthesisTest.cpp
+++ clang/unittests/Tooling/Syntax/SynthesisTest.cpp
@@ -238,12 +238,13 @@
 |-IfStatement Statement synthesized
 | |-'if' IntroducerKeyword synthesized
 | |-'(' synthesized
-| |-BinaryOperatorExpression synthesized
-| | |-IntegerLiteralExpression LeftHandSide synthesized
-| | | `-'1' LiteralToken synthesized
-| | |-'+' OperatorToken synthesized
-| | `-IntegerLiteralExpression RightHandSide synthesized
-| |   `-'1' LiteralToken synthesized
+| |-ExpressionStatement Condition synthesized
+| | `-BinaryOperatorExpression Expression synthesized
+| |   |-IntegerLiteralExpression LeftHandSide synthesized
+| |   | `-'1' LiteralToken synthesized
+| |   |-'+' OperatorToken synthesized
+| |   `-IntegerLiteralExpression RightHandSide synthesized
+| | `-'1' LiteralToken synthesized
 | |-')' synthesized
 | |-CompoundStatement ThenStatement synthesized
 | | |-'{' OpenParen synthesized
Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -204,8 +204,9 @@
 IfStatement Statement
 |-'if' IntroducerKeyword
 |-'('
-|-IntegerLiteralExpression
-| `-'1' LiteralToken
+|-ExpressionStatement Condition
+| `-IntegerLiteralExpression Expression
+|   `-'1' LiteralToken
 |-')'
 `-CompoundStatement ThenStatement
   |-'{' OpenParen
@@ -215,8 +216,9 @@
 IfStatement Statement
 |-'if' IntroducerKeyword
 |-'('
-|-IntegerLiteralExpression
-| `-'1' LiteralToken
+|-ExpressionStatement Condition
+| `-IntegerLiteralExpression Expression
+|   `-'1' LiteralToken
 |-')'
 |-CompoundStatement ThenStatement
 | |-'{' OpenParen
@@ -225,8 +227,9 @@
 `-IfStatement ElseStatement
   |-'if' IntroducerKeyword
   |-'('
-  |-IntegerLiteralExpression
-  | `-'0' LiteralToken
+  |-ExpressionStatement Condition
+  | `-IntegerLiteralExpression Expression
+  |   `-'0' LiteralToken
   |-')'
   `-CompoundStatement ThenStatement
 |-'{' OpenParen
@@ -234,6 +237,61 @@
 )txt"}));
 }
 
+TEST_P(BuildSyntaxTreeTest, IfDecl) {
+  if (!GetParam().isCXX17OrLater()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+void test() {
+  [[if (int a = 5) {}]]
+  [[if (int a; a == 5) {}]]
+}
+)cpp",
+  {R"txt(
+IfStatement Statement
+|-'if' IntroducerKeyword
+|-'('
+|-DeclarationStatement Condition
+| `-SimpleDeclaration
+|   |-'int'
+|   `-DeclaratorList Declarators
+| `-SimpleDeclarator ListElement
+|   |-'a'
+|   |-'='
+|   `-IntegerLiteralExpression
+| `-'5' LiteralToken
+|-')'
+`-CompoundStatement ThenStatement
+  |-'{' OpenParen
+  `-'}' CloseParen
+  )txt",
+   R"txt(
+IfStatement Statement
+|-'if' IntroducerKeyword
+|-'('
+|-DeclarationStatement
+| |-SimpleDeclaration
+| | |-'int'
+| | `-DeclaratorList Declarators
+| |   `-SimpleDeclarator ListElement
+| | `-'a'
+| `-';'
+|-ExpressionStatement Condition
+| `-BinaryOperatorExpression Expression
+|   |-IdExpression LeftHandSide
+|   | `-UnqualifiedId UnqualifiedId
+|   |   `-'a'
+|   |-'==' OperatorToken
+|   `-IntegerLiteralExpression RightHandSide
+| `-'5' LiteralToken
+|-')'
+`-CompoundStatement ThenStatement
+  |-'{' OpenParen
+  `-'}' CloseParen
+)txt"}));
+}
+
 TEST_P(BuildSyntaxTreeTest, For) {
   EXPECT_TRUE(treeDumpEqualOnAnnotations(
   R"cpp(
@@ -420,8 +478,9 @@
 |-IfStatement Statement
 | |-'if' IntroducerKeyword
 | |-'('
-| |-IntegerLiteralExpression
-| | `-'1' LiteralToken
+| |-ExpressionStatement Condition
+| | `-IntegerLiteralExpression Expression
+| |   `-'1' LiteralToken
 | |-')'
 | |-ExpressionStatement ThenStatement
 | | |-CallExpression Expression
@@ -3992,12 +4051,13 @@
 |-IfStatement Statement
 | |-'if' IntroducerKeyword unmodifiable
 | |-'(' unmodifiable
-| |-BinaryOperatorExpression unmodifiable
-| | |-IntegerLiteralExpression LeftHandSide unmodifiable
-| | | `-'1' LiteralToken unmodifiable
-| | |-'+' OperatorToken unmodifiable
-| | `-IntegerLiteralExpression RightHandSide unmodifiable
-| |   `-'1' LiteralToken unmodifiable
+| |-ExpressionStatement Condition unmodifiable
+| | `-BinaryOperatorExpression Expressio

[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-04 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321336.
kbobyrev marked an inline comment as done.
kbobyrev added a comment.

Pass const ref to DynTypedNode in helper.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,69 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
-  int Conflict;
-  int [[V^ar]];
+  bool Whatever;
+  int V^ar;
+  char Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,101 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  // Store Parents list outside of GetSingleParent, so that returned pointer is
+  // not invalidated.
+  DynTypedNodeList Storage(DynTypedNode::create(RenamedDecl));
+  auto GetSingleParent = [&](const DynTypedNode &Node) -> const DynTypedNode * {
+Storage = Ctx.getParents(Node);
+return (Storage.size() == 1) ? Storage.begin() : nullptr;
+  };
+
+  // We need to get to the enclosing scope: NamedDecl's parent is typically
+  // DeclStmt, so enclosing scope would be the second order parent.
+  const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
+  if (!Parent || !Parent->get())
+return nullptr;
+  Parent = GetSingleParent(*Parent);
+
+  // The following helpers check corresponding AST nodes for variable
+  // declarations with the name collision.
+  auto CheckDeclStmt = [&](const DeclStmt *DS,
+   StringRef Name) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == Name)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const Stmt *S,
+   StringRef Name) -> const NamedDecl * {
+if (const auto *CS = dyn_cast_or_null(S))
+  for (const auto *Node : CS->children())
+if (const auto *Result = CheckDeclStmt(dyn_cast(Node), Name))
+  return Result;
+return nullptr;
+  };
+  auto Che

[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-04 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Looks good, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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


[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-04 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:411
+  if (const auto *EnclosingFor = Parent->get())
+return CheckCompoundStmt(EnclosingFor->getBody(), NewName);
+

another case we could add is FunctionDecl, if we rename a parameter decl, we 
could check collisions in the function body. this can be addressed in a 
follow-up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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


[clang-tools-extra] 5eec9a3 - [clangd] Detect rename conflicits within enclosing scope

2021-02-04 Thread Kirill Bobyrev via cfe-commits

Author: Kirill Bobyrev
Date: 2021-02-04T09:45:42+01:00
New Revision: 5eec9a380a24bf0611c676b5da4933949c787a6b

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

LOG: [clangd] Detect rename conflicits within enclosing scope

This patch allows detecting conflicts with variables defined in the current
CompoundStmt or If/While/For variable init statements.

Reviewed By: hokein

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

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 a857b3479871..bcce307a4362 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,101 @@ std::vector 
findOccurrencesWithinFile(ParsedAST &AST,
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl 
&RenamedDecl,
+   StringRef NewName) {
+  // Store Parents list outside of GetSingleParent, so that returned pointer is
+  // not invalidated.
+  DynTypedNodeList Storage(DynTypedNode::create(RenamedDecl));
+  auto GetSingleParent = [&](const DynTypedNode &Node) -> const DynTypedNode * 
{
+Storage = Ctx.getParents(Node);
+return (Storage.size() == 1) ? Storage.begin() : nullptr;
+  };
+
+  // We need to get to the enclosing scope: NamedDecl's parent is typically
+  // DeclStmt, so enclosing scope would be the second order parent.
+  const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
+  if (!Parent || !Parent->get())
+return nullptr;
+  Parent = GetSingleParent(*Parent);
+
+  // The following helpers check corresponding AST nodes for variable
+  // declarations with the name collision.
+  auto CheckDeclStmt = [&](const DeclStmt *DS,
+   StringRef Name) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == Name)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const Stmt *S,
+   StringRef Name) -> const NamedDecl * {
+if (const auto *CS = dyn_cast_or_null(S))
+  for (const auto *Node : CS->children())
+if (const auto *Result = CheckDeclStmt(dyn_cast(Node), Name))
+  return Result;
+return nullptr;
+  };
+  auto CheckConditionVariable = [&](const auto *Scope,
+StringRef Name) -> const NamedDecl * {
+if (!Scope)
+  return nullptr;
+return CheckDeclStmt(Scope->getConditionVariableDeclStmt(), Name);
+  };
+
+  // CompoundStmt is the most common enclosing scope for function-local symbols
+  // In the simplest case we just iterate through sibling DeclStmts and check
+  // for collisions.
+  if (const auto *EnclosingCS = Parent->get()) {
+if (const auto *Result = CheckCompoundStmt(EnclosingCS, NewName))
+  return Result;
+const auto *ScopeParent = GetSingleParent(*Parent);
+// CompoundStmt may be found within if/while/for. In these cases, rename 
can
+// collide with the init-statement variable decalaration, they should be
+// checked.
+if (const auto *Result =
+CheckConditionVariable(ScopeParent->get(), NewName))
+  return Result;
+if (const auto *Result =
+CheckConditionVariable(ScopeParent->get(), NewName))
+  return Result;
+if (const auto *For = ScopeParent->get())
+  if (const auto *Result = CheckDeclStmt(
+  dyn_cast_or_null(For->getInit()), NewName))
+return Result;
+// Also check if there is a name collision with function arguments.
+if (const auto *Function = ScopeParent->get())
+  for (const auto *Parameter : Function->parameters())
+if (Parameter->getName() == NewName)
+  return Parameter;
+return nullptr;
+  }
+
+  // When renaming a variable within init-statement with

[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-04 Thread Kirill Bobyrev via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5eec9a380a24: [clangd] Detect rename conflicits within 
enclosing scope (authored by kbobyrev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,69 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
-  int Conflict;
-  int [[V^ar]];
+  bool Whatever;
+  int V^ar;
+  char Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,101 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  // Store Parents list outside of GetSingleParent, so that returned pointer is
+  // not invalidated.
+  DynTypedNodeList Storage(DynTypedNode::create(RenamedDecl));
+  auto GetSingleParent = [&](const DynTypedNode &Node) -> const DynTypedNode * {
+Storage = Ctx.getParents(Node);
+return (Storage.size() == 1) ? Storage.begin() : nullptr;
+  };
+
+  // We need to get to the enclosing scope: NamedDecl's parent is typically
+  // DeclStmt, so enclosing scope would be the second order parent.
+  const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
+  if (!Parent || !Parent->get())
+return nullptr;
+  Parent = GetSingleParent(*Parent);
+
+  // The following helpers check corresponding AST nodes for variable
+  // declarations with the name collision.
+  auto CheckDeclStmt = [&](const DeclStmt *DS,
+   StringRef Name) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == Name)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const Stmt *S,
+   StringRef Name) -> const NamedDecl * {
+if (const auto *CS = dyn_cast_or_null(S))
+  for (const auto *Node : CS->children())
+if (const auto *Result = CheckDeclStmt(dy

[PATCH] D94472: [clang][cli] Command line round-trip for HeaderSearch options

2021-02-04 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG225ccf0c50a8: [clang][cli] Command line round-trip for 
HeaderSearch options (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D94472?vs=321137&id=321344#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94472

Files:
  clang/CMakeLists.txt
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Frontend/round-trip-cc1-args.c
  clang/tools/driver/cc1_main.cpp
  llvm/include/llvm/Option/ArgList.h
  llvm/lib/Option/ArgList.cpp

Index: llvm/lib/Option/ArgList.cpp
===
--- llvm/lib/Option/ArgList.cpp
+++ llvm/lib/Option/ArgList.cpp
@@ -90,11 +90,22 @@
 }
 
 std::vector ArgList::getAllArgValues(OptSpecifier Id) const {
+  recordQueriedOpts(Id);
   SmallVector Values;
   AddAllArgValues(Values, Id);
   return std::vector(Values.begin(), Values.end());
 }
 
+void ArgList::AddAllArgsExcept(ArgStringList &Output,
+   const DenseSet &ExcludeIds) const {
+  for (const Arg *Arg : *this) {
+if (!ExcludeIds.contains(Arg->getOption().getID())) {
+  Arg->claim();
+  Arg->render(*this, Output);
+}
+  }
+}
+
 void ArgList::AddAllArgsExcept(ArgStringList &Output,
ArrayRef Ids,
ArrayRef ExcludeIds) const {
Index: llvm/include/llvm/Option/ArgList.h
===
--- llvm/include/llvm/Option/ArgList.h
+++ llvm/include/llvm/Option/ArgList.h
@@ -137,6 +137,16 @@
   /// The first and last index of each different OptSpecifier ID.
   DenseMap OptRanges;
 
+  /// The OptSpecifiers that were queried from this argument list.
+  mutable DenseSet QueriedOpts;
+
+  /// Record the queried OptSpecifiers.
+  template 
+  void recordQueriedOpts(OptSpecifiers... Ids) const {
+SmallVector OptsSpecifiers({toOptSpecifier(Ids).getID()...});
+QueriedOpts.insert(OptsSpecifiers.begin(), OptsSpecifiers.end());
+  }
+
   /// Get the range of indexes in which options with the specified IDs might
   /// reside, or (0, 0) if there are no such options.
   OptRange getRange(std::initializer_list Ids) const;
@@ -203,6 +213,7 @@
   template
   iterator_range>
   filtered(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.begin() + Range.first;
 auto E = Args.begin() + Range.second;
@@ -214,6 +225,7 @@
   template
   iterator_range>
   filtered_reverse(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.rend() - Range.second;
 auto E = Args.rend() - Range.first;
@@ -308,6 +320,10 @@
   A->render(*this, Output);
   }
 
+  /// AddAllArgsExcept - Render all arguments not matching any of the excluded
+  /// ids.
+  void AddAllArgsExcept(ArgStringList &Output,
+const DenseSet &ExcludeIds) const;
   /// AddAllArgsExcept - Render all arguments matching any of the given ids
   /// and not matching any of the excluded ids.
   void AddAllArgsExcept(ArgStringList &Output, ArrayRef Ids,
@@ -342,6 +358,12 @@
   ///
   void ClaimAllArgs() const;
 
+  /// Return the OptSpecifiers queried from this argument list.
+  const DenseSet &getQueriedOpts() const { return QueriedOpts; }
+
+  /// Clear the set of queried OptSpecifiers.
+  void clearQueriedOpts() const { QueriedOpts.clear(); }
+
   /// @}
   /// @name Arg Synthesis
   /// @{
Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -203,6 +203,12 @@
   IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
+
+  // Setup round-trip remarks for the DiagnosticsEngine used in CreateFromArgs.
+  if (find(Argv, StringRef("-Rround-trip-cc1-args")) != Argv.end())
+Diags.setSeverity(diag::remark_cc1_round_trip_generated,
+  diag::Severity::Remark, {});
+
   bool Success = CompilerInvocation::CreateFromArgs(Clang->getInvocation(),
 Argv, Diags, Argv0);
 
Index: clang/test/Frontend/round-trip-cc1-args.c
===
--- /dev/null
+++ clang/test/Frontend/round-trip-cc1-args.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 %s -no-round-trip-args -Rround-trip-cc1-args 2>&1 | FileCheck

[clang] 225ccf0 - [clang][cli] Command line round-trip for HeaderSearch options

2021-02-04 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-02-04T10:18:34+01:00
New Revision: 225ccf0c50a8d4e03b51f2f09a8e8776328363d8

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

LOG: [clang][cli] Command line round-trip for HeaderSearch options

This patch implements generation of remaining header search arguments.
It's done manually in C++ as opposed to TableGen, because we need the 
flexibility and don't anticipate reuse.

This patch also tests the generation of header search options via a round-trip. 
This way, the code gets exercised whenever Clang is built and tested in asserts 
mode. All `check-clang` tests pass.

Reviewed By: dexonsmith

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

Added: 
clang/test/Frontend/round-trip-cc1-args.c

Modified: 
clang/CMakeLists.txt
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Driver/Options.td
clang/include/clang/Frontend/CompilerInvocation.h
clang/lib/Frontend/CompilerInvocation.cpp
clang/tools/driver/cc1_main.cpp
llvm/include/llvm/Option/ArgList.h
llvm/lib/Option/ArgList.cpp

Removed: 




diff  --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index 9e74014134a0..7e1e58fdc138 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -465,6 +465,8 @@ option(CLANG_ENABLE_STATIC_ANALYZER
 
 option(CLANG_ENABLE_PROTO_FUZZER "Build Clang protobuf fuzzer." OFF)
 
+option(CLANG_ROUND_TRIP_CC1_ARGS "Round-trip command line arguments in -cc1." 
OFF)
+
 if(NOT CLANG_ENABLE_STATIC_ANALYZER AND CLANG_ENABLE_ARCMT)
   message(FATAL_ERROR "Cannot disable static analyzer while enabling ARCMT or 
Z3")
 endif()
@@ -473,6 +475,10 @@ if(CLANG_ENABLE_ARCMT)
   set(CLANG_ENABLE_OBJC_REWRITER ON)
 endif()
 
+if (CLANG_ROUND_TRIP_CC1_ARGS)
+  add_definitions(-DCLANG_ROUND_TRIP_CC1_ARGS=ON)
+endif()
+
 # Clang version information
 set(CLANG_EXECUTABLE_VERSION
 "${CLANG_VERSION_MAJOR}" CACHE STRING

diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index ad13f923fb63..ad5ccf4c106f 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -536,4 +536,11 @@ def err_drv_invalid_object_mode : Error<"OBJECT_MODE 
setting %0 is not recognize
 
 def err_aix_default_altivec_abi : Error<
   "The default Altivec ABI on AIX is not yet supported, use '-mabi=vec-extabi' 
for the extended Altivec ABI">;
+
+def note_cc1_round_trip_original : Note<"Original arguments in %0 round-trip: 
%1">;
+def note_cc1_round_trip_generated : Note<"Generated arguments #%1 in %0 
round-trip: %2">;
+def remark_cc1_round_trip_generated : Remark<"Generated arguments #%1 in %0 
round-trip: %2">, InGroup;
+def err_cc1_round_trip_fail_then_ok : Error<"Original arguments parse failed, 
then succeeded in %0 round-trip">;
+def err_cc1_round_trip_ok_then_fail : Error<"Generated arguments parse failed 
in %0 round-trip">;
+def err_cc1_round_trip_mismatch : Error<"Generated arguments do not match in 
%0 round-trip">;
 }

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 04ba89aa457e..bceed225e256 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -437,6 +437,7 @@ def ModuleBuild : DiagGroup<"module-build">;
 def ModuleImport : DiagGroup<"module-import">;
 def ModuleConflict : DiagGroup<"module-conflict">;
 def ModuleFileExtension : DiagGroup<"module-file-extension">;
+def RoundTripCC1Args : DiagGroup<"round-trip-cc1-args">;
 def NewlineEOF : DiagGroup<"newline-eof">;
 def Nullability : DiagGroup<"nullability">;
 def NullabilityDeclSpec : DiagGroup<"nullability-declspec">;

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index edaa42741062..d76bc37b88d3 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -520,6 +520,11 @@ def gen_reproducer: Flag<["-"], "gen-reproducer">, 
InternalDebugOpt,
 def gen_cdb_fragment_path: Separate<["-"], "gen-cdb-fragment-path">, 
InternalDebugOpt,
   HelpText<"Emit a compilation database fragment to the specified directory">;
 
+def round_trip_args : Flag<["-"], "round-trip-args">, Flags<[CC1Option, 
NoDriverOption]>,
+  HelpText<"Enable command line arguments round-trip.">;
+def no_round_trip_args : Flag<["-"], "no-round-trip-args">, Flags<[CC1Option, 
NoDriverOption]>,
+  HelpText<"Disable command line arguments round-trip.">;
+
 def _migrate : Flag<["--"], "migrate">, Flags<[NoXarchOption]>,
   HelpText<"Run the migrator">;
 def ccc_objcmt_migrate : Separate<["-"], "ccc-objcmt-migrate">,

diff  --git a/clang/include/clan

[clang] 6625680 - [clang-cl] Remove the /fallback option

2021-02-04 Thread Hans Wennborg via cfe-commits

Author: Hans Wennborg
Date: 2021-02-04T10:33:16+01:00
New Revision: 6625680a581c5e29c53d9f58d864cc6cd3cd05f6

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

LOG: [clang-cl] Remove the /fallback option

As discussed in
https://lists.llvm.org/pipermail/cfe-dev/2021-January/067524.html

It doesn't appear to be used, isn't really maintained, and adds some
complexity to the code. Let's remove it.

Differential revision: https://reviews.llvm.org/D95876

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/docs/UsersManual.rst
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticOptions.def
clang/include/clang/Driver/Job.h
clang/include/clang/Driver/Options.td
clang/include/clang/Frontend/TextDiagnostic.h
clang/lib/Driver/Job.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Clang.h
clang/lib/Driver/ToolChains/MSVC.cpp
clang/lib/Driver/ToolChains/MSVC.h
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Frontend/TextDiagnostic.cpp
clang/lib/Frontend/TextDiagnosticPrinter.cpp
clang/test/Driver/cl-options.c
clang/test/Driver/cl-pch.cpp
clang/test/Misc/diag-format.c

Removed: 
clang/test/Driver/cl-fallback.c



diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d1a5156f0d00..ff73ac92b758 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -76,7 +76,8 @@ Modified Compiler Flags
 Removed Compiler Flags
 -
 
-- ...
+- The clang-cl ``/fallback`` flag, which made clang-cl invoke Microsoft Visual
+  C++ on files it couldn't compile itself, has been removed.
 
 New Pragmas in Clang
 

diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index a2fc8c06dc6e..fae22feef07b 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -3501,7 +3501,6 @@ Execute ``clang-cl /?`` to see a list of supported 
options:
   /execution-charset:
   Runtime encoding, supports only UTF-8
   /E  Preprocess to stdout
-  /fallback   Fall back to cl.exe if clang-cl fails to compile
   /FA Output assembly code file during compilation
   /Fa  Output assembly code to this file during 
compilation (with /FA)
   /Fe  Set output executable file or directory (ends in 
/ or \)
@@ -3847,18 +3846,6 @@ This could lead to very subtle bugs. Using 
``-fvisibility-inlines-hidden`` can
 lead to the same issue. To avoid it in this case, make `S::foo()` or
 `internal()` non-inline, or mark them `dllimport/dllexport` explicitly.
 
-The /fallback Option
-
-
-When clang-cl is run with the ``/fallback`` option, it will first try to
-compile files itself. For any file that it fails to compile, it will fall back
-and try to compile the file by invoking cl.exe.
-
-This option is intended to be used as a temporary means to build projects where
-clang-cl cannot successfully compile all the files. clang-cl may fail to 
compile
-a file either because it cannot generate code for some C++ feature, or because
-it cannot parse some Microsoft language extension.
-
 Finding Clang runtime libraries
 ^^^
 

diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index ad5ccf4c106f..00a2cae52e9b 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -210,9 +210,6 @@ def warn_drv_yc_multiple_inputs_clang_cl : Warning<
   "support for '/Yc' with more than one source file not implemented yet; flag 
ignored">,
   InGroup;
 
-def err_drv_dllexport_inlines_and_fallback : Error<
-  "option '/Zc:dllexportInlines-' is ABI-changing and not compatible with 
'/fallback'">;
-
 def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
 def err_drv_invalid_int_value : Error<"invalid integral value '%1' in '%0'">;
 def err_drv_invalid_value_with_suggestion : Error<"invalid value '%1' in 
'%0','%2'">;
@@ -392,9 +389,6 @@ def err_test_module_file_extension_format : Error<
   "-ftest-module-file-extension argument '%0' is not of the required form "
   "'blockname:major:minor:hashed:user info'">;
 
-def warn_drv_invoking_fallback : Warning<"falling back to %0">,
-  InGroup;
-
 def warn_slash_u_filename : Warning<"'/U%0' treated as the '/U' option">,
   InGroup>;
 def note_use_dashdash : Note<"Use '--' to treat subsequent arguments as 
filenames">;

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index bceed225e256..fcac6f44aa9a

[PATCH] D95876: [clang-cl] Remove the /fallback option

2021-02-04 Thread Hans Wennborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6625680a581c: [clang-cl] Remove the /fallback option 
(authored by hans).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95876

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/UsersManual.rst
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticOptions.def
  clang/include/clang/Driver/Job.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/TextDiagnostic.h
  clang/lib/Driver/Job.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Clang.h
  clang/lib/Driver/ToolChains/MSVC.cpp
  clang/lib/Driver/ToolChains/MSVC.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/lib/Frontend/TextDiagnosticPrinter.cpp
  clang/test/Driver/cl-fallback.c
  clang/test/Driver/cl-options.c
  clang/test/Driver/cl-pch.cpp
  clang/test/Misc/diag-format.c

Index: clang/test/Misc/diag-format.c
===
--- clang/test/Misc/diag-format.c
+++ clang/test/Misc/diag-format.c
@@ -20,11 +20,11 @@
 // RUN: %clang -fsyntax-only -fdiagnostics-format=msvc -fno-show-column -fmsc-version=1900 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2015_ORIG
 //
 // RUN: %clang -fsyntax-only -fno-show-column %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=NO_COLUMN
-//
-// RUN: not %clang -fsyntax-only -Werror -fdiagnostics-format=msvc-fallback -fmsc-version=1300 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2010-FALLBACK
-// RUN: not %clang -fsyntax-only -Werror -fdiagnostics-format=msvc-fallback -fms-compatibility-version=13.00 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2010-FALLBACK
-// RUN: not %clang -fsyntax-only -Werror -fdiagnostics-format=msvc-fallback -fmsc-version=1800 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2013-FALLBACK
-// RUN: not %clang -fsyntax-only -Werror -fdiagnostics-format=msvc-fallback -fmsc-version=1900 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2015-FALLBACK
+
+
+
+
+
 
 
 
@@ -42,7 +42,4 @@
 // VI: {{.*}} +36:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
 // MSVC2015_ORIG: {{.*}}(36): warning: extra tokens at end of #endif directive [-Wextra-tokens]
 // NO_COLUMN: {{.*}}:36: warning: extra tokens at end of #endif directive [-Wextra-tokens]
-// MSVC2010-FALLBACK: {{.*}}(36,7) : error(clang): extra tokens at end of #endif directive
-// MSVC2013-FALLBACK: {{.*}}(36,8) : error(clang): extra tokens at end of #endif directive
-// MSVC2015-FALLBACK: {{.*}}(36,8): error(clang): extra tokens at end of #endif directive
 int x;
Index: clang/test/Driver/cl-pch.cpp
===
--- clang/test/Driver/cl-pch.cpp
+++ clang/test/Driver/cl-pch.cpp
@@ -333,39 +333,6 @@
 // uses the last one.  This is true for e.g. /Fo too, so not warning on this
 // is self-consistent with clang-cl's flag handling.
 
-// Interaction with /fallback
-
-// /Yc /fallback => /Yc not passed on (but /FI is)
-// RUN: %clang_cl -Werror /Ycpchfile.h /FIpchfile.h /Fpfoo.pch /fallback /c -### -- %s 2>&1 \
-// RUN:   | FileCheck -check-prefix=CHECK-YC-FALLBACK %s
-// Note that in /fallback builds, if creation of the pch fails the main compile
-// does still run so that /fallback can have an effect (this part is not tested)
-// CHECK-YC-FALLBACK: cc1
-// CHECK-YC-FALLBACK: -emit-obj
-// CHECK-YC-FALLBACK: -include-pch
-// CHECK-YC-FALLBACK: foo.pch
-// CHECK-YC-FALLBACK: ||
-// CHECK-YC-FALLBACK: cl.exe
-// CHECK-YC-FALLBACK-NOT: -include-pch
-// CHECK-YC-FALLBACK-NOT: /Ycpchfile.h
-// CHECK-YC-FALLBACK: /FIpchfile.h
-// CHECK-YC-FALLBACK-NOT: /Fpfoo.pch
-
-// /Yu /fallback => /Yu not passed on (but /FI is)
-// RUN: %clang_cl -Werror /Yupchfile.h /FIpchfile.h /Fpfoo.pch /fallback /c -### -- %s 2>&1 \
-// RUN:   | FileCheck -check-prefix=CHECK-YU-FALLBACK %s
-// CHECK-YU-FALLBACK-NOT: -emit-pch
-// CHECK-YU-FALLBACK: cc1
-// CHECK-YU-FALLBACK: -emit-obj
-// CHECK-YU-FALLBACK: -include-pch
-// CHECK-YU-FALLBACK: foo.pch
-// CHECK-YU-FALLBACK: ||
-// CHECK-YU-FALLBACK: cl.exe
-// CHECK-YU-FALLBACK-NOT: -include-pch
-// CHECK-YU-FALLBACK-NOT: /Yupchfile.h
-// CHECK-YU-FALLBACK: /FIpchfile.h
-// CHECK-YU-FALLBACK-NOT: /Fpfoo.pch
-
 // /FI without /Yu => pch file not used, even if it exists (different from
 // -include, which picks up .gch files if they exist).
 // RUN: touch %t.pch
Index: clang/test/Driver/cl-options.c
===
--- clang/test/Driver/cl-options.c
+++ clang/test/Driver/cl-options.c
@@ -530,8 +530,6 @@
 // NoDllExportInlines: "-fno-dllexport-inlines"
 // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck -check-prefix=DllExportI

[PATCH] D95778: [OpenCL] Introduce new language options for OpenCL keywords.

2021-02-04 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov updated this revision to Diff 321348.
azabaznov added a comment.

Renamed language options and adjusted comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95778

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Sema/SemaType.cpp


Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -2060,10 +2060,9 @@
   !PointeeType->isSamplerT() &&
   !PointeeType.hasAddressSpace())
 PointeeType = S.getASTContext().getAddrSpaceQualType(
-PointeeType,
-S.getLangOpts().OpenCLCPlusPlus || S.getLangOpts().OpenCLVersion == 200
-? LangAS::opencl_generic
-: LangAS::opencl_private);
+PointeeType, S.getLangOpts().OpenCLGenericAddressSpace
+ ? LangAS::opencl_generic
+ : LangAS::opencl_private);
   return PointeeType;
 }
 
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -3896,8 +3896,8 @@
 case tok::kw_pipe:
   if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
 !getLangOpts().OpenCLCPlusPlus)) {
-// OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
-// support the "pipe" word as identifier.
+// OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
+// should support the "pipe" word as identifier.
 Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
 goto DoneWithDeclSpec;
   }
@@ -4017,8 +4017,7 @@
 case tok::kw___generic:
   // generic address space is introduced only in OpenCL v2.0
   // see OpenCL C Spec v2.0 s6.5.5
-  if (Actions.getLangOpts().OpenCLVersion < 200 &&
-  !Actions.getLangOpts().OpenCLCPlusPlus) {
+  if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
 DiagID = diag::err_opencl_unknown_type_specifier;
 PrevSpec = Tok.getIdentifierInfo()->getNameStart();
 isInvalid = true;
@@ -5070,8 +5069,7 @@
   default: return false;
 
   case tok::kw_pipe:
-return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
-   getLangOpts().OpenCLCPlusPlus;
+return getLangOpts().OpenCLPipe;
 
   case tok::identifier:   // foo::bar
 // Unfortunate hack to support "Class.factoryMethod" notation.
@@ -5599,8 +5597,7 @@
   if (Kind == tok::star || Kind == tok::caret)
 return true;
 
-  if (Kind == tok::kw_pipe &&
-  ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
+  if (Kind == tok::kw_pipe && Lang.OpenCLPipe)
 return true;
 
   if (!Lang.CPlusPlus)
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2092,6 +2092,9 @@
 Opts.ZVector = 0;
 Opts.setDefaultFPContractMode(LangOptions::FPM_On);
 Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
+Opts.OpenCLPipe = Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200;
+Opts.OpenCLGenericAddressSpace =
+Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200;
 
 // Include default header file for OpenCL.
 if (Opts.IncludeDefaultHeader) {
Index: clang/include/clang/Basic/LangOptions.def
===
--- clang/include/clang/Basic/LangOptions.def
+++ clang/include/clang/Basic/LangOptions.def
@@ -215,6 +215,8 @@
 LANGOPT(OpenCLVersion , 32, 0, "OpenCL C version")
 LANGOPT(OpenCLCPlusPlus   , 1, 0, "C++ for OpenCL")
 LANGOPT(OpenCLCPlusPlusVersion , 32, 0, "C++ for OpenCL version")
+LANGOPT(OpenCLGenericAddressSpace, 1, 0, "OpenCL generic keyword")
+LANGOPT(OpenCLPipe   , 1, 0, "OpenCL pipe keyword")
 LANGOPT(NativeHalfType, 1, 0, "Native half type support")
 LANGOPT(NativeHalfArgsAndReturns, 1, 0, "Native half args and returns")
 LANGOPT(HalfArgsAndReturns, 1, 0, "half args and returns")


Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -2060,10 +2060,9 @@
   !PointeeType->isSamplerT() &&
   !PointeeType.hasAddressSpace())
 PointeeType = S.getASTContext().getAddrSpaceQualType(
-PointeeType,
-S.getLangOpts().OpenCLCPlusPlus || S.getLangOpts().OpenCLVersion == 200
-? LangAS::opencl_generic
-: LangAS::opencl_private);
+PointeeType, S.getLangOpts().OpenCLGenericAddressSpace
+ ? LangAS::opencl_generic
+ : LangAS::opencl_private);
   return Po

[PATCH] D95915: [clang][driver] Only warn once about invalid -stdlib value

2021-02-04 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 321349.
tbaeder added a comment.

Here a version without the local static bools. If this is good to go, I can add 
some tests.


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

https://reviews.llvm.org/D95915

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp

Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -74,7 +74,9 @@
 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
  const ArgList &Args)
 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
-  CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
+  CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)),
+  isCXXStdlibTypeCached(false), isRuntimeLibTypeCached(false),
+  isUnwindLibTypeCached(false) {
   if (D.CCCIsCXX()) {
 if (auto CXXStdlibPath = getCXXStdlibPath())
   getFilePaths().push_back(*CXXStdlibPath);
@@ -873,66 +875,91 @@
 
 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
 const ArgList &Args) const {
+  if (isRuntimeLibTypeCached)
+return runtimeLibType;
+
   const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
 
   // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
   if (LibName == "compiler-rt")
-return ToolChain::RLT_CompilerRT;
+runtimeLibType = ToolChain::RLT_CompilerRT;
   else if (LibName == "libgcc")
-return ToolChain::RLT_Libgcc;
+runtimeLibType = ToolChain::RLT_Libgcc;
   else if (LibName == "platform")
-return GetDefaultRuntimeLibType();
+runtimeLibType = GetDefaultRuntimeLibType();
+  else {
+if (A)
+  getDriver().Diag(diag::err_drv_invalid_rtlib_name)
+  << A->getAsString(Args);
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
+runtimeLibType = GetDefaultRuntimeLibType();
+  }
 
-  return GetDefaultRuntimeLibType();
+  isRuntimeLibTypeCached = true;
+  return runtimeLibType;
 }
 
 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
 const ArgList &Args) const {
+  if (isUnwindLibTypeCached)
+return unwindLibType;
+
   const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
 
   if (LibName == "none")
-return ToolChain::UNW_None;
+unwindLibType = ToolChain::UNW_None;
   else if (LibName == "platform" || LibName == "") {
 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
 if (RtLibType == ToolChain::RLT_CompilerRT)
-  return ToolChain::UNW_None;
+  unwindLibType = ToolChain::UNW_None;
 else if (RtLibType == ToolChain::RLT_Libgcc)
-  return ToolChain::UNW_Libgcc;
+  unwindLibType = ToolChain::UNW_Libgcc;
   } else if (LibName == "libunwind") {
 if (GetRuntimeLibType(Args) == RLT_Libgcc)
   getDriver().Diag(diag::err_drv_incompatible_unwindlib);
-return ToolChain::UNW_CompilerRT;
+unwindLibType = ToolChain::UNW_CompilerRT;
   } else if (LibName == "libgcc")
-return ToolChain::UNW_Libgcc;
+unwindLibType = ToolChain::UNW_Libgcc;
+  else {
+if (A)
+  getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
+  << A->getAsString(Args);
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
-<< A->getAsString(Args);
+unwindLibType = GetDefaultUnwindLibType();
+  }
+
+  isUnwindLibTypeCached = true;
 
-  return GetDefaultUnwindLibType();
+  return unwindLibType;
 }
 
 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
+  if (isCXXStdlibTypeCached)
+return cxxStdlibType;
+
   const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
 
   // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
   if (LibName == "libc++")
-return ToolChain::CST_Libcxx;
+cxxStdlibType = ToolChain::CST_Libcxx;
   else if (LibName == "libstdc++")
-return ToolChain::CST_Libstdcxx;
+cxxStdlibType = ToolChain::CST_Libstdcxx;
   else if (LibName == "platform")
-return GetDefaultCXXStdlibType();
+cxxStdlibType = GetDefaultCXXStdlibType();
+  else {
+if (A)
+  getDriver().Diag(diag::err_drv_invalid_stdlib_name)
+  << A->getAsString(Args);
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
+cxxStdlibType = GetDefaultCXXStdlibType();
+  }
+
+  isCXXStdlibTypeCached = true;
 
-  return GetDefaultCXXStdlibType();
+  return cxxStdlibType;
 }
 
 /// Utility function to add a system include directory to CC1 arguments.
Index: clang/include/clang/Driver/ToolChain.h
===
--- clang/include/clang/Driver/ToolChain.h
+++ clang/include/c

[PATCH] D95778: [OpenCL] Introduce new language options for OpenCL keywords.

2021-02-04 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95778

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


[PATCH] D96007: [AArch64] Enable stack clash protection for AArch64 linux in clang

2021-02-04 Thread Oliver Stannard (Linaro) via Phabricator via cfe-commits
ostannard created this revision.
ostannard added reviewers: serge-sans-paille, jnspaulsson, bzEq, tnfchris.
Herald added subscribers: danielkiss, kristof.beyls.
ostannard requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This allows the -fstack-clash-protection option to be used for AArch64
Linux.

Linux for AArch64 uses a 64k stack guard, instead of the 4k guard
assumed by the backend, so we set the stack-probe-size function
attribute to configure this, and the -mstack-probe-size= option can be
used to override this.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96007

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/stack-clash-protection.c
  clang/test/Driver/stack-clash-protection.c


Index: clang/test/Driver/stack-clash-protection.c
===
--- clang/test/Driver/stack-clash-protection.c
+++ clang/test/Driver/stack-clash-protection.c
@@ -21,12 +21,20 @@
 // SCP-ll-win64-NOT: attributes {{.*}} "probe-stack"="inline-asm"
 // SCP-ll-win64: argument unused during compilation: '-fstack-clash-protection'
 
+// RUN: %clang -target aarch64-unknown-linux -fstack-clash-protection -S 
-emit-llvm -o- %s | FileCheck %s -check-prefix=SCP-aarch64
+// SCP-aarch64: attributes {{.*}} "probe-stack"="inline-asm"
+// SCP-aarch64-SAME: "stack-probe-size"="65536"
+
 int foo(int c) {
   int r;
   __asm__("sub %0, %%rsp"
   :
   : "rm"(c)
+#ifdef __aarch64__
+  : "sp");
+#else
   : "rsp");
+#endif
   __asm__("mov %%rsp, %0"
   : "=rm"(r)::);
   return r;
Index: clang/test/CodeGen/stack-clash-protection.c
===
--- clang/test/CodeGen/stack-clash-protection.c
+++ clang/test/CodeGen/stack-clash-protection.c
@@ -3,6 +3,9 @@
 // RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
 // RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
 // RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64_be-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=65536 | FileCheck %s 
--check-prefix=CHECK --check-prefix=LARGE-GUARD
 
 // CHECK: define{{.*}} void @large_stack() #[[A:.*]] {
 void large_stack() {
@@ -23,3 +26,5 @@
 }
 
 // CHECK: attributes #[[A]] = {{.*}} "probe-stack"="inline-asm"
+// LARGE-GUARD-SAME: "stack-probe-size"="65536"
+// CHECK-NOT: "stack-probe-size"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3091,12 +3091,20 @@
 return;
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
-  !EffectiveTriple.isPPC64())
+  !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
 return;
 
   if (Args.hasFlag(options::OPT_fstack_clash_protection,
-   options::OPT_fno_stack_clash_protection, false))
+   options::OPT_fno_stack_clash_protection, false)) {
 CmdArgs.push_back("-fstack-clash-protection");
+
+if (Args.hasArg(options::OPT_mstack_probe_size)) {
+  StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
+  CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
+} else if (EffectiveTriple.isAArch64()) {
+  CmdArgs.push_back("-mstack-probe-size=65536");
+}
+  }
 }
 
 static void RenderTrivialAutoVarInitOptions(const Driver &D,
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -1664,8 +1664,12 @@
   if (CodeGenOpts.UnwindTables)
 B.addAttribute(llvm::Attribute::UWTable);
 
-  if (CodeGenOpts.StackClashProtector)
+  if (CodeGenOpts.StackClashProtector) {
 B.addAttribute("probe-stack", "inline-asm");
+if (CodeGenOpts.StackProbeSize != 4096)
+  B.addAttribute("stack-probe-size",
+ llvm::utostr(CodeGenOpts.StackProbeSize));
+  }
 
   if (!hasUnwindExceptions(LangOpts))
 B.addAttribute(llvm::Attribute::NoUnwind);


Index: clang/test/Driver/stack-clash-protection.c
===
--- clang/test/Driver/stack-clash-protection.c
+++ clang/test/Driver/stack-clash-protection.c
@@ -21,12 +21,20 @@
 // SCP-ll-win64-NOT: attributes {{.*}} "probe-stack"="inline-asm"
 // SCP-ll-win64: argument unused 

[PATCH] D95778: [OpenCL] Introduce new language options for OpenCL keywords.

2021-02-04 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia added a comment.

LGTM! Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95778

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


[PATCH] D94952: [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-02-04 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added inline comments.



Comment at: clang-tools-extra/clangd/index/FileIndex.cpp:433
 PreambleSymbols.update(
-Uri, std::make_unique(std::move(*IF->Symbols)),
+FilePath ? *FilePath : (consumeError(FilePath.takeError()), Uri),
+std::make_unique(std::move(*IF->Symbols)),

ArcsinX wrote:
> sammccall wrote:
> > ArcsinX wrote:
> > > ArcsinX wrote:
> > > > sammccall wrote:
> > > > > ArcsinX wrote:
> > > > > > sammccall wrote:
> > > > > > > Is this change related? It changes the key scheme for the 
> > > > > > > preamble index from URIs to paths, but I'm not sure why.
> > > > > > > 
> > > > > > > Do we have multiple URIs pointing to the same path? What are they 
> > > > > > > concretely?
> > > > > > This is the main thing in this patch. I will try to explain.
> > > > > > We use these keys to create the file list, which is used by 
> > > > > > `indexedFiles()`.
> > > > > > Currently, the preamble index contains URI's instead of paths (as a 
> > > > > > file list), that leads to the function returned by 
> > > > > > `PreambleIndex::indexedFiles()` always return `false` (because we 
> > > > > > pass to this function paths, not URI's). So, we always take data 
> > > > > > from the preamble index (but maybe we should not in some cases).
> > > > > > 
> > > > > Oooh... I'm not sure how I misunderstood the original so much :-( And 
> > > > > I missed it in this patch description as well, apologies.
> > > > > 
> > > > > My impression was that the file list was derived from the index data, 
> > > > > rather than from the keys, which were always intended to be 
> > > > > opaque/arbitrary.
> > > > > (At various times, these have been filenames, URIs, and other things 
> > > > > IIRC. And until relatively recently, the preamble index keys were the 
> > > > > file the preamble was built from, not the file containing the symbol!)
> > > > > 
> > > > > It feels like using URIs extracted from symbols might not be 
> > > > > *completely* robust. Because having CanonicalDeclaration etc set to a 
> > > > > file might not line up exactly with the idea that we indexed the 
> > > > > file. But we do use this partitioning for FileShardedIndex, so it has 
> > > > > to work well enough.
> > > > > 
> > > > > The advantage of using the extracted URIs would be: also works for 
> > > > > non-file-sharded indexes like --index-file, avoid a bunch of 
> > > > > conversion between URI and path, and we get to keep the 
> > > > > simpler/flexible design for FileSymbols where the key is opaque.
> > > > > 
> > > > > Does this seem feasible to you?
> > > > > that leads to the function returned by 
> > > > > `PreambleIndex::indexedFiles()` always return `false` (because we 
> > > > > pass to this function paths, not URI's)
> > > > 
> > > > This is a bit incorrect.
> > > > We pass to this function URI, but this URI is converted to path. i.e. 
> > > > `MemIndex::indexedFiles()`, `Dex::indexedFiles()` expect that `Files` 
> > > > are paths, but they are URI's for the preamble index. That's why 
> > > > `PreambleIndex::indexedFiles()` always return `false`.
> > > I also do not like these path <=> URI conversions. But what about empty 
> > > files?, e.g.:
> > > - open a file
> > > - remove everything from this file
> > > - the dynamic index has no symbols with definition/declaration from this 
> > > file, so we do not have this file in the dynamic index file list.
> > > - the static index has symbols with definition/declaration from this 
> > > file, so we have this file in the static index file list.
> > > - we will show stale results from the static index for this file.
> > > 
> > > 
> > > Unsure, maybe it's ok to ignore the problem with empty files, seems this 
> > > is the only case when the file was indexed, but we have no symbols 
> > > located there.
> > > 
> > > Overall, I like the idea to use URI's instead of paths. I think we could 
> > > implement it first as a separate patch and after that return to this one.
> > > 
> > > What do you think?
> > Right, completely empty files are going to be mishandled., in the same way 
> > that before your changes we mishandled files that had no results from the 
> > query.
> > 
> > I do still think this is the way to go though, because:
> >  - completely empty files are much rarer
> >  - again this is a peer to an FileShardedIndex issue where empty files get 
> > no shards. Therefore *within* the dynamic index, we'll never clear out the 
> > symbols for a file while the file is emptied
> >  - having SymbolCollector explicitly the files indexed is the principled 
> > solution to both problems, and that seems feasible for us to do at some 
> > point.
> > 
> > > Overall, I like the idea to use URI's instead of paths. I think we could 
> > > implement it first as a separate patch and after that return to this one.
> > 
> > That sounds great if you don't mind!
> > (Is there a reason we can't land the rest of this patch as-is already?)
> > (Is there

[PATCH] D96009: [clangd] Improve name conflict detection

2021-02-04 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added a reviewer: hokein.
Herald added subscribers: usaxena95, kadircet, arphaman.
kbobyrev requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Follow-up on D95925 : adds better detection 
for function arguments and also
checks for conflicts in muli-variable init statements in ForStmt.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96009

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


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,10 @@
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or TypeLoc in case of function arguments), so enclosing scope
+  // would be the second order parent.
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent || !(Parent->get() || Parent->get()))
 return nullptr;
   Parent = GetSingleParent(*Parent);
 
@@ -407,8 +408,21 @@
   }
   if (const auto *EnclosingWhile = Parent->get())
 return CheckCompoundStmt(EnclosingWhile->getBody(), NewName);
-  if (const auto *EnclosingFor = Parent->get())
+  if (const auto *EnclosingFor = Parent->get()) {
+// Check for conflicts with other declarations within initialization
+// statement.
+if (const auto *Result = CheckDeclStmt(
+dyn_cast_or_null(EnclosingFor->getInit()), NewName))
+  return Result;
 return CheckCompoundStmt(EnclosingFor->getBody(), NewName);
+  }
+  if (const auto *EnclosingFunction = Parent->get()) {
+// Check for conflicts with other arguments.
+for (const auto *Parameter : EnclosingFunction->parameters())
+  if (Parameter != &RenamedDecl && Parameter->getName() == NewName)
+return Parameter;
+return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
+  }
 
   return nullptr;
 }


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,10 @@
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or TypeLoc in case of function arguments), so enclosing scope
+  // would be the second order parent.
   const auto *Pa

[PATCH] D95886: [OpenCL][Docs] Link page explaining tooling for offline compilation

2021-02-04 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia updated this revision to Diff 321369.
Anastasia added a comment.

Addressed Sven's comments.


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

https://reviews.llvm.org/D95886

Files:
  clang/docs/UsersManual.rst


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -2889,8 +2889,10 @@
 portable IR is produced that can be used with various vendor
 tools as well as open source tools such as `SPIRV-LLVM Translator
 `_
-to produce SPIR-V binary.
-
+to produce SPIR-V binary. More details are provided in `the offline
+compilation from OpenCL kernel sources into SPIR-V using open source
+tools
+`_.
 
 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
 supports full profile. There is only very limited support of the embedded


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -2889,8 +2889,10 @@
 portable IR is produced that can be used with various vendor
 tools as well as open source tools such as `SPIRV-LLVM Translator
 `_
-to produce SPIR-V binary.
-
+to produce SPIR-V binary. More details are provided in `the offline
+compilation from OpenCL kernel sources into SPIR-V using open source
+tools
+`_.
 
 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
 supports full profile. There is only very limited support of the embedded
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95886: [OpenCL][Docs] Link page explaining tooling for offline compilation

2021-02-04 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!


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

https://reviews.llvm.org/D95886

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


[PATCH] D95976: [OpenMP] Simplify offloading parallel call codegen

2021-02-04 Thread Giorgis Georgakoudis via Phabricator via cfe-commits
ggeorgakoudis updated this revision to Diff 321375.
ggeorgakoudis added a comment.

Fix type for IfCond, formatting


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95976

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  openmp/libomptarget/deviceRTLs/common/src/omptarget.cu
  openmp/libomptarget/deviceRTLs/common/src/parallel.cu
  openmp/libomptarget/deviceRTLs/common/src/support.cu
  openmp/libomptarget/deviceRTLs/common/support.h
  openmp/libomptarget/deviceRTLs/interface.h

Index: openmp/libomptarget/deviceRTLs/interface.h
===
--- openmp/libomptarget/deviceRTLs/interface.h
+++ openmp/libomptarget/deviceRTLs/interface.h
@@ -177,6 +177,7 @@
  * The struct is identical to the one in the kmp.h file.
  * We maintain the same data structure for compatibility.
  */
+typedef short kmp_int16;
 typedef int kmp_int32;
 typedef struct ident {
   kmp_int32 reserved_1; /**<  might be used in Fortran; see above  */
@@ -437,6 +438,22 @@
 EXTERN void __kmpc_end_sharing_variables();
 EXTERN void __kmpc_get_shared_variables(void ***GlobalArgs);
 
+/// Entry point to start a new parallel region.
+///
+/// \param ident   The source identifier.
+/// \param global_tid  The global thread ID.
+/// \param if_expr The if(expr), or 1 if none given.
+/// \param num_threads The num_threads(expr), or -1 if none given.
+/// \param proc_bind   The proc_bind, or `proc_bind_default` if none given.
+/// \param fn  The outlined parallel region function.
+/// \param wrapper_fn  The worker wrapper function of fn.
+/// \param argsThe pointer array of arguments to fn.
+/// \param nargs   The number of arguments to fn.
+EXTERN void __kmpc_parallel_51(ident_t *ident, kmp_int32 global_tid,
+   kmp_int32 if_expr, kmp_int32 num_threads,
+   int proc_bind, void *fn, void *wrapper_fn,
+   void **args, size_t nargs);
+
 // SPMD execution mode interrogation function.
 EXTERN int8_t __kmpc_is_spmd_exec_mode();
 
Index: openmp/libomptarget/deviceRTLs/common/support.h
===
--- openmp/libomptarget/deviceRTLs/common/support.h
+++ openmp/libomptarget/deviceRTLs/common/support.h
@@ -95,4 +95,9 @@
 DEVICE unsigned int *GetTeamsReductionTimestamp();
 DEVICE char *GetTeamsReductionScratchpad();
 
+// Invoke an outlined parallel function unwrapping global, shared arguments (up
+// to 16).
+DEVICE void __kmp_invoke_microtask(kmp_int32 global_tid, kmp_int32 bound_tid,
+   void *fn, void **args, size_t nargs);
+
 #endif
Index: openmp/libomptarget/deviceRTLs/common/src/support.cu
===
--- openmp/libomptarget/deviceRTLs/common/src/support.cu
+++ openmp/libomptarget/deviceRTLs/common/src/support.cu
@@ -265,4 +265,110 @@
   return static_cast(ReductionScratchpadPtr) + 256;
 }
 
+// Invoke an outlined parallel function unwrapping arguments (up
+// to 16).
+DEVICE void __kmp_invoke_microtask(kmp_int32 global_tid, kmp_int32 bound_tid,
+   void *fn, void **args, size_t nargs) {
+  switch (nargs) {
+  case 0:
+((void (*)(kmp_int32 *, kmp_int32 *))fn)(&global_tid, &bound_tid);
+break;
+  case 1:
+((void (*)(kmp_int32 *, kmp_int32 *, void *))fn)(&global_tid, &bound_tid,
+ args[0]);
+break;
+  case 2:
+((void (*)(kmp_int32 *, kmp_int32 *, void *, void *))fn)(
+&global_tid, &bound_tid, args[0], args[1]);
+break;
+  case 3:
+((void (*)(kmp_int32 *, kmp_int32 *, void *, void *, void *))fn)(
+&global_tid, &bound_tid, args[0], args[1], args[2]);
+break;
+  case 4:
+((void (*)(kmp_int32 *, kmp_int32 *, void *, void *, void *, void *))fn)(
+&global_tid, &bound_tid, args[0], args[1], args[2], args[3]);
+break;
+  case 5:
+((void (*)(kmp_int32 *, kmp_int32 *, void *, void *, void *, void *,
+   void *))fn)(&global_tid, &bound_tid, args[0], args[1], args[2],
+   args[3], args[4]);
+break;
+  case 6:
+((void (*)(kmp_int32 *, kmp_int32 *, void *, void *, void *, void *, void *,
+   void *))fn)(&global_tid, &bound_tid, args[0], args[1], args[2],
+   args[3], args[4], args[5]);
+break;
+  case 7:
+((void (*)(kmp_int32 *, kmp_int32 *, void *, void *, void *, void *, void *,
+   void *, void *))fn)(&global_tid, &bound_tid, args[0], args[1],
+   args[2], args[3], args[4], args[5], args[6]);
+break;
+  case 8:
+((void (*)(kmp_int32 *, kmp_int32 *, void *, void *, void *, void *, void *,
+   void *, void *, void *))fn)(&global_tid, &bou

[clang] 4874ff0 - Revert "[hip][cuda] Enable extended lambda support on Windows."

2021-02-04 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2021-02-04T07:10:46-05:00
New Revision: 4874ff02417916cc9ff994b34abcb5e563056546

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

LOG: Revert "[hip][cuda] Enable extended lambda support on Windows."

This reverts commit a2fdf9d4d734732a6fa9288f1ffdf12bf8618123.
Slightly speculative, seeing several cuda tests fail on this
Windows bot: http://45.33.8.238/win/32620/step_7.txt

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/include/clang/AST/DeclCXX.h
clang/include/clang/AST/Mangle.h
clang/include/clang/AST/MangleNumberingContext.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/CXXABI.h
clang/lib/AST/DeclCXX.cpp
clang/lib/AST/ItaniumCXXABI.cpp
clang/lib/AST/ItaniumMangle.cpp
clang/lib/AST/MicrosoftCXXABI.cpp
clang/lib/CodeGen/CGCUDANV.cpp
clang/lib/Sema/SemaLambda.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/test/CodeGenCUDA/ms-linker-options.cu
clang/test/CodeGenCUDA/unnamed-types.cu

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index ae69a68608b7..ce47d54e44b0 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -538,9 +538,6 @@ class ASTContext : public RefCountedBase {
   /// need them (like static local vars).
   llvm::MapVector MangleNumbers;
   llvm::MapVector StaticLocalNumbers;
-  /// Mapping the associated device lambda mangling number if present.
-  mutable llvm::DenseMap
-  DeviceLambdaManglingNumbers;
 
   /// Mapping that stores parameterIndex values for ParmVarDecls when
   /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.

diff  --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index 89006b1cfa7f..e32101bb2276 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1735,12 +1735,6 @@ class CXXRecordDecl : public RecordDecl {
 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
   }
 
-  /// Set the device side mangling number.
-  void setDeviceLambdaManglingNumber(unsigned Num) const;
-
-  /// Retrieve the device side mangling number.
-  unsigned getDeviceLambdaManglingNumber() const;
-
   /// Returns the inheritance model used for this record.
   MSInheritanceModel getMSInheritanceModel() const;
 

diff  --git a/clang/include/clang/AST/Mangle.h 
b/clang/include/clang/AST/Mangle.h
index 13b436cdca3e..6506ad542cc3 100644
--- a/clang/include/clang/AST/Mangle.h
+++ b/clang/include/clang/AST/Mangle.h
@@ -107,9 +107,6 @@ class MangleContext {
   virtual bool shouldMangleCXXName(const NamedDecl *D) = 0;
   virtual bool shouldMangleStringLiteral(const StringLiteral *SL) = 0;
 
-  virtual bool isDeviceMangleContext() const { return false; }
-  virtual void setDeviceMangleContext(bool) {}
-
   // FIXME: consider replacing raw_ostream & with something like SmallString &.
   void mangleName(GlobalDecl GD, raw_ostream &);
   virtual void mangleCXXName(GlobalDecl GD, raw_ostream &) = 0;

diff  --git a/clang/include/clang/AST/MangleNumberingContext.h 
b/clang/include/clang/AST/MangleNumberingContext.h
index eb33759682d6..f1ca6a05dbaf 100644
--- a/clang/include/clang/AST/MangleNumberingContext.h
+++ b/clang/include/clang/AST/MangleNumberingContext.h
@@ -52,11 +52,6 @@ class MangleNumberingContext {
   /// this context.
   virtual unsigned getManglingNumber(const TagDecl *TD,
  unsigned MSLocalManglingNumber) = 0;
-
-  /// Retrieve the mangling number of a new lambda expression with the
-  /// given call operator within the device context. No device number is
-  /// assigned if there's no device numbering context is associated.
-  virtual unsigned getDeviceManglingNumber(const CXXMethodDecl *) { return 0; }
 };
 
 } // end namespace clang

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1c4942a37112..2fca81d25345 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -6558,7 +6558,7 @@ class Sema final {
   /// Number lambda for linkage purposes if necessary.
   void handleLambdaNumbering(
   CXXRecordDecl *Class, CXXMethodDecl *Method,
-  Optional> Mangling = None);
+  Optional> Mangling = None);
 
   /// Endow the lambda scope info with the relevant properties.
   void buildLambdaScope(sema::LambdaScopeInfo *LSI,

diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 0d723fbbcd8c..085c50c0667b 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -2848,8 +2848,6 @@ ExpectedDecl ASTNodeI

[clang] 3a1513c - [flang][driver] Add forced form flags and -ffixed-line-length

2021-02-04 Thread Faris Rehman via cfe-commits

Author: Faris Rehman
Date: 2021-02-04T12:24:15Z
New Revision: 3a1513c142f4a1ddb97d882a12c89f90cb2529ac

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

LOG: [flang][driver] Add forced form flags and -ffixed-line-length

Add support for the following layout options:
* -ffree-form
* -ffixed-form
- -ffixed-line-length=n (alias -ffixed-line-length-n)
Additionally remove options `-fno-free-form` and `-fno-fixed-form` as they were 
initially added to forward to gfortran but gfortran does not support these 
flags.

This patch adds the flag FlangOnlyOption to the existing options 
`-ffixed-form`, `-ffree-form` and `-ffree-line-length-` in Options.td. As of 
commit 6a75496836ea14bcfd2f4b59d35a1cad4ac58cee, these flags are not currently 
forwarded to gfortran anyway.

The default fixed line length in FrontendOptions is 72, based off the current 
default in Fortran::parser::Options. The line length cannot be set to a 
negative integer, or a positive integer less than 7 excluding 0, consistent 
with the behaviour of gfortran.

This patch does not add `-ffree-line-length-n` as Fortran::parser::Options does 
not have a variable for free form columns.
Whilst the `fixedFormColumns` variable is used in f18 for 
`-ffree-line-length-n`, f18 only allows 
`-ffree-line-length-none`/`-ffree-line-length-0` and not a user-specified 
value. `fixedFormcolumns` cannot be used in the new driver as it is ignored in 
the frontend when dealing with free form files.

Summary of changes:
- Remove -fno-fixed-form and -fno-free-form from Options.td
- Make -ffixed-form, -ffree-form and -ffree-line-length-n FlangOnlyOption in 
Options.td
- Create AddFortranDialectOptions method in Flang.cpp
- Create FortranForm enum in FrontendOptions.h
- Add fortranForm_ and fixedFormColumns_ to Fortran::frontend::FrontendOptions
- Update fixed-form-test.f so that it guarantees that it fails when forced as a 
free form file to better facilitate testing.

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

Added: 
flang/test/Flang-Driver/Inputs/fixed-line-length-test.f
flang/test/Flang-Driver/fixed-free-flag.f90
flang/test/Flang-Driver/fixed-line-length.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
clang/lib/Driver/ToolChains/Flang.h
flang/include/flang/Frontend/FrontendOptions.h
flang/lib/Frontend/CompilerInstance.cpp
flang/lib/Frontend/CompilerInvocation.cpp
flang/test/Flang-Driver/Inputs/fixed-form-test.f
flang/test/Flang-Driver/driver-help-hidden.f90
flang/test/Flang-Driver/driver-help.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index b7eac8e67573..920b6c0adf89 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4129,7 +4129,6 @@ def fblas_matmul_limit_EQ : Joined<["-"], 
"fblas-matmul-limit=">, Group, 
Group;
 def ffpe_trap_EQ : Joined<["-"], "ffpe-trap=">, Group;
 def ffree_line_length_VALUE : Joined<["-"], "ffree-line-length-">, 
Group;
 def finit_character_EQ : Joined<["-"], "finit-character=">, 
Group;
@@ -4163,8 +4162,6 @@ defm dump_fortran_original : 
BooleanFFlag<"dump-fortran-original">, Group, Group;
 defm external_blas : BooleanFFlag<"external-blas">, Group;
 defm f2c : BooleanFFlag<"f2c">, Group;
-defm fixed_form : BooleanFFlag<"fixed-form">, Group;
-defm free_form : BooleanFFlag<"free-form">, Group;
 defm frontend_optimize : BooleanFFlag<"frontend-optimize">, 
Group;
 defm implicit_none : BooleanFFlag<"implicit-none">, Group;
 defm init_local_zero : BooleanFFlag<"init-local-zero">, Group;
@@ -4207,6 +4204,20 @@ def sycl_std_EQ : Joined<["-"], "sycl-std=">, 
Group, Flags<[CC1Optio
 def test_io : Flag<["-"], "test-io">, Flags<[HelpHidden, FlangOption, 
FC1Option, FlangOnlyOption]>, Group,
   HelpText<"Run the InputOuputTest action. Use for development and testing 
only.">;
 
+let Flags = [FC1Option, FlangOption, FlangOnlyOption] in {
+
+def ffixed_form : Flag<["-"], "ffixed-form">, Group,
+  HelpText<"Process source files in fixed form">;
+def ffree_form : Flag<["-"], "ffree-form">, Group,
+  HelpText<"Process source files in free form">;
+def ffixed_line_length_EQ : Joined<["-"], "ffixed-line-length=">, 
Group,
+  HelpText<"Use  as character line width in fixed mode">,
+  DocBrief<[{Set column after which characters are ignored in typical 
fixed-form lines in the source
+file}]>;
+def ffixed_line_length_VALUE : Joined<["-"], "ffixed-line-length-">, 
Group, Alias;
+
+}
+
 
//===--===//
 // CC1 Options
 
//===--===//

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/

[PATCH] D95460: [flang][driver] Add forced form flags and -ffixed-line-length

2021-02-04 Thread Faris via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3a1513c142f4: [flang][driver] Add forced form flags and 
-ffixed-line-length (authored by FarisRehman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95460

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/ToolChains/Flang.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInstance.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/test/Flang-Driver/Inputs/fixed-form-test.f
  flang/test/Flang-Driver/Inputs/fixed-line-length-test.f
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Flang-Driver/fixed-free-flag.f90
  flang/test/Flang-Driver/fixed-line-length.f90

Index: flang/test/Flang-Driver/fixed-line-length.f90
===
--- /dev/null
+++ flang/test/Flang-Driver/fixed-line-length.f90
@@ -0,0 +1,56 @@
+! Ensure argument -ffixed-line-length=n works as expected.
+
+! REQUIRES: new-flang-driver
+
+!--
+! FLANG DRIVER (flang-new)
+!--
+! RUN: %flang-new -E %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=DEFAULTLENGTH
+! RUN: not %flang-new -E -ffixed-line-length=-2 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=NEGATIVELENGTH
+! RUN: not %flang-new -E -ffixed-line-length=3 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=INVALIDLENGTH
+! RUN: %flang-new -E -ffixed-line-length=none %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=UNLIMITEDLENGTH
+! RUN: %flang-new -E -ffixed-line-length=0 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=UNLIMITEDLENGTH
+! RUN: %flang-new -E -ffixed-line-length=13 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=LENGTH13
+
+!
+! FRONTEND FLANG DRIVER (flang-new -fc1)
+!
+! RUN: %flang-new -fc1 -E %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=DEFAULTLENGTH
+! RUN: not %flang-new -fc1 -E -ffixed-line-length=-2 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=NEGATIVELENGTH
+! RUN: not %flang-new -fc1 -E -ffixed-line-length=3 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=INVALIDLENGTH
+! RUN: %flang-new -fc1 -E -ffixed-line-length=none %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=UNLIMITEDLENGTH
+! RUN: %flang-new -fc1 -E -ffixed-line-length=0 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=UNLIMITEDLENGTH
+! RUN: %flang-new -fc1 -E -ffixed-line-length=13 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=LENGTH13
+
+!-
+! COMMAND ALIAS -ffixed-line-length-n
+!-
+! RUN: %flang-new -E -ffixed-line-length-13 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=LENGTH13
+! RUN: %flang-new -fc1 -E -ffixed-line-length-13 %S/Inputs/fixed-line-length-test.f  2>&1 | FileCheck %s --check-prefix=LENGTH13
+
+!-
+! EXPECTED OUTPUT WITH DEFAULT LENGTH
+!-
+! The line should be trimmed to 72 characters when reading based on the default value of fixed line length.
+! DEFAULTLENGTH: program{{(a{58})}}
+
+!-
+! EXPECTED OUTPUT WITH A NEGATIVE LENGTH
+!-
+! NEGATIVELENGTH: invalid value '-2' in 'ffixed-line-length=','value must be 'none' or a non-negative integer'
+
+!-
+! EXPECTED OUTPUT WITH LENGTH LESS THAN 7
+!-
+! INVALIDLENGTH: invalid value '3' in 'ffixed-line-length=','value must be at least seven'
+
+!---
+! EXPECTED OUTPUT WITH UNLIMITED LENGTH
+!---
+! The line should not be trimmed and so 73 characters (including spaces) should be read.
+! UNLIMITEDLENGTH: program{{(a{59})}}
+
+!
+! EXPECTED OUTPUT WITH LENGTH 13
+!
+! LENGTH13: program
Index: flang/test/Flang-Driver/fixed-free-flag.f90
===
--- /dev/null
+++ flang/test/Flang-Driver/fixed-free-flag.f90
@@ -0,0 +1,25 @@
+! Ensure arguments -ffree-form and -ffixed-form work as expected.
+
+! REQUIRES: new-flang-driver
+
+!--
+! FLANG DRIVER (flang-new)
+!--
+! RUN: not %flang-new -fsyntax-only -ffree-form %S/Inputs/fixed-form-test.f  2>&1 | FileCheck %s --

[PATCH] D95860: [clang][Frontend] Fix a crash in DiagnosticRenderer.

2021-02-04 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

In D95860#2539453 , @balazske wrote:

> Probably it is not worth to find a better solution. In the case of 
> CloneChecker the range starts and ends on different line that is not possible 
> to print on a single line in the output.
> This code could work:
> [code...]
> With this solution the following result is printed:
>
>   llvm-project/clang/test/Analysis/copypaste/clone-end-in-other-file.cpp:9:3: 
> warning: Duplicate code detected [alpha.clone.CloneChecker]
> if (i == 10) // expected-warning{{Duplicate code detected}}
> ^~~
>   
> llvm-project/clang/test/Analysis/copypaste/clone-end-in-other-file.cpp:11:3: 
> note: Similar code here
> if (i == 10) // expected-note{{Similar code here}}
> ^~
>   1 warning generated.
>
> This is not better than the result with the existing code:
>
>   llvm-project/clang/test/Analysis/copypaste/clone-end-in-other-file.cpp:9:3: 
> warning: Duplicate code detected [alpha.clone.CloneChecker]
> if (i == 10) // expected-warning{{Duplicate code detected}}
> ^
>   
> llvm-project/clang/test/Analysis/copypaste/clone-end-in-other-file.cpp:11:3: 
> note: Similar code here
> if (i == 10) // expected-note{{Similar code here}}
> ^
>   1 warning generated.

I think you are right. There is no gain in complicating this. I don't think 
there is anything that we can do about this.
Your original patch, simply ignoring the `end` if that is invalid or from a 
different file is fine by me.

Thank you for going the extra mile!

In D95860#2538845 , @balazske wrote:

> I realized that the added test cases show different problems: One is when one 
> of `Begin` or `End` is invalid, other if the FileID's are different. Probably 
> we can find a better solution for the second problem. So the patch needs to 
> be splitted and the case with the **crash-diagnostic-renderer.cpp** goes into 
> the first part.

I don't mind committing this in one go.
However, whichever you choose, please update the revision summary according to 
the commit message.
You should definitely describe both of these issues you found.

Thanks for your effort.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95860

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


[PATCH] D96016: Release notes: Deprecate the clang-cl /fallback flag (patch for the release/12.x branch)

2021-02-04 Thread Hans Wennborg via Phabricator via cfe-commits
hans created this revision.
hans added a reviewer: tstellar.
hans requested review of this revision.
Herald added a project: clang.

As discussed in 
https://lists.llvm.org/pipermail/cfe-dev/2021-January/067524.html

The flag has been removed on the main branch in D95876 


Tom: okay if I push this to the release branch?


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96016

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -109,6 +109,10 @@
 The following options are deprecated and ignored. They will be removed in
 future versions of Clang.
 
+- The clang-cl ``/fallback`` flag, which made clang-cl invoke Microsoft Visual
+  C++ on files it couldn't compile itself, has been deprecated. It will be
+  removed in Clang 13.
+
 - ...
 
 Modified Compiler Flags


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -109,6 +109,10 @@
 The following options are deprecated and ignored. They will be removed in
 future versions of Clang.
 
+- The clang-cl ``/fallback`` flag, which made clang-cl invoke Microsoft Visual
+  C++ on files it couldn't compile itself, has been deprecated. It will be
+  removed in Clang 13.
+
 - ...
 
 Modified Compiler Flags
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96009: [clangd] Improve name conflict detection

2021-02-04 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Thanks!




Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:343
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent || !(Parent->get() || Parent->get()))
 return nullptr;

I'd use `get` which seems safer -- typeLoc is a very 
generic class


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96009

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


[PATCH] D69322: [hip][cuda] Enable extended lambda support on Windows.

2021-02-04 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Hi, a whole bunch of cuda-related tests failed on windows with this in 
(http://45.33.8.238/win/32620/summary.html). Did you run check-clang before 
committing? I reverted this for now in 4874ff02417916cc9ff994b34abcb5e563056546 
 . After 
the revert, all tests pass again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69322

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


[clang] 62e4f22 - [clang] Add AddClang.cmake to the list of the CMake modules that are installed

2021-02-04 Thread Andrzej Warzynski via cfe-commits

Author: Andrzej Warzynski
Date: 2021-02-04T12:38:38Z
New Revision: 62e4f22e297ade62fd1e463e7c846df96148ffc4

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

LOG: [clang] Add AddClang.cmake to the list of the CMake modules that are 
installed

This makes sure that AddClang.cmake is installed alongside other Clang
CMake modules. This mirrors LLVM and MLIR in this respect and is
required when building the new Flang driver out of tree (as it depends
on Clang and includes AddClang.cmake).

Reviewed By: bogner

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

Added: 


Modified: 
clang/cmake/modules/CMakeLists.txt

Removed: 




diff  --git a/clang/cmake/modules/CMakeLists.txt 
b/clang/cmake/modules/CMakeLists.txt
index d233f552f01f..79fefa08772f 100644
--- a/clang/cmake/modules/CMakeLists.txt
+++ b/clang/cmake/modules/CMakeLists.txt
@@ -61,6 +61,7 @@ if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
 
   install(FILES
 ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/ClangConfig.cmake
+${CMAKE_CURRENT_SOURCE_DIR}/AddClang.cmake
 DESTINATION ${CLANG_INSTALL_PACKAGE_DIR}
 COMPONENT clang-cmake-exports)
 



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


[PATCH] D94533: [clang] Add AddClang.cmake to the list of the CMake modules that are installed

2021-02-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG62e4f22e297a: [clang] Add AddClang.cmake to the list of the 
CMake modules that are installed (authored by awarzynski).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94533

Files:
  clang/cmake/modules/CMakeLists.txt


Index: clang/cmake/modules/CMakeLists.txt
===
--- clang/cmake/modules/CMakeLists.txt
+++ clang/cmake/modules/CMakeLists.txt
@@ -61,6 +61,7 @@
 
   install(FILES
 ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/ClangConfig.cmake
+${CMAKE_CURRENT_SOURCE_DIR}/AddClang.cmake
 DESTINATION ${CLANG_INSTALL_PACKAGE_DIR}
 COMPONENT clang-cmake-exports)
 


Index: clang/cmake/modules/CMakeLists.txt
===
--- clang/cmake/modules/CMakeLists.txt
+++ clang/cmake/modules/CMakeLists.txt
@@ -61,6 +61,7 @@
 
   install(FILES
 ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/ClangConfig.cmake
+${CMAKE_CURRENT_SOURCE_DIR}/AddClang.cmake
 DESTINATION ${CLANG_INSTALL_PACKAGE_DIR}
 COMPONENT clang-cmake-exports)
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95776: [OpenCL] Add macro definitions of OpenCL C 3.0 features

2021-02-04 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov updated this revision to Diff 321385.
azabaznov added a comment.

Features remain defined in header for OpenCL C 2.0; adjusted the test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95776

Files:
  clang/include/clang/Basic/OpenCLExtensions.def
  clang/lib/Basic/Targets.cpp
  clang/lib/Headers/opencl-c-base.h
  clang/test/SemaOpenCL/features.cl

Index: clang/test/SemaOpenCL/features.cl
===
--- /dev/null
+++ clang/test/SemaOpenCL/features.cl
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -triple spir-unknown-unknown -finclude-default-header %s -E -dM -o - -x cl -cl-std=CL2.0 -cl-ext=-all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=FEATURES
+// RUN: %clang_cc1 -triple spir-unknown-unknown -finclude-default-header %s -E -dM -o - -x cl -cl-std=CL2.0 -cl-ext=+all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=FEATURES
+// RUN: %clang_cc1 -triple spir-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL3.0 -cl-ext=-all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=NO-FEATURES
+// RUN: %clang_cc1 -triple spir-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL3.0 -cl-ext=+all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=FEATURES
+// RUN: %clang_cc1 -triple r600-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL3.0 \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=NO-FEATURES
+
+// FULL OpenCL profile
+#ifndef __opencl_c_int64
+#error "Macro __opencl_c_int64 should be defined"
+#endif
+
+// Note that this test features which are both language related
+// and defined in header for OpenCL C 2.0
+
+// FEATURES: #define __opencl_c_atomic_order_acq_rel 1
+// FEATURES: #define __opencl_c_atomic_order_seq_cst 1
+// FEATURES: #define __opencl_c_device_enqueue 1
+// FEATURES: #define __opencl_c_generic_address_space 1
+// FEATURES: #define __opencl_c_images 1
+// FEATURES: #define __opencl_c_pipes 1
+// FEATURES: #define __opencl_c_program_scope_global_variables 1
+// FEATURES: #define __opencl_c_read_write_images 1
+
+// NO-FEATURES-NOT: __opencl_c_atomic_order_acq_rel
+// NO-FEATURES-NOT: __opencl_c_atomic_order_seq_cst
+// NO-FEATURES-NOT: __opencl_c_device_enqueue
+// NO-FEATURES-NOT: __opencl_c_generic_address_space
+// NO-FEATURES-NOT: __opencl_c_images
+// NO-FEATURES-NOT: __opencl_c_pipes
+// NO-FEATURES-NOT: __opencl_c_program_scope_global_variables
+// NO-FEATURES-NOT: __opencl_c_read_write_images
Index: clang/lib/Headers/opencl-c-base.h
===
--- clang/lib/Headers/opencl-c-base.h
+++ clang/lib/Headers/opencl-c-base.h
@@ -24,6 +24,21 @@
 #endif // defined(__SPIR__)
 #endif // (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 
+// Define feature macros for OpenCL C 2.0
+#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ == 200)
+#define __opencl_c_pipes 1
+#define __opencl_c_generic_address_space 1
+#define __opencl_c_work_group_collective_functions 1
+#define __opencl_c_atomic_order_acq_rel 1
+#define __opencl_c_atomic_order_seq_cst 1
+#define __opencl_c_atomic_scope_device 1
+#define __opencl_c_atomic_scope_all_devices 1
+#define __opencl_c_device_enqueue 1
+#define __opencl_c_read_write_images 1
+#define __opencl_c_program_scope_global_variables 1
+#define __opencl_c_images 1
+#endif
+
 // built-in scalar data types:
 
 /**
Index: clang/lib/Basic/Targets.cpp
===
--- clang/lib/Basic/Targets.cpp
+++ clang/lib/Basic/Targets.cpp
@@ -720,7 +720,9 @@
 /// and language version
 void TargetInfo::getOpenCLFeatureDefines(const LangOptions &Opts,
  MacroBuilder &Builder) const {
-
+  // FIXME: OpenCL options which affect language semantics/syntax
+  // should be moved into LangOptions, thus macro definitions of
+  // such options is better to be done in clang::InitializePreprocessor
   auto defineOpenCLExtMacro = [&](llvm::StringRef Name, unsigned AvailVer,
   unsigned CoreVersions,
   unsigned OptionalVersions) {
@@ -737,7 +739,6 @@
   defineOpenCLExtMacro(#Ext, Avail, Core, Opt);
 #include "clang/Basic/OpenCLExtensions.def"
 
-  // FIXME: OpenCL options which affect language semantics/syntax
-  // should be moved into LangOptions, thus macro definitions of
-  // such options is better to be done in clang::InitializePreprocessor
+  // Assume compiling for FULL profile
+  Builder.defineMacro("__opencl_c_int64");
 }
Index: clang/include/clang/Basic/OpenCLExtensions.def
===
--- clang/include/clang/Basic/OpenCLExtensions.def
+++ clang/include/clang/Basic/OpenCLExtensions.def
@@ -64,7 +64,7 @@
 OPENCL_EXTENSION(cl_khr_fp16, 100)
 OPENCL_EXTENSION(cl_khr_int64_base_atomics, 100)
 OPENCL_EXTENSION(cl_

[PATCH] D96017: [clang-check] Add tokens-dump in clang-check.

2021-02-04 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: kbobyrev.
hokein requested review of this revision.
Herald added a project: clang.

It is useful for syntax-tree developement.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96017

Files:
  clang/tools/clang-check/ClangCheck.cpp


Index: clang/tools/clang-check/ClangCheck.cpp
===
--- clang/tools/clang-check/ClangCheck.cpp
+++ clang/tools/clang-check/ClangCheck.cpp
@@ -88,6 +88,9 @@
 static cl::opt SyntaxTreeDump("syntax-tree-dump",
 cl::desc("dump the syntax tree"),
 cl::cat(ClangCheckCategory));
+static cl::opt TokensDump("tokens-dump",
+cl::desc("dump the preprocessed tokens"),
+cl::cat(ClangCheckCategory));
 
 namespace {
 
@@ -148,6 +151,8 @@
 
   void HandleTranslationUnit(clang::ASTContext &AST) override {
 clang::syntax::TokenBuffer TB = std::move(Collector).consume();
+if (TokensDump)
+  llvm::outs() << TB.dumpForTests();
 clang::syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(), TB);
 llvm::outs() << clang::syntax::buildSyntaxTree(A, AST)->dump(
 AST.getSourceManager());
@@ -217,7 +222,7 @@
 FrontendFactory = newFrontendActionFactory();
   else if (Fixit)
 FrontendFactory = newFrontendActionFactory();
-  else if (SyntaxTreeDump)
+  else if (SyntaxTreeDump || TokensDump)
 FrontendFactory = newFrontendActionFactory();
   else
 FrontendFactory = newFrontendActionFactory(&CheckFactory);


Index: clang/tools/clang-check/ClangCheck.cpp
===
--- clang/tools/clang-check/ClangCheck.cpp
+++ clang/tools/clang-check/ClangCheck.cpp
@@ -88,6 +88,9 @@
 static cl::opt SyntaxTreeDump("syntax-tree-dump",
 cl::desc("dump the syntax tree"),
 cl::cat(ClangCheckCategory));
+static cl::opt TokensDump("tokens-dump",
+cl::desc("dump the preprocessed tokens"),
+cl::cat(ClangCheckCategory));
 
 namespace {
 
@@ -148,6 +151,8 @@
 
   void HandleTranslationUnit(clang::ASTContext &AST) override {
 clang::syntax::TokenBuffer TB = std::move(Collector).consume();
+if (TokensDump)
+  llvm::outs() << TB.dumpForTests();
 clang::syntax::Arena A(AST.getSourceManager(), AST.getLangOpts(), TB);
 llvm::outs() << clang::syntax::buildSyntaxTree(A, AST)->dump(
 AST.getSourceManager());
@@ -217,7 +222,7 @@
 FrontendFactory = newFrontendActionFactory();
   else if (Fixit)
 FrontendFactory = newFrontendActionFactory();
-  else if (SyntaxTreeDump)
+  else if (SyntaxTreeDump || TokensDump)
 FrontendFactory = newFrontendActionFactory();
   else
 FrontendFactory = newFrontendActionFactory(&CheckFactory);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D94952: [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-02-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Sorry, forgot to stamp this!




Comment at: clang-tools-extra/clangd/index/FileIndex.cpp:419
   CollectMainFileRefs(CollectMainFileRefs),
+  PreambleSymbols(IndexContents::Symbols),
   PreambleIndex(std::make_unique()),

seems we include relations too?



Comment at: clang-tools-extra/clangd/index/FileIndex.cpp:421
   PreambleIndex(std::make_unique()),
+  MainFileSymbols(IndexContents::All),
   MainFileIndex(std::make_unique()) {}

(this should take into account CollectMainFileRefs, but actually if you sync to 
HEAD it's always true now)



Comment at: clang-tools-extra/clangd/index/FileIndex.h:74
 public:
+  FileSymbols(IndexContents IdxContents = IndexContents::None);
   /// Updates all slabs associated with the \p Key.

It seems error-prone to have a default here.
(I guess it's for making tests shorter? Are there enough callsites for it to 
matter?)

If we must have a default, All seems to make more sense than None.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94952

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


[PATCH] D95776: [OpenCL] Add macro definitions of OpenCL C 3.0 features

2021-02-04 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/test/SemaOpenCL/features.cl:1
+// RUN: %clang_cc1 -triple spir-unknown-unknown -finclude-default-header %s -E 
-dM -o - -x cl -cl-std=CL2.0 -cl-ext=-all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=FEATURES

since `-cl-ext=-all` doesn't affect the header functionality I suggest to drop 
it and use one one line with `-finclude-default-header`. Parsing time with this 
header is 300x slower so we should minimise its use in tests to avoid negative 
impact on clang testing.

Would it make sense to add a line without the header with `-cl-std=CL2.0` 
or/and `-cl-std=CL1.2` to check that there are indeed no macros defined?



Comment at: clang/test/SemaOpenCL/features.cl:14
+#ifndef __opencl_c_int64
+#error "Macro __opencl_c_int64 should be defined"
+#endif

Do you want to add -verify and expected-no-diagnostics directive for this or 
just change to FileCheck too?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95776

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


[PATCH] D93095: Introduce -Wreserved-identifier

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/Sema/reserved-identifier.c:49-50
+// FIXME: According to clang declaration context layering, _preserved belongs 
to
+// the translation unit, so we emit a warning. It's unclear that's what the
+// standard mandate, but it's such a corner case we can live with it.
+void func(struct _preserved { int a; } r) {} // expected-warning 
{{'_preserved' is a reserved identifier}}

rsmith wrote:
> aaron.ballman wrote:
> > I think we're correct to warn on this. Because the type specifier appears 
> > within the parameter list, it has function prototype scope per C2x 6.2.1p4. 
> > However, the identifier `_preserved` is put into the struct name space, 
> > which hits the "in the tag name spaces" part of: "All identifiers that 
> > begin with an underscore are reserved for use as identifiers with file 
> > scope in both the ordinary and tag name spaces".
> `_preserved` is not an identifier with file scope, so I think we shouldn't 
> warn here. Perhaps the problem is that we're doing this check before the 
> struct gets reparented into the function declaration (which only happens 
> after we finish parsing all the parameters and build the function 
> declaration).
> 
> We could perhaps check the `Scope` in addition to checking the `DeclContext` 
> to detect such cases.
> _preserved is not an identifier with file scope, so I think we shouldn't warn 
> here. 

Hmm, my thinking was that if the implementation added a conflicting definition 
of what `_preserved` is, it'd break the user's code. But you're right, the 
identifier is in the tag name space but not with file scope, so not warning is 
correct.



Comment at: clang/test/Sema/reserved-identifier.c:53
+
+extern char *_strdup(const char *); // expected-warning {{'_strdup' is a 
reserved identifier}}
+

rsmith wrote:
> aaron.ballman wrote:
> > This is a case I don't think we should warn on. As some examples showing 
> > this sort of thing in the wild:
> > 
> > https://codesearch.isocpp.org/actcd19/main/m/mcrl2/mcrl2_201409.0-1/3rd-party/svc/source/lz.cpp
> > https://codesearch.isocpp.org/actcd19/main/m/mcrl2/mcrl2_201409.0-1/3rd-party/svc/source/svc1.cpp
> You mean, specifically for `_strdup`? In general, this looks exactly the like 
> the kind of declaration we'd want to warn on. If we don't want a warning 
> here, we could perhaps recognize `_strdup` as a builtin lib function. (I 
> think they shouldn't warn, because we'll inject a builtin declaration, so 
> this would be a redeclaration. We should test that!)
> You mean, specifically for _strdup?

Yes, but it's a more general pattern than just `_strdup`. C code (esp older C 
code) will sometimes add an external declaration to avoid having to use a 
`#include` for just one symbol. Additionally, some popular platforms (like 
Windows) add a bunch of functions in the implementation namespace like 
`_strdup` (and many, many others).

Perhaps an option would be to always warn, and if we find that users run into 
this situation a lot in practice, we could split the diagnostic so that users 
can control whether to warn on forward declarations of functions.


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

https://reviews.llvm.org/D93095

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


[PATCH] D94661: [clang-format] [PR19056] Add support for access modifiers indentation

2021-02-04 Thread Jakub Budiský via Phabricator via cfe-commits
Budovi updated this revision to Diff 321392.
Budovi added a comment.

Changes:

- Added release notes
- Changed the documentation (tried to make it more clear in response to the 
confusion about the added option)

Hopefully there is a full context in the patch this time.


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

https://reviews.llvm.org/D94661

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -15453,6 +15453,7 @@
   CHECK_PARSE_BOOL(DerivePointerAlignment);
   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
   CHECK_PARSE_BOOL(DisableFormat);
+  CHECK_PARSE_BOOL(IndentAccessModifiers);
   CHECK_PARSE_BOOL(IndentCaseLabels);
   CHECK_PARSE_BOOL(IndentCaseBlocks);
   CHECK_PARSE_BOOL(IndentGotoLabels);
@@ -19050,6 +19051,52 @@
 "}",
 format(Source, Style));
 }
+
+TEST_F(FormatTest, IndentAccessModifiers) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AllowShortEnumsOnASingleLine = false;
+  Style.IndentAccessModifiers = true;
+  verifyFormat("class C {\n"
+   "int i;\n"
+   "};\n",
+   Style);
+  verifyFormat("class C {\n"
+   "  public:\n"
+   "int i;\n"
+   "};\n",
+   Style);
+  verifyFormat("struct S {\n"
+   "  private:\n"
+   "class C {\n"
+   "int j;\n"
+   "\n"
+   "  public:\n"
+   "C();\n"
+   "};\n"
+   "\n"
+   "  public:\n"
+   "int i;\n"
+   "};\n",
+   Style);
+  verifyFormat("union C {\n"
+   "int i;\n"
+   "unsigned u;\n"
+   "};\n",
+   Style);
+  verifyFormat("enum class E\n"
+   "{\n"
+   "  A,\n"
+   "  B\n"
+   "};\n",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  class C {\n"
+   "  int i;\n"
+   "  };\n"
+   "  return;\n"
+   "}\n",
+   Style);
+}
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -85,7 +85,7 @@
   void reset();
   void parseFile();
   void parseLevel(bool HasOpeningBrace);
-  void parseBlock(bool MustBeDeclaration, bool AddLevel = true,
+  void parseBlock(bool MustBeDeclaration, unsigned AddLevels = 1u,
   bool MunchSemi = true);
   void parseChildBlock();
   void parsePPDirective();
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -579,7 +579,7 @@
   return h;
 }
 
-void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
+void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, unsigned AddLevels,
  bool MunchSemi) {
   assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
  "'{' or macro block token expected");
@@ -589,7 +589,7 @@
   size_t PPStartHash = computePPHash();
 
   unsigned InitialLevel = Line->Level;
-  nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
+  nextToken(/*LevelDifference=*/AddLevels);
 
   if (MacroBlock && FormatTok->is(tok::l_paren))
 parseParens();
@@ -604,8 +604,7 @@
 
   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
   MustBeDeclaration);
-  if (AddLevel)
-++Line->Level;
+  Line->Level += AddLevels;
   parseLevel(/*HasOpeningBrace=*/true);
 
   if (eof())
@@ -621,7 +620,7 @@
   size_t PPEndHash = computePPHash();
 
   // Munch the closing brace.
-  nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
+  nextToken(/*LevelDifference=*/-AddLevels);
 
   if (MacroBlock && FormatTok->is(tok::l_paren))
 parseParens();
@@ -1125,12 +1124,12 @@
   if (Style.BraceWrapping.AfterExternBlock) {
 addUnwrappedLine();
   }
-  parseBlock(/*MustBeDeclaration=*/true,
- /*AddLevel=*/Style.BraceWrapping.AfterExternBlock);
+  unsigned AddLevels = Style.BraceWrapping.AfterExternBlock ? 1u : 0u;
+  parseBlock(/*MustBeDeclaration=*/true, AddLevels);
 } else {
-   

[PATCH] D94661: [clang-format] [PR19056] Add support for access modifiers indentation

2021-02-04 Thread Jakub Budiský via Phabricator via cfe-commits
Budovi added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:2039
 
+**IndentAccessModifiers** (``bool``)
+  Makes an indentation level for record (``class``, ``struct``, ``union``)

Budovi wrote:
> curdeius wrote:
> > curdeius wrote:
> > > The name `IndentAccessModifiers` is misleading for me. Access modifiers 
> > > are public, protected, private.
> > Hmm, actually that's the description that is misleading.
> Hm. Will go through the bug report again to see how people describe it. I'm 
> open to suggestions, but I'll need to fix it anyway because I see a grammar 
> mistake.
> 
> The current way I tried to go about it is that, without this option, 
> modifiers don't have their own indentation level. Without the offset given by 
> the `AccessModifierOffset` they would just be flush with the record members.
> 
> The introduced option creates a level designated for the access modifiers by 
> shifting the members further to the right.
Hopefully the description is better this time.


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

https://reviews.llvm.org/D94661

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


[PATCH] D95776: [OpenCL] Add macro definitions of OpenCL C 3.0 features

2021-02-04 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov added inline comments.



Comment at: clang/test/SemaOpenCL/features.cl:1
+// RUN: %clang_cc1 -triple spir-unknown-unknown -finclude-default-header %s -E 
-dM -o - -x cl -cl-std=CL2.0 -cl-ext=-all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=FEATURES

Anastasia wrote:
> since `-cl-ext=-all` doesn't affect the header functionality I suggest to 
> drop it and use one one line with `-finclude-default-header`. Parsing time 
> with this header is 300x slower so we should minimise its use in tests to 
> avoid negative impact on clang testing.
> 
> Would it make sense to add a line without the header with `-cl-std=CL2.0` 
> or/and `-cl-std=CL1.2` to check that there are indeed no macros defined?
> Would it make sense to add a line without the header with -cl-std=CL2.0 
> or/and -cl-std=CL1.2 to check that there are indeed no macros defined?

I think this makes no sense since we are planning to use these macros only 
internally for headers. Or if it's planned to include `opencl-c-base.h` by 
default, then this kind of lines can be eliminated for < 3.0 at all.



Comment at: clang/test/SemaOpenCL/features.cl:14
+#ifndef __opencl_c_int64
+#error "Macro __opencl_c_int64 should be defined"
+#endif

Anastasia wrote:
> Do you want to add -verify and expected-no-diagnostics directive for this or 
> just change to FileCheck too?
Ok, I think I'll use FileCheck to be consistent.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95776

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


[PATCH] D96009: [clangd] Improve name conflict detection

2021-02-04 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321398.
kbobyrev marked an inline comment as done.
kbobyrev added a comment.

Use FunctionProtoTypeLoc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96009

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


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,11 @@
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or FunctionProtoTypeLoc in case of function arguments), so
+  // enclosing scope would be the second order parent.
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent ||
+  !(Parent->get() || Parent->get()))
 return nullptr;
   Parent = GetSingleParent(*Parent);
 
@@ -407,8 +409,21 @@
   }
   if (const auto *EnclosingWhile = Parent->get())
 return CheckCompoundStmt(EnclosingWhile->getBody(), NewName);
-  if (const auto *EnclosingFor = Parent->get())
+  if (const auto *EnclosingFor = Parent->get()) {
+// Check for conflicts with other declarations within initialization
+// statement.
+if (const auto *Result = CheckDeclStmt(
+dyn_cast_or_null(EnclosingFor->getInit()), NewName))
+  return Result;
 return CheckCompoundStmt(EnclosingFor->getBody(), NewName);
+  }
+  if (const auto *EnclosingFunction = Parent->get()) {
+// Check for conflicts with other arguments.
+for (const auto *Parameter : EnclosingFunction->parameters())
+  if (Parameter != &RenamedDecl && Parameter->getName() == NewName)
+return Parameter;
+return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
+  }
 
   return nullptr;
 }


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,11 @@
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or FunctionProtoTypeLoc in case of function arguments), so
+  // enclosing scope would be the second order parent.
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent ||
+  !(Parent->get() || Parent->get()))
 return nullptr;
   Parent = GetSinglePar

[PATCH] D95776: [OpenCL] Add macro definitions of OpenCL C 3.0 features

2021-02-04 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/test/SemaOpenCL/features.cl:1
+// RUN: %clang_cc1 -triple spir-unknown-unknown -finclude-default-header %s -E 
-dM -o - -x cl -cl-std=CL2.0 -cl-ext=-all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=FEATURES

azabaznov wrote:
> Anastasia wrote:
> > since `-cl-ext=-all` doesn't affect the header functionality I suggest to 
> > drop it and use one one line with `-finclude-default-header`. Parsing time 
> > with this header is 300x slower so we should minimise its use in tests to 
> > avoid negative impact on clang testing.
> > 
> > Would it make sense to add a line without the header with `-cl-std=CL2.0` 
> > or/and `-cl-std=CL1.2` to check that there are indeed no macros defined?
> > Would it make sense to add a line without the header with -cl-std=CL2.0 
> > or/and -cl-std=CL1.2 to check that there are indeed no macros defined?
> 
> I think this makes no sense since we are planning to use these macros only 
> internally for headers. Or if it's planned to include `opencl-c-base.h` by 
> default, then this kind of lines can be eliminated for < 3.0 at all.
I guess we still need to test the the macros are not added where they are not 
available which is not only OpenCL 3.0 or OpenCL 2.0 but also earlier standards?

For example for OpenCL 1.2 they shouldn't be defined with or without the header?

Btw I suggest to move the header functionality into 
clang/test/Headers/opencl-c-header.cl, where we already tests some extension 
macros for example `cl_khr_subgroup_extended_types` .  In general it would be 
better to partition the tests but parsing that header has been so slow that we 
got shouted at for slowing down the clang testing. 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95776

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


[PATCH] D95799: [analyzer] Symbolicate float values with integral casting

2021-02-04 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.
Herald added a subscriber: nullptr.cpp.

Hi, folk! Please, review this tiny patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95799

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


[clang] 0c65993 - [OpenCL] Fix default address space in template argument deduction.

2021-02-04 Thread Anastasia Stulova via cfe-commits

Author: Anastasia Stulova
Date: 2021-02-04T13:51:53Z
New Revision: 0c65993be186640463ac90415113474d35889dbb

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

LOG: [OpenCL] Fix default address space in template argument deduction.

When deducing a reference type for forwarding references prevent
adding default address space of a template argument if it is given.

This got reported in PR48896 because in OpenCL all parameters are
in private address space and therefore when we initialize a
forwarding reference with a parameter we should just inherit the
address space from it i.e. keep __private instead of __generic.

Tags: #clang

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

Added: 


Modified: 
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/test/SemaOpenCLCXX/address-space-templates.cl

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index ee4316e7a632..6336f3b99452 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3869,7 +3869,7 @@ static bool AdjustFunctionParmAndArgTypesForDeduction(
 //   "lvalue reference to A" is used in place of A for type deduction.
 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
 Arg->isLValue()) {
-  if (S.getLangOpts().OpenCL)
+  if (S.getLangOpts().OpenCL  && !ArgType.hasAddressSpace())
 ArgType = S.Context.getAddrSpaceQualType(ArgType, 
LangAS::opencl_generic);
   ArgType = S.Context.getLValueReferenceType(ArgType);
 }

diff  --git a/clang/test/SemaOpenCLCXX/address-space-templates.cl 
b/clang/test/SemaOpenCLCXX/address-space-templates.cl
index be187de5684b..b7db0e6de3d2 100644
--- a/clang/test/SemaOpenCLCXX/address-space-templates.cl
+++ b/clang/test/SemaOpenCLCXX/address-space-templates.cl
@@ -1,4 +1,4 @@
-//RUN: %clang_cc1 %s -cl-std=clc++ -pedantic -verify -fsyntax-only
+//RUN: %clang_cc1 %s -cl-std=clc++ -pedantic -verify -ast-dump  | FileCheck %s
 
 template 
 struct S {
@@ -28,8 +28,10 @@ template  struct as_pointer {
 typedef typename remove_reference<_Tp>::type* type;
 };
 
+// Check address space deduction in template parameter deduction.
 struct rep {
-  // CHECK |-CXXConstructorDecl {{.*}} rep 'void (const __generic rep 
&__private) __generic'
+  // When there is no address space on a reference use __generic.
+  // CHECK: |-CXXConstructorDecl {{.*}} rep 'void (const __generic rep 
&__private) __generic'
   template::type>
   rep(U&& v) {}
 };
@@ -39,11 +41,22 @@ struct rep_outer : private rep {
 : rep(0) {}
 };
 
+
+template
+void foo4(T t, F f){
+  f(t);
+}
+
 void bar() {
   S sintgl; // expected-note{{in instantiation of template 
class 'S' requested here}}
 
   foo1<__local int>(1); // expected-error{{no matching function for call to 
'foo1'}}
   foo2<__global int>(0);
   foo3<__global int>(); // expected-note{{in instantiation of function 
template specialization 'foo3<__global int>' requested here}}
+
   rep_outer r;
+  int i;
+  // Preserve the address space of the type in forwarding reference.
+  // CHECK: CXXMethodDecl {{.*}} operator() 'void (__private int &__private) 
const __generic'
+  foo4(i, [](auto&& x){;});
 }



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


[PATCH] D95624: [OpenCL][PR48896] Fix default address space in template argument deduction

2021-02-04 Thread Anastasia Stulova via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0c65993be186: [OpenCL] Fix default address space in template 
argument deduction. (authored by Anastasia).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95624

Files:
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaOpenCLCXX/address-space-templates.cl


Index: clang/test/SemaOpenCLCXX/address-space-templates.cl
===
--- clang/test/SemaOpenCLCXX/address-space-templates.cl
+++ clang/test/SemaOpenCLCXX/address-space-templates.cl
@@ -1,4 +1,4 @@
-//RUN: %clang_cc1 %s -cl-std=clc++ -pedantic -verify -fsyntax-only
+//RUN: %clang_cc1 %s -cl-std=clc++ -pedantic -verify -ast-dump  | FileCheck %s
 
 template 
 struct S {
@@ -28,8 +28,10 @@
 typedef typename remove_reference<_Tp>::type* type;
 };
 
+// Check address space deduction in template parameter deduction.
 struct rep {
-  // CHECK |-CXXConstructorDecl {{.*}} rep 'void (const __generic rep 
&__private) __generic'
+  // When there is no address space on a reference use __generic.
+  // CHECK: |-CXXConstructorDecl {{.*}} rep 'void (const __generic rep 
&__private) __generic'
   template::type>
   rep(U&& v) {}
 };
@@ -39,11 +41,22 @@
 : rep(0) {}
 };
 
+
+template
+void foo4(T t, F f){
+  f(t);
+}
+
 void bar() {
   S sintgl; // expected-note{{in instantiation of template 
class 'S' requested here}}
 
   foo1<__local int>(1); // expected-error{{no matching function for call to 
'foo1'}}
   foo2<__global int>(0);
   foo3<__global int>(); // expected-note{{in instantiation of function 
template specialization 'foo3<__global int>' requested here}}
+
   rep_outer r;
+  int i;
+  // Preserve the address space of the type in forwarding reference.
+  // CHECK: CXXMethodDecl {{.*}} operator() 'void (__private int &__private) 
const __generic'
+  foo4(i, [](auto&& x){;});
 }
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3869,7 +3869,7 @@
 //   "lvalue reference to A" is used in place of A for type deduction.
 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
 Arg->isLValue()) {
-  if (S.getLangOpts().OpenCL)
+  if (S.getLangOpts().OpenCL  && !ArgType.hasAddressSpace())
 ArgType = S.Context.getAddrSpaceQualType(ArgType, 
LangAS::opencl_generic);
   ArgType = S.Context.getLValueReferenceType(ArgType);
 }


Index: clang/test/SemaOpenCLCXX/address-space-templates.cl
===
--- clang/test/SemaOpenCLCXX/address-space-templates.cl
+++ clang/test/SemaOpenCLCXX/address-space-templates.cl
@@ -1,4 +1,4 @@
-//RUN: %clang_cc1 %s -cl-std=clc++ -pedantic -verify -fsyntax-only
+//RUN: %clang_cc1 %s -cl-std=clc++ -pedantic -verify -ast-dump  | FileCheck %s
 
 template 
 struct S {
@@ -28,8 +28,10 @@
 typedef typename remove_reference<_Tp>::type* type;
 };
 
+// Check address space deduction in template parameter deduction.
 struct rep {
-  // CHECK |-CXXConstructorDecl {{.*}} rep 'void (const __generic rep &__private) __generic'
+  // When there is no address space on a reference use __generic.
+  // CHECK: |-CXXConstructorDecl {{.*}} rep 'void (const __generic rep &__private) __generic'
   template::type>
   rep(U&& v) {}
 };
@@ -39,11 +41,22 @@
 : rep(0) {}
 };
 
+
+template
+void foo4(T t, F f){
+  f(t);
+}
+
 void bar() {
   S sintgl; // expected-note{{in instantiation of template class 'S' requested here}}
 
   foo1<__local int>(1); // expected-error{{no matching function for call to 'foo1'}}
   foo2<__global int>(0);
   foo3<__global int>(); // expected-note{{in instantiation of function template specialization 'foo3<__global int>' requested here}}
+
   rep_outer r;
+  int i;
+  // Preserve the address space of the type in forwarding reference.
+  // CHECK: CXXMethodDecl {{.*}} operator() 'void (__private int &__private) const __generic'
+  foo4(i, [](auto&& x){;});
 }
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3869,7 +3869,7 @@
 //   "lvalue reference to A" is used in place of A for type deduction.
 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
 Arg->isLValue()) {
-  if (S.getLangOpts().OpenCL)
+  if (S.getLangOpts().OpenCL  && !ArgType.hasAddressSpace())
 ArgType = S.Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
   ArgType = S.Context.getLValueReferenceType(ArgType);
 }
___
cfe-commits mailing list
cfe-commits@l

[clang] 0fb4341 - [OpenCL][Docs] Link page explaining tooling for offline compilation.

2021-02-04 Thread Anastasia Stulova via cfe-commits

Author: Anastasia Stulova
Date: 2021-02-04T14:01:27Z
New Revision: 0fb4341519ef3ac06518ba56bb100277d89cdf11

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

LOG: [OpenCL][Docs] Link page explaining tooling for offline compilation.

Tags: #clang

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

Added: 


Modified: 
clang/docs/UsersManual.rst

Removed: 




diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index fae22feef07b..dfc0ea29487e 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -2901,8 +2901,10 @@ Note that if compiled to bitcode for generic targets 
such as SPIR,
 portable IR is produced that can be used with various vendor
 tools as well as open source tools such as `SPIRV-LLVM Translator
 `_
-to produce SPIR-V binary.
-
+to produce SPIR-V binary. More details are provided in `the offline
+compilation from OpenCL kernel sources into SPIR-V using open source
+tools
+`_.
 
 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
 supports full profile. There is only very limited support of the embedded



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


[PATCH] D95886: [OpenCL][Docs] Link page explaining tooling for offline compilation

2021-02-04 Thread Anastasia Stulova via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0fb4341519ef: [OpenCL][Docs] Link page explaining tooling 
for offline compilation. (authored by Anastasia).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95886

Files:
  clang/docs/UsersManual.rst


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -2901,8 +2901,10 @@
 portable IR is produced that can be used with various vendor
 tools as well as open source tools such as `SPIRV-LLVM Translator
 `_
-to produce SPIR-V binary.
-
+to produce SPIR-V binary. More details are provided in `the offline
+compilation from OpenCL kernel sources into SPIR-V using open source
+tools
+`_.
 
 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
 supports full profile. There is only very limited support of the embedded


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -2901,8 +2901,10 @@
 portable IR is produced that can be used with various vendor
 tools as well as open source tools such as `SPIRV-LLVM Translator
 `_
-to produce SPIR-V binary.
-
+to produce SPIR-V binary. More details are provided in `the offline
+compilation from OpenCL kernel sources into SPIR-V using open source
+tools
+`_.
 
 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
 supports full profile. There is only very limited support of the embedded
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96027: [clangd] Trace queue state for each TUScheduler action.

2021-02-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman, javed.absar.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

The new trace event includes what's already in the queue when adding.
For tracers that follow contexts, the trace event will span the time that the 
action
spends in the queue.
For tracers that follow threads, the trace will be a tiny span on the enqueuing 
thread.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96027

Files:
  clang-tools-extra/clangd/TUScheduler.cpp


Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -465,6 +465,7 @@
 std::string Name;
 steady_clock::time_point AddTime;
 Context Ctx;
+llvm::Optional QueueCtx;
 llvm::Optional Update;
 TUScheduler::ASTActionInvalidation InvalidationPolicy;
 Canceler Invalidate;
@@ -507,7 +508,7 @@
   /// None means no builds yet, null means there was an error while building.
   /// Only written by ASTWorker's thread.
   llvm::Optional> LatestPreamble;
-  std::queue PreambleRequests; /* GUARDED_BY(Mutex) */
+  std::deque PreambleRequests; /* GUARDED_BY(Mutex) */
   /// Signaled whenever LatestPreamble changes state or there's a new
   /// PreambleRequest.
   mutable std::condition_variable PreambleCV;
@@ -826,9 +827,10 @@
   }
   {
 std::lock_guard Lock(Mutex);
-PreambleRequests.push({std::move(Task), std::move(TaskName),
-   steady_clock::now(), Context::current().clone(),
-   llvm::None, TUScheduler::NoInvalidation, nullptr});
+PreambleRequests.push_back({std::move(Task), std::move(TaskName),
+steady_clock::now(), 
Context::current().clone(),
+llvm::None, llvm::None,
+TUScheduler::NoInvalidation, nullptr});
   }
   PreambleCV.notify_all();
   RequestsCV.notify_all();
@@ -1023,9 +1025,34 @@
   std::tie(Ctx, Invalidate) = cancelableTask(
   /*Reason=*/static_cast(ErrorCode::ContentModified));
 }
+// Trace the time the request spends in the queue, and the requests that
+// it's going to wait for.
+llvm::Optional QueueCtx;
+if (trace::enabled()) {
+  // Tracers that follow threads and need strict nesting will see a tiny
+  // instantaneous event "we're enqueueing", and sometime later it runs.
+  WithContext WC(Ctx.clone());
+  trace::Span Tracer("Queued:" + Name);
+  if (Tracer.Args) {
+if (CurrentRequest)
+  SPAN_ATTACH(Tracer, "CurrentRequest", CurrentRequest->Name);
+llvm::json::Array PreambleRequestsNames;
+for (const auto &Req : PreambleRequests)
+  PreambleRequestsNames.push_back(Req.Name);
+SPAN_ATTACH(Tracer, "PreambleRequestsNames",
+std::move(PreambleRequestsNames));
+llvm::json::Array RequestsNames;
+for (const auto &Req : Requests)
+  RequestsNames.push_back(Req.Name);
+SPAN_ATTACH(Tracer, "RequestsNames", std::move(RequestsNames));
+  }
+  // For tracers that follow contexts, keep the trace span's context alive
+  // until we dequeue the request, so they see the full duration.
+  QueueCtx = Context::current().clone();
+}
 Requests.push_back({std::move(Task), std::string(Name), 
steady_clock::now(),
-std::move(Ctx), Update, Invalidation,
-std::move(Invalidate)});
+std::move(Ctx), std::move(QueueCtx), Update,
+Invalidation, std::move(Invalidate)});
   }
   RequestsCV.notify_all();
 }
@@ -1071,13 +1098,16 @@
   // Requests.front(), so prefer them first to preserve LSP order.
   if (!PreambleRequests.empty()) {
 CurrentRequest = std::move(PreambleRequests.front());
-PreambleRequests.pop();
+PreambleRequests.pop_front();
   } else {
 CurrentRequest = std::move(Requests.front());
 Requests.pop_front();
   }
 } // unlock Mutex
 
+// Inform tracing that the request was dequeued.
+CurrentRequest->QueueCtx.reset();
+
 // It is safe to perform reads to CurrentRequest without holding the lock 
as
 // only writer is also this thread.
 {


Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -465,6 +465,7 @@
 std::string Name;
 steady_clock::time_point AddTime;
 Context Ctx;
+llvm::Optional QueueCtx;
 llvm::Optional Update;
 TUScheduler::ASTActionInvalidation InvalidationPolicy;
 Canceler Invalidate;
@@ -507,7 +50

[PATCH] D96032: [flang][driver] Add support for -fopenmp and -fopenacc

2021-02-04 Thread Faris via Phabricator via cfe-commits
FarisRehman created this revision.
Herald added subscribers: dang, guansong, yaxunl.
Herald added a reviewer: sscalpone.
Herald added a reviewer: awarzynski.
Herald added a reviewer: jansvoboda11.
FarisRehman requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

Add support for the following Fortran dialect options:

- -fopenmp
- -fopenacc

Update OpenMP and OpenACC semantics tests to use the new driver if it is built, 
otherwise use f18.
OpenMP tests that include `use omp_lib` or run `test_symbols.sh` have not been 
updated as they require options `-intrinsic-module-directory` and 
`-funparse-with-symbols` which are currently not implemented in the new driver.
Similarly OpenACC tests that run `test_symbols.sh` have not been updated.

This patch also moves semanticsContext to CompilerInvocation and created in 
CompilerInvocation#setSemanticsOpts so that the semantics context can use 
Fortran::parser::Options#features.

Summary of changes:

- Move semanticsContext to CompilerInvocation.h
- Update OpenMP and OpenACC semantics tests that do not rely on 
`-intrinsic-module-directory` and `-funparse-with-symbols` to use %flang


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96032

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInstance.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Semantics/OpenACC/acc-atomic-validity.f90
  flang/test/Semantics/OpenACC/acc-branch.f90
  flang/test/Semantics/OpenACC/acc-cache-validity.f90
  flang/test/Semantics/OpenACC/acc-canonicalization-validity.f90
  flang/test/Semantics/OpenACC/acc-data.f90
  flang/test/Semantics/OpenACC/acc-declare-validity.f90
  flang/test/Semantics/OpenACC/acc-host-data.f90
  flang/test/Semantics/OpenACC/acc-init-validity.f90
  flang/test/Semantics/OpenACC/acc-kernels-loop.f90
  flang/test/Semantics/OpenACC/acc-kernels.f90
  flang/test/Semantics/OpenACC/acc-loop.f90
  flang/test/Semantics/OpenACC/acc-parallel-loop-validity.f90
  flang/test/Semantics/OpenACC/acc-parallel.f90
  flang/test/Semantics/OpenACC/acc-resolve01.f90
  flang/test/Semantics/OpenACC/acc-resolve02.f90
  flang/test/Semantics/OpenACC/acc-routine-validity.f90
  flang/test/Semantics/OpenACC/acc-serial-loop.f90
  flang/test/Semantics/OpenACC/acc-serial.f90
  flang/test/Semantics/OpenACC/acc-set-validity.f90
  flang/test/Semantics/OpenACC/acc-shutdown-validity.f90
  flang/test/Semantics/OpenACC/acc-update-validity.f90
  flang/test/Semantics/OpenACC/acc-wait-validity.f90
  flang/test/Semantics/omp-atomic.f90
  flang/test/Semantics/omp-combined-constructs.f90
  flang/test/Semantics/omp-copyin01.f90
  flang/test/Semantics/omp-copyin02.f90
  flang/test/Semantics/omp-copyin03.f90
  flang/test/Semantics/omp-copyin04.f90
  flang/test/Semantics/omp-copyin05.f90
  flang/test/Semantics/omp-declarative-directive.f90
  flang/test/Semantics/omp-default.f90
  flang/test/Semantics/omp-default02.f90
  flang/test/Semantics/omp-depend01.f90
  flang/test/Semantics/omp-depend02.f90
  flang/test/Semantics/omp-depend03.f90
  flang/test/Semantics/omp-device-constructs.f90
  flang/test/Semantics/omp-do-collapse-positivecases.f90
  flang/test/Semantics/omp-do-collapse.f90
  flang/test/Semantics/omp-do-cycle.f90
  flang/test/Semantics/omp-do-ordered-positivecases.f90
  flang/test/Semantics/omp-do-ordered.f90
  flang/test/Semantics/omp-do-schedule01.f90
  flang/test/Semantics/omp-do-schedule02.f90
  flang/test/Semantics/omp-do01.f90
  flang/test/Semantics/omp-do02.f90
  flang/test/Semantics/omp-do03.f90
  flang/test/Semantics/omp-do04.f90
  flang/test/Semantics/omp-do05.f90
  flang/test/Semantics/omp-do06.f90
  flang/test/Semantics/omp-do07.f90
  flang/test/Semantics/omp-do08.f90
  flang/test/Semantics/omp-do09.f90
  flang/test/Semantics/omp-do10.f90
  flang/test/Semantics/omp-flush01.f90
  flang/test/Semantics/omp-invalid-branch.f90
  flang/test/Semantics/omp-loop-association.f90
  flang/test/Semantics/omp-loop-simd01.f90
  flang/test/Semantics/omp-nested01.f90
  flang/test/Semantics/omp-no-dowhile-in-parallel.f90
  flang/test/Semantics/omp-parallel-private01.f90
  flang/test/Semantics/omp-parallel-private02.f90
  flang/test/Semantics/omp-parallel-private03.f90
  flang/test/Semantics/omp-parallel-private04.f90
  flang/test/Semantics/omp-parallel-shared01.f90
  flang/test/Semantics/omp-parallel-shared02.f90
  flang/test/Semantics/omp-parallel-shared03.f90
  flang/test/Semantics/omp-parallel-shared04.f90
  flang/test/Semantics/omp-parallel01.f90
  flang/test/Semantics/omp-parallel02.f90
  flang/test/Semantics/omp-private01.f90
  flang/test/Seman

[PATCH] D92808: [ObjC][ARC] Use operand bundle 'clang.arc.rv' instead of explicitly emitting retainRV or claimRV calls in the IR

2021-02-04 Thread Florian Hahn via Phabricator via cfe-commits
fhahn accepted this revision.
fhahn added a comment.
This revision is now accepted and ready to land.

Core LLVM parts LGTM, thanks! I'm going to mark this as accepted, given that 
the other parts have been reviewed earlier already


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92808

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


[PATCH] D96033: [clang-repl] Land initial infrastructure for incremental parsing

2021-02-04 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev created this revision.
v.g.vassilev added reviewers: rsmith, lhames, rjmccall, teemperor, aprantl.
Herald added a subscriber: mgorny.
v.g.vassilev requested review of this revision.

In http://lists.llvm.org/pipermail/llvm-dev/2020-July/143257.html we have 
mentioned our plans to make some of the incremental compilation facilities 
available in llvm mainline.

This patch proposes a minimal version of a repl, clang-repl, which enables 
interpreter-like interaction for C++. For instance:

  ./bin/clang-repl
  clang-repl> int i = 42;
  clang-repl> extern "C" int printf(const char*,...);
  clang-repl> auto r1 = printf("i=%d\n", i);
  i=42
  clang-repl> quit

The patch allows very limited functionality, for example, it crashes on invalid 
C++. The design of the proposed patch follows closely the design of cling. The 
idea is to gather feedback and gradually evolve both clang-repl and cling to 
what the community agrees upon.

The IncrementalParser class is responsible for driving the clang parser and 
codegen and allows the compiler infrastructure to process more than one input. 
Every input adds to the “ever-growing” translation unit. That model is enabled 
by an IncrementalAction which prevents teardown when HandleTranslationUnit.

The IncrementalExecutor class hides some of the underlying implementation 
details of the concrete JIT infrastructure. It exposes the minimal set of 
functionality required by our incremental compiler/interpreter.

The Transaction class keeps track of the AST and the LLVM IR for each 
incremental input. That tracking information will be later used to implement 
error recovery.

The Interpreter class orchestrates the IncrementalParser and the 
IncrementalExecutor to model interpreter-like behavior. It provides the public 
API which can be used (in future) when using the interpreter library.


Repository:
  rC Clang

https://reviews.llvm.org/D96033

Files:
  clang/include/clang/CodeGen/CodeGenAction.h
  clang/include/clang/Frontend/FrontendAction.h
  clang/include/clang/Interpreter/Interpreter.h
  clang/include/clang/Interpreter/Transaction.h
  clang/include/clang/Parse/Parser.h
  clang/lib/CMakeLists.txt
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/IncrementalExecutor.cpp
  clang/lib/Interpreter/IncrementalExecutor.h
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/IncrementalParser.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/test/CMakeLists.txt
  clang/test/Interpreter/execute.c
  clang/test/Interpreter/sanity.c
  clang/tools/CMakeLists.txt
  clang/tools/clang-repl/CMakeLists.txt
  clang/tools/clang-repl/ClangRepl.cpp
  clang/unittests/CMakeLists.txt
  clang/unittests/CodeGen/CMakeLists.txt
  clang/unittests/CodeGen/IncrementalProcessingTest.cpp
  clang/unittests/Interpreter/CMakeLists.txt
  clang/unittests/Interpreter/InterpreterTest.cpp

Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- /dev/null
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -0,0 +1,93 @@
+//===- unittests/Interpreter/InterpreterTest.cpp --- Interpreter tests ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Unit tests for our Interpreter library.
+//
+//===--===//
+
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Interpreter/Interpreter.h"
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclGroup.h"
+
+#include "llvm/ADT/ArrayRef.h"
+
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+namespace {
+
+static std::unique_ptr createInterpreter() {
+  std::vector ClangArgs = {"-Xclang", "-emit-llvm-only"};
+  auto CI = cantFail(clang::IncrementalCompilerBuilder::create(ClangArgs));
+  return std::move(cantFail(clang::Interpreter::create(std::move(CI;
+}
+
+TEST(InterpreterTest, Sanity) {
+  std::unique_ptr Interp = createInterpreter();
+  Transaction &R1(cantFail(Interp->Parse("void g(); void g() {}")));
+  EXPECT_EQ(2U, R1.Decls.size());
+
+  Transaction &R2(cantFail(Interp->Parse("int i;")));
+  EXPECT_EQ(1U, R2.Decls.size());
+}
+
+static std::string DeclToString(DeclGroupRef DGR) {
+  return llvm::cast(DGR.getSingleDecl())->getQualifiedNameAsString();
+}
+
+TEST(InterpreterTest, IncrementalInputTopLevelDecls) {
+  std::unique_ptr Interp = createInterpreter();
+  auto R1OrErr = Interp->Parse("int var1 = 42; int f() { return var1; }");
+  // gtest doesn't expand into explicit bool conversions.
+  EXPECT_TRUE(!!R1OrErr);
+  auto R1 = R1OrErr->Decls;
+  EXPECT_EQ(2U, R1.size());
+  EXPECT_EQ("var1", DeclToString(R1[0]));
+  EXPECT_EQ("f", DeclToString(R1[1]));
+
+  auto R2OrErr = Interp->

[PATCH] D94661: [clang-format] [PR19056] Add support for access modifiers indentation

2021-02-04 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius requested changes to this revision.
curdeius added a comment.
This revision now requires changes to proceed.

We're getting close :).




Comment at: clang/unittests/Format/FormatTest.cpp:19056
+TEST_F(FormatTest, IndentAccessModifiers) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AllowShortEnumsOnASingleLine = false;

Please add an assertion that IndentWidth == 2 to make the test easier to 
understand.



Comment at: clang/unittests/Format/FormatTest.cpp:19086
+   Style);
+  verifyFormat("enum class E\n"
+   "{\n"

Add a comment that `enum`s are not concerned.



Comment at: clang/unittests/Format/FormatTest.cpp:19099
+   Style);
+}
 } // namespace

Add tests with a different IndentWidth.


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

https://reviews.llvm.org/D94661

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


[PATCH] D94661: [clang-format] [PR19056] Add support for access modifiers indentation

2021-02-04 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Don't forget to mark comments as Done when... they're done :).




Comment at: clang/docs/ClangFormatStyleOptions.rst:2039
 
+**IndentAccessModifiers** (``bool``)
+  Makes an indentation level for record (``class``, ``struct``, ``union``)

Budovi wrote:
> Budovi wrote:
> > curdeius wrote:
> > > curdeius wrote:
> > > > The name `IndentAccessModifiers` is misleading for me. Access modifiers 
> > > > are public, protected, private.
> > > Hmm, actually that's the description that is misleading.
> > Hm. Will go through the bug report again to see how people describe it. I'm 
> > open to suggestions, but I'll need to fix it anyway because I see a grammar 
> > mistake.
> > 
> > The current way I tried to go about it is that, without this option, 
> > modifiers don't have their own indentation level. Without the offset given 
> > by the `AccessModifierOffset` they would just be flush with the record 
> > members.
> > 
> > The introduced option creates a level designated for the access modifiers 
> > by shifting the members further to the right.
> Hopefully the description is better this time.
Much better indeed! Thanks!


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

https://reviews.llvm.org/D94661

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


[PATCH] D96016: Release notes: Deprecate the clang-cl /fallback flag (patch for the release/12.x branch)

2021-02-04 Thread Tom Stellard via Phabricator via cfe-commits
tstellar accepted this revision.
tstellar added a comment.
This revision is now accepted and ready to land.

Yes, go ahead and push this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96016

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


[PATCH] D96036: [clang][codegen] Remember string used to create llvm::Regex for optimization remarks

2021-02-04 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Regular expression patterns passed through the command line are being used to 
create an instances of `llvm::Regex` and thrown away.

There is no API to serialize `Regex` back to the original pattern. This means 
we have no way to reconstruct the original pattern from command line. This is 
necessary for serializing `CompilerInvocation`.

This patch stores the original pattern string in `CodeGenOptions` alongside the 
`llvm::Regex` instance.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96036

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1159,8 +1159,8 @@
 }
 
 /// Create a new Regex instance out of the string value in \p RpassArg.
-/// It returns a pointer to the newly generated Regex instance.
-static std::shared_ptr
+/// It returns the string and a pointer to the newly generated Regex instance.
+static CodeGenOptions::RemarkPattern
 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
 Arg *RpassArg) {
   StringRef Val = RpassArg->getValue();
@@ -1171,7 +1171,7 @@
 << RegexError << RpassArg->getAsString(Args);
 Pattern.reset();
   }
-  return Pattern;
+  return {std::string(Val), Pattern};
 }
 
 static bool parseDiagnosticLevelMask(StringRef FlagName,
Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -60,22 +60,19 @@
 bool handleDiagnostics(const DiagnosticInfo &DI) override;
 
 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
-  return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
-  CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
+  return CodeGenOpts.OptimizationRemarkAnalysisPattern.match(PassName);
 }
 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
-  return (CodeGenOpts.OptimizationRemarkMissedPattern &&
-  CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
+  return CodeGenOpts.OptimizationRemarkMissedPattern.match(PassName);
 }
 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
-  return (CodeGenOpts.OptimizationRemarkPattern &&
-  CodeGenOpts.OptimizationRemarkPattern->match(PassName));
+  return CodeGenOpts.OptimizationRemarkPattern.match(PassName);
 }
 
 bool isAnyRemarkEnabled() const override {
-  return (CodeGenOpts.OptimizationRemarkAnalysisPattern ||
-  CodeGenOpts.OptimizationRemarkMissedPattern ||
-  CodeGenOpts.OptimizationRemarkPattern);
+  return (CodeGenOpts.OptimizationRemarkAnalysisPattern.isEnabled() ||
+  CodeGenOpts.OptimizationRemarkMissedPattern.isEnabled() ||
+  CodeGenOpts.OptimizationRemarkPattern.isEnabled());
 }
 
   private:
@@ -722,15 +719,13 @@
   if (D.isPassed()) {
 // Optimization remarks are active only if the -Rpass flag has a regular
 // expression that matches the name of the pass name in \p D.
-if (CodeGenOpts.OptimizationRemarkPattern &&
-CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
+if (CodeGenOpts.OptimizationRemarkPattern.match(D.getPassName()))
   EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
   } else if (D.isMissed()) {
 // Missed optimization remarks are active only if the -Rpass-missed
 // flag has a regular expression that matches the name of the pass
 // name in \p D.
-if (CodeGenOpts.OptimizationRemarkMissedPattern &&
-CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
+if (CodeGenOpts.OptimizationRemarkMissedPattern.match(D.getPassName()))
   EmitOptimizationMessage(
   D, diag::remark_fe_backend_optimization_remark_missed);
   } else {
@@ -741,8 +736,7 @@
   ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
 
 if (ShouldAlwaysPrint ||
-(CodeGenOpts.OptimizationRemarkAnalysisPattern &&
- CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName(
+CodeGenOpts.OptimizationRemarkAnalysisPattern.match(D.getPassName()))
   EmitOptimizationMessage(
   D, diag::remark_fe_backend_optimization_remark_analysis);
   }
@@ -755,8 +749,7 @@
   // regular expression that matches the name of the pass name in \p D.
 
   if (D.shouldAlwaysPrint() ||
-  (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
-   CodeGenOp

[PATCH] D95776: [OpenCL] Add macro definitions of OpenCL C 3.0 features

2021-02-04 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov updated this revision to Diff 321425.
azabaznov added a comment.

Adjusted test one more time: moved header functionality into separate test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95776

Files:
  clang/include/clang/Basic/OpenCLExtensions.def
  clang/lib/Basic/Targets.cpp
  clang/lib/Headers/opencl-c-base.h
  clang/test/Headers/opencl-c-header.cl
  clang/test/SemaOpenCL/features.cl

Index: clang/test/SemaOpenCL/features.cl
===
--- /dev/null
+++ clang/test/SemaOpenCL/features.cl
@@ -0,0 +1,48 @@
+// RUN: %clang_cc1 -triple spir-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL3.0 -cl-ext=-all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=NO-FEATURES
+// RUN: %clang_cc1 -triple spir-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL3.0 -cl-ext=+all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=FEATURES
+// RUN: %clang_cc1 -triple r600-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL3.0 \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=NO-FEATURES
+// RUN: %clang_cc1 -triple r600-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL3.0 -cl-ext=+all \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=FEATURES
+
+// For OpenCL C 2.0 feature macros are defined only in header, so test that earlier OpenCL
+// versions don't define feature macros accidentally and CL2.0 don't define them without header
+// RUN: %clang_cc1 -triple spir-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL1.1 \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=NO-FEATURES
+// RUN: %clang_cc1 -triple spir-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL1.2 \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=NO-FEATURES
+// RUN: %clang_cc1 -triple spir-unknown-unknown %s -E -dM -o - -x cl -cl-std=CL2.0 \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=NO-FEATURES
+// RUN: %clang_cc1 -triple spir-unknown-unknown %s -E -dM -o - -x cl -cl-std=CLC++ \
+// RUN:   | FileCheck -match-full-lines %s  --check-prefix=NO-FEATURES
+
+// Note that __opencl_c_int64 is always defined assuming
+// always compiling for FULL OpenCL profile
+
+// FEATURES: #define __opencl_c_3d_image_writes 1
+// FEATURES: #define __opencl_c_atomic_order_acq_rel 1
+// FEATURES: #define __opencl_c_atomic_order_seq_cst 1
+// FEATURES: #define __opencl_c_device_enqueue 1
+// FEATURES: #define __opencl_c_fp64 1
+// FEATURES: #define __opencl_c_generic_address_space 1
+// FEATURES: #define __opencl_c_images 1
+// FEATURES: #define __opencl_c_int64 1
+// FEATURES: #define __opencl_c_pipes 1
+// FEATURES: #define __opencl_c_program_scope_global_variables 1
+// FEATURES: #define __opencl_c_read_write_images 1
+// FEATURES: #define __opencl_c_subgroups 1
+
+// NO-FEATURES: #define __opencl_c_int64 1
+// NO-FEATURES-NOT: __opencl_c_3d_image_writes
+// NO-FEATURES-NOT: __opencl_c_atomic_order_acq_rel
+// NO-FEATURES-NOT: __opencl_c_atomic_order_seq_cst
+// NO-FEATURES-NOT: __opencl_c_device_enqueue
+// NO-FEATURES-NOT: __opencl_c_fp64
+// NO-FEATURES-NOT: __opencl_c_generic_address_space
+// NO-FEATURES-NOT: __opencl_c_images
+// NO-FEATURES-NOT: __opencl_c_pipes
+// NO-FEATURES-NOT: __opencl_c_program_scope_global_variables
+// NO-FEATURES-NOT: __opencl_c_read_write_images
+// NO-FEATURES-NOT: __opencl_c_subgroups
Index: clang/test/Headers/opencl-c-header.cl
===
--- clang/test/Headers/opencl-c-header.cl
+++ clang/test/Headers/opencl-c-header.cl
@@ -151,4 +151,88 @@
 
 #endif //(defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 
+// OpenCL C features.
+#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ == 200)
+
+#ifndef  __opencl_c_pipes
+#error "Feature macro __opencl_c_pipes should be defined"
+#endif
+#ifndef __opencl_c_generic_address_space
+#error "Feature macro __opencl_c_generic_address_space should be defined"
+#endif
+#ifndef __opencl_c_work_group_collective_functions
+#error "Feature macro __opencl_c_work_group_collective_functions should be defined"
+#endif
+#ifndef __opencl_c_atomic_order_acq_rel
+#error "Feature macro __opencl_c_atomic_order_acq_rel should be defined"
+#endif
+#ifndef __opencl_c_atomic_order_seq_cst
+#error "Feature macro __opencl_c_atomic_order_seq_cst should be defined"
+#endif
+#ifndef __opencl_c_atomic_scope_device
+#error "Feature macro __opencl_c_atomic_scope_device should be defined"
+#endif
+#ifndef __opencl_c_atomic_scope_all_devices
+#error "Feature macro __opencl_c_atomic_scope_all_devices should be defined"
+#endif
+#ifndef __opencl_c_device_enqueue
+#error "Feature macro __opencl_c_device_enqueue should be defined"
+#endif
+#ifndef __opencl_c_read_write_images
+#error "Feature macro __opencl_c_read_write_images should be defined"
+#endif
+#ifndef __opencl_c_program_scope_global_variables
+#error "Feature macro __opencl_c_p

[PATCH] D95915: [clang][driver] Only warn once about invalid -stdlib value

2021-02-04 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

LGTM. It also avoid redundant check.


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

https://reviews.llvm.org/D95915

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


[PATCH] D96043: Treat opencl_unroll_hint subject errors as semantic rather than parse errors

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added a reviewer: Anastasia.
Herald added subscribers: zzheng, yaxunl.
aaron.ballman requested review of this revision.
Herald added a project: clang.

While working on a downstream project, I noticed some issues with the 
`opencl_unroll_hint` implementation. The attribute definition claimed the 
attribute was inheritable (which only applies to declaration attributes) and 
not a statement attribute. Further, it treats subject appertainment errors as 
being parse errors rather than semantic errors, which leads to us accepting 
invalid code. For instance, we currently fail to reject:

  void foo() {
int i = 1000;
__attribute__((nomerge, opencl_unroll_hint(8)))
if (i) { foo(); }
  }

This patch address the issues by clarifying that `opencl_unroll_hint` is a 
statement attribute and handling its appertainment checks in the semantic layer 
instead of the parsing layer. This changes the output of the diagnostic text to 
be more consistent with other appertainment errors.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96043

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaStmtAttr.cpp
  clang/test/Parser/opencl-unroll-hint.cl

Index: clang/test/Parser/opencl-unroll-hint.cl
===
--- clang/test/Parser/opencl-unroll-hint.cl
+++ clang/test/Parser/opencl-unroll-hint.cl
@@ -1,8 +1,21 @@
-//RUN: %clang_cc1 -O0 -cl-std=CL2.0 -fsyntax-only -verify %s
+//RUN: %clang_cc1 -cl-std=CL2.0 -fsyntax-only -verify %s
 
 kernel void B (global int *x) {
-  __attribute__((opencl_unroll_hint(42)))
-  if (x[0]) // expected-error {{OpenCL only supports 'opencl_unroll_hint' attribute on for, while, and do statements}}
+  __attribute__((opencl_unroll_hint(42))) // expected-error {{'opencl_unroll_hint' attribute only applies to 'for', 'while', and 'do' statements}}
+  if (x[0])
 x[0] = 15;
 }
 
+void parse_order_error() {
+  // Ensure we properly diagnose OpenCL loop attributes on the incorrect
+  // subject in the presence of other attributes.
+  int i = 1000;
+  __attribute__((nomerge, opencl_unroll_hint(8))) // expected-error {{'opencl_unroll_hint' attribute only applies to 'for', 'while', and 'do' statements}}
+  if (i) { parse_order_error(); } // Recursive call silences unrelated diagnostic about nomerge.
+
+  __attribute__((opencl_unroll_hint(8), nomerge)) // expected-error {{'opencl_unroll_hint' attribute only applies to 'for', 'while', and 'do' statements}}
+  if (i) { parse_order_error(); } // Recursive call silences unrelated diagnostic about nomerge.
+
+  __attribute__((nomerge, opencl_unroll_hint(8))) // OK
+  while (1) { parse_order_error(); } // Recursive call silences unrelated diagnostic about nomerge.
+}
Index: clang/lib/Sema/SemaStmtAttr.cpp
===
--- clang/lib/Sema/SemaStmtAttr.cpp
+++ clang/lib/Sema/SemaStmtAttr.cpp
@@ -378,6 +378,12 @@
   // determines unrolling factor) or 1 argument (the unroll factor provided
   // by the user).
 
+  if (!isa(St)) {
+S.Diag(A.getLoc(), diag::err_attribute_wrong_decl_type_str)
+<< A << "'for', 'while', and 'do' statements";
+return nullptr;
+  }
+
   unsigned NumArgs = A.getNumArgs();
 
   if (NumArgs > 1) {
Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -98,10 +98,15 @@
 
   ParenBraceBracketBalancer BalancerRAIIObj(*this);
 
+  // Because we're parsing either a statement or a declaration, the order of
+  // attribute parsing is important. [[]] attributes at the start of a
+  // statement are different from [[]] attributes that follow an __attribute__
+  // at the start of the statement. Thus, we're not using MaybeParseAttributes
+  // here because we don't want to allow arbitrary orderings.
   ParsedAttributesWithRange Attrs(AttrFactory);
   MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
-  if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
-return StmtError();
+  if (getLangOpts().OpenCL)
+MaybeParseGNUAttributes(Attrs);
 
   StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
   Stmts, StmtCtx, TrailingElseLoc, Attrs);
@@ -2548,19 +2553,3 @@
   }
   Braces.consumeClose();
 }
-
-bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
-  MaybeParseGNUAttributes(Attrs);
-
-  if (Attrs.empty())
-return true;
-
-  if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
-return true;
-
-  if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
-Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);
-return false;
-  }
-  return true;
-}
Index: clang/include/clang/Parse/P

[PATCH] D96044: DebugInfo: Emit "LocalToUnit" flag on local member function decls.

2021-02-04 Thread James Y Knight via Phabricator via cfe-commits
jyknight created this revision.
jyknight added a reviewer: dblaikie.
Herald added a subscriber: inglorion.
jyknight requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Previously, the definition was so-marked, but the declaration was
not. This resulted in LLVM's dwarf emission treating the function as
being external, and incorrectly emitting DW_AT_external.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96044

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/debug-info-class.cpp


Index: clang/test/CodeGenCXX/debug-info-class.cpp
===
--- clang/test/CodeGenCXX/debug-info-class.cpp
+++ clang/test/CodeGenCXX/debug-info-class.cpp
@@ -24,12 +24,14 @@
 C::~C() {
 }
 
+namespace {
 struct D {
-  D();
-  virtual ~D();
+  D() {}
+  virtual ~D() {}
   void func() {
   }
 };
+} // namespace
 
 struct E {
   E();
@@ -135,11 +137,13 @@
 // CHECK-SAME: DIFlagStaticMember
 // CHECK: [[C_DTOR]] = !DISubprogram(name: "~C"
 
-// CHECK: [[D:![0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: 
"D"
+// CHECK: [[D:![0-9]+]] = distinct !DICompositeType(tag: 
DW_TAG_structure_type, name: "D"
 // CHECK-SAME: size:
-// CHECK-SAME: DIFlagFwdDecl
 // CHECK-NOT:  identifier:
 // CHECK-SAME: ){{$}}
+// CHECK: [[D_FUNC_DECL:![0-9]*]] = !DISubprogram(name: "func",{{.*}} scope: 
[[D]]
+// CHECK-SAME: DISPFlagLocalToUnit
+
 // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "E"
 // CHECK-SAME: DIFlagFwdDecl
 // CHECK-NOT:  identifier:
@@ -150,11 +154,10 @@
 // CHECK-SAME: ){{$}}
 
 // CHECK: !DISubprogram(name: "func",{{.*}} scope: [[D]]
-// CHECK-SAME:  DISPFlagDefinition
-// CHECK-SAME:  declaration: [[D_FUNC_DECL:![0-9]*]]
-// CHECK: [[D_FUNC_DECL]] = !DISubprogram(name: "func",{{.*}} scope: [[D]]
+// CHECK-SAME:  DISPFlagLocalToUnit | DISPFlagDefinition
+// CHECK-SAME:  declaration: [[D_FUNC_DECL]]
 
-// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "inner",{{.*}} 
line: 50
+// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "inner",{{.*}} 
line: 52
 // CHECK-NOT: DIFlagFwdDecl
 // CHECK-SAME: elements: [[G_INNER_MEM:![0-9]*]]
 // CHECK-SAME: identifier: "_ZTSN1G5innerE"
@@ -170,5 +173,5 @@
 // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "A"
 // CHECK: !DIDerivedType(tag: DW_TAG_member, name: "HdrSize"
 //
-// CHECK: ![[EXCEPTLOC]] = !DILocation(line: 91,
-// CHECK: ![[RETLOC]] = !DILocation(line: 90,
+// CHECK: ![[EXCEPTLOC]] = !DILocation(line: 93,
+// CHECK: ![[RETLOC]] = !DILocation(line: 92,
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1729,6 +1729,8 @@
 Flags |= llvm::DINode::FlagLValueReference;
   if (Method->getRefQualifier() == RQ_RValue)
 Flags |= llvm::DINode::FlagRValueReference;
+  if (!Method->isExternallyVisible())
+SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
   if (CGM.getLangOpts().Optimize)
 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
 


Index: clang/test/CodeGenCXX/debug-info-class.cpp
===
--- clang/test/CodeGenCXX/debug-info-class.cpp
+++ clang/test/CodeGenCXX/debug-info-class.cpp
@@ -24,12 +24,14 @@
 C::~C() {
 }
 
+namespace {
 struct D {
-  D();
-  virtual ~D();
+  D() {}
+  virtual ~D() {}
   void func() {
   }
 };
+} // namespace
 
 struct E {
   E();
@@ -135,11 +137,13 @@
 // CHECK-SAME: DIFlagStaticMember
 // CHECK: [[C_DTOR]] = !DISubprogram(name: "~C"
 
-// CHECK: [[D:![0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: "D"
+// CHECK: [[D:![0-9]+]] = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "D"
 // CHECK-SAME: size:
-// CHECK-SAME: DIFlagFwdDecl
 // CHECK-NOT:  identifier:
 // CHECK-SAME: ){{$}}
+// CHECK: [[D_FUNC_DECL:![0-9]*]] = !DISubprogram(name: "func",{{.*}} scope: [[D]]
+// CHECK-SAME: DISPFlagLocalToUnit
+
 // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "E"
 // CHECK-SAME: DIFlagFwdDecl
 // CHECK-NOT:  identifier:
@@ -150,11 +154,10 @@
 // CHECK-SAME: ){{$}}
 
 // CHECK: !DISubprogram(name: "func",{{.*}} scope: [[D]]
-// CHECK-SAME:  DISPFlagDefinition
-// CHECK-SAME:  declaration: [[D_FUNC_DECL:![0-9]*]]
-// CHECK: [[D_FUNC_DECL]] = !DISubprogram(name: "func",{{.*}} scope: [[D]]
+// CHECK-SAME:  DISPFlagLocalToUnit | DISPFlagDefinition
+// CHECK-SAME:  declaration: [[D_FUNC_DECL]]
 
-// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "inner",{{.*}} line: 50
+// CHECK: !DICompositeType(tag: DW_TAG_structure_type, n

[PATCH] D94952: [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-02-04 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 321442.
ArcsinX added a comment.

- Remove default value of `IdxContents` in `FileSymbols` constructor.
- Fix index contents for the preamble index (Symbols => Symbols|Relations).
- Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94952

Files:
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/FileIndex.h
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Index.h
  clang-tools-extra/clangd/index/MemIndex.cpp
  clang-tools-extra/clangd/index/MemIndex.h
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/index/Merge.h
  clang-tools-extra/clangd/index/ProjectAware.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Dex.h
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/DexTests.cpp
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1269,7 +1269,7 @@
   std::string BarPath = testPath("bar.cc");
   // Build the index, the index has "Foo" references from foo.cc and "Bar"
   // references from bar.cc.
-  FileSymbols FSymbols;
+  FileSymbols FSymbols(IndexContents::All);
   FSymbols.update(FooPath, nullptr, buildRefSlab(FooCode, "Foo", FooPath),
   nullptr, false);
   FSymbols.update(BarPath, nullptr, buildRefSlab(BarCode, "Bar", BarPath),
@@ -1346,9 +1346,9 @@
llvm::function_ref
Callback) const override {}
 
-llvm::unique_function
+llvm::unique_function
 indexedFiles() const override {
-  return [](llvm::StringRef) { return false; };
+  return [](llvm::StringRef) { return IndexContents::None; };
 }
 
 size_t estimateMemoryUsage() const override { return 0; }
@@ -1400,9 +1400,9 @@
llvm::function_ref)
 const override {}
 
-llvm::unique_function
+llvm::unique_function
 indexedFiles() const override {
-  return [](llvm::StringRef) { return false; };
+  return [](llvm::StringRef) { return IndexContents::None; };
 }
 
 size_t estimateMemoryUsage() const override { return 0; }
Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -231,11 +231,11 @@
   auto Data = std::make_pair(std::move(Symbols), std::move(Refs));
   llvm::StringSet<> Files = {testPath("foo.cc"), testPath("bar.cc")};
   MemIndex I(std::move(Data.first), std::move(Data.second), RelationSlab(),
- std::move(Files), std::move(Data), Size);
+ std::move(Files), IndexContents::All, std::move(Data), Size);
   auto ContainsFile = I.indexedFiles();
-  EXPECT_TRUE(ContainsFile("unittest:///foo.cc"));
-  EXPECT_TRUE(ContainsFile("unittest:///bar.cc"));
-  EXPECT_FALSE(ContainsFile("unittest:///foobar.cc"));
+  EXPECT_EQ(ContainsFile("unittest:///foo.cc"), IndexContents::All);
+  EXPECT_EQ(ContainsFile("unittest:///bar.cc"), IndexContents::All);
+  EXPECT_EQ(ContainsFile("unittest:///foobar.cc"), IndexContents::None);
 }
 
 TEST(MemIndexTest, TemplateSpecialization) {
@@ -508,23 +508,24 @@
   auto DynData = std::make_pair(std::move(DynSymbols), std::move(DynRefs));
   llvm::StringSet<> DynFiles = {testPath("foo.cc")};
   MemIndex DynIndex(std::move(DynData.first), std::move(DynData.second),
-RelationSlab(), std::move(DynFiles), std::move(DynData),
-DynSize);
+RelationSlab(), std::move(DynFiles), IndexContents::Symbols,
+std::move(DynData), DynSize);
   SymbolSlab StaticSymbols;
   RefSlab StaticRefs;
   auto StaticData =
   std::make_pair(std::move(StaticSymbols), std::move(StaticRefs));
-  llvm::StringSet<> StaticFiles = {testPath("bar.cc")};
-  MemIndex StaticIndex(std::move(StaticData.first),
-   std::move(StaticData.second), RelationSlab(),
-   std::move(StaticFiles), std::move(StaticData),
-   StaticSymbols.bytes() + StaticRefs.bytes());
+  llvm::StringSet<> StaticFiles = {testPath("foo.cc"), testPath("bar.cc")};
+  MemIndex StaticIndex(
+  std::move(StaticData.first), std::move(StaticData.second), RelationSlab(),
+  std::move(StaticFiles), IndexContents::References, std::move(StaticData)

[PATCH] D94952: [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-02-04 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX marked 3 inline comments as done.
ArcsinX added a comment.

Thank you for review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94952

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


[PATCH] D95915: [clang][driver] Only warn once about invalid -stdlib value

2021-02-04 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Test still missing.


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

https://reviews.llvm.org/D95915

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


[clang] a83475d - [Hexagon] Add -mv68 option to driver

2021-02-04 Thread Krzysztof Parzyszek via cfe-commits

Author: Krzysztof Parzyszek
Date: 2021-02-04T10:29:34-06:00
New Revision: a83475d34b4550ff5bd40430d6537e630eb761f1

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

LOG: [Hexagon] Add -mv68 option to driver

Added: 


Modified: 
clang/include/clang/Driver/Options.td

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 920b6c0adf89..a700cab350b7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3774,6 +3774,8 @@ def mv67 : Flag<["-"], "mv67">, 
Group,
   Alias, AliasArgs<["hexagonv67"]>;
 def mv67t : Flag<["-"], "mv67t">, Group,
   Alias, AliasArgs<["hexagonv67t"]>;
+def mv68 : Flag<["-"], "mv68">, Group,
+  Alias, AliasArgs<["hexagonv68"]>;
 def mhexagon_hvx : Flag<["-"], "mhvx">, Group,
   HelpText<"Enable Hexagon Vector eXtensions">;
 def mhexagon_hvx_EQ : Joined<["-"], "mhvx=">,



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


[clang] 985a42f - [flang][driver] Add support for `-J/-module-dir`

2021-02-04 Thread Andrzej Warzynski via cfe-commits

Author: Arnamoy Bhattacharyya
Date: 2021-02-04T16:31:40Z
New Revision: 985a42fdf8ae3117442ea129b684569fa6942a71

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

LOG: [flang][driver] Add support for `-J/-module-dir`

Add support for option -J/-module-dir in the new Flang driver.  This
will allow for including module files in other directories, as the
default search path is currently the working folder. This also provides
an option of storing the output module in the specified folder.

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

Added: 
flang/test/Flang-Driver/write-module.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
clang/lib/Driver/ToolChains/Flang.h
flang/include/flang/Frontend/CompilerInstance.h
flang/include/flang/Frontend/CompilerInvocation.h
flang/lib/Frontend/CompilerInstance.cpp
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Frontend/FrontendActions.cpp
flang/test/Flang-Driver/driver-help-hidden.f90
flang/test/Flang-Driver/driver-help.f90
flang/test/Flang-Driver/include-module.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index a700cab350b7..7bd9a8ab40dc 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -949,6 +949,11 @@ def dependency_dot : Separate<["-"], "dependency-dot">, 
Flags<[CC1Option]>,
 def module_dependency_dir : Separate<["-"], "module-dependency-dir">,
   Flags<[CC1Option]>, HelpText<"Directory to dump module dependencies to">,
   MarshallingInfoString>;
+def module_dir : Separate<["-"], "module-dir">, 
Flags<[FlangOption,FC1Option]>, MetaVarName<"">,
+  HelpText<"Put MODULE files in ">,
+  DocBrief<[{This option specifies where to put .mod files for compiled 
modules.
+It is also added to the list of directories to be searched by an USE statement.
+The default is the current directory.}]>;
 def dsym_dir : JoinedOrSeparate<["-"], "dsym-dir">,
   Flags<[NoXarchOption, RenderAsInput]>,
   HelpText<"Directory to output dSYM's (if any) to">, MetaVarName<"">;
@@ -4121,7 +4126,7 @@ defm devirtualize_speculatively : 
BooleanFFlag<"devirtualize-speculatively">,
 
 // Generic gfortran options.
 def A_DASH : Joined<["-"], "A-">, Group;
-def J : JoinedOrSeparate<["-"], "J">, Flags<[RenderJoined]>, 
Group;
+def J : JoinedOrSeparate<["-"], "J">, 
Flags<[RenderJoined,FlangOption,FC1Option]>, Group, 
Alias;
 def cpp : Flag<["-"], "cpp">, Group;
 def nocpp : Flag<["-"], "nocpp">, Group;
 def static_libgfortran : Flag<["-"], "static-libgfortran">, 
Group;

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 1b8d03406f30..dee2148c231c 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -30,6 +30,10 @@ void Flang::AddPreprocessingOptions(const ArgList &Args,
   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
 }
 
+void Flang::AddOtherOptions(const ArgList &Args, ArgStringList &CmdArgs) const 
{
+  Args.AddAllArgs(CmdArgs, options::OPT_module_dir);
+}
+
 void Flang::ConstructJob(Compilation &C, const JobAction &JA,
  const InputInfo &Output, const InputInfoList &Inputs,
  const ArgList &Args, const char *LinkingOutput) const 
{
@@ -87,6 +91,9 @@ void Flang::ConstructJob(Compilation &C, const JobAction &JA,
 
   AddFortranDialectOptions(Args, CmdArgs);
 
+  // Add other compile options
+  AddOtherOptions(Args, CmdArgs);
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());

diff  --git a/clang/lib/Driver/ToolChains/Flang.h 
b/clang/lib/Driver/ToolChains/Flang.h
index a6efa9ae9bda..efbdbe854e24 100644
--- a/clang/lib/Driver/ToolChains/Flang.h
+++ b/clang/lib/Driver/ToolChains/Flang.h
@@ -39,6 +39,13 @@ class LLVM_LIBRARY_VISIBILITY Flang : public Tool {
   /// \param [out] CmdArgs The list of output command arguments
   void AddPreprocessingOptions(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
+  /// Extract other compilation options from the driver arguments and add them
+  /// to the command arguments.
+  ///
+  /// \param [in] Args The list of input driver arguments
+  /// \param [out] CmdArgs The list of output command arguments
+  void AddOtherOptions(const llvm::opt::ArgList &Args,
+   llvm::opt::ArgStringList &CmdArgs) const;
 
 public:
   Flang(const ToolChain &TC);

diff  --git a/flang/include/flang/Frontend/CompilerInstance.h 
b/flang/include/flang/Frontend/CompilerInstance.h
index 79a05c0ddbbe..a6f5fa970ddb 100644
--- a/flang/include/flang/Frontend/Compile

[PATCH] D95448: [flang][driver] Add support for `-J/-module-dir`

2021-02-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG985a42fdf8ae: [flang][driver] Add support for 
`-J/-module-dir` (authored by arnamoy10, committed by awarzynski).

Changed prior to commit:
  https://reviews.llvm.org/D95448?vs=320617&id=321448#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95448

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/ToolChains/Flang.h
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/lib/Frontend/CompilerInstance.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Flang-Driver/include-module.f90
  flang/test/Flang-Driver/write-module.f90

Index: flang/test/Flang-Driver/write-module.f90
===
--- /dev/null
+++ flang/test/Flang-Driver/write-module.f90
@@ -0,0 +1,10 @@
+! RUN: mkdir -p %t/dir-f18 && %f18 -fparse-only -I tools/flang/include/flang -module %t/dir-f18 %s  2>&1
+! RUN: ls %t/dir-f18/testmodule.mod && not ls %t/testmodule.mod
+
+! RUN: mkdir -p %t/dir-flang-new && %flang-new -fsyntax-only -module-dir %t/dir-flang-new %s  2>&1
+! RUN: ls %t/dir-flang-new/testmodule.mod && not ls %t/testmodule.mod
+
+module testmodule
+  type::t2
+  end type
+end
Index: flang/test/Flang-Driver/include-module.f90
===
--- flang/test/Flang-Driver/include-module.f90
+++ flang/test/Flang-Driver/include-module.f90
@@ -7,12 +7,26 @@
 !--
 ! RUN: not %flang-new -fsyntax-only -I %S/Inputs -I %S/Inputs/module-dir %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
 ! RUN: not %flang-new -fsyntax-only -I %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -I %S/Inputs -J %S/Inputs/module-dir %s 2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang-new -fsyntax-only -J %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -I %S/Inputs -module-dir %S/Inputs/module-dir %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang-new -fsyntax-only -module-dir %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -J %S/Inputs/module-dir -J %S/Inputs/ %s  2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -J %S/Inputs/module-dir -module-dir %S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -module-dir %S/Inputs/module-dir -J%S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
 
 !-
 ! FRONTEND FLANG DRIVER (flang-new -fc1)
 !-
 ! RUN: not %flang-new -fc1 -fsyntax-only -I %S/Inputs -I %S/Inputs/module-dir %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
 ! RUN: not %flang-new -fc1 -fsyntax-only -I %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -I %S/Inputs -J %S/Inputs/module-dir %s 2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang-new -fc1 -fsyntax-only -J %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -I %S/Inputs -module-dir %S/Inputs/module-dir %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang-new -fc1 -fsyntax-only -module-dir %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -J %S/Inputs/module-dir -J %S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -J %S/Inputs/module-dir -module-dir %S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -module-dir %S/Inputs/module-dir -J%S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
 
 !-
 ! EXPECTED OUTPUT FOR MISSING MODULE FILE
@@ -22,6 +36,11 @@
 ! SINGLEINCLUDE-NOT:error: Derived type 't1' not found
 ! SINGLEINCLUDE:error: Derived type 't2' not found
 
+!-
+! EXPECTED OUTPUT FOR MISSING MODULE FILE
+!-
+! DOUBLEINCLUDE:error: Only one '-module-dir/-J' option allowed
+
 !---
 ! EXPECTED OUTPUT FOR ALL MODULES FOUND
 !---
Index: flang/test/Flang-Driver/driver-help.f90
===
--- flang/test/Flang-Driver/driver-help.f90
+++ flang/test/Flang-Driver/driver-help.f90
@@ -30,6 +30,7 @@
 ! HELP-NEXT: -fno-color-diagnostics Disable colors in diagnostics
 ! 

[clang] 1d51c69 - [clang][Arm] Fix handling of -Wa,-march=

2021-02-04 Thread David Spickett via cfe-commits

Author: David Spickett
Date: 2021-02-04T16:36:15Z
New Revision: 1d51c699b9e2ebc5bcfdbe85c74cc871426333d4

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

LOG: [clang][Arm] Fix handling of -Wa,-march=

This fixes Bugzilla #48894 for Arm, where it
was reported that -Wa,-march was not being handled
by the integrated assembler.

This was previously fixed for -Wa,-mthumb by
parsing the argument in ToolChain::ComputeLLVMTriple
instead of CollectArgsForIntegratedAssembler.
It has to be done in the former because the Triple
is read only by the time we get to the latter.

Previously only mcpu would work via -Wa but only because
"-target-cpu" is it's own option to cc1, which we were
able to modify. Target architecture is part of "-target-triple".

This change applies the same workaround to -march and cleans up
handling of -Wa,-mcpu at the same time. There were some
places where we were not using the last instance of an argument.

The existing -Wa,-mthumb code was doing this correctly,
so I've just added tests to confirm that.

Now the same rules will apply to -Wa,-march/-mcpu as would
if you just passed them to the compiler:
* -Wa/-Xassembler options only apply to assembly files.
* Architecture derived from mcpu beats any march options.
* When there are multiple mcpu or multiple march, the last
  one wins.
* If there is a compiler option and an assembler option of
  the same type, we prefer the one that fits the input type.
* If there is an applicable mcpu option but it is overruled
  by an march, the cpu value is still used for the "-target-cpu"
  cc1 option.

Reviewed By: nickdesaulniers

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

Added: 
clang/test/Driver/arm-target-as-march-mcpu.s

Modified: 
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/ToolChains/Arch/ARM.cpp
clang/test/Driver/arm-target-as-mthumb.s

Removed: 




diff  --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index b2ddef141a75..c83638086048 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -786,15 +786,26 @@ std::string ToolChain::ComputeLLVMTriple(const ArgList 
&Args,
 else {
   // Ideally we would check for these flags in
   // CollectArgsForIntegratedAssembler but we can't change the ArchName at
-  // that point. There is no assembler equivalent of -mno-thumb, -marm, or
-  // -mno-arm.
+  // that point.
+  llvm::StringRef WaMArch, WaMCPU;
   for (const auto *A :
Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
 for (StringRef Value : A->getValues()) {
+  // There is no assembler equivalent of -mno-thumb, -marm, or 
-mno-arm.
   if (Value == "-mthumb")
 IsThumb = true;
+  else if (Value.startswith("-march="))
+WaMArch = Value.substr(7);
+  else if (Value.startswith("-mcpu="))
+WaMCPU = Value.substr(6);
 }
   }
+
+  if (WaMCPU.size() || WaMArch.size()) {
+// The way this works means that we prefer -Wa,-mcpu's architecture
+// over -Wa,-march. Which matches the compiler behaviour.
+Suffix = tools::arm::getLLVMArchSuffixForARM(WaMCPU, WaMArch, Triple);
+  }
 }
 // Assembly files should start in ARM mode, unless arch is M-profile, or
 // -mthumb has been passed explicitly to the assembler. Windows is always

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index ef590db1eecd..d0606eb882f1 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -50,11 +50,14 @@ void arm::getARMArchCPUFromArgs(const ArgList &Args, 
llvm::StringRef &Arch,
 
   for (const Arg *A :
Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
-StringRef Value = A->getValue();
-if (Value.startswith("-mcpu="))
-  CPU = Value.substr(6);
-if (Value.startswith("-march="))
-  Arch = Value.substr(7);
+// Use getValues because -Wa can have multiple arguments
+// e.g. -Wa,-mcpu=foo,-mcpu=bar
+for (StringRef Value : A->getValues()) {
+  if (Value.startswith("-mcpu="))
+CPU = Value.substr(6);
+  if (Value.startswith("-march="))
+Arch = Value.substr(7);
+}
   }
 }
 
@@ -290,8 +293,8 @@ void arm::getARMTargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
   Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
   arm::FloatABI ABI = arm::getARMFloatABI(D, Triple, Args);
   arm::ReadTPMode ThreadPointer = arm::getReadTPMode(D, Args);
-  const Arg *WaCPU = nullptr, *WaFPU = nullptr;
-  const Arg *WaHDiv = nullptr, *WaArch = nullptr;
+  llvm::Optional> WaCPU, WaFPU, WaHDiv,
+  WaArch;
 
   // This vector

[PATCH] D95872: [clang][Arm] Fix handling of -Wa,-march=

2021-02-04 Thread David Spickett via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
DavidSpickett marked an inline comment as done.
Closed by commit rG1d51c699b9e2: [clang][Arm] Fix handling of -Wa,-march= 
(authored by DavidSpickett).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95872

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/test/Driver/arm-target-as-march-mcpu.s
  clang/test/Driver/arm-target-as-mthumb.s

Index: clang/test/Driver/arm-target-as-mthumb.s
===
--- clang/test/Driver/arm-target-as-mthumb.s
+++ clang/test/Driver/arm-target-as-mthumb.s
@@ -5,12 +5,18 @@
 // RUN: %clang -target armv7a-linux-gnueabi -### -c -mthumb %s 2>&1 | \
 // RUN: FileCheck -check-prefix=TRIPLE-ARM %s
 // RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mthumb \
-// RUN: %S/Inputs/wildcard1.c  2>&1 | FileCheck -check-prefix=TRIPLE-ARM %s
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck -check-prefix=TRIPLE-ARM %s
+// RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mcpu=cortex-a8,-mthumb \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck -check-prefix=TRIPLE-ARM %s
 
 // TRIPLE-ARM: "-triple" "armv7-unknown-linux-gnueabi"
 
 // RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mthumb %s 2>&1 | \
 // RUN: FileCheck -check-prefix=TRIPLE-THUMB %s
+// RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mcpu=cortex-a8,-mthumb %s 2>&1 | \
+// RUN: FileCheck -check-prefix=TRIPLE-THUMB %s
+// RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mcpu=cortex-a8 -Wa,-mthumb %s 2>&1 | \
+// RUN: FileCheck -check-prefix=TRIPLE-THUMB %s
 // RUN: %clang -target armv7a-linux-gnueabi -### -c -Xassembler -mthumb %s \
 // RUN: 2>&1 | FileCheck -check-prefix=TRIPLE-THUMB %s
 
Index: clang/test/Driver/arm-target-as-march-mcpu.s
===
--- /dev/null
+++ clang/test/Driver/arm-target-as-march-mcpu.s
@@ -0,0 +1,104 @@
+/// These tests make sure that options passed to the assembler
+/// via -Wa or -Xassembler are applied correctly to assembler inputs.
+/// Also we check that the same priority rules apply to compiler and
+/// assembler options.
+///
+/// Note that the cortex-a8 is armv7-a, the cortex-a32 is armv8-a
+/// and clang's default Arm architecture is armv4t.
+
+/// Sanity check how the options behave when passed to the compiler
+// RUN: %clang -target arm-linux-gnueabi -### -c -march=armv7-a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -march=armv7-a+crc %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=TRIPLE-ARMV7,EXT-CRC %s
+
+/// -Wa/-Xassembler doesn't apply to non assembly files
+// RUN: %clang -target arm-linux-gnueabi -### -c -Wa,-march=armv7-a \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck --check-prefix=TRIPLE-ARMV4 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Xassembler -march=armv7-a \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck --check-prefix=TRIPLE-ARMV4 %s
+
+/// -Wa/-Xassembler does apply to assembler input
+// RUN: %clang -target arm-linux-gnueabi -### -c -Wa,-march=armv7-a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Wa,-march=armv7-a+crc %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=TRIPLE-ARMV7,EXT-CRC %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Xassembler -march=armv7-a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Xassembler -march=armv7-a+crc %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=TRIPLE-ARMV7,EXT-CRC %s
+
+/// Check that arch name is still canonicalised
+// RUN: %clang -target arm-linux-gnueabi -### -c -Wa,-march=armv7a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Xassembler -march=armv7 %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+
+/// march to compiler and assembler, we choose the one suited to the input file type
+// RUN: %clang -target arm-linux-gnueabi -### -c -march=armv8-a -Wa,-march=armv7a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -march=armv7-a -Wa,-march=armv8-a \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck --check-prefix=TRIPLE-ARMV7 %s
+
+/// mcpu to compiler and march to assembler, we use the assembler's architecture for assembly files.
+/// We use the target CPU for both.
+// RUN: %clang -target arm-linux-gnueabi -### -c -mcpu=cortex-a8 -Wa,-march=armv8a %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=TRIPLE-ARMV8,CPU-A8 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -mcpu=cortex-a8 -Wa,-march=armv8-a \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck --check-prefixes=TRIPLE-ARMV7,CPU-A8 %s
+

[PATCH] D96049: [Timer] On macOS count number of executed instructions

2021-02-04 Thread Alex Hoppen via Phabricator via cfe-commits
ahoppen created this revision.
Herald added subscribers: dexonsmith, hiraditya, mgorny.
ahoppen requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

In addition to wall time etc. this should allow us to get less noisy
values for time measurements.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96049

Files:
  
clang-tools-extra/test/clang-tidy/infrastructure/clang-tidy-store-check-profile-one-tu.cpp
  llvm/CMakeLists.txt
  llvm/include/llvm/Config/config.h.cmake
  llvm/include/llvm/Support/Timer.h
  llvm/lib/Support/Timer.cpp

Index: llvm/lib/Support/Timer.cpp
===
--- llvm/lib/Support/Timer.cpp
+++ llvm/lib/Support/Timer.cpp
@@ -13,6 +13,7 @@
 #include "llvm/Support/Timer.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Config/config.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Format.h"
@@ -24,6 +25,14 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 
+#if HAVE_UNISTD_H
+#include 
+#endif
+
+#ifdef HAVE_PROC_PID_RUSAGE
+#include 
+#endif
+
 using namespace llvm;
 
 // This ugly hack is brought to you courtesy of constructor/destructor ordering
@@ -120,6 +129,17 @@
   return sys::Process::GetMallocUsage();
 }
 
+static uint64_t getCurInstructionsExecuted() {
+#if defined(HAVE_UNISTD_H) && defined(HAVE_PROC_PID_RUSAGE) && \
+defined(RUSAGE_INFO_V4)
+  struct rusage_info_v4 ru;
+  if (proc_pid_rusage(getpid(), RUSAGE_INFO_V4, (rusage_info_t *)&ru) == 0) {
+return ru.ri_instructions;
+  }
+#endif
+  return 0;
+}
+
 TimeRecord TimeRecord::getCurrentTime(bool Start) {
   using Seconds = std::chrono::duration>;
   TimeRecord Result;
@@ -128,9 +148,11 @@
 
   if (Start) {
 Result.MemUsed = getMemUsage();
+Result.InstructionsExecuted = getCurInstructionsExecuted();
 sys::Process::GetTimeUsage(now, user, sys);
   } else {
 sys::Process::GetTimeUsage(now, user, sys);
+Result.InstructionsExecuted = getCurInstructionsExecuted();
 Result.MemUsed = getMemUsage();
   }
 
@@ -180,6 +202,8 @@
 
   if (Total.getMemUsed())
 OS << format("%9" PRId64 "  ", (int64_t)getMemUsed());
+  if (Total.getInstructionsExecuted())
+OS << format("%9" PRId64 "  ", (int64_t)getInstructionsExecuted());
 }
 
 
@@ -339,6 +363,8 @@
   OS << "   ---Wall Time---";
   if (Total.getMemUsed())
 OS << "  ---Mem---";
+  if (Total.getInstructionsExecuted())
+OS << "  ---Instr---";
   OS << "  --- Name ---\n";
 
   // Loop through all of the timing data, printing it out.
@@ -433,6 +459,10 @@
   OS << delim;
   printJSONValue(OS, R, ".mem", T.getMemUsed());
 }
+if (T.getInstructionsExecuted()) {
+  OS << delim;
+  printJSONValue(OS, R, ".instr", T.getInstructionsExecuted());
+}
   }
   TimersToPrint.clear();
   return delim;
Index: llvm/include/llvm/Support/Timer.h
===
--- llvm/include/llvm/Support/Timer.h
+++ llvm/include/llvm/Support/Timer.h
@@ -24,12 +24,15 @@
 class raw_ostream;
 
 class TimeRecord {
-  double WallTime;   ///< Wall clock time elapsed in seconds.
-  double UserTime;   ///< User time elapsed.
-  double SystemTime; ///< System time elapsed.
-  ssize_t MemUsed;   ///< Memory allocated (in bytes).
+  double WallTime;   ///< Wall clock time elapsed in seconds.
+  double UserTime;   ///< User time elapsed.
+  double SystemTime; ///< System time elapsed.
+  ssize_t MemUsed;   ///< Memory allocated (in bytes).
+  uint64_t InstructionsExecuted; ///< Number of instructions executed
 public:
-  TimeRecord() : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0) {}
+  TimeRecord()
+  : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0),
+InstructionsExecuted(0) {}
 
   /// Get the current time and memory usage.  If Start is true we get the memory
   /// usage before the time, otherwise we get time before memory usage.  This
@@ -42,6 +45,7 @@
   double getSystemTime() const { return SystemTime; }
   double getWallTime() const { return WallTime; }
   ssize_t getMemUsed() const { return MemUsed; }
+  uint64_t getInstructionsExecuted() const { return InstructionsExecuted; }
 
   bool operator<(const TimeRecord &T) const {
 // Sort by Wall Time elapsed, as it is the only thing really accurate
@@ -49,16 +53,18 @@
   }
 
   void operator+=(const TimeRecord &RHS) {
-WallTime   += RHS.WallTime;
-UserTime   += RHS.UserTime;
+WallTime += RHS.WallTime;
+UserTime += RHS.UserTime;
 SystemTime += RHS.SystemTime;
-MemUsed+= RHS.MemUsed;
+MemUsed += RHS.MemUsed;
+InstructionsExecuted += RHS.InstructionsExecuted;
   }
   void operator-=(const TimeRecord &RHS) {
-WallTime   -= RHS.WallTime;
-UserTime   -= RHS.UserTime;
+WallTime -= RHS.

[PATCH] D68682: format::cleanupAroundReplacements removes whole line when Removals leave previously non-blank line blank

2021-02-04 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc updated this revision to Diff 321451.
poelmanc added a comment.
Herald added a subscriber: nullptr.cpp.

Change loop end condition in `findLineEnd` and add several `assert` statements.


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

https://reviews.llvm.org/D68682

Files:
  clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-redundant-void-arg.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-control-flow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-member-init.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
  clang-tools-extra/unittests/clang-change-namespace/ChangeNamespaceTests.cpp
  clang/include/clang/Basic/CharInfo.h
  clang/include/clang/Format/Format.h
  clang/lib/AST/CommentLexer.cpp
  clang/lib/AST/CommentParser.cpp
  clang/lib/Format/Format.cpp
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/CleanupTest.cpp

Index: clang/unittests/Format/CleanupTest.cpp
===
--- clang/unittests/Format/CleanupTest.cpp
+++ clang/unittests/Format/CleanupTest.cpp
@@ -12,6 +12,7 @@
 #include "clang/Tooling/Core/Replacement.h"
 
 #include "gtest/gtest.h"
+#include "llvm/Testing/Support/Annotations.h"
 
 using clang::tooling::ReplacementTest;
 using clang::tooling::toReplacements;
@@ -320,6 +321,11 @@
 return tooling::Replacement(FileName, Offset, Length, Text);
   }
 
+  tooling::Replacement createReplacement(llvm::Annotations::Range Range,
+ StringRef Text) {
+return createReplacement(Range.Begin, Range.End - Range.Begin, Text);
+  }
+
   tooling::Replacement createInsertion(StringRef IncludeDirective) {
 return createReplacement(UINT_MAX, 0, IncludeDirective);
   }
@@ -373,10 +379,12 @@
  "namespace C {\n"
  "namespace D { int i; }\n"
  "inline namespace E { namespace { int y; } }\n"
+ "\n"
  "int x= 0;"
  "}";
-  std::string Expected = "\n\nnamespace C {\n"
- "namespace D { int i; }\n\n"
+  std::string Expected = "\nnamespace C {\n"
+ "namespace D { int i; }\n"
+ "\n"
  "int x= 0;"
  "}";
   tooling::Replacements Replaces =
@@ -386,6 +394,104 @@
   EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
 }
 
+TEST_F(CleanUpReplacementsTest, RemoveLineWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code = "namespace A {$r1[[ // Useless comment]]\n"
+   "  $r2[[int]] $r3[[x]]\t $r4[[=]] $r5[[0;]]\t\n"
+   "  int y\t = 0;$r6[[\t]]\n"
+   "} // namespace A\n";
+  std::string Expected = "namespace A {\n"
+ "  int y\t = 0;\n"
+ "} // namespace A\n";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), ""),
+  createReplacement(Code.range("r5"), ""),
+  createReplacement(Code.range("r6"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, RemoveLinesWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code = R"cpp(struct A {
+  A()
+  $r3[[:]] $r1[[f()]]$r2[[,]]
+$r4[[g()]]
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  std::string Expected = R"cpp(struct A {
+  A()
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, KeepLinesWithInsertsOrReplacesEvenIfBlank) {
+  // Not using raw string literals so newlines and spaces are clear and explicit
+  llvm::Annotations Code = "struct A {\n"
+ "  A() {}\n"
+ "$r3[[]]  $r1[[int]] $r2[[f;]]\n" // "  int f;\n"
+ "  \n"
+ "$r4[[  ]]\n"
+ "};";
+  std::string Expected = "struct A {\n"
+ "  A() {}\n"
+ "\n"
+ "\n"
+ "  \n"
+ "\t\n"
+ "};";
+  tooling::Replacements Replaces =
+  toRep

[PATCH] D95915: [clang][driver] Only warn once about invalid -stdlib value

2021-02-04 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added inline comments.



Comment at: clang/include/clang/Driver/ToolChain.h:169-177
+  mutable bool isCXXStdlibTypeCached;
+  mutable CXXStdlibType cxxStdlibType;
+
+  mutable bool isRuntimeLibTypeCached;
+  mutable RuntimeLibType runtimeLibType;
+
+  mutable bool isUnwindLibTypeCached;

Maybe `llvm::Optional` for each type instead of having two members?


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

https://reviews.llvm.org/D95915

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


[PATCH] D96033: [clang-repl] Land initial infrastructure for incremental parsing

2021-02-04 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor added a comment.

A more general comment: You have to `std::move` your `llvm::Error` variables 
when the result is `llvm::Expected` (otherwise this won't compile).




Comment at: clang/include/clang/Interpreter/Transaction.h:1
+//===--- Transaction.h - Incremental Compilation and Execution---*- C++ 
-*-===//
+//

Could this whole file just be part of `IncrementalParser.h` which is the only 
user ? `clang::Transaction` seems anyway a bit of a generic name, so maybe this 
could become `clang::IncrementalParser::Transaction` then.



Comment at: clang/include/clang/Interpreter/Transaction.h:10
+// This file defines utilities tracking the incrementally processed pieces of
+// code
+//

missing `.`.



Comment at: clang/include/clang/Parse/Parser.h:2403
   }
-
+private:
   /// isForInitDeclaration - Disambiguates between a declaration or an

This doesn't seem to be needed for anything?



Comment at: clang/lib/Interpreter/IncrementalParser.cpp:175
+  memcpy(MBStart, input.data(), InputSize);
+  memcpy(MBStart + InputSize, "\n", 2);
+

I think overwriting the \0 in the buffer isn't necessary. So 
`MBStart[InputSize] = '\n';` should be enough.



Comment at: clang/lib/Interpreter/Interpreter.cpp:43
+#include "llvm/Support/Host.h"
+//
+

I think the comment here/above and some of the empty lines aren't really needed 
here.



Comment at: clang/lib/Interpreter/Interpreter.cpp:140
+
+  if (std::find(ClangArgv.begin(), ClangArgv.end(), " -x") == ClangArgv.end()) 
{
+// We do C++ by default; append right after argv[0] if no "-x" given

`llvm::find(ClangArgv, " -x")`



Comment at: clang/tools/clang-repl/CMakeLists.txt:3
+#  ${LLVM_TARGETS_TO_BUILD}
+#  Option
+  Support

Commented out by mistake?



Comment at: clang/unittests/CodeGen/IncrementalProcessingTest.cpp:56-59
+  std::vector ClangArgs = {"-Xclang", "-emit-llvm-only"};
+  std::vector ClangArgv(ClangArgs.size());
+  std::transform(ClangArgs.begin(), ClangArgs.end(), ClangArgv.begin(),
+ [](const std::string &s) -> const char * { return s.data(); 
});





Comment at: clang/unittests/Interpreter/InterpreterTest.cpp:69
+
+  EXPECT_DEATH((void)Interp->Parse("int var1 = 42;"), "");
+}

I think that's usually used for testing asserts but here it's an invalid memory 
access (which might even work out just if the stars align correctly).

What about either:
1. Shutting down clang-repl cleanly after we hit a diagnostic.
2. Making an assert that we can't codegen a TU that already had any error 
diagnostic (in which case you can surround it with the following):

```
#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
```


Repository:
  rC Clang

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

https://reviews.llvm.org/D96033

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


[PATCH] D96050: [OpenCL] Do not enforce ASTContext for OCL2Qual

2021-02-04 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added a reviewer: Anastasia.
svenvh added a project: clang.
Herald added subscribers: jfb, yaxunl.
svenvh requested review of this revision.
Herald added a subscriber: cfe-commits.

Do not enforce that the expression to obtain the `QualType` for an
OpenCL type starts with an `ASTContext`.  This adds the required
flexibility for handling enum types.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96050

Files:
  clang/lib/Sema/OpenCLBuiltins.td
  clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Index: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
===
--- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -778,8 +778,9 @@
 .Case("RO", "case OCLAQ_ReadOnly:\n")
 .Case("WO", "case OCLAQ_WriteOnly:\n")
 .Case("RW", "case OCLAQ_ReadWrite:\n")
- << "  QT.push_back(Context."
- << Image->getValueAsDef("QTName")->getValueAsString("Name") << ");\n"
+ << "  QT.push_back("
+ << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
+ << ");\n"
  << "  break;\n";
 }
 OS << "  }\n"
@@ -800,8 +801,7 @@
  I++) {
   for (const auto *T :
GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) {
-OS << "Context."
-   << T->getValueAsDef("QTName")->getValueAsString("Name") << ", ";
+OS << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ", ";
   }
 }
 OS << "});\n";
@@ -835,14 +835,13 @@
 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
 
 // Check the Type does not have an "abstract" QualType
-auto QT = T->getValueAsDef("QTName");
+auto QT = T->getValueAsDef("QTExpr");
 if (QT->getValueAsBit("IsAbstract") == 1)
   continue;
 // Emit the cases for non generic, non image types.
-OS << "case OCLT_" << T->getValueAsString("Name") << ":\n";
-OS << "  QT.push_back(Context." << QT->getValueAsString("Name")
-   << ");\n";
-OS << "  break;\n";
+OS << "case OCLT_" << T->getValueAsString("Name") << ":\n"
+   << "  QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n"
+   << "  break;\n";
   }
 
   // End of switch statement.
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -79,10 +79,10 @@
 def ArmIntegerDotProductAccumulateSaturateInt8 : FunctionExtension<"cl_arm_integer_dot_product_accumulate_saturate_int8">;
 
 // Qualified Type.  These map to ASTContext::QualType.
-class QualType {
-  // Name of the field or function in a clang::ASTContext
-  // E.g. Name="IntTy" for the int type, and "getIntPtrType()" for an intptr_t
-  string Name = _Name;
+class QualType {
+  // Expression to obtain the QualType inside OCL2Qual.
+  // E.g. TypeExpr="Context.IntTy" for the int type.
+  string TypeExpr = _TypeExpr;
   // Some QualTypes in this file represent an abstract type for which there is
   // no corresponding AST QualType, e.g. a GenType or an `image2d_t` type
   // without access qualifiers.
@@ -101,11 +101,11 @@
 // OpenCL C basic data types (int, float, image2d_t, ...).
 // Its child classes can represent concrete types (e.g. VectorType) or
 // abstract types (e.g. GenType).
-class Type {
+class Type {
   // Name of the Type.
   string Name = _Name;
   // QualType associated with this type.
-  QualType QTName = _QTName;
+  QualType QTExpr = _QTExpr;
   // Size of the vector (if applicable).
   int VecWidth = 1;
   // Is a pointer.
@@ -121,7 +121,7 @@
 }
 
 // OpenCL vector types (e.g. int2, int3, int16, float8, ...).
-class VectorType : Type<_Ty.Name, _Ty.QTName> {
+class VectorType : Type<_Ty.Name, _Ty.QTExpr> {
   let VecWidth = _VecWidth;
   let AccessQualifier = "";
   // Inherited fields
@@ -133,7 +133,7 @@
 
 // OpenCL pointer types (e.g. int*, float*, ...).
 class PointerType :
-Type<_Ty.Name, _Ty.QTName> {
+Type<_Ty.Name, _Ty.QTExpr> {
   let AddrSpace = _AS.Name;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -144,7 +144,7 @@
 }
 
 // OpenCL const types (e.g. const int).
-class ConstType : Type<_Ty.Name, _Ty.QTName> {
+class ConstType : Type<_Ty.Name, _Ty.QTExpr> {
   let IsConst = 1;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -155,7 +155,7 @@
 }
 
 // OpenCL volatile types (e.g. volatile int).
-class VolatileType : Type<_Ty.Name, _Ty.QTName> {
+class VolatileType : Type<_Ty.Name, _Ty.QTExpr> {
   let IsVolatile = 1;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -167,7 +167,7 @@
 
 // OpenCL image types (e.g. image2d).
 class ImageType :
-Type<_Ty.Name, QualType<_Ty.QTName.Name#_AccessQualifier#"Ty", 0>> {
+Type<_Ty.N

[PATCH] D96051: [OpenCL] Support enum and typedef args in TableGen BIFs

2021-02-04 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added a reviewer: Anastasia.
svenvh added a project: clang.
Herald added subscribers: jfb, yaxunl.
svenvh requested review of this revision.
Herald added a subscriber: cfe-commits.

Add enum and typedef argument support to `-fdeclare-opencl-builtins`,
which was the last major missing feature.

Adding the remaining missing builtins is left as future work.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96051

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/OpenCLBuiltins.td
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
  clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Index: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
===
--- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -715,6 +715,30 @@
 void BuiltinNameEmitter::EmitQualTypeFinder() {
   OS << R"(
 
+// Lookup an OpenCL enum type.
+static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
+  LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
+  Sema::LookupTagName);
+  S.LookupName(Result, S.TUScope);
+  if (Result.empty()) {
+S.Diag(SourceLocation(), diag::err_opencl_type_not_found) << Name;
+return S.Context.VoidTy;
+  }
+  return S.Context.getEnumType(Result.getAsSingle());
+}
+
+// Lookup an OpenCL typedef type.
+static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
+  LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
+  Sema::LookupOrdinaryName);
+  S.LookupName(Result, S.TUScope);
+  if (Result.empty()) {
+S.Diag(SourceLocation(), diag::err_opencl_type_not_found) << Name;
+return S.Context.VoidTy;
+  }
+  return S.Context.getTypedefType(Result.getAsSingle());
+}
+
 // Convert an OpenCLTypeStruct type to a list of QualTypes.
 // Generic types represent multiple types and vector sizes, thus a vector
 // is returned. The conversion is done in two steps:
@@ -723,8 +747,9 @@
 // or a single scalar type for non generic types.
 // Step 2: Qualifiers and other type properties such as vector size are
 // applied.
-static void OCL2Qual(ASTContext &Context, const OpenCLTypeStruct &Ty,
+static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
  llvm::SmallVectorImpl &QT) {
+  ASTContext &Context = S.Context;
   // Number of scalar types in the GenType.
   unsigned GenTypeNumTypes;
   // Pointer to the list of vector sizes for the GenType.
Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -34,6 +34,9 @@
 typedef uint uint4 __attribute__((ext_vector_type(4)));
 typedef long long2 __attribute__((ext_vector_type(2)));
 
+typedef uint cl_mem_fence_flags;
+#define CLK_GLOBAL_MEM_FENCE   0x02
+
 // Enable extensions that are enabled in opencl-c-base.h.
 #if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 #define cl_khr_subgroup_ballot 1
@@ -52,6 +55,18 @@
   atom_cmpxchg((volatile __global unsigned int *)global_p, ui, ui);
 }
 
+// Only test enum arguments when the base header is included, because we need
+// the enum declarations.
+#if !defined(NO_HEADER) && (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
+kernel void test_enum_args(volatile global atomic_int *global_p, global int* expected) {
+  int desired;
+  atomic_compare_exchange_strong_explicit(global_p, expected, desired,
+  memory_order_acq_rel,
+  memory_order_relaxed,
+  memory_scope_work_group);
+}
+#endif
+
 kernel void basic_conversion() {
   double d;
   float f;
@@ -180,6 +195,8 @@
 kernel void basic_work_item() {
   uint ui;
 
+  barrier(CLK_GLOBAL_MEM_FENCE);
+
   get_enqueued_local_size(ui);
 #if !defined(__OPENCL_CPP_VERSION__) && __OPENCL_C_VERSION__ < CL_VERSION_2_0
 // expected-error@-2{{implicit declaration of function 'get_enqueued_local_size' is invalid in OpenCL}}
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -679,7 +679,7 @@
 
 /// Get the QualType instances of the return type and arguments for an OpenCL
 /// builtin function signature.
-/// \param Context (in) The Context instance.
+/// \param S (in) The Sema instance.
 /// \param OpenCLBuiltin (in) The signature currently handled.
 /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
 ///type used as return type or as argument.
@@ -689,20 +689,20 @@
 ///argument, ArgTypes contains QualTypes for the Cartesian product
 ///   

[PATCH] D96052: [clang] add new unwind inline asm clobber which lowers to throwable inline assembly

2021-02-04 Thread Paul via Phabricator via cfe-commits
cynecx created this revision.
cynecx requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96052

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp

Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -228,7 +228,7 @@
 StringRef Clobber = Clobbers[i]->getString();
 // We only check registers, therefore we don't check cc and memory
 // clobbers
-if (Clobber == "cc" || Clobber == "memory")
+if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
   continue;
 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
 // Go over the output's registers we collected
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++ clang/lib/CodeGen/CGStmt.cpp
@@ -2115,13 +2115,15 @@
 }
 
 static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
-  bool ReadOnly, bool ReadNone, bool NoMerge,
-  const AsmStmt &S,
+  bool HasUnwindClobber, bool ReadOnly,
+  bool ReadNone, bool NoMerge, const AsmStmt &S,
   const std::vector &ResultRegTypes,
   CodeGenFunction &CGF,
   std::vector &RegResults) {
-  Result.addAttribute(llvm::AttributeList::FunctionIndex,
-  llvm::Attribute::NoUnwind);
+  if (!HasUnwindClobber)
+Result.addAttribute(llvm::AttributeList::FunctionIndex,
+llvm::Attribute::NoUnwind);
+
   if (NoMerge)
 Result.addAttribute(llvm::AttributeList::FunctionIndex,
 llvm::Attribute::NoMerge);
@@ -2468,13 +2470,18 @@
   }
   Constraints += InOutConstraints;
 
+  bool HasUnwindClobber = false;
+
   // Clobbers
   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
 StringRef Clobber = S.getClobber(i);
 
 if (Clobber == "memory")
   ReadOnly = ReadNone = false;
-else if (Clobber != "cc") {
+else if (Clobber == "unwind") {
+  HasUnwindClobber = true;
+  continue;
+} else if (Clobber != "cc") {
   Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
   if (CGM.getCodeGenOpts().StackClashProtector &&
   getTarget().isSPRegName(Clobber)) {
@@ -2508,6 +2515,9 @@
 Constraints += '}';
   }
 
+  assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
+ "unwind clobber can't be used with asm goto");
+
   // Add machine specific clobbers
   std::string MachineClobbers = getTarget().getClobbers();
   if (!MachineClobbers.empty()) {
@@ -2530,23 +2540,28 @@
   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
   llvm::InlineAsm::AsmDialect AsmDialect = isa(&S) ?
 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
-  llvm::InlineAsm *IA =
-llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
- /* IsAlignStack */ false, AsmDialect);
+  llvm::InlineAsm *IA = llvm::InlineAsm::get(
+  FTy, AsmString, Constraints, HasSideEffect,
+  /* IsAlignStack */ false, AsmDialect, HasUnwindClobber);
   std::vector RegResults;
   if (IsGCCAsmGoto) {
 llvm::CallBrInst *Result =
 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
 EmitBlock(Fallthrough);
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
+  } else if (HasUnwindClobber) {
+llvm::CallBase *Result = EmitCallOrInvoke(IA, Args, "");
+UpdateAsmCallInst(*Result, HasSideEffect, true, ReadOnly, ReadNone,
+  InNoMergeAttributedStmt, S, ResultRegTypes, *this,
+  RegResults);
   } else {
 llvm::CallInst *Result =
 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
   }
 
   assert(RegResults.size() == ResultRegTypes.size());
Index: clang/lib/Basic/TargetInfo.cpp
===
--- clang/lib/Basic/TargetInfo.cpp
+++ clang/lib/Basic/TargetInfo.cpp
@@ -4

[PATCH] D96036: [clang][codegen] Remember string used to create llvm::Regex for optimization remarks

2021-02-04 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.

LGTM! I also have a couple of optional suggestions to consider.




Comment at: clang/include/clang/Basic/CodeGenOptions.h:286
+
+bool isEnabled() const { return Regex != nullptr; }
+

This could also be:
```
explicit operator bool() const { return Regex != nullptr }
```




Comment at: clang/include/clang/Basic/CodeGenOptions.h:288-291
+bool match(StringRef String, SmallVectorImpl *Matches = nullptr,
+   std::string *Error = nullptr) const {
+  return isEnabled() && Regex->match(String, Matches, Error);
+}

Another option would be:
```
llvm::Regex *operator->() const { return Regex.get(); }
```
treating `RemarkPattern` as a pointer wrapper (that also knows the 
`std::string`). WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96036

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


[PATCH] D96053: [clang] add new unwind inline asm clobber which lowers to throwable inline assembly

2021-02-04 Thread Paul via Phabricator via cfe-commits
cynecx created this revision.
cynecx requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96053

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp

Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -228,7 +228,7 @@
 StringRef Clobber = Clobbers[i]->getString();
 // We only check registers, therefore we don't check cc and memory
 // clobbers
-if (Clobber == "cc" || Clobber == "memory")
+if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
   continue;
 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
 // Go over the output's registers we collected
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++ clang/lib/CodeGen/CGStmt.cpp
@@ -2115,13 +2115,15 @@
 }
 
 static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
-  bool ReadOnly, bool ReadNone, bool NoMerge,
-  const AsmStmt &S,
+  bool HasUnwindClobber, bool ReadOnly,
+  bool ReadNone, bool NoMerge, const AsmStmt &S,
   const std::vector &ResultRegTypes,
   CodeGenFunction &CGF,
   std::vector &RegResults) {
-  Result.addAttribute(llvm::AttributeList::FunctionIndex,
-  llvm::Attribute::NoUnwind);
+  if (!HasUnwindClobber)
+Result.addAttribute(llvm::AttributeList::FunctionIndex,
+llvm::Attribute::NoUnwind);
+
   if (NoMerge)
 Result.addAttribute(llvm::AttributeList::FunctionIndex,
 llvm::Attribute::NoMerge);
@@ -2468,13 +2470,18 @@
   }
   Constraints += InOutConstraints;
 
+  bool HasUnwindClobber = false;
+
   // Clobbers
   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
 StringRef Clobber = S.getClobber(i);
 
 if (Clobber == "memory")
   ReadOnly = ReadNone = false;
-else if (Clobber != "cc") {
+else if (Clobber == "unwind") {
+  HasUnwindClobber = true;
+  continue;
+} else if (Clobber != "cc") {
   Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
   if (CGM.getCodeGenOpts().StackClashProtector &&
   getTarget().isSPRegName(Clobber)) {
@@ -2508,6 +2515,9 @@
 Constraints += '}';
   }
 
+  assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
+ "unwind clobber can't be used with asm goto");
+
   // Add machine specific clobbers
   std::string MachineClobbers = getTarget().getClobbers();
   if (!MachineClobbers.empty()) {
@@ -2530,23 +2540,28 @@
   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
   llvm::InlineAsm::AsmDialect AsmDialect = isa(&S) ?
 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
-  llvm::InlineAsm *IA =
-llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
- /* IsAlignStack */ false, AsmDialect);
+  llvm::InlineAsm *IA = llvm::InlineAsm::get(
+  FTy, AsmString, Constraints, HasSideEffect,
+  /* IsAlignStack */ false, AsmDialect, HasUnwindClobber);
   std::vector RegResults;
   if (IsGCCAsmGoto) {
 llvm::CallBrInst *Result =
 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
 EmitBlock(Fallthrough);
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
+  } else if (HasUnwindClobber) {
+llvm::CallBase *Result = EmitCallOrInvoke(IA, Args, "");
+UpdateAsmCallInst(*Result, HasSideEffect, true, ReadOnly, ReadNone,
+  InNoMergeAttributedStmt, S, ResultRegTypes, *this,
+  RegResults);
   } else {
 llvm::CallInst *Result =
 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
   }
 
   assert(RegResults.size() == ResultRegTypes.size());
Index: clang/lib/Basic/TargetInfo.cpp
===
--- clang/lib/Basic/TargetInfo.cpp
+++ clang/lib/Basic/TargetInfo.cpp
@@ -4

[PATCH] D95790: [clang][cli] Documentation of CompilerInvocation parsing/generation

2021-02-04 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese added inline comments.



Comment at: clang/docs/InternalsManual.rst:711
+required for parsing or generating the command line argument.
+
+**Positive Flag**

You should create a separate section here for listing the classes.



Comment at: clang/docs/InternalsManual.rst:770
+The key path defaults to an empty ``std::vector``. Values 
specified
+with each appearance of the option on command line are appended to the vector.
+





Comment at: clang/docs/InternalsManual.rst:843
+implementation is still possible.
+
 The Lexer and Preprocessor Library

Past this you should add a section providing instructions on how to actually 
add marshaling for an option, and cover what to do if the automatic 
infrastructure isn't enough.



Comment at: clang/docs/InternalsManual.rst:590
+the driver options in ``clang/Driver/Options.td``. The information making up an
+option definition include the name and prefix (for example ``-std=``), form and
+position of the option value, help text, aliases and more. Each option may




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95790

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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 321465.
aaron.ballman set the repository for this revision to rG LLVM Github Monorepo.
aaron.ballman added a comment.
Herald added a project: clang.

Updating based on review feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseExprCXX.cpp
  clang/test/AST/ast-dump-lambda.cpp
  clang/test/Parser/cxx0x-lambda-expressions.cpp

Index: clang/test/Parser/cxx0x-lambda-expressions.cpp
===
--- clang/test/Parser/cxx0x-lambda-expressions.cpp
+++ clang/test/Parser/cxx0x-lambda-expressions.cpp
@@ -101,7 +101,6 @@
   }
 
   void attributes() {
-[] [[]] {}; // expected-error {{lambda requires '()' before attribute specifier}}
 [] __attribute__((noreturn)) {}; // expected-error {{lambda requires '()' before attribute specifier}}
 []() [[]]
   mutable {}; // expected-error {{expected body of lambda expression}}
@@ -116,6 +115,14 @@
 []() __attribute__((noreturn)) mutable { while(1); };
 []() mutable
   __attribute__((noreturn)) { while(1); }; // expected-error {{expected body of lambda expression}}
+
+// Testing support for P2173 on adding attributes to the declaration
+// rather than the type.
+[] [[]] () {}; // expected-warning {{an attribute specifier sequence in this position is a C++2b extension}}
+#if __cplusplus > 201703L
+[]  [[]] () {};  // expected-warning {{an attribute specifier sequence in this position is a C++2b extension}}
+#endif
+[] [[]] {}; // expected-warning {{an attribute specifier sequence in this position is a C++2b extension}}
   }
 };
 
Index: clang/test/AST/ast-dump-lambda.cpp
===
--- clang/test/AST/ast-dump-lambda.cpp
+++ clang/test/AST/ast-dump-lambda.cpp
@@ -33,13 +33,14 @@
   []() mutable {};
   []() noexcept {};
   []() -> int { return 0; };
+  [] [[noreturn]] () {};
 }
 // CHECK:Dumping test:
-// CHECK-NEXT:FunctionTemplateDecl {{.*}} <{{.*}}ast-dump-lambda.cpp:15:1, line:36:1> line:15:32{{( imported)?}} test
+// CHECK-NEXT:FunctionTemplateDecl {{.*}} <{{.*}}ast-dump-lambda.cpp:15:1, line:37:1> line:15:32{{( imported)?}} test
 // CHECK-NEXT:|-TemplateTypeParmDecl {{.*}}  col:23{{( imported)?}} referenced typename depth 0 index 0 ... Ts
-// CHECK-NEXT:`-FunctionDecl {{.*}}  line:15:32{{( imported)?}} test 'void (Ts...)'
+// CHECK-NEXT:`-FunctionDecl {{.*}}  line:15:32{{( imported)?}} test 'void (Ts...)'
 // CHECK-NEXT:  |-ParmVarDecl {{.*}}  col:43{{( imported)?}} referenced a 'Ts...' pack
-// CHECK-NEXT:  `-CompoundStmt {{.*}} 
+// CHECK-NEXT:  `-CompoundStmt {{.*}} 
 // CHECK-NEXT:|-DeclStmt {{.*}} 
 // CHECK-NEXT:| `-CXXRecordDecl {{.*}}  line:16:10{{( imported)?}}{{( )?}} struct V definition
 // CHECK-NEXT:|   |-DefinitionData empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init
@@ -275,7 +276,25 @@
 // CHECK-NEXT:| | |-CXXConversionDecl {{.*}}  col:3{{( imported)?}} implicit constexpr operator auto (*)() noexcept 'auto (*() const noexcept)() noexcept' inline
 // CHECK-NEXT:| | `-CXXMethodDecl {{.*}}  col:3{{( imported)?}} implicit __invoke 'auto () noexcept' static inline
 // CHECK-NEXT:| `-CompoundStmt {{.*}} 
-// CHECK-NEXT:`-LambdaExpr {{.*}}  '(lambda at {{.*}}ast-dump-lambda.cpp:35:3)'
+// CHECK-NEXT:|-LambdaExpr {{.*}}  '(lambda at {{.*}}ast-dump-lambda.cpp:35:3)'
+// CHECK-NEXT:| |-CXXRecordDecl {{.*}}  col:3{{( imported)?}} implicit{{( )?}} class definition
+// CHECK-NEXT:| | |-DefinitionData lambda empty standard_layout trivially_copyable literal can_const_default_init
+// CHECK-NEXT:| | | |-DefaultConstructor defaulted_is_constexpr
+// CHECK-NEXT:| | | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param
+// CHECK-NEXT:| | | |-MoveConstructor exists simple trivial needs_implicit
+// CHECK-NEXT:| | | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
+// CHECK-NEXT:| | | |-MoveAssignment
+// CHECK-NEXT:| | | `-Destructor simple irrelevant trivial needs_implicit
+// CHECK-NEXT:| | |-CXXMethodDecl {{.*}}  col:3{{( imported)?}} operator() 'auto () const -> int' inline
+// CHECK-NEXT:| | | `-CompoundStmt {{.*}} 
+// CHECK-NEXT:| | |   `-ReturnStmt {{.*}} 
+// CHECK-NEXT:| | | `-IntegerLiteral {{.*}}  'int' 0
+// CHECK-NEXT:| | |-CXXConversionDecl {{.*}}  col:3{{( imported)?}} implicit constexpr operator int (*)() 'auto (*() const noexcept)() -> int' inline
+// CHECK-NEXT:| | `-CXXMethodDecl {{.*}}  col:3{{( imported)?}} implicit __invoke 'auto () -> int' static inline
+// CHECK-NEXT:| `-CompoundStmt {{.*}} 
+//

[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D95691#2540667 , @rjmccall wrote:

> In D95691#2540619 , @rsmith wrote:
>
>> In D95691#2540450 , @rjmccall wrote:
>>
>>> The warning is a bit weird.  If we don't think it's certain that the 
>>> committee will adopt this syntax, I don't think we should add this patch at 
>>> all; it is not really acceptable to add it and then treat it as a Clang 
>>> extension if the committee rejects it.  If we do think it's certain, we 
>>> should go ahead and consider this a feature of the next major standard.
>>
>> I think it's quite unlikely that the committee would reject the feature at 
>> this stage. Seems OK to me to jump the gun slightly and call this a C++23 
>> extension.
>
> SGTM, then.

That works for me as well -- I'd also be very surprised if the committee 
rejected the feature at this point. When I originally worked on the patch, the 
paper hadn't started its polling in Evolution yet and so it was less clear how 
it would be received.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D96049: [Timer] On macOS count number of executed instructions

2021-02-04 Thread Alex Hoppen via Phabricator via cfe-commits
ahoppen updated this revision to Diff 321467.
ahoppen added a comment.

Fixed an issue caused by me using an old revions as the commit's base.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96049

Files:
  
clang-tools-extra/test/clang-tidy/infrastructure/clang-tidy-store-check-profile-one-tu.cpp
  llvm/CMakeLists.txt
  llvm/include/llvm/Config/config.h.cmake
  llvm/include/llvm/Support/Timer.h
  llvm/lib/Support/Timer.cpp

Index: llvm/lib/Support/Timer.cpp
===
--- llvm/lib/Support/Timer.cpp
+++ llvm/lib/Support/Timer.cpp
@@ -13,6 +13,7 @@
 #include "llvm/Support/Timer.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Config/config.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Format.h"
@@ -24,6 +25,14 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 
+#if HAVE_UNISTD_H
+#include 
+#endif
+
+#ifdef HAVE_PROC_PID_RUSAGE
+#include 
+#endif
+
 using namespace llvm;
 
 // This ugly hack is brought to you courtesy of constructor/destructor ordering
@@ -120,6 +129,17 @@
   return sys::Process::GetMallocUsage();
 }
 
+static uint64_t getCurInstructionsExecuted() {
+#if defined(HAVE_UNISTD_H) && defined(HAVE_PROC_PID_RUSAGE) && \
+defined(RUSAGE_INFO_V4)
+  struct rusage_info_v4 ru;
+  if (proc_pid_rusage(getpid(), RUSAGE_INFO_V4, (rusage_info_t *)&ru) == 0) {
+return ru.ri_instructions;
+  }
+#endif
+  return 0;
+}
+
 TimeRecord TimeRecord::getCurrentTime(bool Start) {
   using Seconds = std::chrono::duration>;
   TimeRecord Result;
@@ -128,9 +148,11 @@
 
   if (Start) {
 Result.MemUsed = getMemUsage();
+Result.InstructionsExecuted = getCurInstructionsExecuted();
 sys::Process::GetTimeUsage(now, user, sys);
   } else {
 sys::Process::GetTimeUsage(now, user, sys);
+Result.InstructionsExecuted = getCurInstructionsExecuted();
 Result.MemUsed = getMemUsage();
   }
 
@@ -180,6 +202,8 @@
 
   if (Total.getMemUsed())
 OS << format("%9" PRId64 "  ", (int64_t)getMemUsed());
+  if (Total.getInstructionsExecuted())
+OS << format("%9" PRId64 "  ", (int64_t)getInstructionsExecuted());
 }
 
 
@@ -339,6 +363,8 @@
   OS << "   ---Wall Time---";
   if (Total.getMemUsed())
 OS << "  ---Mem---";
+  if (Total.getInstructionsExecuted())
+OS << "  ---Instr---";
   OS << "  --- Name ---\n";
 
   // Loop through all of the timing data, printing it out.
@@ -433,6 +459,10 @@
   OS << delim;
   printJSONValue(OS, R, ".mem", T.getMemUsed());
 }
+if (T.getInstructionsExecuted()) {
+  OS << delim;
+  printJSONValue(OS, R, ".instr", T.getInstructionsExecuted());
+}
   }
   TimersToPrint.clear();
   return delim;
Index: llvm/include/llvm/Support/Timer.h
===
--- llvm/include/llvm/Support/Timer.h
+++ llvm/include/llvm/Support/Timer.h
@@ -24,12 +24,15 @@
 class raw_ostream;
 
 class TimeRecord {
-  double WallTime;   ///< Wall clock time elapsed in seconds.
-  double UserTime;   ///< User time elapsed.
-  double SystemTime; ///< System time elapsed.
-  ssize_t MemUsed;   ///< Memory allocated (in bytes).
+  double WallTime;   ///< Wall clock time elapsed in seconds.
+  double UserTime;   ///< User time elapsed.
+  double SystemTime; ///< System time elapsed.
+  ssize_t MemUsed;   ///< Memory allocated (in bytes).
+  uint64_t InstructionsExecuted; ///< Number of instructions executed
 public:
-  TimeRecord() : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0) {}
+  TimeRecord()
+  : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0),
+InstructionsExecuted(0) {}
 
   /// Get the current time and memory usage.  If Start is true we get the memory
   /// usage before the time, otherwise we get time before memory usage.  This
@@ -42,6 +45,7 @@
   double getSystemTime() const { return SystemTime; }
   double getWallTime() const { return WallTime; }
   ssize_t getMemUsed() const { return MemUsed; }
+  uint64_t getInstructionsExecuted() const { return InstructionsExecuted; }
 
   bool operator<(const TimeRecord &T) const {
 // Sort by Wall Time elapsed, as it is the only thing really accurate
@@ -49,16 +53,18 @@
   }
 
   void operator+=(const TimeRecord &RHS) {
-WallTime   += RHS.WallTime;
-UserTime   += RHS.UserTime;
+WallTime += RHS.WallTime;
+UserTime += RHS.UserTime;
 SystemTime += RHS.SystemTime;
-MemUsed+= RHS.MemUsed;
+MemUsed += RHS.MemUsed;
+InstructionsExecuted += RHS.InstructionsExecuted;
   }
   void operator-=(const TimeRecord &RHS) {
-WallTime   -= RHS.WallTime;
-UserTime   -= RHS.UserTime;
+WallTime -= RHS.WallTime;
+UserTime -= RHS.UserTime;
 SystemTime -= RHS.SystemTime;
-MemUsed-= RHS.MemUsed;
+  

[PATCH] D96054: Support unwinding from inline assembly

2021-02-04 Thread Paul via Phabricator via cfe-commits
cynecx created this revision.
cynecx requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96054

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp

Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -228,7 +228,7 @@
 StringRef Clobber = Clobbers[i]->getString();
 // We only check registers, therefore we don't check cc and memory
 // clobbers
-if (Clobber == "cc" || Clobber == "memory")
+if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
   continue;
 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
 // Go over the output's registers we collected
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++ clang/lib/CodeGen/CGStmt.cpp
@@ -2115,13 +2115,15 @@
 }
 
 static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
-  bool ReadOnly, bool ReadNone, bool NoMerge,
-  const AsmStmt &S,
+  bool HasUnwindClobber, bool ReadOnly,
+  bool ReadNone, bool NoMerge, const AsmStmt &S,
   const std::vector &ResultRegTypes,
   CodeGenFunction &CGF,
   std::vector &RegResults) {
-  Result.addAttribute(llvm::AttributeList::FunctionIndex,
-  llvm::Attribute::NoUnwind);
+  if (!HasUnwindClobber)
+Result.addAttribute(llvm::AttributeList::FunctionIndex,
+llvm::Attribute::NoUnwind);
+
   if (NoMerge)
 Result.addAttribute(llvm::AttributeList::FunctionIndex,
 llvm::Attribute::NoMerge);
@@ -2468,13 +2470,18 @@
   }
   Constraints += InOutConstraints;
 
+  bool HasUnwindClobber = false;
+
   // Clobbers
   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
 StringRef Clobber = S.getClobber(i);
 
 if (Clobber == "memory")
   ReadOnly = ReadNone = false;
-else if (Clobber != "cc") {
+else if (Clobber == "unwind") {
+  HasUnwindClobber = true;
+  continue;
+} else if (Clobber != "cc") {
   Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
   if (CGM.getCodeGenOpts().StackClashProtector &&
   getTarget().isSPRegName(Clobber)) {
@@ -2508,6 +2515,9 @@
 Constraints += '}';
   }
 
+  assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
+ "unwind clobber can't be used with asm goto");
+
   // Add machine specific clobbers
   std::string MachineClobbers = getTarget().getClobbers();
   if (!MachineClobbers.empty()) {
@@ -2530,23 +2540,28 @@
   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
   llvm::InlineAsm::AsmDialect AsmDialect = isa(&S) ?
 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
-  llvm::InlineAsm *IA =
-llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
- /* IsAlignStack */ false, AsmDialect);
+  llvm::InlineAsm *IA = llvm::InlineAsm::get(
+  FTy, AsmString, Constraints, HasSideEffect,
+  /* IsAlignStack */ false, AsmDialect, HasUnwindClobber);
   std::vector RegResults;
   if (IsGCCAsmGoto) {
 llvm::CallBrInst *Result =
 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
 EmitBlock(Fallthrough);
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
+  } else if (HasUnwindClobber) {
+llvm::CallBase *Result = EmitCallOrInvoke(IA, Args, "");
+UpdateAsmCallInst(*Result, HasSideEffect, true, ReadOnly, ReadNone,
+  InNoMergeAttributedStmt, S, ResultRegTypes, *this,
+  RegResults);
   } else {
 llvm::CallInst *Result =
 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
   }
 
   assert(RegResults.size() == ResultRegTypes.size());
Index: clang/lib/Basic/TargetInfo.cpp
===
--- clang/lib/Basic/TargetInfo.cpp
+++ clang/lib/Basic/TargetInfo.cpp
@@ -4

[PATCH] D95396: Improve static_assert/_Static_assert diagnostics

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked an inline comment as not done.
aaron.ballman added inline comments.



Comment at: clang/lib/Parse/ParseDeclCXX.cpp:874-876
+if (!getLangOpts().CPlusPlus)
+  Diag(Tok, diag::warn_cxx_static_assert_in_c)
+  << FixItHint::CreateReplacement(Tok.getLocation(), "_Static_assert");

aaron.ballman wrote:
> rsmith wrote:
> > I don't think this diagnostic is useful as-is: on Windows, including 
> > `` doesn't help because it doesn't `#define static_assert`. And 
> > people hitting this also can't switch to using `_Static_assert`, because 
> > MSVC doesn't provide it, only `static_assert`.
> > 
> > If we want to warn here, we could perhaps check whether `` has 
> > been included, but getting that check correct across PCH / modules is not 
> > straightforward. (If we knew what include guard the CRT's `assert.h` used 
> > (if any), I guess we could check whether that's defined, but that'd be a 
> > bit of a hack.) But I'm somewhat inclined to think we don't have a good way 
> > to distinguish between the good cases and the bad ones, so we shouldn't 
> > warn. Hopefully MS will fix their CRT at some point and we can stop 
> > providing this compatibility hack entirely (or start warning on it by 
> > default).
> Are you sure they don't support `_Static_assert` yet? I seem to be able to 
> use it fine: https://godbolt.org/z/vG47he
> 
> That said, this does appear to be only available in newer versions of MSVC, 
> so perhaps you're correct about the diagnostic being a bit unhelpful. My 
> primary concern is that use of `static_assert` in C is a nonconforming 
> extension and we default to `-fms-compatibility` on Windows when Clang is 
> built by MSVC. So it's not difficult to accidentally run into this, but the 
> only warning we give on it with `-Weverything -pedantic` is how it's not 
> compatible with C++98.
> 
> WDYT?
I suppose one option would be to look at what version of MSVC we're trying to 
be compatible with to see if that's a version that supports `/std:c11` and only 
emit this diagnostic in that case, but tbh, that feels like it'll lead to 
confusing diagnostic behavior (esp given that we default to ms compatibility 
mode silently when you build Clang with MSVC on Windows).

Given that MSVC does support `_Static_assert` when you enable C11 or later 
language mode, I'm inclined to warn on this construct by default.

WDYT?


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

https://reviews.llvm.org/D95396

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


[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-04 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 321476.
RedDocMD added a comment.

Updated to use new function


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Analysis/pointer-to-member.cpp

Index: clang/test/Analysis/pointer-to-member.cpp
===
--- clang/test/Analysis/pointer-to-member.cpp
+++ clang/test/Analysis/pointer-to-member.cpp
@@ -287,3 +287,25 @@
   clang_analyzer_eval(a.*ep == 5); // expected-warning{{TRUE}}
 }
 } // namespace testAnonymousMember
+
+namespace testStaticCasting {
+// From bug #48739
+struct Grandfather {
+  int field;
+};
+
+struct Father : public Grandfather {};
+struct Son : public Father {};
+
+void test() {
+  int Son::*sf = &Son::field;
+  Grandfather grandpa;
+  grandpa.field = 10;
+  int Grandfather::*gpf1 = static_cast(sf);
+  int Grandfather::*gpf2 = static_cast(static_cast(sf));
+  int Grandfather::*gpf3 = static_cast(static_cast(static_cast(sf)));
+  clang_analyzer_eval(grandpa.*gpf1 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf2 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf3 == 10); // expected-warning{{TRUE}}
+}
+} // namespace testStaticCasting
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -526,10 +526,9 @@
   case CK_ReinterpretMemberPointer: {
 SVal V = state->getSVal(Ex, LCtx);
 if (auto PTMSV = V.getAs()) {
-  SVal CastedPTMSV = svalBuilder.makePointerToMember(
-  getBasicVals().accumCXXBase(
-  llvm::make_range(
-  CastE->path_begin(), CastE->path_end()), *PTMSV));
+  SVal CastedPTMSV =
+  svalBuilder.makePointerToMember(getBasicVals().accumCXXBase(
+  CastE->path(), *PTMSV, CastE->getCastKind()));
   state = state->BindExpr(CastE, LCtx, CastedPTMSV);
   Bldr.generateNode(CastE, Pred, state);
   continue;
Index: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
===
--- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
+++ clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
@@ -21,8 +21,10 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include 
 #include 
+#include 
 #include 
 
 using namespace clang;
@@ -178,26 +180,62 @@
 
 const PointerToMemberData *BasicValueFactory::accumCXXBase(
 llvm::iterator_range PathRange,
-const nonloc::PointerToMember &PTM) {
+const nonloc::PointerToMember &PTM, const CastKind &kind) {
+  assert((kind == CK_DerivedToBaseMemberPointer ||
+  kind == CK_BaseToDerivedMemberPointer ||
+  kind == CK_ReinterpretMemberPointer) &&
+ "accumCXXBase called with wrong CastKind");
   nonloc::PointerToMember::PTMDataType PTMDT = PTM.getPTMData();
   const NamedDecl *ND = nullptr;
-  llvm::ImmutableList PathList;
+  llvm::ImmutableList BaseSpecList;
 
   if (PTMDT.isNull() || PTMDT.is()) {
 if (PTMDT.is())
   ND = PTMDT.get();
 
-PathList = CXXBaseListFactory.getEmptyList();
-  } else { // const PointerToMemberData *
+BaseSpecList = CXXBaseListFactory.getEmptyList();
+  } else {
 const PointerToMemberData *PTMD = PTMDT.get();
 ND = PTMD->getDeclaratorDecl();
 
-PathList = PTMD->getCXXBaseList();
+BaseSpecList = PTMD->getCXXBaseList();
+  }
+  // First we need to make sure that there are no-repetitions in BaseSpecList
+  llvm::SmallPtrSet BaseSpecSeen;
+  for (const auto &BaseSpec : BaseSpecList) {
+auto BaseType = BaseSpec->getType();
+assert(BaseSpecSeen.find(BaseType) == BaseSpecSeen.end() &&
+   "CXXBaseSpecifier list of PointerToMemberData must not have "
+   "repeated elements");
+BaseSpecSeen.insert(BaseType);
   }
 
-  for (const auto &I : llvm::reverse(PathRange))
-PathList = prependCXXBase(I, PathList);
-  return getPointerToMemberData(ND, PathList);
+  if (kind == CK_DerivedToBaseMemberPointer) {
+// Here we pop off matching CXXBaseSpecifiers from BaseSpecList.
+// Because, CK_DerivedToBaseMemberPointer comes from a static_cast and
+// serves to remove a matching implicit cast. Note that static_cast's that
+// are no-ops do not count since they produce an empty PathRange, a nice
+// thing about Clang AST.
+
+// Now we know that there are no repetitions in BaseSpecList.
+// So, popping the fir

[PATCH] D95745: Support unwinding from inline assembly

2021-02-04 Thread Paul via Phabricator via cfe-commits
cynecx updated this revision to Diff 321479.
cynecx added a comment.

clang-format changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95745

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  llvm/bindings/go/llvm/ir.go
  llvm/include/llvm-c/Core.h
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/InlineAsm.h
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h
  llvm/lib/IR/AsmWriter.cpp
  llvm/lib/IR/ConstantsContext.h
  llvm/lib/IR/Core.cpp
  llvm/lib/IR/InlineAsm.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp

Index: llvm/lib/Transforms/Utils/InlineFunction.cpp
===
--- llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -28,7 +28,6 @@
 #include "llvm/Analysis/EHPersonalities.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/ProfileSummaryInfo.h"
-#include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Analysis/VectorUtils.h"
 #include "llvm/IR/Argument.h"
@@ -44,6 +43,7 @@
 #include "llvm/IR/Dominators.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/InstrTypes.h"
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/Instructions.h"
@@ -61,6 +61,7 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
 #include "llvm/Transforms/Utils/Cloning.h"
+#include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Transforms/Utils/ValueMapper.h"
 #include 
 #include 
@@ -543,9 +544,16 @@
 // instructions require no special handling.
 CallInst *CI = dyn_cast(I);
 
-if (!CI || CI->doesNotThrow() || CI->isInlineAsm())
+if (!CI || CI->doesNotThrow())
   continue;
 
+if (CI->isInlineAsm()) {
+  InlineAsm *IA = cast(CI->getCalledOperand());
+  if (!IA->canThrow()) {
+continue;
+  }
+}
+
 // We do not need to (and in fact, cannot) convert possibly throwing calls
 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
 // invokes.  The caller's "segment" of the deoptimization continuation
Index: llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
===
--- llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -39,6 +39,7 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalVariable.h"
+#include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/InstrTypes.h"
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/Instructions.h"
@@ -2139,9 +2140,13 @@
   }
 
   if (isa(Callee) && !Call.doesNotThrow()) {
-// Inline asm calls cannot throw - mark them 'nounwind'.
-Call.setDoesNotThrow();
-Changed = true;
+InlineAsm *IA = cast(Callee);
+if (!IA->canThrow()) {
+  // Normal inline asm calls cannot throw - mark them
+  // 'nounwind'.
+  Call.setDoesNotThrow();
+  Changed = true;
+}
   }
 
   // Try to optimize the call if possible, we require DataLayout for most of
Index: llvm/lib/IR/InlineAsm.cpp
===
--- llvm/lib/IR/InlineAsm.cpp
+++ llvm/lib/IR/InlineAsm.cpp
@@ -29,11 +29,11 @@
 
 InlineAsm::InlineAsm(FunctionType *FTy, const std::string &asmString,
  const std::string &constraints, bool hasSideEffects,
- bool isAlignStack, AsmDialect asmDialect)
+ bool isAlignStack, AsmDialect asmDialect, bool canThrow)
 : Value(PointerType::getUnqual(FTy), Value::InlineAsmVal),
   AsmString(asmString), Constraints(constraints), FTy(FTy),
   HasSideEffects(hasSideEffects), IsAlignStack(isAlignStack),
-  Dialect(asmDialect) {
+  Dialect(asmDialect), CanThrow(canThrow) {
   // Do various checks on the constraint string and type.
   assert(Verify(getFunctionType(), constraints) &&
  "Function type not legal for constraints!");
@@ -41,9 +41,10 @@
 
 InlineAsm *InlineAsm::get(FunctionType *FTy, StringRef AsmString,
   StringRef Constraints, bool hasSideEffects,
-  bool isAlignStack, AsmDialect asmDialect) {
+  bool isAlignStack, AsmDialect asmDialect,
+  bool canThrow) {
   InlineAsmKeyType Key(AsmString, Constraints, FTy, hasSideEffects,
-   isAlignStack, asmDialect);
+   isAlign

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-04 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.

@vsavchenko, after some experimentation, I found out that handling 
reinterpret_cast will be a real pain. Consider the following:

  struct Base {
int field;
  };
  
  struct Derived : public Base {};
  
  struct DoubleDerived : public Derived {};
  
  struct Some {};
  
  void f() {
int DoubleDerived::* ddf = &Base::field;
int Base::* bf = reinterpret_cast(reinterpret_cast(reinterpret_cast(ddf)));
int Some::* sf = reinterpret_cast(ddf);
Base base;
base.*bf;
  }

The definition of `bf` can be handled I guess by manually discovering when to 
insert a sub-class or when to remove. It will require a bit of code but I guess 
is doable.
As for the next one, also it has to be manually worked out whether it makes 
sense to process this statement further and add a node to the Exploded Graph. 
For the example I gave I don't think it makes a lot of sense. Multiple 
inheritance will make the task a lot worse as far as I can tell.
Should I try to achieve this in another commit? What are your thoughts on this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D96056: [clang][cli] Generate and round-trip CodeGen options

2021-02-04 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This patch implements generation of remaining codegen options and tests it by 
performing parse-generate-parse round trip.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96056

Files:
  clang/include/clang/Basic/XRayInstr.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/XRayInstr.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/OptParser.td

Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -175,7 +175,7 @@
 class MarshallingInfoStringInt
   : MarshallingInfo {
   code Normalizer = "normalizeStringIntegral<"#type#">";
-  code Denormalizer = "denormalizeString";
+  code Denormalizer = "denormalizeString<"#type#">";
 }
 
 class MarshallingInfoStringVector
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -54,6 +54,7 @@
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -620,14 +621,17 @@
   // Run the first parse on the original arguments with dummy options and
   // diagnostics.
   SwapOpts(Res);
-  if (!Parse(Res, OriginalArgs, DummyDiags)) {
+  if (!Parse(Res, OriginalArgs, DummyDiags) ||
+  DummyDiags.getNumWarnings() != 0) {
 // If the first parse did not succeed, it must be user mistake (invalid
 // command line arguments). We won't be able to generate arguments that
 // would reproduce the same result. Let's fail again with the original
 // options and diagnostics, so all side-effects of parsing are visible.
+unsigned NumWarningsBefore = Diags.getNumWarnings();
 SwapOpts(Res);
-if (!Parse(Res, OriginalArgs, Diags))
-  return false;
+auto Success = Parse(Res, OriginalArgs, Diags);
+if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
+  return Success;
 
 // Parse with original options and diagnostics succeeded even though it
 // shouldn't have. Something is off.
@@ -744,16 +748,11 @@
 
 static void getAllNoBuiltinFuncValues(ArgList &Args,
   std::vector &Funcs) {
-  SmallVector Values;
-  for (const auto &Arg : Args) {
-const Option &O = Arg->getOption();
-if (O.matches(options::OPT_fno_builtin_)) {
-  const char *FuncName = Arg->getValue();
-  if (Builtin::Context::isBuiltinFunc(FuncName))
-Values.push_back(FuncName);
-}
-  }
-  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
+  std::vector Values = Args.getAllArgValues(OPT_fno_builtin_);
+  auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) {
+return Builtin::Context::isBuiltinFunc(FuncName);
+  });
+  Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
 }
 
 static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
@@ -1234,6 +1233,15 @@
   }
 }
 
+static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
+  llvm::SmallVector BundleParts;
+  serializeXRayInstrValue(S, BundleParts);
+  std::string Buffer;
+  llvm::raw_string_ostream OS(Buffer);
+  llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
+  return OS.str();
+}
+
 // Set the profile kind using fprofile-instrument-use-path.
 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
   const Twine &ProfileName) {
@@ -1255,12 +1263,258 @@
 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
 }
 
-bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
-  InputKind IK,
-  DiagnosticsEngine &Diags,
-  const llvm::Triple &T,
-  const std::string &OutputFile,
-  const LangOptions &LangOptsRef) {
+void CompilerInvocation::GenerateCodeGenArgs(
+const CodeGenOptions &Opts, SmallVectorImpl &Args,
+StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
+const LangOptions *LangOpts) {
+  const CodeGenOptions &CodeGenOpts = Opts;
+
+  if (Opts.OptimizationLevel == 0)
+GenerateArg(Args, OPT_O0, SA);
+  else
+GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
+
+#define CODEGEN_OPTION_WITH_MARSHALLING(   \
+PREF

[PATCH] D96058: [CodeComplete] Guess type for designated initializers

2021-02-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
sammccall requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This enables:

- completion in { .x.^ }
- completion in { .x = { .^ } }
- type-based ranking of candidates for { .x = ^ }


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96058

Files:
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseInit.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/desig-init.cpp

Index: clang/test/CodeCompletion/desig-init.cpp
===
--- clang/test/CodeCompletion/desig-init.cpp
+++ clang/test/CodeCompletion/desig-init.cpp
@@ -16,8 +16,8 @@
   // CHECK-CC1-NOT: foo
   // CHECK-CC1-NOT: t
 
-  // FIXME: Handle nested designators
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:11:20 %s -o - | count 0
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:11:20 %s -o - | FileCheck -check-prefix=CHECK-NESTED %s
+  // CHECK-NESTED: COMPLETION: t : [#int#]t
 
   Base B = {.t = 2};
   auto z = [](Base B) {};
@@ -29,6 +29,14 @@
   // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:25:11 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC2 %s
   // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:26:13 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC2 %s
   // CHECK-CC2: COMPLETION: t : [#int#]t
+
+  Foo G1{.b = {.t = 0}};
+  Foo G2{.b{.t = 0}};
+  Foo G3{b: {.t = 0}};
+  // RUN: %clang_cc1 -code-completion-at=%s:33:17 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // RUN: %clang_cc1 -code-completion-at=%s:34:14 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // RUN: %clang_cc1 -code-completion-at=%s:35:15 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // CHECK-NESTED-2: COMPLETION: t : [#int#]t
 }
 
 // Handle templates
@@ -41,10 +49,10 @@
 };
 void bar() {
   Test T{.x = 2};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:43:17 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:51:17 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
   // CHECK-CC3: COMPLETION: x : [#T#]x
   Test X{.x = 2};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:46:16 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC4 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:54:16 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC4 %s
   // CHECK-CC4: COMPLETION: x : [#int#]x
   // CHECK-CC4-NEXT: COMPLETION: y : [#char#]y
 }
@@ -52,5 +60,5 @@
 template 
 void aux() {
   Test X{.x = T(2)};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:54:14 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:62:14 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
 }
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -405,6 +405,16 @@
   ExpectedLoc = Tok;
 }
 
+static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
+
+void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
+  QualType BaseType,
+  const Designation &D) {
+  ComputeType = nullptr;
+  Type = getDesignatedType(BaseType, D);
+  ExpectedLoc = Tok;
+}
+
 void PreferredTypeBuilder::enterFunctionArgument(
 SourceLocation Tok, llvm::function_ref ComputeType) {
   this->ComputeType = ComputeType;
@@ -4784,8 +4794,16 @@
 // in case of specializations. Since we might not have a decl for the
 // instantiation/specialization yet, e.g. dependent code.
 static RecordDecl *getAsRecordDecl(const QualType BaseType) {
-  if (auto *RD = BaseType->getAsRecordDecl())
+  if (auto *RD = BaseType->getAsRecordDecl()) {
+if (const auto *CTSD =
+llvm::dyn_cast(RD)) {
+  // Template might not be instantiated yet, fall back to primary template
+  // in such cases.
+  if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+}
 return RD;
+  }
 
   if (const auto *TST = BaseType->getAs()) {
 if (const auto *TD = dyn_cast_or_null(
@@ -5754,25 +5772,37 @@
   return QualType();
 }
 
-void Sema::CodeCompleteDesignator(const QualTyp

[PATCH] D95561: [Clang] Introduce Swift async calling convention.

2021-02-04 Thread Varun Gandhi via Phabricator via cfe-commits
varungandhi-apple updated this revision to Diff 321501.
varungandhi-apple added a comment.

1. Update whitespace and add documentation for swiftasynccall.
2. Update commit message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95561

Files:
  clang/include/clang-c/Index.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/Specifiers.h
  clang/include/clang/CodeGen/SwiftCallingConv.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Basic/Targets/PPC.h
  clang/lib/Basic/Targets/SystemZ.h
  clang/lib/Basic/Targets/WebAssembly.h
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/arm-swiftcall.c
  clang/test/CodeGen/debug-info-cc.c
  clang/test/Sema/attr-c2x.c
  clang/test/Sema/attr-swiftcall.c
  clang/test/Sema/no_callconv.cpp
  clang/test/SemaCXX/attr-swiftcall.cpp
  clang/tools/libclang/CXType.cpp
  llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h
  llvm/lib/Demangle/MicrosoftDemangle.cpp
  llvm/lib/Demangle/MicrosoftDemangleNodes.cpp
  llvm/test/Demangle/ms-mangle.test

Index: llvm/test/Demangle/ms-mangle.test
===
--- llvm/test/Demangle/ms-mangle.test
+++ llvm/test/Demangle/ms-mangle.test
@@ -341,6 +341,9 @@
 ?swift_func@@YSXXZ
 ; CHECK: void __attribute__((__swiftcall__)) swift_func(void)
 
+?swift_async_func@@YTXXZ
+; CHECK: void __attribute__((__swiftasynccall__)) swift_async_func(void)
+
 ??$fn_tmpl@$1?extern_c_func@@YAXXZ@@YAXXZ
 ; CHECK: void __cdecl fn_tmpl<&void __cdecl extern_c_func(void)>(void)
 
Index: llvm/lib/Demangle/MicrosoftDemangleNodes.cpp
===
--- llvm/lib/Demangle/MicrosoftDemangleNodes.cpp
+++ llvm/lib/Demangle/MicrosoftDemangleNodes.cpp
@@ -110,6 +110,9 @@
   case CallingConv::Swift:
 OS << "__attribute__((__swiftcall__)) ";
 break;
+  case CallingConv::SwiftAsync:
+OS << "__attribute__((__swiftasynccall__)) ";
+break;
   default:
 break;
   }
Index: llvm/lib/Demangle/MicrosoftDemangle.cpp
===
--- llvm/lib/Demangle/MicrosoftDemangle.cpp
+++ llvm/lib/Demangle/MicrosoftDemangle.cpp
@@ -1713,6 +1713,8 @@
 return CallingConv::Vectorcall;
   case 'S':
 return CallingConv::Swift;
+  case 'T':
+return CallingConv::SwiftAsync;
   }
 
   return CallingConv::None;
Index: llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h
===
--- llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h
+++ llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h
@@ -67,7 +67,8 @@
   Eabi,
   Vectorcall,
   Regcall,
-  Swift, // Clang-only
+  Swift,  // Clang-only
+  SwiftAsync, // Clang-only
 };
 
 enum class ReferenceKind : uint8_t { None, LValueRef, RValueRef };
Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -664,6 +664,7 @@
   TCALLINGCONV(AAPCS_VFP);
   TCALLINGCONV(IntelOclBicc);
   TCALLINGCONV(Swift);
+  TCALLINGCONV(SwiftAsync);
   TCALLINGCONV(PreserveMost);
   TCALLINGCONV(PreserveAll);
 case CC_SpirFunction: return CXCallingConv_Unexposed;
Index: clang/test/SemaCXX/attr-swiftcall.cpp
===
--- clang/test/SemaCXX/attr-swiftcall.cpp
+++ clang/test/SemaCXX/attr-swiftcall.cpp
@@ -1,14 +1,20 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsyntax-only -verify %s
 
 #define SWIFTCALL __attribute__((swiftcall))
+#define SWIFTASYNCCALL __attribute__((swiftasynccall))
 #define INDIRECT_RESULT __attribute__((swift_indirect_result))
 #define ERROR_RESULT __attribute__((swift_error_result))
 #define CONTEXT __attribute__((swift_context))
+#define ASYNC_CONTEXT __attribute__((swift_async_context))
 
 int notAFunction SWIFTCALL; // expected-warning {{'swiftcall' only applies to function types; type here is 'int'}}
+int notAnAsyncFunction SWIFTASYNCCALL; // expected-warning {{'swiftasynccall' only applies to function types; type here is 'int'}}
 void variadic(int x, ...) SWIFTCALL; // expected-error {{variadic function cannot use swiftcall calling convention}}
+void variadic_async(int x, ...) SWIFTASYNCCALL; // expected-error {{variadic function cannot use swiftasynccall calling convention}}
 void multiple_ccs(int x) SWIFTCALL __attribute__((vectorcall)); // expected-error {{vectorcall and swiftcall attributes are not compatible}}
+vo

[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

Uh, I think we're a couple standard releases past the point at which we should 
have reconsidered this schema.  I guess the problem is that we can't say 
`-Wpre-c++23-compat` without jumping the gun.  Is there a problem with 
`-Wc++20-compat` and then having the earlier warning groups imply the later 
ones?  That seems to be what we do with `-Wc++98-compat`; did we abandon that 
approach intentionally?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

rjmccall wrote:
> Uh, I think we're a couple standard releases past the point at which we 
> should have reconsidered this schema.  I guess the problem is that we can't 
> say `-Wpre-c++23-compat` without jumping the gun.  Is there a problem with 
> `-Wc++20-compat` and then having the earlier warning groups imply the later 
> ones?  That seems to be what we do with `-Wc++98-compat`; did we abandon that 
> approach intentionally?
@rsmith may have more background here. I was following the pattern already in 
the file, but I tend to agree that this pattern is not leading us somewhere 
good. FWIW, I ran into a similar situation with this on the C side of things in 
D95396, so we should probably be consistent there too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

aaron.ballman wrote:
> rjmccall wrote:
> > Uh, I think we're a couple standard releases past the point at which we 
> > should have reconsidered this schema.  I guess the problem is that we can't 
> > say `-Wpre-c++23-compat` without jumping the gun.  Is there a problem with 
> > `-Wc++20-compat` and then having the earlier warning groups imply the later 
> > ones?  That seems to be what we do with `-Wc++98-compat`; did we abandon 
> > that approach intentionally?
> @rsmith may have more background here. I was following the pattern already in 
> the file, but I tend to agree that this pattern is not leading us somewhere 
> good. FWIW, I ran into a similar situation with this on the C side of things 
> in D95396, so we should probably be consistent there too.
My understanding is that the //command-line user// is expected to pass
- `clang++ -std=c++20 -Wc++11-compat` to indicate "I want //actually// to 
compile in C++20 mode, but give me warnings about anything that would prevent 
compiling in C++11 mode"
- `clang++ -std=c++17 -Wc++14-compat` to indicate "I want //actually// to 
compile in C++17 mode, but give me warnings about anything that would prevent 
compiling in C++14 mode"
- `clang++ -std=c++14 -Wc++20-compat` to indicate "I want //actually// to 
compile in C++14 mode, but give me warnings about anything that would prevent 
compiling in C++20 mode" — EXCEPT that I think this is not supported. My 
impression is that forward-compatibility warnings are generally just rolled 
into `-Wall` and not handled separately beyond that?

I don't think any human user is expected to pass 
`-Wc++98-c++11-c++14-c++17-c++20-compat` by hand; it's just an internal name 
for a particular subset of `-Wc++98-compat`.

IOW, we could choose a new naming scheme for it, but that would be a purely 
internal change that won't affect how command-line users interact with Clang at 
all (for better and for worse).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D94367: [Clang][Driver] Add -ffinite-loops flags

2021-02-04 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.
Herald added a reviewer: jansvoboda11.

@atmnpatel reverse ping. Just curious if you think you'll have time to follow 
up on this patch soonish?

Otherwise I'm probably going to add at least the `-fno-finite-loops` option, 
because we have users which code breaks due to the `mustprogress` loop deletion 
changes (because of problems in the source code, but they need a way to disable 
until they can fix all sources)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94367

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


[PATCH] D94367: [Clang][Driver] Add -ffinite-loops flags

2021-02-04 Thread Atmn Patel via Phabricator via cfe-commits
atmnpatel added a comment.

@fhahn  Sorry for the hold up, I don't think I'll get to this relatively soon, 
I'll abandon this one and D94366  to sweep the 
board.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94367

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


[PATCH] D94367: [Clang][Driver] Add -ffinite-loops flags

2021-02-04 Thread Atmn Patel via Phabricator via cfe-commits
atmnpatel added a comment.

Wait actually, we're gonna need D94366  
anyways, I'll get address @xbolva00's comments by eod.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94367

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


[PATCH] D94367: [Clang][Driver] Add -ffinite-loops flags

2021-02-04 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

In D94367#2542809 , @atmnpatel wrote:

> Wait actually, we're gonna need D94366  
> anyways, I'll get address @xbolva00's comments by eod.

FWIW I think we should sort this one (D94367 ) 
first, because it may simplify D94366 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94367

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


[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-04 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn added a comment.

This looks like a definite step forward. Thank you!

Can you do an AArch64 test case showing long double? Right now there's no 
128-bit test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D96000: Don't emit coverage mapping for excluded functions

2021-02-04 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added inline comments.



Comment at: clang/test/CodeGen/profile-filter.c:27
+// EXCLUDE: @__covrec_{{[0-9A-F]+}}u = linkonce_odr hidden constant <{ i64, 
i32, i64, i64, [{{.*}} x i8] }> <{ {{.*}} }>, section "__llvm_covfun"
+// EXCLUDE-NOT: @__covrec_{{[0-9A-F]+}}u = linkonce_odr hidden constant <{ 
i64, i32, i64, i64, [{{.*}} x i8] }> <{ {{.*}} }>, section "__llvm_covfun"
+

This is somewhat difficult to interpret. Would you be open to specifying 
-dump-coverage-mapping (e.g. https://godbolt.org/z/5PvvEv), in a separate cc1 
invocation if needed, and checking that instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96000

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


[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-04 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added a comment.

Should we add tests for mlong-double-64, -80, -128?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D96058: [CodeComplete] Guess type for designated initializers

2021-02-04 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

Thanks! LG with a small concern around possible effects on member completions 
for uninstantiated templates.




Comment at: clang/lib/Parse/ParseInit.cpp:163
+DesignatorCompletionInfo DesignatorCompletion) {
+  if (!getPreprocessor().isCodeCompletionEnabled())
+DesignatorCompletion.PreferredBaseType = QualType(); // skip field lookup

it might be nice to make the whole preferredtypebuilder a no-op on construction 
when codecompletion is disabled. but that can be an adventure for another day.



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:4803
+  if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+}

i think this means we are going to offer completion for uninstantiated 
specializations using the primary template now (through 
`Sema::CodeCompleteMemberReferenceExpr`), which i am not sure is possible, but 
should be an improvement in either case.

but not having any tests (especially failing) makes me a little anxious.



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:5790
+  if (const FieldDecl *FD = llvm::dyn_cast(Member))
+NextType = FD->getType();
+  }

why don't we break after the first one ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96058

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


  1   2   >