[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-01-24 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Ping!!!


https://reviews.llvm.org/D41537



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


[PATCH] D41454: [clangd] Add ClangdUnit diagnostics tests using annotated code.

2018-01-24 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.
Herald added subscribers: hintonda, ioeric, jkorous-apple.

LGTM.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41454



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


[PATCH] D42428: [CodeComplete] only respect LoadExternal hint at namespace/tu scope

2018-01-24 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rC Clang

https://reviews.llvm.org/D42428



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


r323310 - Refactor RecursiveASTVisitor test for post-order traversal

2018-01-24 Thread Raphael Isemann via cfe-commits
Author: teemperor
Date: Wed Jan 24 01:40:16 2018
New Revision: 323310

URL: http://llvm.org/viewvc/llvm-project?rev=323310&view=rev
Log:
Refactor RecursiveASTVisitor test for post-order traversal

Summary:
The new test is now in the right directory with the other ASTVisitor tests and 
uses
now the provided TestVisitor framework.

Subscribers: hintonda, v.g.vassilev, klimek, cfe-commits, mgorny

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

Added:
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp
Removed:
cfe/trunk/unittests/AST/PostOrderASTVisitor.cpp
Modified:
cfe/trunk/unittests/AST/CMakeLists.txt
cfe/trunk/unittests/Tooling/CMakeLists.txt

Modified: cfe/trunk/unittests/AST/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/CMakeLists.txt?rev=323310&r1=323309&r2=323310&view=diff
==
--- cfe/trunk/unittests/AST/CMakeLists.txt (original)
+++ cfe/trunk/unittests/AST/CMakeLists.txt Wed Jan 24 01:40:16 2018
@@ -15,7 +15,6 @@ add_clang_unittest(ASTTests
   EvaluateAsRValueTest.cpp
   ExternalASTSourceTest.cpp
   NamedDeclPrinterTest.cpp
-  PostOrderASTVisitor.cpp
   SourceLocationTest.cpp
   StmtPrinterTest.cpp
   )

Removed: cfe/trunk/unittests/AST/PostOrderASTVisitor.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/PostOrderASTVisitor.cpp?rev=323309&view=auto
==
--- cfe/trunk/unittests/AST/PostOrderASTVisitor.cpp (original)
+++ cfe/trunk/unittests/AST/PostOrderASTVisitor.cpp (removed)
@@ -1,128 +0,0 @@
-//===- unittests/AST/PostOrderASTVisitor.cpp - Declaration printer tests 
--===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===--===//
-//
-// This file contains tests for the post-order traversing functionality
-// of RecursiveASTVisitor.
-//
-//===--===//
-
-#include "clang/AST/RecursiveASTVisitor.h"
-#include "clang/Tooling/Tooling.h"
-#include "gtest/gtest.h"
-
-using namespace clang;
-
-namespace {
-
-  class RecordingVisitor
-: public RecursiveASTVisitor {
-
-bool VisitPostOrder;
-  public:
-explicit RecordingVisitor(bool VisitPostOrder)
-  : VisitPostOrder(VisitPostOrder) {
-}
-
-// List of visited nodes during traversal.
-std::vector VisitedNodes;
-
-bool shouldTraversePostOrder() const { return VisitPostOrder; }
-
-bool VisitUnaryOperator(UnaryOperator *Op) {
-  VisitedNodes.push_back(Op->getOpcodeStr(Op->getOpcode()));
-  return true;
-}
-
-bool VisitBinaryOperator(BinaryOperator *Op) {
-  VisitedNodes.push_back(Op->getOpcodeStr());
-  return true;
-}
-
-bool VisitIntegerLiteral(IntegerLiteral *Lit) {
-  VisitedNodes.push_back(Lit->getValue().toString(10, false));
-  return true;
-}
-
-bool VisitVarDecl(VarDecl* D) {
-  VisitedNodes.push_back(D->getNameAsString());
-  return true;
-}
-
-bool VisitCXXMethodDecl(CXXMethodDecl *D) {
-  VisitedNodes.push_back(D->getQualifiedNameAsString());
-  return true;
-}
-
-bool VisitReturnStmt(ReturnStmt *S) {
-  VisitedNodes.push_back("return");
-  return true;
-}
-
-bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
-  VisitedNodes.push_back(Declaration->getQualifiedNameAsString());
-  return true;
-}
-
-bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
-  VisitedNodes.push_back(T->getDecl()->getQualifiedNameAsString());
-  return true;
-}
-  };
-
-}
-
-TEST(RecursiveASTVisitor, PostOrderTraversal) {
-  auto ASTUnit = tooling::buildASTFromCode(
-"class A {"
-"  class B {"
-"int foo() { while(4) { int i = 9; int j = -5; } return (1 + 3) + 2; }"
-"  };"
-"};"
-  );
-  auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();
-  // We traverse the translation unit and store all
-  // visited nodes.
-  RecordingVisitor Visitor(true);
-  Visitor.TraverseTranslationUnitDecl(TU);
-
-  std::vector expected = {"4", "9",  "i", "5","-",
-   "j", "1",  "3", "+","2",
-   "+", "return", "A::B::foo", "A::B", 
"A"};
-  // Compare the list of actually visited nodes
-  // with the expected list of visited nodes.
-  ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
-  for (std::size_t I = 0; I < expected.size(); I++) {
-ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
-  }
-}
-
-TEST(RecursiveASTVisitor, NoPostOrderTraversal) {
-  auto ASTUnit = tooling::buildASTFromCode(
-"class A {"
-"  class B {"
-"int foo() { return 1 + 2; }"
-"

[PATCH] D37557: Refactor RecursiveASTVisitor test for post-order traversal

2018-01-24 Thread Raphael Isemann via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323310: Refactor RecursiveASTVisitor test for post-order 
traversal (authored by teemperor, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D37557?vs=131204&id=131205#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37557

Files:
  cfe/trunk/unittests/AST/CMakeLists.txt
  cfe/trunk/unittests/AST/PostOrderASTVisitor.cpp
  cfe/trunk/unittests/Tooling/CMakeLists.txt
  cfe/trunk/unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp

Index: cfe/trunk/unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp
===
--- cfe/trunk/unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp
+++ cfe/trunk/unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp
@@ -0,0 +1,116 @@
+//===- unittests/Tooling/RecursiveASTVisitorPostOrderASTVisitor.cpp ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This file contains tests for the post-order traversing functionality
+// of RecursiveASTVisitor.
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+class RecordingVisitor : public TestVisitor {
+
+  bool VisitPostOrder;
+
+public:
+  explicit RecordingVisitor(bool VisitPostOrder)
+  : VisitPostOrder(VisitPostOrder) {}
+
+  // List of visited nodes during traversal.
+  std::vector VisitedNodes;
+
+  bool shouldTraversePostOrder() const { return VisitPostOrder; }
+
+  bool VisitUnaryOperator(UnaryOperator *Op) {
+VisitedNodes.push_back(Op->getOpcodeStr(Op->getOpcode()));
+return true;
+  }
+
+  bool VisitBinaryOperator(BinaryOperator *Op) {
+VisitedNodes.push_back(Op->getOpcodeStr());
+return true;
+  }
+
+  bool VisitIntegerLiteral(IntegerLiteral *Lit) {
+VisitedNodes.push_back(Lit->getValue().toString(10, false));
+return true;
+  }
+
+  bool VisitVarDecl(VarDecl *D) {
+VisitedNodes.push_back(D->getNameAsString());
+return true;
+  }
+
+  bool VisitCXXMethodDecl(CXXMethodDecl *D) {
+VisitedNodes.push_back(D->getQualifiedNameAsString());
+return true;
+  }
+
+  bool VisitReturnStmt(ReturnStmt *S) {
+VisitedNodes.push_back("return");
+return true;
+  }
+
+  bool VisitCXXRecordDecl(CXXRecordDecl *D) {
+if (!D->isImplicit())
+  VisitedNodes.push_back(D->getQualifiedNameAsString());
+return true;
+  }
+
+  bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
+VisitedNodes.push_back(T->getDecl()->getQualifiedNameAsString());
+return true;
+  }
+};
+} // namespace
+
+TEST(RecursiveASTVisitor, PostOrderTraversal) {
+  // We traverse the translation unit and store all visited nodes.
+  RecordingVisitor Visitor(true);
+  Visitor.runOver("class A {\n"
+  "  class B {\n"
+  "int foo() {\n"
+  "  while(4) { int i = 9; int j = -5; }\n"
+  "  return (1 + 3) + 2; }\n"
+  "  };\n"
+  "};\n");
+
+  std::vector expected = {"4", "9",  "i", "5","-",
+   "j", "1",  "3", "+","2",
+   "+", "return", "A::B::foo", "A::B", "A"};
+  // Compare the list of actually visited nodes with the expected list of
+  // visited nodes.
+  ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
+  for (std::size_t I = 0; I < expected.size(); I++) {
+ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
+  }
+}
+
+TEST(RecursiveASTVisitor, NoPostOrderTraversal) {
+  // We traverse the translation unit and store all visited nodes.
+  RecordingVisitor Visitor(false);
+  Visitor.runOver("class A {\n"
+  "  class B {\n"
+  "int foo() { return 1 + 2; }\n"
+  "  };\n"
+  "};\n");
+
+  std::vector expected = {"A", "A::B", "A::B::foo", "return",
+   "+", "1","2"};
+  // Compare the list of actually visited nodes with the expected list of
+  // visited nodes.
+  ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
+  for (std::size_t I = 0; I < expected.size(); I++) {
+ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
+  }
+}
Index: cfe/trunk/unittests/Tooling/CMakeLists.txt
===
--- cfe/trunk/unittests/Tooling/CMakeLists.txt
+++ cfe/trunk/unittests/Tooling/CMakeLists.txt
@@ -25,6 +25,7 @@
   RecursiveASTVisitorTestCallVisitor.cpp
   RecursiveASTVisitorTestDeclV

[PATCH] D37557: Refactor RecursiveASTVisitor test for post-order traversal

2018-01-24 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor updated this revision to Diff 131204.
teemperor added a comment.
Herald added a subscriber: hintonda.

- Rebased and clang formatted.


https://reviews.llvm.org/D37557

Files:
  unittests/AST/CMakeLists.txt
  unittests/AST/PostOrderASTVisitor.cpp
  unittests/Tooling/CMakeLists.txt
  unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp

Index: unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp
===
--- /dev/null
+++ unittests/Tooling/RecursiveASTVisitorTestPostOrderVisitor.cpp
@@ -0,0 +1,116 @@
+//===- unittests/Tooling/RecursiveASTVisitorPostOrderASTVisitor.cpp ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This file contains tests for the post-order traversing functionality
+// of RecursiveASTVisitor.
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+class RecordingVisitor : public TestVisitor {
+
+  bool VisitPostOrder;
+
+public:
+  explicit RecordingVisitor(bool VisitPostOrder)
+  : VisitPostOrder(VisitPostOrder) {}
+
+  // List of visited nodes during traversal.
+  std::vector VisitedNodes;
+
+  bool shouldTraversePostOrder() const { return VisitPostOrder; }
+
+  bool VisitUnaryOperator(UnaryOperator *Op) {
+VisitedNodes.push_back(Op->getOpcodeStr(Op->getOpcode()));
+return true;
+  }
+
+  bool VisitBinaryOperator(BinaryOperator *Op) {
+VisitedNodes.push_back(Op->getOpcodeStr());
+return true;
+  }
+
+  bool VisitIntegerLiteral(IntegerLiteral *Lit) {
+VisitedNodes.push_back(Lit->getValue().toString(10, false));
+return true;
+  }
+
+  bool VisitVarDecl(VarDecl *D) {
+VisitedNodes.push_back(D->getNameAsString());
+return true;
+  }
+
+  bool VisitCXXMethodDecl(CXXMethodDecl *D) {
+VisitedNodes.push_back(D->getQualifiedNameAsString());
+return true;
+  }
+
+  bool VisitReturnStmt(ReturnStmt *S) {
+VisitedNodes.push_back("return");
+return true;
+  }
+
+  bool VisitCXXRecordDecl(CXXRecordDecl *D) {
+if (!D->isImplicit())
+  VisitedNodes.push_back(D->getQualifiedNameAsString());
+return true;
+  }
+
+  bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
+VisitedNodes.push_back(T->getDecl()->getQualifiedNameAsString());
+return true;
+  }
+};
+} // namespace
+
+TEST(RecursiveASTVisitor, PostOrderTraversal) {
+  // We traverse the translation unit and store all visited nodes.
+  RecordingVisitor Visitor(true);
+  Visitor.runOver("class A {\n"
+  "  class B {\n"
+  "int foo() {\n"
+  "  while(4) { int i = 9; int j = -5; }\n"
+  "  return (1 + 3) + 2; }\n"
+  "  };\n"
+  "};\n");
+
+  std::vector expected = {"4", "9",  "i", "5","-",
+   "j", "1",  "3", "+","2",
+   "+", "return", "A::B::foo", "A::B", "A"};
+  // Compare the list of actually visited nodes with the expected list of
+  // visited nodes.
+  ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
+  for (std::size_t I = 0; I < expected.size(); I++) {
+ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
+  }
+}
+
+TEST(RecursiveASTVisitor, NoPostOrderTraversal) {
+  // We traverse the translation unit and store all visited nodes.
+  RecordingVisitor Visitor(false);
+  Visitor.runOver("class A {\n"
+  "  class B {\n"
+  "int foo() { return 1 + 2; }\n"
+  "  };\n"
+  "};\n");
+
+  std::vector expected = {"A", "A::B", "A::B::foo", "return",
+   "+", "1","2"};
+  // Compare the list of actually visited nodes with the expected list of
+  // visited nodes.
+  ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
+  for (std::size_t I = 0; I < expected.size(); I++) {
+ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
+  }
+}
Index: unittests/Tooling/CMakeLists.txt
===
--- unittests/Tooling/CMakeLists.txt
+++ unittests/Tooling/CMakeLists.txt
@@ -25,6 +25,7 @@
   RecursiveASTVisitorTestCallVisitor.cpp
   RecursiveASTVisitorTestDeclVisitor.cpp
   RecursiveASTVisitorTestExprVisitor.cpp
+  RecursiveASTVisitorTestPostOrderVisitor.cpp
   RecursiveASTVisitorTestTypeLocVisitor.cpp
   RefactoringActionRulesTest.cpp
   RefactoringCallbacksTest.cpp
Index: unittests/AST/PostOrderASTVisitor.cpp
===
--- unittests/AST/PostOrderASTVisitor.cpp
+++ /dev/null
@@ -1,128 +0,0 @@
-//===- unittests/AST/PostOrderASTVisitor

[PATCH] D39571: [clangd] DidChangeConfiguration Notification

2018-01-24 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Hi @simark , thanks for picking up this change.




Comment at: clangd/ClangdLSPServer.cpp:302
 
+// FIXME: This function needs to be properly tested.
+void ClangdLSPServer::onChangeConfiguration(

Are you planning to to address this FIXME before checking the code in?



Comment at: clangd/GlobalCompilationDatabase.h:64
 
+  void setCompileCommandsDir(Path P) {
+std::lock_guard Lock(Mutex);

Maybe move definition to `.cpp` file?




Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D39571



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


[PATCH] D42373: [clang-format] Disable string literal breaking for text protos

2018-01-24 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

So, we found out other cases where this is especially painful:

- breaking long URLs into multiple lines
- updating the text of a paragraph and breaking again with combination of 
no-reflow

We could disable it for now and enable it when we have string literal reflow.


Repository:
  rC Clang

https://reviews.llvm.org/D42373



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


r323316 - Fix typos of occurred and occurrence

2018-01-24 Thread Malcolm Parsons via cfe-commits
Author: malcolm.parsons
Date: Wed Jan 24 02:26:09 2018
New Revision: 323316

URL: http://llvm.org/viewvc/llvm-project?rev=323316&view=rev
Log:
Fix typos of occurred and occurrence

Modified:
cfe/trunk/docs/ClangFormatStyleOptions.rst
cfe/trunk/include/clang/Analysis/CloneDetection.h
cfe/trunk/include/clang/Format/Format.h
cfe/trunk/include/clang/Lex/VariadicMacroSupport.h
cfe/trunk/include/clang/Tooling/Core/Diagnostic.h
cfe/trunk/lib/Analysis/CloneDetection.cpp
cfe/trunk/test/Driver/hexagon-hvx.c
cfe/trunk/tools/clang-import-test/clang-import-test.cpp
cfe/trunk/tools/scan-build-py/libscanbuild/analyze.py

Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=323316&r1=323315&r2=323316&view=diff
==
--- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
+++ cfe/trunk/docs/ClangFormatStyleOptions.rst Wed Jan 24 02:26:09 2018
@@ -1590,7 +1590,7 @@ the configuration (without a prefix: ``A
   precedence over a matching enclosing function name for determining the
   language of the raw string contents.
 
-  If a canonical delimiter is specified, occurences of other delimiters for
+  If a canonical delimiter is specified, occurrences of other delimiters for
   the same language will be updated to the canonical if possible.
 
   There should be at most one specification per language and each delimiter

Modified: cfe/trunk/include/clang/Analysis/CloneDetection.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/CloneDetection.h?rev=323316&r1=323315&r2=323316&view=diff
==
--- cfe/trunk/include/clang/Analysis/CloneDetection.h (original)
+++ cfe/trunk/include/clang/Analysis/CloneDetection.h Wed Jan 24 02:26:09 2018
@@ -351,7 +351,7 @@ struct FilenamePatternConstraint {
 /// Analyzes the pattern of the referenced variables in a statement.
 class VariablePattern {
 
-  /// Describes an occurence of a variable reference in a statement.
+  /// Describes an occurrence of a variable reference in a statement.
   struct VariableOccurence {
 /// The index of the associated VarDecl in the Variables vector.
 size_t KindID;
@@ -362,7 +362,7 @@ class VariablePattern {
 : KindID(KindID), Mention(Mention) {}
   };
 
-  /// All occurences of referenced variables in the order of appearance.
+  /// All occurrences of referenced variables in the order of appearance.
   std::vector Occurences;
   /// List of referenced variables in the order of appearance.
   /// Every item in this list is unique.

Modified: cfe/trunk/include/clang/Format/Format.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=323316&r1=323315&r2=323316&view=diff
==
--- cfe/trunk/include/clang/Format/Format.h (original)
+++ cfe/trunk/include/clang/Format/Format.h Wed Jan 24 02:26:09 2018
@@ -1395,7 +1395,7 @@ struct FormatStyle {
   /// precedence over a matching enclosing function name for determining the
   /// language of the raw string contents.
   ///
-  /// If a canonical delimiter is specified, occurences of other delimiters for
+  /// If a canonical delimiter is specified, occurrences of other delimiters 
for
   /// the same language will be updated to the canonical if possible.
   ///
   /// There should be at most one specification per language and each delimiter

Modified: cfe/trunk/include/clang/Lex/VariadicMacroSupport.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/VariadicMacroSupport.h?rev=323316&r1=323315&r2=323316&view=diff
==
--- cfe/trunk/include/clang/Lex/VariadicMacroSupport.h (original)
+++ cfe/trunk/include/clang/Lex/VariadicMacroSupport.h Wed Jan 24 02:26:09 2018
@@ -55,7 +55,7 @@ namespace clang {
 
 /// Client code should call this function as soon as the Preprocessor has
 /// either completed lexing the macro's definition tokens, or an error
-/// occured and the context is being exited.  This function is idempotent
+/// occurred and the context is being exited.  This function is idempotent
 /// (might be explicitly called, and then reinvoked via the destructor).
 void exitScope() {
   Ident__VA_ARGS__->setIsPoisoned(true);

Modified: cfe/trunk/include/clang/Tooling/Core/Diagnostic.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Core/Diagnostic.h?rev=323316&r1=323315&r2=323316&view=diff
==
--- cfe/trunk/include/clang/Tooling/Core/Diagnostic.h (original)
+++ cfe/trunk/include/clang/Tooling/Core/Diagnostic.h Wed Jan 24 02:26:09 2018
@@ -33,7 +33,7 @@ struct DiagnosticMessage {
   DiagnosticMe

[PATCH] D42416: [Driver] Add support for mips32 and scudo

2018-01-24 Thread Simon Dardis via Phabricator via cfe-commits
sdardis marked an inline comment as done.
sdardis added a comment.

Thanks, will fix the nit on commit.


Repository:
  rC Clang

https://reviews.llvm.org/D42416



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


[PATCH] D42373: [clang-format] Disable string literal breaking for text protos

2018-01-24 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

Change the comment and possibly also the patch description along the lines of 
what I have suggested. Other than that, looks good to me.




Comment at: lib/Format/Format.cpp:679
+
+// In protos, string literals are commonly multiline and already broken-up.
+// Don't break them up even further, especially since we don't support

Make this comment:

  // Text protos are currently mostly formatted inside C++ raw string literals 
and
  // often the current breaking behavior of string literals is not beneficial 
there.
  // Investigate turning this on once proper string reflow has been implemented.


Repository:
  rC Clang

https://reviews.llvm.org/D42373



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


[PATCH] D42466: [Sema] Allow disabling typo correction when doing code completion.

2018-01-24 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ilya-biryukov.

Repository:
  rC Clang

https://reviews.llvm.org/D42466

Files:
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  lib/Sema/Sema.cpp
  unittests/Sema/CodeCompleteTest.cpp

Index: unittests/Sema/CodeCompleteTest.cpp
===
--- unittests/Sema/CodeCompleteTest.cpp
+++ unittests/Sema/CodeCompleteTest.cpp
@@ -28,8 +28,9 @@
 
 class VisitedContextFinder: public CodeCompleteConsumer {
 public:
-  VisitedContextFinder(VisitedContextResults &Results)
-  : CodeCompleteConsumer(/*CodeCompleteOpts=*/{},
+  VisitedContextFinder(VisitedContextResults &Results,
+   const CodeCompleteOptions &CCOpts)
+  : CodeCompleteConsumer(CCOpts,
  /*CodeCompleteConsumer*/ false),
 VCResults(Results),
 CCTUInfo(std::make_shared()) {}
@@ -63,18 +64,21 @@
 
 class CodeCompleteAction : public SyntaxOnlyAction {
 public:
-  CodeCompleteAction(ParsedSourceLocation P, VisitedContextResults &Results)
-  : CompletePosition(std::move(P)), VCResults(Results) {}
+  CodeCompleteAction(ParsedSourceLocation P, const CodeCompleteOptions &CCOpts,
+ VisitedContextResults &Results)
+  : CompletePosition(std::move(P)), CCOpts(std::move(CCOpts)),
+VCResults(Results) {}
 
   bool BeginInvocation(CompilerInstance &CI) override {
 CI.getFrontendOpts().CodeCompletionAt = CompletePosition;
-CI.setCodeCompletionConsumer(new VisitedContextFinder(VCResults));
+CI.setCodeCompletionConsumer(new VisitedContextFinder(VCResults, CCOpts));
 return true;
   }
 
 private:
   // 1-based code complete position ;
   ParsedSourceLocation CompletePosition;
+  CodeCompleteOptions CCOpts;
   VisitedContextResults& VCResults;
 };
 
@@ -88,7 +92,8 @@
   static_cast(Offset - StartOfLine + 1)};
 }
 
-VisitedContextResults runCodeCompleteOnCode(StringRef Code) {
+VisitedContextResults
+runCodeCompleteOnCode(StringRef Code, const CodeCompleteOptions &CCOpts = {}) {
   VisitedContextResults Results;
   auto TokenOffset = Code.find('^');
   assert(TokenOffset != StringRef::npos &&
@@ -99,7 +104,7 @@
  "expected exactly one completion token ^ inside the code");
 
   auto Action = llvm::make_unique(
-  offsetToPosition(WithoutToken, TokenOffset), Results);
+  offsetToPosition(WithoutToken, TokenOffset), CCOpts, Results);
   clang::tooling::runToolOnCodeWithArgs(Action.release(), Code, {"-std=c++11"},
 TestCCName);
   return Results;
@@ -131,4 +136,14 @@
   EXPECT_TRUE(VisitedNS.empty());
 }
 
+TEST(SemaCodeCompleteTest, DisableTypoCorrection) {
+  CodeCompleteOptions CCOpts;
+  CCOpts.DisableTypoCorrection = 1;
+  auto VisitedNS = runCodeCompleteOnCode(R"cpp(
+ namespace clang {}
+ clangd::^
+  )cpp", CCOpts);
+  EXPECT_TRUE(VisitedNS.empty());
+}
+
 } // namespace
Index: lib/Sema/Sema.cpp
===
--- lib/Sema/Sema.cpp
+++ lib/Sema/Sema.cpp
@@ -25,6 +25,7 @@
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Sema/CodeCompleteConsumer.h"
 #include "clang/Sema/CXXFieldCollector.h"
 #include "clang/Sema/DelayedDiagnostic.h"
 #include "clang/Sema/ExternalSemaSource.h"
@@ -139,7 +140,9 @@
   TUKind(TUKind), NumSFINAEErrors(0), AccessCheckingSFINAE(false),
   InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
   ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
-  DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
+  DisableTypoCorrection(
+  CodeCompleter ? CodeCompleter->disableTypoCorrection() : false),
+  TyposCorrected(0), AnalysisWarnings(*this),
   ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
   CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
   TUScope = nullptr;
Index: include/clang/Sema/CodeCompleteOptions.h
===
--- include/clang/Sema/CodeCompleteOptions.h
+++ include/clang/Sema/CodeCompleteOptions.h
@@ -39,10 +39,13 @@
   /// full results. If false, declarations from the preamble may be omitted.
   unsigned LoadExternal : 1;
 
+  /// Whether to disable typo correction when Sema does code completion.
+  unsigned DisableTypoCorrection : 1;
+
   CodeCompleteOptions()
   : IncludeMacros(0), IncludeCodePatterns(0), IncludeGlobals(1),
 IncludeNamespaceLevelDecls(1), IncludeBriefComments(0),
-LoadExternal(1) {}
+LoadExternal(1), DisableTypoCorrection(0) {}
 };
 
 } // namespace clang
Index: include/clang/Sema/CodeCompleteConsumer.h
===
--- include/clang/Sema/CodeCompleteConsumer.h
+++ include/cla

[PATCH] D42373: [clang-format] Disable string literal breaking for text protos

2018-01-24 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 131216.
krasimir added a comment.

- Update comment


Repository:
  rC Clang

https://reviews.llvm.org/D42373

Files:
  lib/Format/Format.cpp


Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -675,6 +675,12 @@
   if (Language == FormatStyle::LK_TextProto) {
 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
 GoogleStyle.Language = FormatStyle::LK_TextProto;
+
+// Text protos are currently mostly formatted inside C++ raw string 
literals
+// and often the current breaking behavior of string literals is not
+// beneficial there. Investigate turning this on once proper string reflow
+// has been implemented.
+GoogleStyle.BreakStringLiterals = false;
 return GoogleStyle;
   }
 


Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -675,6 +675,12 @@
   if (Language == FormatStyle::LK_TextProto) {
 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
 GoogleStyle.Language = FormatStyle::LK_TextProto;
+
+// Text protos are currently mostly formatted inside C++ raw string literals
+// and often the current breaking behavior of string literals is not
+// beneficial there. Investigate turning this on once proper string reflow
+// has been implemented.
+GoogleStyle.BreakStringLiterals = false;
 return GoogleStyle;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323319 - [clang-format] Disable string literal breaking for text protos

2018-01-24 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Jan 24 03:18:39 2018
New Revision: 323319

URL: http://llvm.org/viewvc/llvm-project?rev=323319&view=rev
Log:
[clang-format] Disable string literal breaking for text protos

Summary:
Commonly string literals in protos are already multiline, so breaking them
further is undesirable.

Reviewers: djasper

Reviewed By: djasper

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/lib/Format/Format.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=323319&r1=323318&r2=323319&view=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Jan 24 03:18:39 2018
@@ -675,6 +675,12 @@ FormatStyle getGoogleStyle(FormatStyle::
   if (Language == FormatStyle::LK_TextProto) {
 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
 GoogleStyle.Language = FormatStyle::LK_TextProto;
+
+// Text protos are currently mostly formatted inside C++ raw string 
literals
+// and often the current breaking behavior of string literals is not
+// beneficial there. Investigate turning this on once proper string reflow
+// has been implemented.
+GoogleStyle.BreakStringLiterals = false;
 return GoogleStyle;
   }
 


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


[PATCH] D42373: [clang-format] Disable string literal breaking for text protos

2018-01-24 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323319: [clang-format] Disable string literal breaking for 
text protos (authored by krasimir, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42373

Files:
  cfe/trunk/lib/Format/Format.cpp


Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -675,6 +675,12 @@
   if (Language == FormatStyle::LK_TextProto) {
 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
 GoogleStyle.Language = FormatStyle::LK_TextProto;
+
+// Text protos are currently mostly formatted inside C++ raw string 
literals
+// and often the current breaking behavior of string literals is not
+// beneficial there. Investigate turning this on once proper string reflow
+// has been implemented.
+GoogleStyle.BreakStringLiterals = false;
 return GoogleStyle;
   }
 


Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -675,6 +675,12 @@
   if (Language == FormatStyle::LK_TextProto) {
 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
 GoogleStyle.Language = FormatStyle::LK_TextProto;
+
+// Text protos are currently mostly formatted inside C++ raw string literals
+// and often the current breaking behavior of string literals is not
+// beneficial there. Investigate turning this on once proper string reflow
+// has been implemented.
+GoogleStyle.BreakStringLiterals = false;
 return GoogleStyle;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42467: FreeBSD needs also execinfo

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen created this revision.
devnexen added reviewers: joerg, vitalybuka.
devnexen created this object with visibility "All Users".
Herald added subscribers: cfe-commits, krytarowski, emaste.

As NetBSD, FreeBSD needs execinfo for backtrace's matters.


Repository:
  rC Clang

https://reviews.llvm.org/D42467

Files:
  lib/Driver/ToolChains/CommonArgs.cpp


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -553,7 +553,8 @@
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -553,7 +553,8 @@
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42467: FreeBSD needs also execinfo and libutil

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 131220.
devnexen retitled this revision from "FreeBSD needs also execinfo" to "FreeBSD 
needs also execinfo and libutil".
devnexen edited the summary of this revision.

Repository:
  rC Clang

https://reviews.llvm.org/D42467

Files:
  lib/Driver/ToolChains/CommonArgs.cpp


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -550,10 +550,12 @@
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
   // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -550,10 +550,12 @@
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
   // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42467: FreeBSD needs also execinfo and libutil

2018-01-24 Thread Kamil Rytarowski via Phabricator via cfe-commits
krytarowski added a comment.

Do you plan to use MSan? If so, `-lkvm` might be useful as well.




Comment at: lib/Driver/ToolChains/CommonArgs.cpp:552
 CmdArgs.push_back("-ldl");
   // Required for forkpty on some OSes
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||

`Required for functions like forkpty on some OSes`


Repository:
  rC Clang

https://reviews.llvm.org/D42467



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


[PATCH] D42242: Make libc++abi work with gcc's ARM unwind library

2018-01-24 Thread Benjamin Buch via Phabricator via cfe-commits
bebuch requested changes to this revision.
bebuch added a comment.
This revision now requires changes to proceed.

I get some new errors:

  /home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp: In 
function ‘void __cxxabiv1::scan_eh_tab(__cxxabiv1::{anonymous}::scan_results&, 
_Unwind_Action, bool, _Unwind_Control_Block*, _Unwind_Context*)’:
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:564:22: 
error: ‘_URC_FATAL_PHASE1_ERROR’ was not declared in this scope
   results.reason = _URC_FATAL_PHASE1_ERROR;
^
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:584:30: 
error: ‘_URC_FATAL_PHASE2_ERROR’ was not declared in this scope
   results.reason = _URC_FATAL_PHASE2_ERROR;
^
  /home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp: In 
function ‘_Unwind_Reason_Code __cxxabiv1::__gxx_personality_v0(_Unwind_State, 
_Unwind_Control_Block*, _Unwind_Context*)’:
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:1074:16: 
error: ‘_URC_FATAL_PHASE1_ERROR’ was not declared in this scope
   return _URC_FATAL_PHASE1_ERROR;
  ^
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:1087:11: 
error: invalid conversion from ‘int’ to ‘_Unwind_State’ [-fpermissive]
   state &= ~_US_FORCE_UNWIND;
 ^
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:1090:12: 
warning: enumeration value ‘_US_ACTION_MASK’ not handled in switch [-Wswitch]
   switch (state) {
  ^
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:1090:12: 
warning: enumeration value ‘_US_FORCE_UNWIND’ not handled in switch [-Wswitch]
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:1090:12: 
warning: enumeration value ‘_US_END_OF_STACK’ not handled in switch [-Wswitch]
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:1167:12: 
error: ‘_URC_FATAL_PHASE1_ERROR’ was not declared in this scope
   return _URC_FATAL_PHASE1_ERROR;
  ^
  
/home/pi/projects/llvm/llvm/projects/libcxxabi/src/cxa_personality.cpp:1168:1: 
error: control reaches end of non-void function [-Werror=return-type]
   }
   ^

`_URC_FATAL_PHASE1_ERROR` and `_URC_FATAL_PHASE2_ERROR` should be `enum` values 
of `_Unwind_Reason_Code`, but this is defined in `unwind-arm-common.h` as:

  typedef enum
{
  _URC_OK = 0,   /* operation completed successfully */
  _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
  _URC_END_OF_STACK = 5,
  _URC_HANDLER_FOUND = 6,
  _URC_INSTALL_CONTEXT = 7,
  _URC_CONTINUE_UNWIND = 8,
  _URC_FAILURE = 9   /* unspecified failure of some kind */
}
  _Unwind_Reason_Code;

In other unwind libraries these values are defined: 
https://github.com/llvm-mirror/libunwind/blob/master/include/unwind.h
In the arm version it isn't: 
https://github.com/gcc-mirror/gcc/blob/gcc-4_9-branch/gcc/ginclude/unwind-arm-common.h


https://reviews.llvm.org/D42242



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


[PATCH] D42291: [libcxx] Correctly handle invalid regex character class names

2018-01-24 Thread Mikhail Maltsev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCXX323322: [libcxx] Correctly handle invalid regex character 
class names (authored by miyuki, committed by ).

Repository:
  rCXX libc++

https://reviews.llvm.org/D42291

Files:
  include/regex
  test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp


Index: include/regex
===
--- include/regex
+++ include/regex
@@ -4013,7 +4013,7 @@
 char_class_type __class_type =
 __traits_.lookup_classname(__first, __temp, __flags_ & icase);
 if (__class_type == 0)
-__throw_regex_error();
+__throw_regex_error();
 __ml->__add_class(__class_type);
 __first = _VSTD::next(__temp, 2);
 return __first;
Index: test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
===
--- test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
+++ test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
@@ -0,0 +1,37 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: libcpp-no-exceptions
+// 
+
+// template > class 
basic_regex;
+
+// template 
+//basic_regex(const basic_string& s);
+
+#include 
+#include 
+#include "test_macros.h"
+
+static bool error_ctype_thrown(const char *pat)
+{
+bool result = false;
+try {
+std::regex re(pat);
+} catch (const std::regex_error &ex) {
+result = (ex.code() == std::regex_constants::error_ctype);
+}
+return result;
+}
+
+int main()
+{
+assert(error_ctype_thrown("[[::]]"));
+assert(error_ctype_thrown("[[:error:]]"));
+}


Index: include/regex
===
--- include/regex
+++ include/regex
@@ -4013,7 +4013,7 @@
 char_class_type __class_type =
 __traits_.lookup_classname(__first, __temp, __flags_ & icase);
 if (__class_type == 0)
-__throw_regex_error();
+__throw_regex_error();
 __ml->__add_class(__class_type);
 __first = _VSTD::next(__temp, 2);
 return __first;
Index: test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
===
--- test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
+++ test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
@@ -0,0 +1,37 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: libcpp-no-exceptions
+// 
+
+// template > class basic_regex;
+
+// template 
+//basic_regex(const basic_string& s);
+
+#include 
+#include 
+#include "test_macros.h"
+
+static bool error_ctype_thrown(const char *pat)
+{
+bool result = false;
+try {
+std::regex re(pat);
+} catch (const std::regex_error &ex) {
+result = (ex.code() == std::regex_constants::error_ctype);
+}
+return result;
+}
+
+int main()
+{
+assert(error_ctype_thrown("[[::]]"));
+assert(error_ctype_thrown("[[:error:]]"));
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42291: [libcxx] Correctly handle invalid regex character class names

2018-01-24 Thread Mikhail Maltsev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323322: [libcxx] Correctly handle invalid regex character 
class names (authored by miyuki, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42291?vs=130584&id=131226#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42291

Files:
  libcxx/trunk/include/regex
  libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp


Index: libcxx/trunk/include/regex
===
--- libcxx/trunk/include/regex
+++ libcxx/trunk/include/regex
@@ -4013,7 +4013,7 @@
 char_class_type __class_type =
 __traits_.lookup_classname(__first, __temp, __flags_ & icase);
 if (__class_type == 0)
-__throw_regex_error();
+__throw_regex_error();
 __ml->__add_class(__class_type);
 __first = _VSTD::next(__temp, 2);
 return __first;
Index: libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
===
--- libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
+++ libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
@@ -0,0 +1,37 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: libcpp-no-exceptions
+// 
+
+// template > class 
basic_regex;
+
+// template 
+//basic_regex(const basic_string& s);
+
+#include 
+#include 
+#include "test_macros.h"
+
+static bool error_ctype_thrown(const char *pat)
+{
+bool result = false;
+try {
+std::regex re(pat);
+} catch (const std::regex_error &ex) {
+result = (ex.code() == std::regex_constants::error_ctype);
+}
+return result;
+}
+
+int main()
+{
+assert(error_ctype_thrown("[[::]]"));
+assert(error_ctype_thrown("[[:error:]]"));
+}


Index: libcxx/trunk/include/regex
===
--- libcxx/trunk/include/regex
+++ libcxx/trunk/include/regex
@@ -4013,7 +4013,7 @@
 char_class_type __class_type =
 __traits_.lookup_classname(__first, __temp, __flags_ & icase);
 if (__class_type == 0)
-__throw_regex_error();
+__throw_regex_error();
 __ml->__add_class(__class_type);
 __first = _VSTD::next(__temp, 2);
 return __first;
Index: libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
===
--- libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
+++ libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
@@ -0,0 +1,37 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: libcpp-no-exceptions
+// 
+
+// template > class basic_regex;
+
+// template 
+//basic_regex(const basic_string& s);
+
+#include 
+#include 
+#include "test_macros.h"
+
+static bool error_ctype_thrown(const char *pat)
+{
+bool result = false;
+try {
+std::regex re(pat);
+} catch (const std::regex_error &ex) {
+result = (ex.code() == std::regex_constants::error_ctype);
+}
+return result;
+}
+
+int main()
+{
+assert(error_ctype_thrown("[[::]]"));
+assert(error_ctype_thrown("[[:error:]]"));
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] r323322 - [libcxx] Correctly handle invalid regex character class names

2018-01-24 Thread Mikhail Maltsev via cfe-commits
Author: miyuki
Date: Wed Jan 24 04:45:18 2018
New Revision: 323322

URL: http://llvm.org/viewvc/llvm-project?rev=323322&view=rev
Log:
[libcxx] Correctly handle invalid regex character class names

Summary:
Currently when a regular expression contains an invalid character
class name std::regex constructors throw an std::regex_error with
std::regex_constants::error_brack code.

This patch changes the code to std::regex_constants::error_ctype and
adds a test.

Reviewers: EricWF, mclow.lists

Reviewed By: mclow.lists

Subscribers: cfe-commits

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

Added:
libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
Modified:
libcxx/trunk/include/regex

Modified: libcxx/trunk/include/regex
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/regex?rev=323322&r1=323321&r2=323322&view=diff
==
--- libcxx/trunk/include/regex (original)
+++ libcxx/trunk/include/regex Wed Jan 24 04:45:18 2018
@@ -4013,7 +4013,7 @@ basic_regex<_CharT, _Traits>::__parse_ch
 char_class_type __class_type =
 __traits_.lookup_classname(__first, __temp, __flags_ & icase);
 if (__class_type == 0)
-__throw_regex_error();
+__throw_regex_error();
 __ml->__add_class(__class_type);
 __first = _VSTD::next(__temp, 2);
 return __first;

Added: libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp?rev=323322&view=auto
==
--- libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp 
(added)
+++ libcxx/trunk/test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp Wed 
Jan 24 04:45:18 2018
@@ -0,0 +1,37 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: libcpp-no-exceptions
+// 
+
+// template > class 
basic_regex;
+
+// template 
+//basic_regex(const basic_string& s);
+
+#include 
+#include 
+#include "test_macros.h"
+
+static bool error_ctype_thrown(const char *pat)
+{
+bool result = false;
+try {
+std::regex re(pat);
+} catch (const std::regex_error &ex) {
+result = (ex.code() == std::regex_constants::error_ctype);
+}
+return result;
+}
+
+int main()
+{
+assert(error_ctype_thrown("[[::]]"));
+assert(error_ctype_thrown("[[:error:]]"));
+}


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


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen added a comment.

In https://reviews.llvm.org/D42467#986214, @krytarowski wrote:

> Do you plan to use MSan? If so, `-lkvm` might be useful as well.


This is indeed the plan. Updated.


Repository:
  rC Clang

https://reviews.llvm.org/D42467



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


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 131229.
devnexen retitled this revision from "FreeBSD needs also execinfo and libutil" 
to "FreeBSD needs also execinfo, libutil and libkvm".
devnexen edited the summary of this revision.

Repository:
  rC Clang

https://reviews.llvm.org/D42467

Files:
  lib/Driver/ToolChains/CommonArgs.cpp


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -550,13 +550,16 @@
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
   // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lkvm");
 }
 


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -550,13 +550,16 @@
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
   // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lkvm");
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread Kamil Rytarowski via Phabricator via cfe-commits
krytarowski added a comment.

Please update the `-lutil` comment in the code according to the comment. I can 
land this for you once it will be accepted.


Repository:
  rC Clang

https://reviews.llvm.org/D42467



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


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen added a comment.

In https://reviews.llvm.org/D42467#986279, @krytarowski wrote:

> Please update the `-lutil` comment in the code according to the comment. I 
> can land this for you once it will be accepted.


In fact the review comment is wrong/confusing :-) lutil is for forkpty only as 
NetBSD.


Repository:
  rC Clang

https://reviews.llvm.org/D42467



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


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread Kamil Rytarowski via Phabricator via cfe-commits
krytarowski added a comment.

In https://reviews.llvm.org/D42467#986280, @devnexen wrote:

> In https://reviews.llvm.org/D42467#986279, @krytarowski wrote:
>
> > Please update the `-lutil` comment in the code according to the comment. I 
> > can land this for you once it will be accepted.
>
>
> In fact the review comment is wrong/confusing :-) lutil is for forkpty only 
> as NetBSD.


`Needed for additional utility functions on some OSes`?


Repository:
  rC Clang

https://reviews.llvm.org/D42467



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


[PATCH] D42335: [ASTImporter] Supporting CXXOperatorCallExpr, SizeOfPackExpr, DependentTemplateSpecializationType, DependentSizedArray, CXXTypeidExpr importing.

2018-01-24 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added inline comments.



Comment at: lib/AST/ASTImporter.cpp:6207
+TypeSourceInfo *TSI = Importer.Import(E->getTypeOperandSourceInfo());
+if (!TSI && E->getTypeOperandSourceInfo())
+  return nullptr;

As I see from usage of `getTypeOperandSourceInfo()`, it cannot return nullptr. 
`getExprOperand()` is used unchecked sometimes too, but not everywhere.



Comment at: unittests/AST/ASTImporterTest.cpp:653
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(hasDescendant(cxxTypeidExpr(;
+}

This will find only the first `typeid()`. How about something like this:
```
void declToImport() {"
 "  int x;"
 " auto a = typeid(int), b = typeid(x);"
 "}",
 Lang_CXX, "", Lang_CXX, Verifier,
 functionDecl(has(varDecl(hasName("a"), 
hasInitializer(cxxTypeidExpr())),
  has(varDecl(hasName("b"), 
hasInitializer(cxxTypeidExpr(;
```
?


https://reviews.llvm.org/D42335



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


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 131239.
devnexen edited the summary of this revision.

Repository:
  rC Clang

https://reviews.llvm.org/D42467

Files:
  lib/Driver/ToolChains/CommonArgs.cpp


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -549,14 +549,17 @@
   TC.getTriple().getOS() != llvm::Triple::NetBSD &&
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
-  // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  // Required for additional utility functions on some OSes
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lkvm");
 }
 


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -549,14 +549,17 @@
   TC.getTriple().getOS() != llvm::Triple::NetBSD &&
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
-  // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  // Required for additional utility functions on some OSes
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lkvm");
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42474: [DO NOT SUBMIT] Provide results with '.' to '->' corrections in completion

2018-01-24 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
Herald added a subscriber: cfe-commits.

Not intended to be submitted, this is a suggestion on how to make the
code in https://reviews.llvm.org/D41537 easier.


Repository:
  rC Clang

https://reviews.llvm.org/D42474

Files:
  include/clang/Sema/Sema.h
  lib/Parse/ParseExpr.cpp
  lib/Sema/SemaCodeComplete.cpp

Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -3981,107 +3981,121 @@
 }
 
 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
+   Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement) {
   if (!Base || !CodeCompleter)
 return;
-  
+
   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
   if (ConvertedBase.isInvalid())
 return;
-  Base = ConvertedBase.get();
-  
-  QualType BaseType = Base->getType();
+  QualType ConvertedBaseType = ConvertedBase.get()->getType();
 
-  if (IsArrow) {
-if (const PointerType *Ptr = BaseType->getAs())
-  BaseType = Ptr->getPointeeType();
-else if (BaseType->isObjCObjectPointerType())
-  /*Do nothing*/ ;
-else
-  return;
-  }
-  
   enum CodeCompletionContext::Kind contextKind;
-  
+
   if (IsArrow) {
 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
-  }
-  else {
-if (BaseType->isObjCObjectPointerType() ||
-BaseType->isObjCObjectOrInterfaceType()) {
+  } else {
+if (ConvertedBaseType->isObjCObjectPointerType() ||
+ConvertedBaseType->isObjCObjectOrInterfaceType()) {
   contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
-}
-else {
+} else {
   contextKind = CodeCompletionContext::CCC_DotMemberAccess;
 }
   }
 
-  CodeCompletionContext CCContext(contextKind, BaseType);
+  CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
-CodeCompleter->getCodeCompletionTUInfo(),
-CCContext,
+CodeCompleter->getCodeCompletionTUInfo(), CCContext,
 &ResultBuilder::IsMember);
-  Results.EnterNewScope();
-  if (const RecordType *Record = BaseType->getAs()) {
-AddRecordMembersCompletionResults(*this, Results, S, BaseType,
-  Record->getDecl());
-  } else if (const auto *TST = BaseType->getAs()) {
-TemplateName TN = TST->getTemplateName();
-if (const auto *TD =
-dyn_cast_or_null(TN.getAsTemplateDecl())) {
-  CXXRecordDecl *RD = TD->getTemplatedDecl();
-  AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
-}
-  } else if (const auto *ICNT = BaseType->getAs()) {
-if (auto *RD = ICNT->getDecl())
-  AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
-  } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
-// Objective-C property reference.
-AddedPropertiesSet AddedProperties;
-
-if (const ObjCObjectPointerType *ObjCPtr =
-BaseType->getAsObjCInterfacePointerType()) {
-  // Add property results based on our interface.
-  assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
-  AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
-/*AllowNullaryMethods=*/true, CurContext,
-AddedProperties, Results, IsBaseExprStatement);
-}
-
-// Add properties from the protocols in a qualified interface.
-for (auto *I : BaseType->getAs()->quals())
-  AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
-CurContext, AddedProperties, Results,
-IsBaseExprStatement);
-  } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
- (!IsArrow && BaseType->isObjCObjectType())) {
-// Objective-C instance variable access.
-ObjCInterfaceDecl *Class = nullptr;
-if (const ObjCObjectPointerType *ObjCPtr
-= BaseType->getAs())
-  Class = ObjCPtr->getInterfaceDecl();
-else
-  Class = BaseType->getAs()->getInterface();
-
-// Add all ivars from this class and its superclasses.
-if (Class) {
-  CodeCompletionDeclConsumer Consumer(Results, CurContext);
-  Results.setFilter(&ResultBuilder::IsObjCIvar);
-  LookupVisibleDecls(
-  Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
-  /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
+
+  auto DoCompletion = [&](Expr *Base, bool IsArrow) -> bool {
+if (!Base)
+  return false;
+
+ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
+if (ConvertedBase.isInvalid())
+  return false;
+Bas

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-01-24 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Sorry for not taking a look for a long time. I think that would be a very 
useful feature to have.
Here are a few comments (also see the inline comments)

- Please add tests
- How would the clients know how to correct dot to arrow? It'd be cool if code 
completion results to provide a replacement for that (e.g. return a `FixItHint` 
that should be applied along with the completion items that have 
`RequiresDotToArrowCorrection == true`).
- We should probably have a more general option, i.e. `AllowCorrections`. We 
could reuse it for other advanced completion scenarios.
- This patch calls `HandleCodeCompleteResults` twice and it breaks at least one 
existing client (clangd) and, arguably, makes the contract of 
`CodeCompleteConsumer` more complicated. I have a patch that addresses that: 
https://reviews.llvm.org/D42474. The change also moves some of the code to 
parser, arguably making the overall patch.




Comment at: include/clang/Sema/CodeCompleteConsumer.h:493
+   StringRef ParentName, const char *BriefComment,
+   bool RequiresDotToArrowCorrection = false);
   ~CodeCompletionString() = default;

Maybe remove the default argument?
This constructor seems to only be called `CodeCompletionBuilder::TakeString`.



Comment at: include/clang/Sema/CodeCompleteConsumer.h:595
   const char *BriefComment;
+  bool RequiresDotToArrowCorrection = false;
   

Maybe remove `= false`, initialize in constructor to be consistent with how 
other members are initialized?



Comment at: include/clang/Sema/CodeCompleteConsumer.h:612
+unsigned Priority, CXAvailabilityKind Availability,
+bool RequiresDotToArrowCorrection = false)
 : Allocator(Allocator), CCTUInfo(CCTUInfo),

Maybe remove the default argument too?
This method seems to have only 5 callsites, they should be very easy to update.



Comment at: include/clang/Sema/CodeCompleteOptions.h:43
+  /// Show also results after dot to arrow correction if arrow operator can be 
applied.
+  unsigned TryArrowInsteadOfDot : 1;
+

Could we make a more general option (say, `IncludeCorrections`)?
Arrow instead of dot is useful, but we might try to add more items that require 
various corrections when doing completions and it would be nice to reuse the 
option between those.



Comment at: lib/Sema/SemaCodeComplete.cpp:4066
+  } else {
+const DeclarationName ArrowOpName =
+SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Arrow);

The code here seems to replicate what the parser does, so certifying that's 
it's correct is hard and we may not pick up the changes when something changes 
in parser.
I suggest we compute the `Expr* Base` for an alternate operator and pass it to 
code complete function. Here's a change that does that, feel free to pick it up 
unless you have objections to my line of thought: D42474 (it's missing marking 
the results with proper flags, so that's something that should be extended).


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-01-24 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

I also propose to try correcting in both directions, i.e. here's how completion 
completion could work with this feature:

  struct X { int foobarbaz; };
  
  void test() {
X var;
X* ptr;
std::unique_ptr uptr;
 
var->foobar // replace with var.foobarbaz
ptr.foobar // replace with ptr->foobar
uptr->get // replace with uptr.get
uptr.foobar // replace with uptr->foobarbaz
  }


https://reviews.llvm.org/D41537



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


[PATCH] D42466: [Sema] Allow disabling typo correction when doing code completion.

2018-01-24 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: lib/Sema/Sema.cpp:143
   ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
-  DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
+  DisableTypoCorrection(
+  CodeCompleter ? CodeCompleter->disableTypoCorrection() : false),

It seems weird that typo-correction is only controlled by `CodeCompleter` for 
all of `Sema`.
I wonder whether putting that into `FrontendOptions` makes more sense. WDYT?


Repository:
  rC Clang

https://reviews.llvm.org/D42466



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


[PATCH] D41539: [CodeGen] Decorate aggregate accesses with TBAA tags

2018-01-24 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev updated this revision to Diff 131257.
kosarev added a comment.

The copying functions changed to take LValues. It seems Address-taking versions 
are not very useful so we don't bother with overloading.


https://reviews.llvm.org/D41539

Files:
  lib/CodeGen/CGAtomic.cpp
  lib/CodeGen/CGCall.cpp
  lib/CodeGen/CGClass.cpp
  lib/CodeGen/CGExprAgg.cpp
  lib/CodeGen/CGExprCXX.cpp
  lib/CodeGen/CGObjC.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGStmt.cpp
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  lib/CodeGen/CodeGenTBAA.cpp
  lib/CodeGen/CodeGenTBAA.h
  lib/CodeGen/ItaniumCXXABI.cpp
  test/CodeGen/tbaa-struct.cpp

Index: test/CodeGen/tbaa-struct.cpp
===
--- test/CodeGen/tbaa-struct.cpp
+++ test/CodeGen/tbaa-struct.cpp
@@ -1,75 +1,122 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -o - -O1 %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -o - -O1 %s | \
+// RUN: FileCheck -check-prefixes=CHECK,CHECK-OLD %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -new-struct-path-tbaa \
+// RUN: -emit-llvm -o - -O1 %s | \
+// RUN: FileCheck -check-prefixes=CHECK,CHECK-NEW %s
 //
-// Check that we generate !tbaa.struct metadata for struct copies.
+// Check that we generate TBAA metadata for struct copies correctly.
+
 struct A {
   short s;
   int i;
   char c;
   int j;
 };
 
-void copy(struct A *a, struct A *b) {
-  *a = *b;
-}
+typedef A __attribute__((may_alias)) AA;
 
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 16, i32 4, i1 false), !tbaa.struct [[TS:!.*]]
+void copy(A *a1, A *a2) {
+// CHECK-LABEL: _Z4copyP1AS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_A:![0-9]*]]
+  *a1 = *a2;
+}
 
 struct B {
-  char c1;
-  struct A a;
-  int ii;
+  char c;
+  A a;
+  int i;
 };
 
-void copy2(struct B *a, struct B *b) {
-  *a = *b;
+void copy2(B *b1, B *b2) {
+// CHECK-LABEL: _Z5copy2P1BS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS2:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_B:![0-9]*]]
+  *b1 = *b2;
 }
 
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 24, i32 4, i1 false), !tbaa.struct [[TS2:!.*]]
+struct S {
+  _Complex char cc;
+  _Complex int ci;
+};
 
-typedef _Complex int T2;
-typedef _Complex char T5;
-typedef _Complex int T7;
-typedef struct T4 { T5 field0; T7 field1; } T4;
-typedef union T1 { T2 field0; T4 field1; } T1;
+union U {
+  _Complex int ci;
+  S s;
+};
 
-void copy3 (T1 *a, T1 *b) {
-  *a = *b;
+void copy3(U *u1, U *u2) {
+// CHECK-LABEL: _Z5copy3P1US0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS3:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_U:![0-9]*]]
+  *u1 = *u2;
 }
 
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 12, i32 4, i1 false), !tbaa.struct [[TS3:!.*]]
-
 // Make sure that zero-length bitfield works.
-#define ATTR __attribute__ ((ms_struct))
-struct five {
+struct C {
   char a;
-  int :0;/* ignored; prior field is not a bitfield. */
+  int : 0;  // Shall not be ignored; see r185018.
   char b;
   char c;
-} ATTR;
-void copy4(struct five *a, struct five *b) {
-  *a = *b;
+} __attribute__((ms_struct));
+
+void copy4(C *c1, C *c2) {
+// CHECK-LABEL: _Z5copy4P1CS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS4:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_C:![0-9]*]]
+  *c1 = *c2;
 }
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 3, i32 1, i1 false), !tbaa.struct [[TS4:!.*]]
 
-struct six {
+struct D {
   char a;
-  int :0;
+  int : 0;
   char b;
   char c;
 };
-void copy5(struct six *a, struct six *b) {
-  *a = *b;
+
+void copy5(D *d1, D *d2) {
+// CHECK-LABEL: _Z5copy5P1DS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS5:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_D:![0-9]*]]
+  *d1 = *d2;
+}
+
+void copy6(AA *a1, A *a2) {
+// CHECK-LABEL: _Z5copy6P1AS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_char:![0-9]*]]
+  *a1 = *a2;
+}
+
+void copy7(A *a1, AA *a2) {
+// CHECK-LABEL: _Z5copy7P1AS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_char]]
+  *a1 = *a2;
 }
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 6, i32 1, i1 false), !tbaa.struct [[TS5:!.*]]
 
-// CHECK: [[TS]] = !{i64 0, i64 2, !{{.*}}, i64 4, i64 4, !{{.*}}, i64 8, i64 1, !{{.*}}, i64 12, i64 4, !{{.*}}}
-// CHECK: [[CHAR:!.*]] = !{!"omnipotent char", !{{.*}}}
-// CHECK: [[TAG_INT:!.*]] = !{[[INT:!.*]], [[INT]], i64 0}
-// CHECK: [[INT]] = !{!"int", [[CHAR]]
-// CHECK: [[TAG_C

[PATCH] D41938: [Analyzer] SValBuilder Comparison Rearrangement (with Restrictions and Analyzer Option)

2018-01-24 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

Thank you for your comments. Since the original author of this particular code 
is Artem, I think he will answer your questions.


https://reviews.llvm.org/D41938



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


r323330 - clang-cl: Parse /permissive-, /Bt, Bt+ (PR32672)

2018-01-24 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Wed Jan 24 07:18:12 2018
New Revision: 323330

URL: http://llvm.org/viewvc/llvm-project?rev=323330&view=rev
Log:
clang-cl: Parse /permissive-, /Bt, Bt+ (PR32672)

Modified:
cfe/trunk/include/clang/Driver/CLCompatOptions.td
cfe/trunk/test/Driver/cl-options.c

Modified: cfe/trunk/include/clang/Driver/CLCompatOptions.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CLCompatOptions.td?rev=323330&r1=323329&r2=323330&view=diff
==
--- cfe/trunk/include/clang/Driver/CLCompatOptions.td (original)
+++ cfe/trunk/include/clang/Driver/CLCompatOptions.td Wed Jan 24 07:18:12 2018
@@ -326,6 +326,7 @@ def _SLASH_kernel_ : CLIgnoredFlag<"kern
 def _SLASH_nologo : CLIgnoredFlag<"nologo">;
 def _SLASH_Og : CLIgnoredFlag<"Og">;
 def _SLASH_openmp_ : CLIgnoredFlag<"openmp-">;
+def _SLASH_permissive_ : CLIgnoredFlag<"permissive-">;
 def _SLASH_RTC : CLIgnoredJoined<"RTC">;
 def _SLASH_sdl : CLIgnoredFlag<"sdl">;
 def _SLASH_sdl_ : CLIgnoredFlag<"sdl-">;
@@ -346,6 +347,8 @@ def _SLASH_Zo_ : CLIgnoredFlag<"Zo-">;
 // Unsupported:
 
 def _SLASH_AI : CLJoined<"AI">;
+def _SLASH_Bt : CLFlag<"Bt">;
+def _SLASH_Bt_plus : CLFlag<"Bt+">;
 def _SLASH_clr : CLJoined<"clr">;
 def _SLASH_doc : CLJoined<"doc">;
 def _SLASH_FA_joined : CLJoined<"FA">;

Modified: cfe/trunk/test/Driver/cl-options.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=323330&r1=323329&r2=323330&view=diff
==
--- cfe/trunk/test/Driver/cl-options.c (original)
+++ cfe/trunk/test/Driver/cl-options.c Wed Jan 24 07:18:12 2018
@@ -344,6 +344,7 @@
 // RUN:/kernel- \
 // RUN:/nologo \
 // RUN:/openmp- \
+// RUN:/permissive- \
 // RUN:/RTC1 \
 // RUN:/sdl \
 // RUN:/sdl- \
@@ -376,6 +377,8 @@
 // (/Zs is for syntax-only)
 // RUN: %clang_cl /Zs \
 // RUN: /AIfoo \
+// RUN: /Bt \
+// RUN: /Bt+ \
 // RUN: /clr:pure \
 // RUN: /docname \
 // RUN: /EHsc \


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


[PATCH] D42480: [clangd] Provide a helper to report estimated memory usage per-file

2018-01-24 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added reviewers: sammccall, ioeric, hokein.
Herald added subscribers: jkorous-apple, klimek.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42480

Files:
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/ClangdUnitStore.cpp
  clangd/ClangdUnitStore.h
  unittests/clangd/ClangdTests.cpp

Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -17,6 +17,7 @@
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
 #include 
@@ -28,6 +29,14 @@
 
 namespace clang {
 namespace clangd {
+
+using ::testing::ElementsAre;
+using ::testing::Eq;
+using ::testing::Gt;
+using ::testing::IsEmpty;
+using ::testing::Pair;
+using ::testing::UnorderedElementsAre;
+
 namespace {
 
 // Don't wait for async ops in clangd test more than that to avoid blocking
@@ -416,6 +425,42 @@
   EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags());
 }
 
+TEST_F(ClangdVFSTest, MemoryUsage) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, DiagConsumer, FS,
+  /*AsyncThreadsCount=*/0,
+  /*StorePreamblesInMemory=*/true);
+
+  // No need to sync reparses, because reparses are performed on the calling
+  // thread.
+  Path FooCpp = getVirtualTestFilePath("foo.cpp").str();
+  const auto SourceContents = R"cpp(
+struct Something {
+  int method();
+};
+)cpp";
+  Path BarCpp = getVirtualTestFilePath("bar.cpp").str();
+
+  FS.Files[FooCpp] = "";
+  FS.Files[BarCpp] = "";
+
+  EXPECT_THAT(Server.getUsedBytesPerFile(), IsEmpty());
+
+  Server.addDocument(Context::empty(), FooCpp, SourceContents);
+  Server.addDocument(Context::empty(), BarCpp, SourceContents);
+
+  EXPECT_THAT(Server.getUsedBytesPerFile(),
+  UnorderedElementsAre(Pair(FooCpp, Gt(0u)), Pair(BarCpp, Gt(0u;
+
+  Server.removeDocument(Context::empty(), FooCpp);
+  EXPECT_THAT(Server.getUsedBytesPerFile(), ElementsAre(Pair(BarCpp, Gt(0u;
+
+  Server.removeDocument(Context::empty(), BarCpp);
+  EXPECT_THAT(Server.getUsedBytesPerFile(), IsEmpty());
+}
+
 class ClangdThreadingTest : public ClangdVFSTest {};
 
 TEST_F(ClangdThreadingTest, StressTest) {
Index: clangd/ClangdUnitStore.h
===
--- clangd/ClangdUnitStore.h
+++ clangd/ClangdUnitStore.h
@@ -45,7 +45,7 @@
 return It->second;
   }
 
-  std::shared_ptr getFile(PathRef File) {
+  std::shared_ptr getFile(PathRef File) const {
 std::lock_guard Lock(Mutex);
 
 auto It = OpenedFiles.find(File);
@@ -58,8 +58,11 @@
   /// returns it.
   std::shared_ptr removeIfPresent(PathRef File);
 
+  /// Gets used memory for each of the stored files.
+  std::vector> getUsedBytesPerFile() const;
+
 private:
-  std::mutex Mutex;
+  mutable std::mutex Mutex;
   llvm::StringMap> OpenedFiles;
   ASTParsedCallback ASTCallback;
 };
Index: clangd/ClangdUnitStore.cpp
===
--- clangd/ClangdUnitStore.cpp
+++ clangd/ClangdUnitStore.cpp
@@ -25,3 +25,13 @@
   OpenedFiles.erase(It);
   return Result;
 }
+std::vector>
+CppFileCollection::getUsedBytesPerFile() const {
+  std::lock_guard Lock(Mutex);
+  std::vector> Result;
+  Result.reserve(OpenedFiles.size());
+  for (auto &&PathAndFile : OpenedFiles)
+Result.push_back(
+{PathAndFile.first().str(), PathAndFile.second->getUsedBytes()});
+  return Result;
+}
Index: clangd/ClangdUnit.h
===
--- clangd/ClangdUnit.h
+++ clangd/ClangdUnit.h
@@ -96,6 +96,10 @@
 
   const std::vector &getDiagnostics() const;
 
+  /// Returns the esitmated size of the AST and the accessory structures, in
+  /// bytes. Does not include the size of the preamble.
+  std::size_t getUsedBytes() const;
+
 private:
   ParsedAST(std::shared_ptr Preamble,
 std::unique_ptr Clang,
@@ -224,6 +228,10 @@
   // files in the CppFileCollection always have a compile command available.
   llvm::Optional getLastCommand() const;
 
+  /// Returns an estimated size, in bytes, currently occupied by the AST and the
+  /// Preamble.
+  std::size_t getUsedBytes() const;
+
 private:
   /// A helper guard that manages the state of CppFile during rebuild.
   class RebuildGuard {
@@ -253,6 +261,11 @@
   std::condition_variable RebuildCond;
   llvm::Optional LastCommand;
 
+  /// Size of the last built AST, in bytes.
+  std::size_t ASTMemUsage;
+  /// Size of the last build Preamble, in bytes.
+  std::size_t PreambleMemUsage;
+
   /// Promise and future for the latests AST. Fulfilled during rebuild.
   /// We use std::shared_ptr here because MVSC fails to compile non-copyable
  

Re: r323008 - [Lex] Fix crash on code completion in comment in included file.

2018-01-24 Thread Hans Wennborg via cfe-commits
On Wed, Jan 24, 2018 at 4:30 PM, Hans Wennborg  wrote:
> Merged to 6.0 in r32 as requested in PR36043. Richard, please
> complain if you don't agree.

Actually cc'ing Richard this time.

>
> On Sat, Jan 20, 2018 at 12:41 AM, Volodymyr Sapsai via cfe-commits
>  wrote:
>> Author: vsapsai
>> Date: Fri Jan 19 15:41:47 2018
>> New Revision: 323008
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=323008&view=rev
>> Log:
>> [Lex] Fix crash on code completion in comment in included file.
>>
>> This fixes PR32732 by updating CurLexerKind to reflect available lexers.
>> We were hitting null pointer in Preprocessor::Lex because CurLexerKind
>> was CLK_Lexer but CurLexer was null. And we set it to null in
>> Preprocessor::HandleEndOfFile when exiting a file with code completion
>> point.
>>
>> To reproduce the crash it is important for a comment to be inside a
>> class specifier. In this case in Parser::ParseClassSpecifier we improve
>> error recovery by pushing a semicolon token back into the preprocessor
>> and later on try to lex a token because we haven't reached the end of
>> file.
>>
>> Also clang crashes only on code completion in included file, i.e. when
>> IncludeMacroStack is not empty. Though we reset CurLexer even if include
>> stack is empty. The difference is that during pushing back a semicolon
>> token, preprocessor calls EnterCachingLexMode which decides it is
>> already in caching mode because various lexers are null and
>> IncludeMacroStack is not empty. As the result, CurLexerKind remains
>> CLK_Lexer instead of updating to CLK_CachingLexer.
>>
>> rdar://problem/34787685
>>
>> Reviewers: akyrtzi, doug.gregor, arphaman
>>
>> Reviewed By: arphaman
>>
>> Subscribers: cfe-commits, kfunk, arphaman, nemanjai, kbarton
>>
>> Differential Revision: https://reviews.llvm.org/D41688
>>
>> Added:
>> cfe/trunk/test/CodeCompletion/Inputs/comments.h
>> cfe/trunk/test/CodeCompletion/comments.cpp
>> Modified:
>> cfe/trunk/lib/Lex/PPCaching.cpp
>> cfe/trunk/lib/Lex/PPLexerChange.cpp
>>
>> Modified: cfe/trunk/lib/Lex/PPCaching.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPCaching.cpp?rev=323008&r1=323007&r2=323008&view=diff
>> ==
>> --- cfe/trunk/lib/Lex/PPCaching.cpp (original)
>> +++ cfe/trunk/lib/Lex/PPCaching.cpp Fri Jan 19 15:41:47 2018
>> @@ -105,8 +105,10 @@ void Preprocessor::CachingLex(Token &Res
>>  }
>>
>>  void Preprocessor::EnterCachingLexMode() {
>> -  if (InCachingLexMode())
>> +  if (InCachingLexMode()) {
>> +assert(CurLexerKind == CLK_CachingLexer && "Unexpected lexer kind");
>>  return;
>> +  }
>>
>>PushIncludeMacroStack();
>>CurLexerKind = CLK_CachingLexer;
>>
>> Modified: cfe/trunk/lib/Lex/PPLexerChange.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPLexerChange.cpp?rev=323008&r1=323007&r2=323008&view=diff
>> ==
>> --- cfe/trunk/lib/Lex/PPLexerChange.cpp (original)
>> +++ cfe/trunk/lib/Lex/PPLexerChange.cpp Fri Jan 19 15:41:47 2018
>> @@ -444,6 +444,7 @@ bool Preprocessor::HandleEndOfFile(Token
>>}
>>
>>CurPPLexer = nullptr;
>> +  recomputeCurLexerKind();
>>return true;
>>  }
>>
>>
>> Added: cfe/trunk/test/CodeCompletion/Inputs/comments.h
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeCompletion/Inputs/comments.h?rev=323008&view=auto
>> ==
>> --- cfe/trunk/test/CodeCompletion/Inputs/comments.h (added)
>> +++ cfe/trunk/test/CodeCompletion/Inputs/comments.h Fri Jan 19 15:41:47 2018
>> @@ -0,0 +1,4 @@
>> +// PR32732
>> +struct B {
>> +  // <- code completion
>> +};
>>
>> Added: cfe/trunk/test/CodeCompletion/comments.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeCompletion/comments.cpp?rev=323008&view=auto
>> ==
>> --- cfe/trunk/test/CodeCompletion/comments.cpp (added)
>> +++ cfe/trunk/test/CodeCompletion/comments.cpp Fri Jan 19 15:41:47 2018
>> @@ -0,0 +1,13 @@
>> +// Note: the run lines follow their respective tests, since line/column
>> +// matter in this test.
>> +
>> +#include "comments.h"
>> +
>> +struct A {
>> +  // <- code completion
>> +  /* <- code completion */
>> +};
>> +
>> +// RUN: %clang_cc1 -I %S/Inputs -fsyntax-only -code-completion-at=%s:7:6 %s
>> +// RUN: %clang_cc1 -I %S/Inputs -fsyntax-only -code-completion-at=%s:8:6 %s
>> +// RUN: %clang_cc1 -I %S/Inputs -fsyntax-only 
>> -code-completion-at=%S/Inputs/comments.h:3:6 %s
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/

Re: r323008 - [Lex] Fix crash on code completion in comment in included file.

2018-01-24 Thread Hans Wennborg via cfe-commits
Merged to 6.0 in r32 as requested in PR36043. Richard, please
complain if you don't agree.

On Sat, Jan 20, 2018 at 12:41 AM, Volodymyr Sapsai via cfe-commits
 wrote:
> Author: vsapsai
> Date: Fri Jan 19 15:41:47 2018
> New Revision: 323008
>
> URL: http://llvm.org/viewvc/llvm-project?rev=323008&view=rev
> Log:
> [Lex] Fix crash on code completion in comment in included file.
>
> This fixes PR32732 by updating CurLexerKind to reflect available lexers.
> We were hitting null pointer in Preprocessor::Lex because CurLexerKind
> was CLK_Lexer but CurLexer was null. And we set it to null in
> Preprocessor::HandleEndOfFile when exiting a file with code completion
> point.
>
> To reproduce the crash it is important for a comment to be inside a
> class specifier. In this case in Parser::ParseClassSpecifier we improve
> error recovery by pushing a semicolon token back into the preprocessor
> and later on try to lex a token because we haven't reached the end of
> file.
>
> Also clang crashes only on code completion in included file, i.e. when
> IncludeMacroStack is not empty. Though we reset CurLexer even if include
> stack is empty. The difference is that during pushing back a semicolon
> token, preprocessor calls EnterCachingLexMode which decides it is
> already in caching mode because various lexers are null and
> IncludeMacroStack is not empty. As the result, CurLexerKind remains
> CLK_Lexer instead of updating to CLK_CachingLexer.
>
> rdar://problem/34787685
>
> Reviewers: akyrtzi, doug.gregor, arphaman
>
> Reviewed By: arphaman
>
> Subscribers: cfe-commits, kfunk, arphaman, nemanjai, kbarton
>
> Differential Revision: https://reviews.llvm.org/D41688
>
> Added:
> cfe/trunk/test/CodeCompletion/Inputs/comments.h
> cfe/trunk/test/CodeCompletion/comments.cpp
> Modified:
> cfe/trunk/lib/Lex/PPCaching.cpp
> cfe/trunk/lib/Lex/PPLexerChange.cpp
>
> Modified: cfe/trunk/lib/Lex/PPCaching.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPCaching.cpp?rev=323008&r1=323007&r2=323008&view=diff
> ==
> --- cfe/trunk/lib/Lex/PPCaching.cpp (original)
> +++ cfe/trunk/lib/Lex/PPCaching.cpp Fri Jan 19 15:41:47 2018
> @@ -105,8 +105,10 @@ void Preprocessor::CachingLex(Token &Res
>  }
>
>  void Preprocessor::EnterCachingLexMode() {
> -  if (InCachingLexMode())
> +  if (InCachingLexMode()) {
> +assert(CurLexerKind == CLK_CachingLexer && "Unexpected lexer kind");
>  return;
> +  }
>
>PushIncludeMacroStack();
>CurLexerKind = CLK_CachingLexer;
>
> Modified: cfe/trunk/lib/Lex/PPLexerChange.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPLexerChange.cpp?rev=323008&r1=323007&r2=323008&view=diff
> ==
> --- cfe/trunk/lib/Lex/PPLexerChange.cpp (original)
> +++ cfe/trunk/lib/Lex/PPLexerChange.cpp Fri Jan 19 15:41:47 2018
> @@ -444,6 +444,7 @@ bool Preprocessor::HandleEndOfFile(Token
>}
>
>CurPPLexer = nullptr;
> +  recomputeCurLexerKind();
>return true;
>  }
>
>
> Added: cfe/trunk/test/CodeCompletion/Inputs/comments.h
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeCompletion/Inputs/comments.h?rev=323008&view=auto
> ==
> --- cfe/trunk/test/CodeCompletion/Inputs/comments.h (added)
> +++ cfe/trunk/test/CodeCompletion/Inputs/comments.h Fri Jan 19 15:41:47 2018
> @@ -0,0 +1,4 @@
> +// PR32732
> +struct B {
> +  // <- code completion
> +};
>
> Added: cfe/trunk/test/CodeCompletion/comments.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeCompletion/comments.cpp?rev=323008&view=auto
> ==
> --- cfe/trunk/test/CodeCompletion/comments.cpp (added)
> +++ cfe/trunk/test/CodeCompletion/comments.cpp Fri Jan 19 15:41:47 2018
> @@ -0,0 +1,13 @@
> +// Note: the run lines follow their respective tests, since line/column
> +// matter in this test.
> +
> +#include "comments.h"
> +
> +struct A {
> +  // <- code completion
> +  /* <- code completion */
> +};
> +
> +// RUN: %clang_cc1 -I %S/Inputs -fsyntax-only -code-completion-at=%s:7:6 %s
> +// RUN: %clang_cc1 -I %S/Inputs -fsyntax-only -code-completion-at=%s:8:6 %s
> +// RUN: %clang_cc1 -I %S/Inputs -fsyntax-only 
> -code-completion-at=%S/Inputs/comments.h:3:6 %s
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r323330 - clang-cl: Parse /permissive-, /Bt, Bt+ (PR32672)

2018-01-24 Thread Nico Weber via cfe-commits
(see also this thread for some prior discussion on /permissive-:
https://marc.info/?t=14930460853&r=1&w=2 Ignoring seems like a good
thing to do for now.)

On Wed, Jan 24, 2018 at 10:18 AM, Hans Wennborg via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: hans
> Date: Wed Jan 24 07:18:12 2018
> New Revision: 323330
>
> URL: http://llvm.org/viewvc/llvm-project?rev=323330&view=rev
> Log:
> clang-cl: Parse /permissive-, /Bt, Bt+ (PR32672)
>
> Modified:
> cfe/trunk/include/clang/Driver/CLCompatOptions.td
> cfe/trunk/test/Driver/cl-options.c
>
> Modified: cfe/trunk/include/clang/Driver/CLCompatOptions.td
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/
> clang/Driver/CLCompatOptions.td?rev=323330&r1=323329&r2=323330&view=diff
> 
> ==
> --- cfe/trunk/include/clang/Driver/CLCompatOptions.td (original)
> +++ cfe/trunk/include/clang/Driver/CLCompatOptions.td Wed Jan 24 07:18:12
> 2018
> @@ -326,6 +326,7 @@ def _SLASH_kernel_ : CLIgnoredFlag<"kern
>  def _SLASH_nologo : CLIgnoredFlag<"nologo">;
>  def _SLASH_Og : CLIgnoredFlag<"Og">;
>  def _SLASH_openmp_ : CLIgnoredFlag<"openmp-">;
> +def _SLASH_permissive_ : CLIgnoredFlag<"permissive-">;
>  def _SLASH_RTC : CLIgnoredJoined<"RTC">;
>  def _SLASH_sdl : CLIgnoredFlag<"sdl">;
>  def _SLASH_sdl_ : CLIgnoredFlag<"sdl-">;
> @@ -346,6 +347,8 @@ def _SLASH_Zo_ : CLIgnoredFlag<"Zo-">;
>  // Unsupported:
>
>  def _SLASH_AI : CLJoined<"AI">;
> +def _SLASH_Bt : CLFlag<"Bt">;
> +def _SLASH_Bt_plus : CLFlag<"Bt+">;
>  def _SLASH_clr : CLJoined<"clr">;
>  def _SLASH_doc : CLJoined<"doc">;
>  def _SLASH_FA_joined : CLJoined<"FA">;
>
> Modified: cfe/trunk/test/Driver/cl-options.c
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/
> cl-options.c?rev=323330&r1=323329&r2=323330&view=diff
> 
> ==
> --- cfe/trunk/test/Driver/cl-options.c (original)
> +++ cfe/trunk/test/Driver/cl-options.c Wed Jan 24 07:18:12 2018
> @@ -344,6 +344,7 @@
>  // RUN:/kernel- \
>  // RUN:/nologo \
>  // RUN:/openmp- \
> +// RUN:/permissive- \
>  // RUN:/RTC1 \
>  // RUN:/sdl \
>  // RUN:/sdl- \
> @@ -376,6 +377,8 @@
>  // (/Zs is for syntax-only)
>  // RUN: %clang_cl /Zs \
>  // RUN: /AIfoo \
> +// RUN: /Bt \
> +// RUN: /Bt+ \
>  // RUN: /clr:pure \
>  // RUN: /docname \
>  // RUN: /EHsc \
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42484: [clangd] Limit completion results.

2018-01-24 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: ioeric, jkorous-apple, ilya-biryukov, klimek.

- truncate symbols from static/dynamic index to the limited number

(which would save lots of cost in constructing the merged symbols).

- add an CLI option allowing to limit the number of returned completion results.

(default to 100)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42484

Files:
  clangd/CodeComplete.cpp
  clangd/index/Merge.cpp
  clangd/tool/ClangdMain.cpp
  unittests/clangd/CodeCompleteTests.cpp


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -529,6 +529,18 @@
   UnorderedElementsAre(Named("local"), Named("Index"), Named("both")));
 }
 
+TEST(CompletionTest, SemaIndexMergeWithLimit) {
+  clangd::CodeCompleteOptions Opts;
+  Opts.Limit = 1;
+  auto Results = completions(
+  R"cpp(
+  namespace ns { int local; void both(); }
+  void f() { ::ns::^ }
+  )cpp",
+  {func("ns::both"), cls("ns::Index")}, Opts);
+  EXPECT_EQ(Results.items.size(), Opts.Limit);
+}
+
 TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -124,6 +124,12 @@
 "eventually. Don't rely on it."),
 llvm::cl::init(""), llvm::cl::Hidden);
 
+static llvm::cl::opt LimitCompletionResult(
+"limit-completion-results",
+llvm::cl::desc("Limit the number of completion results returned by clangd. 
"
+   "0 means no limit."),
+llvm::cl::init(100), llvm::cl::Hidden);
+
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "clangd");
 
@@ -215,6 +221,7 @@
   clangd::CodeCompleteOptions CCOpts;
   CCOpts.EnableSnippets = EnableSnippets;
   CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
+  CCOpts.Limit =  LimitCompletionResult;
   // Initialize and run ClangdLSPServer.
   ClangdLSPServer LSPServer(Out, WorkerThreadsCount, StorePreamblesInMemory,
 CCOpts, ResourceDirRef, CompileCommandsDirPath,
Index: clangd/index/Merge.cpp
===
--- clangd/index/Merge.cpp
+++ clangd/index/Merge.cpp
@@ -50,7 +50,7 @@
  for (const Symbol &S : Dyn)
if (!SeenDynamicSymbols.count(S.ID))
  Callback(S);
- return More;
+ return !More; // returning true indicates the result is complete.
   }
 
 private:
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -864,6 +864,8 @@
 SymbolSlab::Builder ResultsBuilder;
 // Build the query.
 FuzzyFindRequest Req;
+if (Opts.Limit)
+  Req.MaxCandidateCount = Opts.Limit;
 Req.Query = Filter->pattern();
 Req.Scopes =
 getQueryScopes(Recorder.CCContext, 
Recorder.CCSema->getSourceManager());


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -529,6 +529,18 @@
   UnorderedElementsAre(Named("local"), Named("Index"), Named("both")));
 }
 
+TEST(CompletionTest, SemaIndexMergeWithLimit) {
+  clangd::CodeCompleteOptions Opts;
+  Opts.Limit = 1;
+  auto Results = completions(
+  R"cpp(
+  namespace ns { int local; void both(); }
+  void f() { ::ns::^ }
+  )cpp",
+  {func("ns::both"), cls("ns::Index")}, Opts);
+  EXPECT_EQ(Results.items.size(), Opts.Limit);
+}
+
 TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -124,6 +124,12 @@
 "eventually. Don't rely on it."),
 llvm::cl::init(""), llvm::cl::Hidden);
 
+static llvm::cl::opt LimitCompletionResult(
+"limit-completion-results",
+llvm::cl::desc("Limit the number of completion results returned by clangd. "
+   "0 means no limit."),
+llvm::cl::init(100), llvm::cl::Hidden);
+
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "clangd");
 
@@ -215,6 +221,7 @@
   clangd::CodeCompleteOptions CCOpts;
   CCOpts.EnableSnippets = EnableSnippets;
   CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
+  CCOpts.Limit =  LimitCompletionResult;
   // Initialize and run ClangdLSPServer.
   ClangdLSPServer LSPServer(Out, WorkerThreadsCount, StorePreamblesInMemory,
 CCOpts, ResourceDirRef, Com

[PATCH] D42484: [clangd] Limit completion results.

2018-01-24 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.

Thank you!




Comment at: clangd/tool/ClangdMain.cpp:128
+static llvm::cl::opt LimitCompletionResult(
+"limit-completion-results",
+llvm::cl::desc("Limit the number of completion results returned by clangd. 
"

nit: our flag names are generally too long, I think. is completion-limit enough?



Comment at: clangd/tool/ClangdMain.cpp:131
+   "0 means no limit."),
+llvm::cl::init(100), llvm::cl::Hidden);
+

I think we probably want to keep the default at 0 for now. I'm fine with 100 
personally, but talk to Ilya if you want to change the default :-)

This shouldn't be hidden.



Comment at: clangd/tool/ClangdMain.cpp:224
   CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
+  CCOpts.Limit =  LimitCompletionResult;
   // Initialize and run ClangdLSPServer.

nit: whitespace



Comment at: unittests/clangd/CodeCompleteTests.cpp:541
+  {func("ns::both"), cls("ns::Index")}, Opts);
+  EXPECT_EQ(Results.items.size(), Opts.Limit);
+}

also assert Results.isIncomplete


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42484



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


[PATCH] D39571: [clangd] DidChangeConfiguration Notification

2018-01-24 Thread Simon Marchi via Phabricator via cfe-commits
simark added inline comments.



Comment at: clangd/ClangdLSPServer.cpp:302
 
+// FIXME: This function needs to be properly tested.
+void ClangdLSPServer::onChangeConfiguration(

ilya-biryukov wrote:
> Are you planning to to address this FIXME before checking the code in?
Following what you said here:

https://reviews.llvm.org/D39571?id=124024#inline-359345

I have not really looked into what was wrong with the test, and what is missing 
in the infrastructure to make it work.  But I assumed that the situation did 
not change since then.  Can you enlighten me on what the problem was, and what 
is missing?



Comment at: clangd/GlobalCompilationDatabase.h:64
 
+  void setCompileCommandsDir(Path P) {
+std::lock_guard Lock(Mutex);

ilya-biryukov wrote:
> Maybe move definition to `.cpp` file?
> 
> 
Will do.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D39571



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


[PATCH] D42455: Don't create hidden dllimport global values

2018-01-24 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm


https://reviews.llvm.org/D42455



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


[PATCH] D42301: [ASTImporter] Support LambdaExprs and improve template support

2018-01-24 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin updated this revision to Diff 131279.
a.sidorin added a comment.

Addressed review comments


Repository:
  rC Clang

https://reviews.llvm.org/D42301

Files:
  lib/AST/ASTImporter.cpp
  lib/AST/ASTStructuralEquivalence.cpp
  lib/AST/ExternalASTMerger.cpp
  test/ASTMerge/class-template/Inputs/class-template1.cpp
  test/ASTMerge/class-template/Inputs/class-template2.cpp
  test/ASTMerge/class-template/test.cpp
  test/ASTMerge/exprs-cpp/Inputs/exprs3.cpp
  test/ASTMerge/exprs-cpp/test.cpp
  test/ASTMerge/function-cpp/Inputs/function-1.cpp
  test/ASTMerge/function-cpp/test.cpp
  test/Import/template-specialization/Inputs/T.cpp
  test/Import/template-specialization/test.cpp
  unittests/AST/ASTImporterTest.cpp

Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -11,9 +11,9 @@
 //
 //===--===//
 
+#include "MatchVerifier.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTImporter.h"
-#include "MatchVerifier.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Tooling.h"
@@ -99,7 +99,11 @@
   if (FoundDecls.size() != 1)
 return testing::AssertionFailure() << "Multiple declarations were found!";
 
-  auto Imported = Importer.Import(*FoundDecls.begin());
+  // Sanity check: the node being imported should match in the same way as
+  // the result node.
+  EXPECT_TRUE(Verifier.match(FoundDecls.front(), AMatcher));
+
+  auto Imported = Importer.Import(FoundDecls.front());
   if (!Imported)
 return testing::AssertionFailure() << "Import failed, nullptr returned!";
 
@@ -624,7 +628,7 @@
 TEST(ImportDecl, ImportUsingDecl) {
   MatchVerifier Verifier;
   testImport("namespace foo { int bar; }"
- "int declToImport(){ using foo::bar; }",
+ "void declToImport() { using foo::bar; }",
  Lang_CXX, "", Lang_CXX, Verifier,
  functionDecl(
has(
@@ -665,22 +669,22 @@
  "}"
  "void instantiate() { declToImport(); }",
  Lang_CXX, "", Lang_CXX, Verifier,
- functionTemplateDecl(has(functionDecl(has(
- compoundStmt(has(unresolvedLookupExpr(;
+ functionTemplateDecl(has(functionDecl(
+ has(compoundStmt(has(unresolvedLookupExpr(;
 }
 
 TEST(ImportExpr, ImportCXXUnresolvedConstructExpr) {
   MatchVerifier Verifier;
-  testImport("template  class C { T t; };"
+  testImport("template  struct C { T t; };"
  "template  void declToImport() {"
  "  C d;"
  "  d.t = T();"
  "}"
  "void instantiate() { declToImport(); }",
  Lang_CXX, "", Lang_CXX, Verifier,
  functionTemplateDecl(has(functionDecl(has(compoundStmt(has(
  binaryOperator(has(cxxUnresolvedConstructExpr());
-  testImport("template  class C { T t; };"
+  testImport("template  struct C { T t; };"
  "template  void declToImport() {"
  "  C d;"
  "  (&d)->t = T();"
@@ -691,5 +695,22 @@
  binaryOperator(has(cxxUnresolvedConstructExpr());
 }
 
+/// Check that function "declToImport()" (which is the templated function
+/// for corresponding FunctionTemplateDecl) is not added into DeclContext.
+/// Same for class template declarations.
+TEST(ImportDecl, ImportTemplatedDeclForTemplate) {
+  MatchVerifier Verifier;
+  testImport("template  void declToImport() { T a = 1; }"
+ "void instantiate() { declToImport(); }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionTemplateDecl(hasAncestor(translationUnitDecl(
+ unless(has(functionDecl(hasName("declToImport";
+  testImport("template  struct declToImport { T t; };"
+ "void instantiate() { declToImport(); }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ classTemplateDecl(hasAncestor(translationUnitDecl(
+ unless(has(cxxRecordDecl(hasName("declToImport";
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: test/Import/template-specialization/test.cpp
===
--- test/Import/template-specialization/test.cpp
+++ test/Import/template-specialization/test.cpp
@@ -1,7 +1,10 @@
 // RUN: clang-import-test -import %S/Inputs/T.cpp -expression %s
-// XFAIL: *
+
 void expr() {
   A::B b1;
   A::B b2;
   b1.f + b2.g;
 }
+
+static_assert(f() == 0, "");
+static_assert(f() == 4, "");
Index: test/Import/template-specialization/Inputs/T.cpp
===
--- test/Import/template-specialization/Inputs/T.cpp
+++ test/Import/template-specialization/Inputs/T.cpp
@@ -12,3 +12,7 @@
 int g;
   };
 };
+
+
+te

[PATCH] D42301: [ASTImporter] Support LambdaExprs and improve template support

2018-01-24 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

In https://reviews.llvm.org/D42301#984695, @xazax.hun wrote:

> High level note: `clang::TypeAliasDecl` has the same issue as 
> `CXXRecordDecl`, so templated versions should not be added to the 
> DeclContext. Could you add that just for the sake of completeness?


I'd rather create a separate patch - this one is already large enough. Is it OK?


Repository:
  rC Clang

https://reviews.llvm.org/D42301



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


[PATCH] D42466: [Sema] Allow disabling typo correction when doing code completion.

2018-01-24 Thread Haojian Wu via Phabricator via cfe-commits
hokein abandoned this revision.
hokein added inline comments.



Comment at: lib/Sema/Sema.cpp:143
   ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
-  DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
+  DisableTypoCorrection(
+  CodeCompleter ? CodeCompleter->disableTypoCorrection() : false),

ilya-biryukov wrote:
> It seems weird that typo-correction is only controlled by `CodeCompleter` for 
> all of `Sema`.
> I wonder whether putting that into `FrontendOptions` makes more sense. WDYT?
Yeah, it is weird. 

After looking through the code of Sema, modifying `DisableTypoCorrection` is 
not the right way - as this method variable is controlled by Sema internally 
(it will change the value back and forth). 

Fortunately I figured out clang already provides a way to control the typo 
correction. We don't need this patch. Sorry for the noise.


Repository:
  rC Clang

https://reviews.llvm.org/D42466



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


[PATCH] D42490: [cmake] Set cmake policy CMP0068 to suppress warnings on OSX

2018-01-24 Thread Don Hinton via Phabricator via cfe-commits
hintonda created this revision.
hintonda added reviewers: beanz, compnerd, phosek, EricWF.
Herald added subscribers: cfe-commits, mgorny.

Set cmake policy CMP0068=NEW, if available -- depends on 
https://reviews.llvm.org/D42463 which
also adds target property "BUILD_WITH_INSTALL_NAME_DIR On" to maintain
current behavior.

This is needed to suppress warnings on OSX starting with cmake version
3.9.6.


Repository:
  rC Clang

https://reviews.llvm.org/D42490

Files:
  CMakeLists.txt


Index: CMakeLists.txt
===
--- CMakeLists.txt
+++ CMakeLists.txt
@@ -1,5 +1,9 @@
 cmake_minimum_required(VERSION 3.4.3)
 
+if(POLICY CMP0068)
+  cmake_policy(SET CMP0068 NEW)
+endif()
+
 # If we are not building as a part of LLVM, build Clang as an
 # standalone project, using LLVM as an external library:
 if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR )


Index: CMakeLists.txt
===
--- CMakeLists.txt
+++ CMakeLists.txt
@@ -1,5 +1,9 @@
 cmake_minimum_required(VERSION 3.4.3)
 
+if(POLICY CMP0068)
+  cmake_policy(SET CMP0068 NEW)
+endif()
+
 # If we are not building as a part of LLVM, build Clang as an
 # standalone project, using LLVM as an external library:
 if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR )
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42491: [clangd] Disable typo correction when doing code completion.

2018-01-24 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ilya-biryukov.
Herald added subscribers: ioeric, jkorous-apple, klimek.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42491

Files:
  clangd/CodeComplete.cpp
  unittests/clangd/CodeCompleteTests.cpp


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -602,6 +602,14 @@
 Doc("Doooc"), Detail("void";
 }
 
+TEST(CodeCompleteTest, DisableTypoCorrection) {
+  auto Results = completions(R"cpp(
+ namespace clang { int v; }
+ void f() { clangd::^
+  )cpp");
+  EXPECT_TRUE(Results.items.empty());
+}
+
 SignatureHelp signatures(StringRef Text) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -379,10 +379,6 @@
   // Qualified completion ("std::vec^"), we have two cases depending on whether
   // the qualifier can be resolved by Sema.
   if ((*SS)->isValid()) { // Resolved qualifier.
-// FIXME: Disable Sema typo correction during code completion.
-// The resolved qualifier might not perfectly match the written qualifier.
-// e.g. "namespace clang { clangd::^ }", we will get "clang" declaration
-// for completion "clangd::".
 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
   }
 
@@ -678,6 +674,9 @@
   auto &DiagOpts = Clang->getDiagnosticOpts();
   DiagOpts.IgnoreWarnings = true;
 
+  // Disable typo correction in Sema.
+  Clang->getLangOpts().SpellChecking = false;
+
   auto &FrontendOpts = Clang->getFrontendOpts();
   FrontendOpts.SkipFunctionBodies = true;
   FrontendOpts.CodeCompleteOpts = Options;


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -602,6 +602,14 @@
 Doc("Doooc"), Detail("void";
 }
 
+TEST(CodeCompleteTest, DisableTypoCorrection) {
+  auto Results = completions(R"cpp(
+ namespace clang { int v; }
+ void f() { clangd::^
+  )cpp");
+  EXPECT_TRUE(Results.items.empty());
+}
+
 SignatureHelp signatures(StringRef Text) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -379,10 +379,6 @@
   // Qualified completion ("std::vec^"), we have two cases depending on whether
   // the qualifier can be resolved by Sema.
   if ((*SS)->isValid()) { // Resolved qualifier.
-// FIXME: Disable Sema typo correction during code completion.
-// The resolved qualifier might not perfectly match the written qualifier.
-// e.g. "namespace clang { clangd::^ }", we will get "clang" declaration
-// for completion "clangd::".
 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
   }
 
@@ -678,6 +674,9 @@
   auto &DiagOpts = Clang->getDiagnosticOpts();
   DiagOpts.IgnoreWarnings = true;
 
+  // Disable typo correction in Sema.
+  Clang->getLangOpts().SpellChecking = false;
+
   auto &FrontendOpts = Clang->getFrontendOpts();
   FrontendOpts.SkipFunctionBodies = true;
   FrontendOpts.CodeCompleteOpts = Options;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42493: [clang-format] Fix ObjC message arguments formatting.

2018-01-24 Thread Jacek Olesiak via Phabricator via cfe-commits
jolesiak created this revision.
Herald added subscribers: cfe-commits, klimek.
jolesiak edited the summary of this revision.

Fixes formatting of ObjC message arguments when inline block is a first
argument.

Having inline block as a first when method has multiple parameters is
discouraged by Apple:
"It’s best practice to use only one block argument to a method. If the
method also needs other non-block arguments, the block should come last"
(https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html#//apple_ref/doc/uid/TP40011210-CH8-SW7),
it should be correctly formatted nevertheless.

Current formatting:
[object blockArgument:^{

  a = 42;

}

  anotherArg:42];

Fixed (colon alignment):
[object

  blockArgument:^{
a = 42;
  }
 anotherArg:42];

Test Plan: make -j12 FormatTests && tools/clang/unittests/Format/FormatTests


Repository:
  rC Clang

https://reviews.llvm.org/D42493

Files:
  lib/Format/ContinuationIndenter.cpp
  lib/Format/FormatToken.h
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestObjC.cpp


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -655,6 +655,31 @@
"ofSize:aa:bbb\n"
"  atOrigin:cc:dd];");
 
+  // Inline block as a first argument.
+  verifyFormat("[object justBlock:^{\n"
+   "  a = 42;\n"
+   "}];");
+  verifyFormat("[object\n"
+   "justBlock:^{\n"
+   "  a = 42;\n"
+   "}\n"
+   " notBlock:42\n"
+   "a:42];");
+  verifyFormat("[object\n"
+   "firstBlock:^{\n"
+   "  a = 42;\n"
+   "}\n"
+   "blockWithLongerName:^{\n"
+   "  a = 42;\n"
+   "}];");
+  verifyFormat("[object\n"
+   "blockWithLongerName:^{\n"
+   "  a = 42;\n"
+   "}\n"
+   "secondBlock:^{\n"
+   "  a = 42;\n"
+   "}];");
+
   Style.ColumnLimit = 70;
   verifyFormat(
   "void f() {\n"
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -401,6 +401,8 @@
 if (Contexts.back().FirstObjCSelectorName) {
   Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
   Contexts.back().LongestObjCSelectorName;
+  Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts =
+  Left->ParameterCount;
   if (Left->BlockParameterCount > 1)
 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
 }
@@ -414,6 +416,7 @@
   TT_DesignatedInitializerLSquare)) {
   Left->Type = TT_ObjCMethodExpr;
   StartsObjCMethodExpr = true;
+  Left->ParameterCount = 0;
   Contexts.back().ColonIsObjCMethodExpr = true;
   if (Parent && Parent->is(tok::r_paren))
 Parent->Type = TT_CastRParen;
@@ -486,7 +489,10 @@
   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
   ++Left->BlockParameterCount;
-if (Current->is(tok::comma)) {
+if (Left->Type == TT_ObjCMethodExpr) {
+  if (Current->is(tok::colon))
+++Left->ParameterCount;
+} else if (Current->is(tok::comma)) {
   ++Left->ParameterCount;
   if (!Left->Role)
 Left->Role.reset(new CommaSeparatedList(Style));
Index: lib/Format/FormatToken.h
===
--- lib/Format/FormatToken.h
+++ lib/Format/FormatToken.h
@@ -240,6 +240,10 @@
   /// e.g. because several of them are block-type.
   unsigned LongestObjCSelectorName = 0;
 
+  /// \brief How many parts ObjC selector have (i.e. how many parameters method
+  /// has).
+  unsigned ObjCSelectorNameParts = 0;
+
   /// \brief Stores the number of required fake parentheses and the
   /// corresponding operator precedence.
   ///
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -266,6 +266,11 @@
 return true;
   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
 return true;
+  if (Style.Language == FormatStyle::LK_ObjC &&
+  Current.ObjCSelectorNameParts > 1 &&
+  Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
+return true;
+  }
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
 Style.isCpp() &&

[PATCH] D42464: add prefix with '_' support for property name. Corresponding apple dev doc: https://developer.apple.com/library/content/qa/qa1908/_index.html

2018-01-24 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added inline comments.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:52
 /// FIXME: provide fix for snake_case to snakeCase
-FixItHint generateFixItHint(const ObjCPropertyDecl *Decl) {
-  if (isupper(Decl->getName()[0])) {
-auto NewName = Decl->getName().str();
-NewName[0] = tolower(NewName[0]);
-return FixItHint::CreateReplacement(
-CharSourceRange::getTokenRange(SourceRange(Decl->getLocation())),
-llvm::StringRef(NewName));
+FixItHint generateFixItHint(const ObjCPropertyDecl *Decl, bool isCategory) {
+  auto Name = Decl->getName();

Instead of bool isCategory, how about an enum NamingStyle:

```
enum NamingStyle {
  StandardProperty = 1,
  CategoryProperty = 2,
}
```




Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:102
+bool hasCategoryPropertyPrefix(const llvm::StringRef &PropertyName) {
+  for (size_t i = 0; i < PropertyName.size() - 1; ++i) {
+if (PropertyName[i] == '_') {

I think this is an off-by-one error, right? Change:

  i < PropertyName.size() - 1

to

  i < PropertyName.size()




Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:103-105
+if (PropertyName[i] == '_') {
+  return true;
+}

Do we really want a leading _ to count? I think this might need to be a regular 
expression instead, something like:

  ^[a-zA-Z][a-zA-Z0-9]+_[a-zA-Z0-9][a-zA-Z0-9_]*$




Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:120
+  auto RegexExp = llvm::Regex(
+  llvm::StringRef(validPropertyNameRegex(Acronyms).replace(0, 2, "^")));
+  return RegexExp.match(llvm::StringRef(PropertyName.substr(Start + 1)));

I don't understand what this is doing. Why are we replacing things in a regex?

I don't think this is very maintainable. Can you rewrite it for legibility, 
please?



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:147
+  auto NodeKind = std::string(ParentContext->getDeclKindName());
+  if (NodeKind == "ObjCCategory" &&
+  hasCategoryPropertyPrefix(MatchedDecl->getName())) {

Is a class extension treated as a category? If so, we probably need to treat it 
specially.

e.g.:

Foo.h:

```
@interface Foo
@end
```

Foo.m:

```
@interface Foo ()
@property (nonatomic, readonly) int foo_bar;
@end
```

should not be allowed.

Can you handle this and add tests, please?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42464



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


r323345 - [CUDA] Disable PGO and coverage instrumentation in NVPTX.

2018-01-24 Thread Artem Belevich via cfe-commits
Author: tra
Date: Wed Jan 24 09:41:02 2018
New Revision: 323345

URL: http://llvm.org/viewvc/llvm-project?rev=323345&view=rev
Log:
[CUDA] Disable PGO and coverage instrumentation in NVPTX.

NVPTX does not have runtime support necessary for profiling to work
and even call arc collection is prohibitively expensive. Furthermore,
there's no easy way to collect the samples. NVPTX also does not
support global constructors that clang generates if sample/arc collection
is enabled.

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

Added:
cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu
Modified:
cfe/trunk/lib/Driver/ToolChains/Clang.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=323345&r1=323344&r2=323345&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Wed Jan 24 09:41:02 2018
@@ -3625,7 +3625,11 @@ void Clang::ConstructJob(Compilation &C,
   options::OPT_finstrument_function_entry_bare))
 A->render(Args, CmdArgs);
 
-  addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
+  // NVPTX doesn't support PGO or coverage. There's no runtime support for
+  // sampling, overhead of call arc collection is way too high and there's no
+  // way to collect the output.
+  if (!Triple.isNVPTX())
+addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
 
   if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
 ABICompatArg->render(Args, CmdArgs);

Added: cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu?rev=323345&view=auto
==
--- cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu (added)
+++ cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu Wed Jan 24 09:41:02 2018
@@ -0,0 +1,34 @@
+// Check that profiling/coverage arguments doen't get passed down to 
device-side
+// compilation.
+//
+// REQUIRES: clang-driver
+//
+// XRUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// XRUN:   -fprofile-generate %s 2>&1 | \
+// XRUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -fprofile-instr-generate %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -ftest-coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20   \
+// RUN:   -fprofile-instr-generate -fcoverage-mapping %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF,GCOV %s
+//
+//
+// CHECK-NOT: error: unsupported option '-fprofile
+// CHECK-NOT: error: invalid argument
+// CHECK-DAG: "-fcuda-is-device"
+// CHECK-NOT: "-f{{[^"]*coverage.*}}"
+// CHECK-NOT: "-fprofile{{[^"]*}}"
+// CHECK: "-triple" "x86_64--linux-gnu"
+// PROF-DAG: "-fprofile{{.*}}"
+// GCOV-DAG: "-f{{(coverage|emit-coverage).*}}"


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


[PATCH] D42452: [CUDA] Disable PGO and coverage instrumentation in NVPTX.

2018-01-24 Thread Artem Belevich via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323345: [CUDA] Disable PGO and coverage instrumentation in 
NVPTX. (authored by tra, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42452?vs=131170&id=131298#toc

Repository:
  rC Clang

https://reviews.llvm.org/D42452

Files:
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/cuda-no-pgo-or-coverage.cu


Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3625,7 +3625,11 @@
   options::OPT_finstrument_function_entry_bare))
 A->render(Args, CmdArgs);
 
-  addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
+  // NVPTX doesn't support PGO or coverage. There's no runtime support for
+  // sampling, overhead of call arc collection is way too high and there's no
+  // way to collect the output.
+  if (!Triple.isNVPTX())
+addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
 
   if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
 ABICompatArg->render(Args, CmdArgs);
Index: test/Driver/cuda-no-pgo-or-coverage.cu
===
--- test/Driver/cuda-no-pgo-or-coverage.cu
+++ test/Driver/cuda-no-pgo-or-coverage.cu
@@ -0,0 +1,34 @@
+// Check that profiling/coverage arguments doen't get passed down to 
device-side
+// compilation.
+//
+// REQUIRES: clang-driver
+//
+// XRUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// XRUN:   -fprofile-generate %s 2>&1 | \
+// XRUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -fprofile-instr-generate %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -ftest-coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20   \
+// RUN:   -fprofile-instr-generate -fcoverage-mapping %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF,GCOV %s
+//
+//
+// CHECK-NOT: error: unsupported option '-fprofile
+// CHECK-NOT: error: invalid argument
+// CHECK-DAG: "-fcuda-is-device"
+// CHECK-NOT: "-f{{[^"]*coverage.*}}"
+// CHECK-NOT: "-fprofile{{[^"]*}}"
+// CHECK: "-triple" "x86_64--linux-gnu"
+// PROF-DAG: "-fprofile{{.*}}"
+// GCOV-DAG: "-f{{(coverage|emit-coverage).*}}"


Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3625,7 +3625,11 @@
   options::OPT_finstrument_function_entry_bare))
 A->render(Args, CmdArgs);
 
-  addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
+  // NVPTX doesn't support PGO or coverage. There's no runtime support for
+  // sampling, overhead of call arc collection is way too high and there's no
+  // way to collect the output.
+  if (!Triple.isNVPTX())
+addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
 
   if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
 ABICompatArg->render(Args, CmdArgs);
Index: test/Driver/cuda-no-pgo-or-coverage.cu
===
--- test/Driver/cuda-no-pgo-or-coverage.cu
+++ test/Driver/cuda-no-pgo-or-coverage.cu
@@ -0,0 +1,34 @@
+// Check that profiling/coverage arguments doen't get passed down to device-side
+// compilation.
+//
+// REQUIRES: clang-driver
+//
+// XRUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// XRUN:   -fprofile-generate %s 2>&1 | \
+// XRUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -fprofile-instr-generate %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -ftest-coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20   \
+// RUN:   -fprofile-instr-generate -fcoverage-mapping %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF,GCOV %s
+//
+//
+// CHECK-NOT: error: unsupported option '-fprofile
+// CHECK-NOT: error: invalid argument
+// CHECK-DAG: "-fcuda-is-device"
+// CHECK-NOT: "-f{{[^"]*coverage.*}}"
+// CHECK-NOT: "-fprofile{{[^"]*}}"
+// CHECK: "-triple" "x86_64--linux-gnu"
+// PROF-DAG: "-fprofile{{.*}}"
+// GCOV-DAG: "-f{{(coverage|emit-coverag

[PATCH] D42452: [CUDA] Disable PGO and coverage instrumentation in NVPTX.

2018-01-24 Thread Artem Belevich via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323345: [CUDA] Disable PGO and coverage instrumentation in 
NVPTX. (authored by tra, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42452?vs=131170&id=131299#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42452

Files:
  cfe/trunk/lib/Driver/ToolChains/Clang.cpp
  cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu


Index: cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu
===
--- cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu
+++ cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu
@@ -0,0 +1,34 @@
+// Check that profiling/coverage arguments doen't get passed down to 
device-side
+// compilation.
+//
+// REQUIRES: clang-driver
+//
+// XRUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// XRUN:   -fprofile-generate %s 2>&1 | \
+// XRUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -fprofile-instr-generate %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -ftest-coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20   \
+// RUN:   -fprofile-instr-generate -fcoverage-mapping %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF,GCOV %s
+//
+//
+// CHECK-NOT: error: unsupported option '-fprofile
+// CHECK-NOT: error: invalid argument
+// CHECK-DAG: "-fcuda-is-device"
+// CHECK-NOT: "-f{{[^"]*coverage.*}}"
+// CHECK-NOT: "-fprofile{{[^"]*}}"
+// CHECK: "-triple" "x86_64--linux-gnu"
+// PROF-DAG: "-fprofile{{.*}}"
+// GCOV-DAG: "-f{{(coverage|emit-coverage).*}}"
Index: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp
@@ -3625,7 +3625,11 @@
   options::OPT_finstrument_function_entry_bare))
 A->render(Args, CmdArgs);
 
-  addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
+  // NVPTX doesn't support PGO or coverage. There's no runtime support for
+  // sampling, overhead of call arc collection is way too high and there's no
+  // way to collect the output.
+  if (!Triple.isNVPTX())
+addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
 
   if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
 ABICompatArg->render(Args, CmdArgs);


Index: cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu
===
--- cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu
+++ cfe/trunk/test/Driver/cuda-no-pgo-or-coverage.cu
@@ -0,0 +1,34 @@
+// Check that profiling/coverage arguments doen't get passed down to device-side
+// compilation.
+//
+// REQUIRES: clang-driver
+//
+// XRUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// XRUN:   -fprofile-generate %s 2>&1 | \
+// XRUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -fprofile-instr-generate %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 \
+// RUN:   -ftest-coverage %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,GCOV %s
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20   \
+// RUN:   -fprofile-instr-generate -fcoverage-mapping %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=CHECK,PROF,GCOV %s
+//
+//
+// CHECK-NOT: error: unsupported option '-fprofile
+// CHECK-NOT: error: invalid argument
+// CHECK-DAG: "-fcuda-is-device"
+// CHECK-NOT: "-f{{[^"]*coverage.*}}"
+// CHECK-NOT: "-fprofile{{[^"]*}}"
+// CHECK: "-triple" "x86_64--linux-gnu"
+// PROF-DAG: "-fprofile{{.*}}"
+// GCOV-DAG: "-f{{(coverage|emit-coverage).*}}"
Index: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp
@@ -3625,7 +3625,11 @@
   options::OPT_finstrument_function_entry_bare))
 A->render(Args, CmdArgs);
 
-  addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
+  // NVPTX doesn't support PGO or coverage. There's no runtime support for
+  // sampling, overhead of call arc collection is way too high and there's no
+  // way to collect the output.
+  if (!Triple.isNVP

[PATCH] D42428: [CodeComplete] only respect LoadExternal hint at namespace/tu scope

2018-01-24 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323347: [CodeComplete] only respect LoadExternal hint at 
namespace/tu scope (authored by sammccall, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42428

Files:
  cfe/trunk/include/clang-c/Index.h
  cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
  cfe/trunk/lib/Sema/SemaLookup.cpp
  cfe/trunk/test/Index/complete-pch-skip.cpp


Index: cfe/trunk/include/clang-c/Index.h
===
--- cfe/trunk/include/clang-c/Index.h
+++ cfe/trunk/include/clang-c/Index.h
@@ -5247,9 +5247,9 @@
   CXCodeComplete_IncludeBriefComments = 0x04,
 
   /**
-   * \brief Whether to speed up completion by omitting some entities which are
-   * defined in the preamble. There's no guarantee any particular entity will
-   * be omitted. This may be useful if the headers are indexed externally.
+   * Whether to speed up completion by omitting top- or namespace-level 
entities
+   * defined in the preamble. There's no guarantee any particular entity is
+   * omitted. This may be useful if the headers are indexed externally.
*/
   CXCodeComplete_SkipPreamble = 0x08
 };
Index: cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
===
--- cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
+++ cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
@@ -35,8 +35,8 @@
   /// Show brief documentation comments in code completion results.
   unsigned IncludeBriefComments : 1;
 
-  /// Hint whether to load data from the external AST in order to provide
-  /// full results. If false, declarations from the preamble may be omitted.
+  /// Hint whether to load data from the external AST to provide full results.
+  /// If false, namespace-level declarations from the preamble may be omitted.
   unsigned LoadExternal : 1;
 
   CodeCompleteOptions()
Index: cfe/trunk/test/Index/complete-pch-skip.cpp
===
--- cfe/trunk/test/Index/complete-pch-skip.cpp
+++ cfe/trunk/test/Index/complete-pch-skip.cpp
@@ -3,8 +3,9 @@
 }
 
 int main() { return ns:: }
+int main2() { return ns::foo(). }
 
-// RUN: echo "namespace ns { int foo; }" > %t.h
+// RUN: echo "namespace ns { struct foo { int baz }; }" > %t.h
 // RUN: c-index-test -write-pch %t.h.pch -x c++-header %t.h
 //
 // RUN: c-index-test -code-completion-at=%s:5:26 -include %t.h %s | FileCheck 
-check-prefix=WITH-PCH %s
@@ -23,3 +24,7 @@
 // NO-PCH: {TypedText bar}
 // NO-PCH-NOT: foo
 
+// Verify that we still get member results from the preamble.
+// RUN: env CINDEXTEST_COMPLETION_SKIP_PREAMBLE=1 c-index-test 
-code-completion-at=%s:6:32 -include %t.h %s | FileCheck -check-prefix=MEMBER %s
+// MEMBER: {TypedText baz}
+
Index: cfe/trunk/lib/Sema/SemaLookup.cpp
===
--- cfe/trunk/lib/Sema/SemaLookup.cpp
+++ cfe/trunk/lib/Sema/SemaLookup.cpp
@@ -3543,10 +3543,13 @@
   if (CXXRecordDecl *Class = dyn_cast(Ctx))
 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
 
+  // We sometimes skip loading namespace-level results (they tend to be huge).
+  bool Load = LoadExternal ||
+  !(isa(Ctx) || isa(Ctx));
   // Enumerate all of the results in this context.
   for (DeclContextLookupResult R :
-   LoadExternal ? Ctx->lookups()
-: Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
+   Load ? Ctx->lookups()
+: Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
 for (auto *D : R) {
   if (auto *ND = Result.getAcceptableDecl(D)) {
 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);


Index: cfe/trunk/include/clang-c/Index.h
===
--- cfe/trunk/include/clang-c/Index.h
+++ cfe/trunk/include/clang-c/Index.h
@@ -5247,9 +5247,9 @@
   CXCodeComplete_IncludeBriefComments = 0x04,
 
   /**
-   * \brief Whether to speed up completion by omitting some entities which are
-   * defined in the preamble. There's no guarantee any particular entity will
-   * be omitted. This may be useful if the headers are indexed externally.
+   * Whether to speed up completion by omitting top- or namespace-level entities
+   * defined in the preamble. There's no guarantee any particular entity is
+   * omitted. This may be useful if the headers are indexed externally.
*/
   CXCodeComplete_SkipPreamble = 0x08
 };
Index: cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
===
--- cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
+++ cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
@@ -35,8 +35,8 @@
   /// Show brief documentation comments in code completion results.
   unsigned IncludeBriefComments : 1;
 
-  /// Hint whether to load data fr

r323347 - [CodeComplete] only respect LoadExternal hint at namespace/tu scope

2018-01-24 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Wed Jan 24 09:50:20 2018
New Revision: 323347

URL: http://llvm.org/viewvc/llvm-project?rev=323347&view=rev
Log:
[CodeComplete] only respect LoadExternal hint at namespace/tu scope

Reviewers: ilya-biryukov

Subscribers: cfe-commits

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

Modified:
cfe/trunk/include/clang-c/Index.h
cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
cfe/trunk/lib/Sema/SemaLookup.cpp
cfe/trunk/test/Index/complete-pch-skip.cpp

Modified: cfe/trunk/include/clang-c/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang-c/Index.h?rev=323347&r1=323346&r2=323347&view=diff
==
--- cfe/trunk/include/clang-c/Index.h (original)
+++ cfe/trunk/include/clang-c/Index.h Wed Jan 24 09:50:20 2018
@@ -5247,9 +5247,9 @@ enum CXCodeComplete_Flags {
   CXCodeComplete_IncludeBriefComments = 0x04,
 
   /**
-   * \brief Whether to speed up completion by omitting some entities which are
-   * defined in the preamble. There's no guarantee any particular entity will
-   * be omitted. This may be useful if the headers are indexed externally.
+   * Whether to speed up completion by omitting top- or namespace-level 
entities
+   * defined in the preamble. There's no guarantee any particular entity is
+   * omitted. This may be useful if the headers are indexed externally.
*/
   CXCodeComplete_SkipPreamble = 0x08
 };

Modified: cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/CodeCompleteOptions.h?rev=323347&r1=323346&r2=323347&view=diff
==
--- cfe/trunk/include/clang/Sema/CodeCompleteOptions.h (original)
+++ cfe/trunk/include/clang/Sema/CodeCompleteOptions.h Wed Jan 24 09:50:20 2018
@@ -35,8 +35,8 @@ public:
   /// Show brief documentation comments in code completion results.
   unsigned IncludeBriefComments : 1;
 
-  /// Hint whether to load data from the external AST in order to provide
-  /// full results. If false, declarations from the preamble may be omitted.
+  /// Hint whether to load data from the external AST to provide full results.
+  /// If false, namespace-level declarations from the preamble may be omitted.
   unsigned LoadExternal : 1;
 
   CodeCompleteOptions()

Modified: cfe/trunk/lib/Sema/SemaLookup.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaLookup.cpp?rev=323347&r1=323346&r2=323347&view=diff
==
--- cfe/trunk/lib/Sema/SemaLookup.cpp (original)
+++ cfe/trunk/lib/Sema/SemaLookup.cpp Wed Jan 24 09:50:20 2018
@@ -3543,10 +3543,13 @@ static void LookupVisibleDecls(DeclConte
   if (CXXRecordDecl *Class = dyn_cast(Ctx))
 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
 
+  // We sometimes skip loading namespace-level results (they tend to be huge).
+  bool Load = LoadExternal ||
+  !(isa(Ctx) || isa(Ctx));
   // Enumerate all of the results in this context.
   for (DeclContextLookupResult R :
-   LoadExternal ? Ctx->lookups()
-: Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
+   Load ? Ctx->lookups()
+: Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
 for (auto *D : R) {
   if (auto *ND = Result.getAcceptableDecl(D)) {
 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);

Modified: cfe/trunk/test/Index/complete-pch-skip.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/complete-pch-skip.cpp?rev=323347&r1=323346&r2=323347&view=diff
==
--- cfe/trunk/test/Index/complete-pch-skip.cpp (original)
+++ cfe/trunk/test/Index/complete-pch-skip.cpp Wed Jan 24 09:50:20 2018
@@ -3,8 +3,9 @@ int bar;
 }
 
 int main() { return ns:: }
+int main2() { return ns::foo(). }
 
-// RUN: echo "namespace ns { int foo; }" > %t.h
+// RUN: echo "namespace ns { struct foo { int baz }; }" > %t.h
 // RUN: c-index-test -write-pch %t.h.pch -x c++-header %t.h
 //
 // RUN: c-index-test -code-completion-at=%s:5:26 -include %t.h %s | FileCheck 
-check-prefix=WITH-PCH %s
@@ -23,3 +24,7 @@ int main() { return ns:: }
 // NO-PCH: {TypedText bar}
 // NO-PCH-NOT: foo
 
+// Verify that we still get member results from the preamble.
+// RUN: env CINDEXTEST_COMPLETION_SKIP_PREAMBLE=1 c-index-test 
-code-completion-at=%s:6:32 -include %t.h %s | FileCheck -check-prefix=MEMBER %s
+// MEMBER: {TypedText baz}
+


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


[clang-tools-extra] r323350 - [clangd] add test for r323347 CodeComplete behavior we rely on

2018-01-24 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Wed Jan 24 09:53:32 2018
New Revision: 323350

URL: http://llvm.org/viewvc/llvm-project?rev=323350&view=rev
Log:
[clangd] add test for r323347 CodeComplete behavior we rely on

Modified:
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Modified: clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp?rev=323350&r1=323349&r2=323350&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp Wed Jan 24 
09:53:32 2018
@@ -537,12 +537,13 @@ TEST(CompletionTest, IndexSuppressesPrea
   /*StorePreamblesInMemory=*/true);
 
   FS.Files[getVirtualTestFilePath("bar.h")] =
-  R"cpp(namespace ns { int preamble; })cpp";
+  R"cpp(namespace ns { struct preamble { int member; }; })cpp";
   auto File = getVirtualTestFilePath("foo.cpp");
   Annotations Test(R"cpp(
   #include "bar.h"
   namespace ns { int local; }
-  void f() { ns::^ }
+  void f() { ns::^; }
+  void f() { ns::preamble().$2^; }
   )cpp");
   Server.addDocument(Context::empty(), File, Test.code()).wait();
   clangd::CodeCompleteOptions Opts = {};
@@ -562,6 +563,11 @@ TEST(CompletionTest, IndexSuppressesPrea
   .second.Value;
   EXPECT_THAT(WithIndex.items,
   UnorderedElementsAre(Named("local"), Named("index")));
+  auto ClassFromPreamble =
+  Server.codeComplete(Context::empty(), File, Test.point("2"), Opts)
+  .get()
+  .second.Value;
+  EXPECT_THAT(ClassFromPreamble.items, Contains(Named("member")));
 }
 
 TEST(CompletionTest, DynamicIndexMultiFile) {


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


[PATCH] D39571: [clangd] DidChangeConfiguration Notification

2018-01-24 Thread Simon Marchi via Phabricator via cfe-commits
simark updated this revision to Diff 131305.
simark added a comment.

Move implementation of setCompileCommandsDir to .cpp


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D39571

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/DraftStore.cpp
  clangd/DraftStore.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/GlobalCompilationDatabase.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/ProtocolHandlers.cpp
  clangd/ProtocolHandlers.h

Index: clangd/ProtocolHandlers.h
===
--- clangd/ProtocolHandlers.h
+++ clangd/ProtocolHandlers.h
@@ -57,6 +57,8 @@
   virtual void onRename(Ctx C, RenameParams &Parames) = 0;
   virtual void onDocumentHighlight(Ctx C,
TextDocumentPositionParams &Params) = 0;
+  virtual void onChangeConfiguration(Ctx C,
+ DidChangeConfigurationParams &Params) = 0;
 };
 
 void registerCallbackHandlers(JSONRPCDispatcher &Dispatcher, JSONOutput &Out,
Index: clangd/ProtocolHandlers.cpp
===
--- clangd/ProtocolHandlers.cpp
+++ clangd/ProtocolHandlers.cpp
@@ -73,4 +73,6 @@
   Register("workspace/executeCommand", &ProtocolCallbacks::onCommand);
   Register("textDocument/documentHighlight",
&ProtocolCallbacks::onDocumentHighlight);
+  Register("workspace/didChangeConfiguration",
+   &ProtocolCallbacks::onChangeConfiguration);
 }
Index: clangd/Protocol.h
===
--- clangd/Protocol.h
+++ clangd/Protocol.h
@@ -264,6 +264,20 @@
 };
 bool fromJSON(const json::Expr &, DidChangeWatchedFilesParams &);
 
+/// Clangd extension to manage a workspace/didChangeConfiguration notification
+/// since the data received is described as 'any' type in LSP.
+struct ClangdConfigurationParamsChange {
+  llvm::Optional compilationDatabasePath;
+};
+bool fromJSON(const json::Expr &, ClangdConfigurationParamsChange &);
+
+struct DidChangeConfigurationParams {
+  // We use this predefined struct because it is easier to use
+  // than the protocol specified type of 'any'.
+  ClangdConfigurationParamsChange settings;
+};
+bool fromJSON(const json::Expr &, DidChangeConfigurationParams &);
+
 struct FormattingOptions {
   /// Size of a tab in spaces.
   int tabSize;
Index: clangd/Protocol.cpp
===
--- clangd/Protocol.cpp
+++ clangd/Protocol.cpp
@@ -381,5 +381,15 @@
   };
 }
 
+bool fromJSON(const json::Expr &Params, DidChangeConfigurationParams &CCP) {
+  json::ObjectMapper O(Params);
+  return O && O.map("settings", CCP.settings);
+}
+
+bool fromJSON(const json::Expr &Params, ClangdConfigurationParamsChange &CCPC) {
+  json::ObjectMapper O(Params);
+  return O && O.map("compilationDatabasePath", CCPC.compilationDatabasePath);
+}
+
 } // namespace clangd
 } // namespace clang
Index: clangd/GlobalCompilationDatabase.h
===
--- clangd/GlobalCompilationDatabase.h
+++ clangd/GlobalCompilationDatabase.h
@@ -61,6 +61,8 @@
   /// Uses the default fallback command, adding any extra flags.
   tooling::CompileCommand getFallbackCommand(PathRef File) const override;
 
+  void setCompileCommandsDir(Path P);
+
   /// Sets the extra flags that should be added to a file.
   void setExtraFlagsForFile(PathRef File, std::vector ExtraFlags);
 
Index: clangd/GlobalCompilationDatabase.cpp
===
--- clangd/GlobalCompilationDatabase.cpp
+++ clangd/GlobalCompilationDatabase.cpp
@@ -52,6 +52,12 @@
   return C;
 }
 
+void DirectoryBasedGlobalCompilationDatabase::setCompileCommandsDir(Path P) {
+  std::lock_guard Lock(Mutex);
+  CompileCommandsDir = P;
+  CompilationDatabases.clear();
+}
+
 void DirectoryBasedGlobalCompilationDatabase::setExtraFlagsForFile(
 PathRef File, std::vector ExtraFlags) {
   std::lock_guard Lock(Mutex);
Index: clangd/DraftStore.h
===
--- clangd/DraftStore.h
+++ clangd/DraftStore.h
@@ -40,6 +40,10 @@
   /// \return version and contents of the stored document.
   /// For untracked files, a (0, None) pair is returned.
   VersionedDraft getDraft(PathRef File) const;
+
+  /// \return List of names of drafts in this store.
+  std::vector getActiveFiles() const;
+
   /// \return version of the tracked document.
   /// For untracked files, 0 is returned.
   DocVersion getVersion(PathRef File) const;
Index: clangd/DraftStore.cpp
===
--- clangd/DraftStore.cpp
+++ clangd/DraftStore.cpp
@@ -21,6 +21,16 @@
   return It->second;
 }
 
+std::vector DraftStore::getActiveFiles() const {
+  std::lock_guard Lock(Mutex);
+  std::vector ResultVector;
+
+  for (auto Draft : D

[PATCH] D40787: [clang-tidy] Replace the usage of std::uncaught_exception with std::uncaught_exceptions

2018-01-24 Thread Daniel Kolozsvari via Phabricator via cfe-commits
koldaniel added inline comments.
Herald added a subscriber: hintonda.



Comment at: test/clang-tidy/modernize-use-uncaught-exceptions.cpp:64
+  // CHECK-MESSAGES: [[@LINE-1]]:10: warning: 'std::uncaught_exception' is 
deprecated, use 'std::uncaught_exceptions' instead
+  // CHECK-FIXES: foo = &uncaught_exceptions;
+

aaron.ballman wrote:
> Applying this fix will break the code so that it no longer compiles.
True, declaration of foo should be changed from type bool to int too. Since as 
I can see this could cause a lot of problems, shouldn't be there only a warning 
without fixits?



Comment at: test/clang-tidy/modernize-use-uncaught-exceptions.cpp:68
+  // CHECK-MESSAGES: [[@LINE-1]]:22: warning: 'std::uncaught_exception' is 
deprecated, use 'std::uncaught_exceptions' instead
+  // CHECK-FIXES: res = doSomething2();
+

aaron.ballman wrote:
> This fix seems bad. If the user accepts the fix, then the code will diagnose 
> because there's no longer a matching call to `doSomething2()`.
Same type error as earlier, should a fix be applied (changing the type of the 
parameter in template definition would be unlucky too, maybe a wrapper function 
which could be passed to doSomething2() and does the conversion) or only a 
warning?


https://reviews.llvm.org/D40787



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


Re: [analyzer] Add support for __builtin_constant_p to BuiltinFunctionChecker

2018-01-24 Thread George Karpenkov via cfe-commits
Hi Felix,

If you would like to get the patch reviewed and committed the best way is to 
create a review in phabricator
(http://reviews.llvm.org) and add Devin Coughlin, me, and Artem Dergachev as 
reviewers.

> On Jan 16, 2018, at 7:30 PM, Vedant Kumar  wrote:
> 
> + Devin and George
> 
>> On Jan 14, 2018, at 10:44 AM, Felix Kostenzer via cfe-commits 
>>  wrote:
>> 
>> 
>> Hi,
>> 
>> Added evaluation of __builtin_constant_p to the dedicated StaticAnalyzer 
>> checker
>> along with a regression test.
>> 
>> 'make clang-test' results:
>> 
>> Testing Time: 335.63s
>> Expected Passes : 11769
>> Expected Failures : 19
>> Unsupported Tests : 50
>> 
>> - 
>> felix<0001-analyzer-add-builtin_constant_p-support.patch>___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
> 

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


[PATCH] D41938: [Analyzer] SValBuilder Comparison Rearrangement (with Restrictions and Analyzer Option)

2018-01-24 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

George's style comments are usually super spot-on. Please feel free to improve 
my code. Also it was only written as a proof-of-concept because i failed to 
explain my approach with natural language, so it definitely needs polishing. 
I'd let you know when i disagree with anything :)




Comment at: lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:472
+  if (BinaryOperator::isComparisonOp(Op) &&
+  Opts.shouldAggressivelySimplifyRelationalComparison()) {
+if (ResultTy != SVB.getConditionType())

george.karpenkov wrote:
> I am confused why the option `shouldAggressivelySimplifyRelationalComparison` 
> is checked here. Do we rewrite cases where `Op` is additive even if the 
> option is not checked? It's generally better to check the flag outside of the 
> rearranging function, so that the high-level logic can be seen.
> Do we rewrite cases where `Op` is additive even if the option is not checked?

Yes. Because for additive ops the presumably-expensive clamped-by-max/4 check 
is not necessary (and is indeed skipped below).

This should be documented though.



Comment at: test/Analysis/svalbuilder-rearrange-comparisons.c:19
+  if (x < -(((int)INT_MAX) / 4))
+exit(1);
+  return x;

george.karpenkov wrote:
> assert would express intent better
Yeah, but it's also a bit more painful to write in tests (i.e. 
`__builtin_assert()` and macros).



Comment at: test/Analysis/svalbuilder-rearrange-comparisons.c:28
+  clang_analyzer_dump(x == y);
+  // expected-warning@-1{{((conj_$2{int}) - (conj_$5{int})) == 0}}
+}

george.karpenkov wrote:
> Can we also have integration-like tests where rearrangement would affect 
> observable behavior?
> 
> Also, `clang_analyzer_dump` is a debugging function, and I am not sure 
> whether we should rely on its output in tests.
Yeah, this test would be painful to maintain if we change the dump output. I 
guess we definitely need more integration tests.

I still wish there were ways to write "this" sort of tests without relying on 
dumps. Eg.:
```
clang_analyzer_denote(x, "$x");
clang_analyzer_denote(y, "$y");
clang_analyzer_express(x == y); // expected-warning{{($x - $y) == 0}}
```
It should be easy to make an `SValVisitor` that does that.

Given how painful this would be to actually update these numerous tests, i'm 
fine with leaving a comment explaining the above, as a bit of technical debt - 
for anyone who would need to update them in the future.

We still need more integration tests though.



Comment at: test/Analysis/svalbuilder-rearrange-comparisons.c:100
+  clang_analyzer_dump(x == y);
+  // expected-warning@-1{{1 S32b}}
+}

This one, for instance, is essentially an integration test. You can easily 
replace the last dump with clang_analyzer_eval(x == y) and the test would still 
test the same thing. All tests here that expect a concrete integer in the last 
check should probably be just converted to clang_analyzer_eval tests.


https://reviews.llvm.org/D41938



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


r323360 - [Hexagon] Accept lowercase b in -hvx-length=64b and -hvx-length=128b

2018-01-24 Thread Krzysztof Parzyszek via cfe-commits
Author: kparzysz
Date: Wed Jan 24 10:42:19 2018
New Revision: 323360

URL: http://llvm.org/viewvc/llvm-project?rev=323360&view=rev
Log:
[Hexagon] Accept lowercase b in -hvx-length=64b and -hvx-length=128b

Modified:
cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp
cfe/trunk/test/Driver/hexagon-hvx.c

Modified: cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp?rev=323360&r1=323359&r2=323360&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp Wed Jan 24 10:42:19 2018
@@ -46,7 +46,7 @@ static void handleHVXWarnings(const Driv
   // Handle the unsupported values passed to mhvx-length.
   if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_length_EQ)) {
 StringRef Val = A->getValue();
-if (Val != "64B" && Val != "128B")
+if (!Val.equals_lower("64b") && !Val.equals_lower("128b"))
   D.Diag(diag::err_drv_unsupported_option_argument)
   << A->getOption().getName() << Val;
   }

Modified: cfe/trunk/test/Driver/hexagon-hvx.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/hexagon-hvx.c?rev=323360&r1=323359&r2=323360&view=diff
==
--- cfe/trunk/test/Driver/hexagon-hvx.c (original)
+++ cfe/trunk/test/Driver/hexagon-hvx.c Wed Jan 24 10:42:19 2018
@@ -21,6 +21,9 @@
 
 // RUN: %clang -c %s -### -target hexagon-unknown-elf -mv62 -mhvx \
 // RUN:  -mhvx-length=128B 2>&1 | FileCheck -check-prefix=CHECKHVX2 %s
+
+// RUN: %clang -c %s -### -target hexagon-unknown-elf -mv62 -mhvx \
+// RUN:  -mhvx-length=128b 2>&1 | FileCheck -check-prefix=CHECKHVX2 %s
 // CHECKHVX2-NOT: "-target-feature" "+hvx-length64b"
 // CHECKHVX2: "-target-feature" "+hvx-length128b"
 
@@ -79,8 +82,10 @@
 // The default mode on v60,v62 is 64B.
 // RUN: %clang -c %s -### -target hexagon-unknown-elf -mv60 -mhvx \
 // RUN:  2>&1 | FileCheck -check-prefix=CHECK-HVXLENGTH-64B %s
-// RUN: %clang -c %s -### -target hexagon-unknown-elf -mv60 -mhvx 
-mhvx-length=64B\
-// RUN:  2>&1 | FileCheck -check-prefix=CHECK-HVXLENGTH-64B %s
+// RUN: %clang -c %s -### -target hexagon-unknown-elf -mv60 -mhvx \
+// RUN:  -mhvx-length=64b 2>&1 | FileCheck -check-prefix=CHECK-HVXLENGTH-64B %s
+// RUN: %clang -c %s -### -target hexagon-unknown-elf -mv60 -mhvx \
+// RUN:  -mhvx-length=64B 2>&1 | FileCheck -check-prefix=CHECK-HVXLENGTH-64B %s
 // CHECK-HVXLENGTH-64B: "-target-feature" "+hvx{{.*}}" "-target-feature" 
"+hvx-length64b"
 // RUN: %clang -c %s -### -target hexagon-unknown-elf -mv62 -mhvx 
-mhvx-length=128B\
 // RUN:  2>&1 | FileCheck -check-prefix=CHECK-HVXLENGTH-128B %s


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


r323361 - Don't create hidden dllimport global values.

2018-01-24 Thread Rafael Espindola via cfe-commits
Author: rafael
Date: Wed Jan 24 10:58:32 2018
New Revision: 323361

URL: http://llvm.org/viewvc/llvm-project?rev=323361&view=rev
Log:
Don't create hidden dllimport global values.

Hidden visibility is almost the opposite of dllimport. We were
producing them before (dllimport wins in the existing llvm
implementation), but now the llvm verifier produces an error.

Added:
cfe/trunk/test/CodeGenCXX/hidden-dllimport.cpp
Modified:
cfe/trunk/lib/CodeGen/CodeGenModule.cpp

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=323361&r1=323360&r2=323361&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Wed Jan 24 10:58:32 2018
@@ -694,6 +694,8 @@ llvm::ConstantInt *CodeGenModule::getSiz
 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
 const NamedDecl *D,
 ForDefinition_t IsForDefinition) const 
{
+  if (GV->hasDLLImportStorageClass())
+return;
   // Internal definitions always have default visibility.
   if (GV->hasLocalLinkage()) {
 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);

Added: cfe/trunk/test/CodeGenCXX/hidden-dllimport.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/hidden-dllimport.cpp?rev=323361&view=auto
==
--- cfe/trunk/test/CodeGenCXX/hidden-dllimport.cpp (added)
+++ cfe/trunk/test/CodeGenCXX/hidden-dllimport.cpp Wed Jan 24 10:58:32 2018
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -emit-llvm 
-fvisibility-inlines-hidden -o - %s | FileCheck %s
+
+// We used to declare this hidden dllimport, which is contradictory.
+
+// CHECK: declare dllimport void @"\01?bar@foo@@QEAAXXZ"(%struct.foo*)
+
+struct __attribute__((dllimport)) foo {
+  void bar() {}
+};
+void zed(foo *p) { p->bar(); }


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


r323362 - IRGen: Emit an inline implementation of __builtin_wmemcmp on MSVCRT platforms.

2018-01-24 Thread Peter Collingbourne via cfe-commits
Author: pcc
Date: Wed Jan 24 10:59:58 2018
New Revision: 323362

URL: http://llvm.org/viewvc/llvm-project?rev=323362&view=rev
Log:
IRGen: Emit an inline implementation of __builtin_wmemcmp on MSVCRT platforms.

The MSVC runtime library does not provide a definition of wmemcmp,
so we need an inline implementation.

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

Added:
cfe/trunk/test/CodeGen/wmemcmp.c
Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=323362&r1=323361&r2=323362&view=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Wed Jan 24 10:59:58 2018
@@ -1741,6 +1741,63 @@ RValue CodeGenFunction::EmitBuiltinExpr(
 Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
 return RValue::get(Dest.getPointer());
   }
+  case Builtin::BI__builtin_wmemcmp: {
+// The MSVC runtime library does not provide a definition of wmemcmp, so we
+// need an inline implementation.
+if (!getTarget().getTriple().isOSMSVCRT())
+  break;
+
+llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
+
+Value *Dst = EmitScalarExpr(E->getArg(0));
+Value *Src = EmitScalarExpr(E->getArg(1));
+Value *Size = EmitScalarExpr(E->getArg(2));
+
+BasicBlock *Entry = Builder.GetInsertBlock();
+BasicBlock *CmpGT = createBasicBlock("wmemcmp.gt");
+BasicBlock *CmpLT = createBasicBlock("wmemcmp.lt");
+BasicBlock *Next = createBasicBlock("wmemcmp.next");
+BasicBlock *Exit = createBasicBlock("wmemcmp.exit");
+Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
+Builder.CreateCondBr(SizeEq0, Exit, CmpGT);
+
+EmitBlock(CmpGT);
+PHINode *DstPhi = Builder.CreatePHI(Dst->getType(), 2);
+DstPhi->addIncoming(Dst, Entry);
+PHINode *SrcPhi = Builder.CreatePHI(Src->getType(), 2);
+SrcPhi->addIncoming(Src, Entry);
+PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
+SizePhi->addIncoming(Size, Entry);
+CharUnits WCharAlign =
+getContext().getTypeAlignInChars(getContext().WCharTy);
+Value *DstCh = Builder.CreateAlignedLoad(WCharTy, DstPhi, WCharAlign);
+Value *SrcCh = Builder.CreateAlignedLoad(WCharTy, SrcPhi, WCharAlign);
+Value *DstGtSrc = Builder.CreateICmpUGT(DstCh, SrcCh);
+Builder.CreateCondBr(DstGtSrc, Exit, CmpLT);
+
+EmitBlock(CmpLT);
+Value *DstLtSrc = Builder.CreateICmpULT(DstCh, SrcCh);
+Builder.CreateCondBr(DstLtSrc, Exit, Next);
+
+EmitBlock(Next);
+Value *NextDst = Builder.CreateConstInBoundsGEP1_32(WCharTy, DstPhi, 1);
+Value *NextSrc = Builder.CreateConstInBoundsGEP1_32(WCharTy, SrcPhi, 1);
+Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
+Value *NextSizeEq0 =
+Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
+Builder.CreateCondBr(NextSizeEq0, Exit, CmpGT);
+DstPhi->addIncoming(NextDst, Next);
+SrcPhi->addIncoming(NextSrc, Next);
+SizePhi->addIncoming(NextSize, Next);
+
+EmitBlock(Exit);
+PHINode *Ret = Builder.CreatePHI(IntTy, 4);
+Ret->addIncoming(ConstantInt::get(IntTy, 0), Entry);
+Ret->addIncoming(ConstantInt::get(IntTy, 1), CmpGT);
+Ret->addIncoming(ConstantInt::get(IntTy, -1), CmpLT);
+Ret->addIncoming(ConstantInt::get(IntTy, 0), Next);
+return RValue::get(Ret);
+  }
   case Builtin::BI__builtin_dwarf_cfa: {
 // The offset in bytes from the first argument to the CFA.
 //

Added: cfe/trunk/test/CodeGen/wmemcmp.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/wmemcmp.c?rev=323362&view=auto
==
--- cfe/trunk/test/CodeGen/wmemcmp.c (added)
+++ cfe/trunk/test/CodeGen/wmemcmp.c Wed Jan 24 10:59:58 2018
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 %s -triple x86_64-pc-win32 -emit-llvm -o - | FileCheck %s
+
+typedef __SIZE_TYPE__ size_t;
+typedef __WCHAR_TYPE__ wchar_t;
+
+int wmemcmp_test(const wchar_t *s1, const wchar_t *s2, size_t n) {
+  // CHECK: [[S1:%.*]] = load
+  // CHECK: [[S2:%.*]] = load
+  // CHECK: [[N:%.*]] = load
+  // CHECK: [[N0:%.*]] = icmp eq i64 [[N]], 0
+  // CHECK: br i1 [[N0]], label %[[EXIT:.*]], label %[[GT:.*]]
+
+  // CHECK: [[GT]]:
+  // CHECK: [[S1P:%.*]] = phi i16* [ [[S1]], %[[ENTRY:.*]] ], [ [[S1N:.*]], 
%[[NEXT:.*]] ]
+  // CHECK: [[S2P:%.*]] = phi i16* [ [[S2]], %[[ENTRY]] ], [ [[S2N:.*]], 
%[[NEXT]] ]
+  // CHECK: [[NP:%.*]] = phi i64 [ [[N]], %[[ENTRY]] ], [ [[NN:.*]], %[[NEXT]] 
]
+  // CHECK: [[S1L:%.*]] = load i16, i16* [[S1P]], align 2
+  // CHECK: [[S2L:%.*]] = load i16, i16* [[S2P]], align 2
+  // CHECK: [[CMPGT:%.*]] = icmp ugt i16 [[S1L]], [[S2L]]
+  // CHECK: br i1 [[CMPGT]], label %[[EXIT]], label %[[LT:.*]]
+
+  // CHECK: [[LT]]:
+  // CHECK: [[CMPLT:%.*]] = icmp ult i16 [[S1L]], [[S2L

[PATCH] D42455: Don't create hidden dllimport global values

2018-01-24 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola closed this revision.
espindola added a comment.

323361


https://reviews.llvm.org/D42455



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


[PATCH] D40787: [clang-tidy] Replace the usage of std::uncaught_exception with std::uncaught_exceptions

2018-01-24 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: test/clang-tidy/modernize-use-uncaught-exceptions.cpp:64
+  // CHECK-MESSAGES: [[@LINE-1]]:10: warning: 'std::uncaught_exception' is 
deprecated, use 'std::uncaught_exceptions' instead
+  // CHECK-FIXES: foo = &uncaught_exceptions;
+

koldaniel wrote:
> aaron.ballman wrote:
> > Applying this fix will break the code so that it no longer compiles.
> True, declaration of foo should be changed from type bool to int too. Since 
> as I can see this could cause a lot of problems, shouldn't be there only a 
> warning without fixits?
I think the right approach here is to warn and not suggest a fix-it.



Comment at: test/clang-tidy/modernize-use-uncaught-exceptions.cpp:68
+  // CHECK-MESSAGES: [[@LINE-1]]:22: warning: 'std::uncaught_exception' is 
deprecated, use 'std::uncaught_exceptions' instead
+  // CHECK-FIXES: res = doSomething2();
+

koldaniel wrote:
> aaron.ballman wrote:
> > This fix seems bad. If the user accepts the fix, then the code will 
> > diagnose because there's no longer a matching call to `doSomething2()`.
> Same type error as earlier, should a fix be applied (changing the type of the 
> parameter in template definition would be unlucky too, maybe a wrapper 
> function which could be passed to doSomething2() and does the conversion) or 
> only a warning?
Similarly, I would only warn here as well, and not suggest a fix-it.


https://reviews.llvm.org/D40787



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


[PATCH] D42464: add prefix with '_' support for property name. Corresponding apple dev doc: https://developer.apple.com/library/content/qa/qa1908/_index.html

2018-01-24 Thread Yan Zhang via Phabricator via cfe-commits
Wizard added inline comments.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:102
+bool hasCategoryPropertyPrefix(const llvm::StringRef &PropertyName) {
+  for (size_t i = 0; i < PropertyName.size() - 1; ++i) {
+if (PropertyName[i] == '_') {

benhamilton wrote:
> I think this is an off-by-one error, right? Change:
> 
>   i < PropertyName.size() - 1
> 
> to
> 
>   i < PropertyName.size()
> 
I was thinking of not letting go anything that ends with "_" otherwise I have 
to do more sanity check later.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:103-105
+if (PropertyName[i] == '_') {
+  return true;
+}

benhamilton wrote:
> Do we really want a leading _ to count? I think this might need to be a 
> regular expression instead, something like:
> 
>   ^[a-zA-Z][a-zA-Z0-9]+_[a-zA-Z0-9][a-zA-Z0-9_]*$
> 
Yes it is better to use a regex instead. I would use 
^[a-z]+_[a-zA-Z0-9][a-zA-Z0-9_]+$ to make sure we are not having anything like 
foo_



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:120
+  auto RegexExp = llvm::Regex(
+  llvm::StringRef(validPropertyNameRegex(Acronyms).replace(0, 2, "^")));
+  return RegexExp.match(llvm::StringRef(PropertyName.substr(Start + 1)));

benhamilton wrote:
> I don't understand what this is doing. Why are we replacing things in a regex?
> 
> I don't think this is very maintainable. Can you rewrite it for legibility, 
> please?
It is a little awkward here because in the matcher, the regex use "::" to 
indicate matching start, but in llvm::regex it is the conventional "^". I will 
add some comments here.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42464



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


[PATCH] D42457: [analyzer] Don't communicate evaluation failures through memregion hierarchy.

2018-01-24 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h:572
+bool IsConstructorWithImproperlyModeledTargetRegion : 1;
+bool IsArrayConstructorOrDestructor : 1;
+  };

george.karpenkov wrote:
> OK my C++ knowledge is weak here.
>  What happens if you don't initialize those at the callsite and then read? 
> Wouldn't be safer to set them both to false in the declaration?
Yeah, i guess i'd add a constructor. Unfortunately inline initialization for 
bitfields is not available until `C++20`. So i hope we'd be able to get rid of 
this construct before we switch to C++20 =)



Comment at: include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h:661
+  /// When the lookahead fails, a temporary region is returned, and a flag is
+  /// set in \p Flags.
   const MemRegion *getRegionForConstructedObject(const CXXConstructExpr *CE,

george.karpenkov wrote:
> Which flag?
The //respective// flag. To be exact, the 
`IntentionallyLongTemporaryFlagNameThatNobodyWouldEverBotherToReadCorrectly` 
one :)

Fxd thx :)


https://reviews.llvm.org/D42457



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


[PATCH] D42457: [analyzer] Don't communicate evaluation failures through memregion hierarchy.

2018-01-24 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 131321.
NoQ marked 8 inline comments as done.
NoQ added a comment.

Address comments.


https://reviews.llvm.org/D42457

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  test/Analysis/new.cpp

Index: test/Analysis/new.cpp
===
--- test/Analysis/new.cpp
+++ test/Analysis/new.cpp
@@ -311,8 +311,7 @@
 void testArrayDestr() {
   NoReturnDtor *p = new NoReturnDtor[2];
   delete[] p; // Calls the base destructor which aborts, checked below
-  //TODO: clang_analyzer_eval should not be called
-  clang_analyzer_eval(true); // expected-warning{{TRUE}}
+  clang_analyzer_eval(true); // no-warning
 }
 
 // Invalidate Region even in case of default destructor
Index: lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
+++ lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
@@ -622,9 +622,9 @@
   CIP_DisallowedAlways
 };
 
-static CallInlinePolicy mayInlineCallKind(const CallEvent &Call,
-  const ExplodedNode *Pred,
-  AnalyzerOptions &Opts) {
+static CallInlinePolicy
+mayInlineCallKind(const CallEvent &Call, const ExplodedNode *Pred,
+  AnalyzerOptions &Opts, ExprEngine::EvalCallOptions CallOpts) {
   const LocationContext *CurLC = Pred->getLocationContext();
   const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame();
   switch (Call.getKind()) {
@@ -658,18 +658,8 @@
 // initializers for array fields in default move/copy constructors.
 // We still allow construction into ElementRegion targets when they don't
 // represent array elements.
-const MemRegion *Target = Ctor.getCXXThisVal().getAsRegion();
-if (Target && isa(Target)) {
-  if (ParentExpr)
-if (const CXXNewExpr *NewExpr = dyn_cast(ParentExpr))
-  if (NewExpr->isArray())
-return CIP_DisallowedOnce;
-
-  if (const TypedValueRegion *TR = dyn_cast(
-  cast(Target)->getSuperRegion()))
-if (TR->getValueType()->isArrayType())
-  return CIP_DisallowedOnce;
-}
+if (CallOpts.IsArrayConstructorOrDestructor)
+  return CIP_DisallowedOnce;
 
 // Inlining constructors requires including initializers in the CFG.
 const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
@@ -688,7 +678,7 @@
 // FIXME: This is a hack. We don't handle temporary destructors
 // right now, so we shouldn't inline their constructors.
 if (CtorExpr->getConstructionKind() == CXXConstructExpr::CK_Complete)
-  if (!Target || isa(Target))
+  if (CallOpts.IsConstructorWithImproperlyModeledTargetRegion)
 return CIP_DisallowedOnce;
 
 break;
@@ -702,11 +692,8 @@
 assert(ADC->getCFGBuildOptions().AddImplicitDtors && "No CFG destructors");
 (void)ADC;
 
-const CXXDestructorCall &Dtor = cast(Call);
-
 // FIXME: We don't handle constructors or destructors for arrays properly.
-const MemRegion *Target = Dtor.getCXXThisVal().getAsRegion();
-if (Target && isa(Target))
+if (CallOpts.IsArrayConstructorOrDestructor)
   return CIP_DisallowedOnce;
 
 break;
@@ -847,7 +834,8 @@
 }
 
 bool ExprEngine::shouldInlineCall(const CallEvent &Call, const Decl *D,
-  const ExplodedNode *Pred) {
+  const ExplodedNode *Pred,
+  EvalCallOptions CallOpts) {
   if (!D)
 return false;
 
@@ -894,7 +882,7 @@
   // FIXME: this checks both static and dynamic properties of the call, which
   // means we're redoing a bit of work that could be cached in the function
   // summary.
-  CallInlinePolicy CIP = mayInlineCallKind(Call, Pred, Opts);
+  CallInlinePolicy CIP = mayInlineCallKind(Call, Pred, Opts, CallOpts);
   if (CIP != CIP_Allowed) {
 if (CIP == CIP_DisallowedAlways) {
   assert(!MayInline.hasValue() || MayInline.getValue());
@@ -946,7 +934,8 @@
 }
 
 void ExprEngine::defaultEvalCall(NodeBuilder &Bldr, ExplodedNode *Pred,
- const CallEvent &CallTemplate) {
+ const CallEvent &CallTemplate,
+ EvalCallOptions CallOpts) {
   // Make sure we have the most recent state attached to the call.
   ProgramStateRef State = Pred->getState();
   CallEventRef<> Call = CallTemplate.cloneWithState(State);
@@ -969,7 +958,7 @@
   } else {
 RuntimeDefinition RD = Call->getRuntimeDefinition();
 const Decl *D = RD.getDecl();
-if (shouldInlineCall(*Call, D, Pred)) {
+if (shouldInlineCall(*Call, D, Pred, CallOpts)) {
   if (RD.mayHaveOtherDefinitions()) {
 AnalyzerOptions &Options = getAnalysisManager().options;

r323368 - Revert r323051 "[cmake] Use CLANG_BINARY_DIR to determine the build directory."

2018-01-24 Thread Vassil Vassilev via cfe-commits
Author: vvassilev
Date: Wed Jan 24 11:26:50 2018
New Revision: 323368

URL: http://llvm.org/viewvc/llvm-project?rev=323368&view=rev
Log:
Revert r323051 "[cmake] Use CLANG_BINARY_DIR to determine the build directory."

This broke swift builds.

Thanks for the post-commit review of Chris Bieneman and Davide Italiano!

Modified:
cfe/trunk/cmake/modules/CMakeLists.txt

Modified: cfe/trunk/cmake/modules/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/cmake/modules/CMakeLists.txt?rev=323368&r1=323367&r2=323368&view=diff
==
--- cfe/trunk/cmake/modules/CMakeLists.txt (original)
+++ cfe/trunk/cmake/modules/CMakeLists.txt Wed Jan 24 11:26:50 2018
@@ -2,7 +2,7 @@
 # link against them. LLVM calls its version of this file LLVMExports.cmake, but
 # the usual CMake convention seems to be ${Project}Targets.cmake.
 set(CLANG_INSTALL_PACKAGE_DIR lib${LLVM_LIBDIR_SUFFIX}/cmake/clang)
-set(clang_cmake_builddir "${CLANG_BINARY_DIR}/${CLANG_INSTALL_PACKAGE_DIR}")
+set(clang_cmake_builddir "${CMAKE_BINARY_DIR}/${CLANG_INSTALL_PACKAGE_DIR}")
 
 # Keep this in sync with llvm/cmake/CMakeLists.txt!
 set(LLVM_INSTALL_PACKAGE_DIR lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm)


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


[PATCH] D42497: clang-cl: Simplify handling of /arch: flag.

2018-01-24 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: rnk.
Herald added subscribers: fedor.sergeev, kristof.beyls, sdardis, emaste, 
aemerson.

r213083 initially implemented /arch: support by mapping it to CPU features. 
Then r241077 additionally mapped it to CPU, which made the feature flags 
redundant (if harmless). This change here removes the redundant mapping to 
feature flags, and rewrites test/Driver/cl-x86-flags.c to be a bit more of an 
integration test that checks for preprocessor defines like __AVX__ (like 
documented on MSDN) instead of for driver flags.

To keep emitting `warn_drv_unused_argument` we need to pipe a Driver to 
getX86TargetCPU() which makes the patch look larger than it is. The interesting 
bit is the change to X86.cpp, and to the test.

No intended behavior change.

This is in preparation for adding support for /arch:AVX512(F).


https://reviews.llvm.org/D42497

Files:
  lib/Driver/ToolChains/Arch/Mips.cpp
  lib/Driver/ToolChains/Arch/Mips.h
  lib/Driver/ToolChains/Arch/X86.cpp
  lib/Driver/ToolChains/Arch/X86.h
  lib/Driver/ToolChains/Clang.cpp
  lib/Driver/ToolChains/CommonArgs.cpp
  lib/Driver/ToolChains/CommonArgs.h
  lib/Driver/ToolChains/FreeBSD.cpp
  lib/Driver/ToolChains/Gnu.cpp
  lib/Driver/ToolChains/Linux.cpp
  lib/Driver/ToolChains/NetBSD.cpp
  lib/Driver/ToolChains/OpenBSD.cpp
  test/Driver/cl-x86-flags.c

Index: test/Driver/cl-x86-flags.c
===
--- test/Driver/cl-x86-flags.c
+++ test/Driver/cl-x86-flags.c
@@ -1,88 +1,92 @@
 // REQUIRES: x86-registered-target
 
+// expected-no-diagnostics
+
 // We support -m32 and -m64.  We support all x86 CPU feature flags in gcc's -m
 // flag space.
 // RUN: %clang_cl /Zs /WX -m32 -m64 -msse3 -msse4.1 -mavx -mno-avx \
 // RUN: --target=i386-pc-win32 -### -- 2>&1 %s | FileCheck -check-prefix=MFLAGS %s
 // MFLAGS-NOT: argument unused during compilation
 
-// RUN: %clang_cl -m32 -arch:IA32 --target=i386 -### -- 2>&1 %s | FileCheck -check-prefix=IA32 %s
-// IA32: "-target-cpu" "i386"
-// IA32-NOT: -target-feature
-// IA32-NOT: argument unused during compilation
+// RUN: %clang_cl -m32 -arch:IA32 --target=i386-pc-windows /c -Xclang -verify -DTEST_32_ARCH_IA32 -- %s
+#if defined(TEST_32_ARCH_IA32)
+#if _M_IX86_FP || __AVX__ || __AVX2__ || __AVX512F__  || __AVX512BW__
+#error fail
+#endif
+#endif
 
-// RUN: %clang_cl -m32 -arch:ia32 --target=i386 -### -- 2>&1 %s | FileCheck -check-prefix=ia32 %s
+// arch: args are case-sensitive.
+// RUN: %clang_cl -m32 -arch:ia32 --target=i386-pc-windows -### -- 2>&1 %s | FileCheck -check-prefix=ia32 %s
 // ia32: argument unused during compilation
-// ia32-NOT: -target-feature
 
-// RUN: %clang_cl -m64 -arch:IA32 --target=x86_64 -### -- 2>&1 %s | FileCheck -check-prefix=IA3264 %s
+// RUN: %clang_cl -m64 -arch:IA32 --target=x86_64-pc-windows -### -- 2>&1 %s | FileCheck -check-prefix=IA3264 %s
 // IA3264: argument unused during compilation
-// IA3264-NOT: -target-feature
 
-// RUN: %clang_cl -m32 -arch:SSE --target=i386 -### -- 2>&1 %s | FileCheck -check-prefix=SSE %s
-// SSE: "-target-cpu" "pentium3"
-// SSE: -target-feature
-// SSE: +sse
-// SSE-NOT: argument unused during compilation
+// RUN: %clang_cl -m32 -arch:SSE --target=i386-pc-windows /c -Xclang -verify -DTEST_32_ARCH_SSE -- %s
+#if defined(TEST_32_ARCH_SSE)
+#if _M_IX86_FP != 1 || __AVX__ || __AVX2__ || __AVX512F__  || __AVX512BW__
+#error fail
+#endif
+#endif
 
-// RUN: %clang_cl -m32 -arch:sse --target=i386 -### -- 2>&1 %s | FileCheck -check-prefix=sse %s
+// RUN: %clang_cl -m32 -arch:sse --target=i386-pc-windows -### -- 2>&1 %s | FileCheck -check-prefix=sse %s
 // sse: argument unused during compilation
-// sse-NOT: -target-feature
 
-// RUN: %clang_cl -m32 -arch:SSE2 --target=i386 -### -- 2>&1 %s | FileCheck -check-prefix=SSE2 %s
-// SSE2: "-target-cpu" "pentium4"
-// SSE2: -target-feature
-// SSE2: +sse2
-// SSE2-NOT: argument unused during compilation
+// RUN: %clang_cl -m32 -arch:SSE2 --target=i386-pc-windows /c -Xclang -verify -DTEST_32_ARCH_SSE2 -- %s
+#if defined(TEST_32_ARCH_SSE2)
+#if _M_IX86_FP != 2 || __AVX__ || __AVX2__ || __AVX512F__  || __AVX512BW__
+#error fail
+#endif
+#endif
 
-// RUN: %clang_cl -m32 -arch:sse2 --target=i386 -### -- 2>&1 %s | FileCheck -check-prefix=sse %s
+// RUN: %clang_cl -m32 -arch:sse2 --target=i386-pc-windows -### -- 2>&1 %s | FileCheck -check-prefix=sse %s
 // sse2: argument unused during compilation
-// sse2-NOT: -target-feature
 
-// RUN: %clang_cl -m64 -arch:SSE --target=x86_64 -### -- 2>&1 %s | FileCheck -check-prefix=SSE64 %s
+// RUN: %clang_cl -m64 -arch:SSE --target=x86_64-pc-windows -### -- 2>&1 %s | FileCheck -check-prefix=SSE64 %s
 // SSE64: argument unused during compilation
-// SSE64-NOT: -target-feature
-// SSE64-NOT: pentium3
 
-// RUN: %clang_cl -m64 -arch:SSE2 --target=x86_64 -### -- 2>&1 %s | FileCheck -check-prefix=SSE264 %s
+// RUN: %clang_cl -m64 -arch:SSE2 --target=x86_64-pc-windows -### -- 2>&1 %s | FileCheck -ch

[PATCH] D42498: [ExprConstant] Fix crash when initialize an indirect field with another field.

2018-01-24 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: rsmith, efriedma.

When indirect field is initialized with another field, you have
MemberExpr with CXXThisExpr that corresponds to the field's immediate
anonymous parent. But 'this' was referring to the non-anonymous parent.
So when we were building LValue Designator, it was incorrect as it had
wrong starting point. Usage of such designator would cause unexpected
APValue changes and crashes.

The fix is in adjusting 'this' for indirect fields from non-anonymous
parent to the field's immediate parent.

Discovered by OSS-Fuzz:
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=4985

rdar://problem/36359187


https://reviews.llvm.org/D42498

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constant-expression-cxx1y.cpp

Index: clang/test/SemaCXX/constant-expression-cxx1y.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx1y.cpp
+++ clang/test/SemaCXX/constant-expression-cxx1y.cpp
@@ -1021,3 +1021,44 @@
 }
 static_assert(evalNested(), "");
 } // namespace PR19741
+
+namespace IndirectFields {
+
+// Reference indirect field.
+struct A {
+  struct {
+union {
+  int x = x = 3; // expected-note {{outside its lifetime}}
+};
+  };
+  constexpr A() {}
+};
+static_assert(A().x == 3, ""); // expected-error{{not an integral constant expression}} expected-note{{in call to 'A()'}}
+
+// Reference another indirect field, with different 'this'.
+struct B {
+  struct {
+union {
+  int x = 3;
+};
+int y = x;
+  };
+  constexpr B() {}
+};
+static_assert(B().y == 3, "");
+
+// Nested evaluation of indirect field initializers.
+struct C {
+  union {
+int x = 1;
+  };
+};
+struct D {
+  struct {
+C c;
+int y = c.x + 1;
+  };
+};
+static_assert(D().y == 2, "");
+
+} // namespace IndirectFields
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -449,6 +449,9 @@
 /// Index - The call index of this call.
 unsigned Index;
 
+/// IndirectField - The indirect field being evaluated.
+const IndirectFieldDecl *IndirectField = nullptr;
+
 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
 // on the overall stack usage of deeply-recursing constexpr evaluataions.
 // (We should cache this map rather than recomputing it repeatedly.)
@@ -4370,6 +4373,7 @@
   for (const auto *I : Definition->inits()) {
 LValue Subobject = This;
 APValue *Value = &Result;
+Frame.IndirectField = nullptr;
 
 // Determine the subobject to initialize.
 FieldDecl *FD = nullptr;
@@ -4399,6 +4403,7 @@
 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
   // Walk the indirect field decl's chain to find the object to initialize,
   // and make sure we've initialized every step along it.
+  Frame.IndirectField = IFD;
   for (auto *C : IFD->chain()) {
 FD = cast(C);
 CXXRecordDecl *CD = cast(FD->getParent());
@@ -4437,6 +4442,7 @@
   Success = false;
 }
   }
+  Frame.IndirectField = nullptr;
 
   return Success &&
  EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
@@ -5612,6 +5618,20 @@
 
 Result.setFrom(Info.Ctx, RVal);
   }
+} else if (Info.CurrentCall->IndirectField) {
+  // Fields of anonymous structs/unions can refer to other fields. In this
+  // case the 'this' expression corresponds to anonymous struct/union but
+  // Info.CurrentCall->This corresponds to the field's non-anonymous parent.
+  for (auto *C : Info.CurrentCall->IndirectField->chain()) {
+const FieldDecl *FD = cast(C);
+if (!FD->isImplicit()) {
+  assert(E->getType()->getPointeeCXXRecordDecl() == FD->getParent() &&
+ "Should adjust LValue to refer to the same 'this'");
+  break;
+}
+if (!HandleLValueMember(Info, E, Result, FD))
+  return false;
+  }
 }
 return true;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323370 - [analyzer] Assume that the allocated value is non-null before construction.

2018-01-24 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Wed Jan 24 12:32:26 2018
New Revision: 323370

URL: http://llvm.org/viewvc/llvm-project?rev=323370&view=rev
Log:
[analyzer] Assume that the allocated value is non-null before construction.

I.e. not after. In the c++-allocator-inlining=true mode, we need to make the
assumption that the conservatively evaluated operator new() has returned a
non-null value. Previously we did this on CXXNewExpr, but now we have to do that
before calling the constructor, because some clever constructors are sometimes
assuming that their "this" is null and doing weird stuff. We would also crash
upon evaluating CXXNewExpr when the allocator was inlined and returned null and
had a throw specification; this is UB even for custom allocators, but we still
need not to crash.

Added more FIXME tests to ensure that eventually we fix calling the constructor
for null return values.

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

Added:
cfe/trunk/test/Analysis/new-ctor-null-throw.cpp
Modified:
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
cfe/trunk/test/Analysis/new-ctor-conservative.cpp
cfe/trunk/test/Analysis/new-ctor-null.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp?rev=323370&r1=323369&r2=323370&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp Wed Jan 24 12:32:26 2018
@@ -500,9 +500,24 @@ void ExprEngine::VisitCXXNewAllocatorCal
 // is breaking too much to evaluate the no-op symbolic cast over it, so we
 // skip it for now.
 ProgramStateRef State = I->getState();
-ValueBldr.generateNode(
-CNE, I,
-setCXXNewAllocatorValue(State, CNE, LCtx, State->getSVal(CNE, LCtx)));
+SVal RetVal = State->getSVal(CNE, LCtx);
+
+// If this allocation function is not declared as non-throwing, failures
+// /must/ be signalled by exceptions, and thus the return value will never
+// be NULL. -fno-exceptions does not influence this semantics.
+// FIXME: GCC has a -fcheck-new option, which forces it to consider the 
case
+// where new can return NULL. If we end up supporting that option, we can
+// consider adding a check for it here.
+// C++11 [basic.stc.dynamic.allocation]p3.
+if (const FunctionDecl *FD = CNE->getOperatorNew()) {
+  QualType Ty = FD->getType();
+  if (const auto *ProtoType = Ty->getAs())
+if (!ProtoType->isNothrow(getContext()))
+  State = State->assume(RetVal.castAs(), true);
+}
+
+ValueBldr.generateNode(CNE, I,
+   setCXXNewAllocatorValue(State, CNE, LCtx, RetVal));
   }
 
   ExplodedNodeSet DstPostPostCallCallback;
@@ -559,21 +574,21 @@ void ExprEngine::VisitCXXNewExpr(const C
 State = Call->invalidateRegions(blockCount);
 if (!State)
   return;
-  }
 
-  // If this allocation function is not declared as non-throwing, failures
-  // /must/ be signalled by exceptions, and thus the return value will never be
-  // NULL. -fno-exceptions does not influence this semantics.
-  // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
-  // where new can return NULL. If we end up supporting that option, we can
-  // consider adding a check for it here.
-  // C++11 [basic.stc.dynamic.allocation]p3.
-  if (FD) {
-QualType Ty = FD->getType();
-if (const FunctionProtoType *ProtoType = Ty->getAs())
-  if (!ProtoType->isNothrow(getContext()))
-if (auto dSymVal = symVal.getAs())
-  State = State->assume(*dSymVal, true);
+// If this allocation function is not declared as non-throwing, failures
+// /must/ be signalled by exceptions, and thus the return value will never
+// be NULL. -fno-exceptions does not influence this semantics.
+// FIXME: GCC has a -fcheck-new option, which forces it to consider the 
case
+// where new can return NULL. If we end up supporting that option, we can
+// consider adding a check for it here.
+// C++11 [basic.stc.dynamic.allocation]p3.
+if (FD) {
+  QualType Ty = FD->getType();
+  if (const auto *ProtoType = Ty->getAs())
+if (!ProtoType->isNothrow(getContext()))
+  if (auto dSymVal = symVal.getAs())
+State = State->assume(*dSymVal, true);
+}
   }
 
   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);

Modified: cfe/trunk/test/Analysis/new-ctor-conservative.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/new-ctor-conservative.cpp?rev=323370&r1=323369&r2=323370&view=diff
==
--- cfe/trunk/test/Analysis/new-ctor-conservative.cpp (original)
+++ cfe/trunk/test/Analysis/new-ctor-conservative.cpp Wed Jan 24 12:32:26 2018
@@ -1,6 +1,7 @@
-// RUN: %clang_analyz

[PATCH] D42192: [analyzer] Assume that the allocated value is non-null before construction, not after.

2018-01-24 Thread Phabricator via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323370: [analyzer] Assume that the allocated value is 
non-null before construction. (authored by dergachev, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42192?vs=130335&id=131326#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42192

Files:
  cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  cfe/trunk/test/Analysis/new-ctor-conservative.cpp
  cfe/trunk/test/Analysis/new-ctor-null-throw.cpp
  cfe/trunk/test/Analysis/new-ctor-null.cpp

Index: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -500,9 +500,24 @@
 // is breaking too much to evaluate the no-op symbolic cast over it, so we
 // skip it for now.
 ProgramStateRef State = I->getState();
-ValueBldr.generateNode(
-CNE, I,
-setCXXNewAllocatorValue(State, CNE, LCtx, State->getSVal(CNE, LCtx)));
+SVal RetVal = State->getSVal(CNE, LCtx);
+
+// If this allocation function is not declared as non-throwing, failures
+// /must/ be signalled by exceptions, and thus the return value will never
+// be NULL. -fno-exceptions does not influence this semantics.
+// FIXME: GCC has a -fcheck-new option, which forces it to consider the case
+// where new can return NULL. If we end up supporting that option, we can
+// consider adding a check for it here.
+// C++11 [basic.stc.dynamic.allocation]p3.
+if (const FunctionDecl *FD = CNE->getOperatorNew()) {
+  QualType Ty = FD->getType();
+  if (const auto *ProtoType = Ty->getAs())
+if (!ProtoType->isNothrow(getContext()))
+  State = State->assume(RetVal.castAs(), true);
+}
+
+ValueBldr.generateNode(CNE, I,
+   setCXXNewAllocatorValue(State, CNE, LCtx, RetVal));
   }
 
   ExplodedNodeSet DstPostPostCallCallback;
@@ -559,21 +574,21 @@
 State = Call->invalidateRegions(blockCount);
 if (!State)
   return;
-  }
 
-  // If this allocation function is not declared as non-throwing, failures
-  // /must/ be signalled by exceptions, and thus the return value will never be
-  // NULL. -fno-exceptions does not influence this semantics.
-  // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
-  // where new can return NULL. If we end up supporting that option, we can
-  // consider adding a check for it here.
-  // C++11 [basic.stc.dynamic.allocation]p3.
-  if (FD) {
-QualType Ty = FD->getType();
-if (const FunctionProtoType *ProtoType = Ty->getAs())
-  if (!ProtoType->isNothrow(getContext()))
-if (auto dSymVal = symVal.getAs())
-  State = State->assume(*dSymVal, true);
+// If this allocation function is not declared as non-throwing, failures
+// /must/ be signalled by exceptions, and thus the return value will never
+// be NULL. -fno-exceptions does not influence this semantics.
+// FIXME: GCC has a -fcheck-new option, which forces it to consider the case
+// where new can return NULL. If we end up supporting that option, we can
+// consider adding a check for it here.
+// C++11 [basic.stc.dynamic.allocation]p3.
+if (FD) {
+  QualType Ty = FD->getType();
+  if (const auto *ProtoType = Ty->getAs())
+if (!ProtoType->isNothrow(getContext()))
+  if (auto dSymVal = symVal.getAs())
+State = State->assume(*dSymVal, true);
+}
   }
 
   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
Index: cfe/trunk/test/Analysis/new-ctor-null.cpp
===
--- cfe/trunk/test/Analysis/new-ctor-null.cpp
+++ cfe/trunk/test/Analysis/new-ctor-null.cpp
@@ -1,6 +1,7 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-config c++-allocator-inlining=true -std=c++11 -verify %s
 
 void clang_analyzer_eval(bool);
+void clang_analyzer_warnIfReached();
 
 typedef __typeof__(sizeof(int)) size_t;
 
@@ -13,11 +14,23 @@
 
 struct S {
   int x;
-  S() : x(1) {}
+  S() : x(1) {
+// FIXME: Constructor should not be called with null this, even if it was
+// returned by operator new().
+clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  }
   ~S() {}
 };
 
 void testArrays() {
   S *s = new S[10]; // no-crash
   s[0].x = 2; // expected-warning{{Dereference of null pointer}}
 }
+
+int global;
+void testInvalidationOnConstructionIntoNull() {
+  global = 0;
+  S *s = new S();
+  // FIXME: Should be FALSE - we should not invalidate globals.
+  clang_analyzer_eval(global); // expected-warning{{UNKNOWN}}
+}
Index: cfe/trunk/test/Analysis/new-ctor-null-throw.cpp
==

[PATCH] D42499: [clangd] Modify the Span API so that Spans propagate with contexts.

2018-01-24 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, ioeric, jkorous-apple, klimek.

This is probably the right behavior for distributed tracers, and makes unpaired
begin-end events impossible without requiring Spans to be bound to a thread.

The API is conceptually clean but syntactically awkward. As discussed offline,
this is basically a naming problem and will go away if (when) we use TLS to
store the current context.

The apparently-unrelated change to onScopeExit are because its move semantics
broken if Func is POD-like since r322838. This is true of function pointers,
and the lambda I use here that captures two pointers only.
I've raised this issue on llvm-dev and will revert this part if we fix it in
some other way.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42499

Files:
  clangd/ClangdUnit.cpp
  clangd/Context.h
  clangd/Function.h
  clangd/JSONRPCDispatcher.cpp
  clangd/Trace.cpp
  clangd/Trace.h
  unittests/clangd/TraceTests.cpp

Index: unittests/clangd/TraceTests.cpp
===
--- unittests/clangd/TraceTests.cpp
+++ unittests/clangd/TraceTests.cpp
@@ -78,8 +78,8 @@
 auto JSONTracer = trace::createJSONTracer(OS);
 trace::Session Session(*JSONTracer);
 {
-  trace::Span S(Context::empty(), "A");
-  trace::log(Context::empty(), "B");
+  Context Ctx = trace::span(Context::empty(), "A");
+  trace::log(Ctx, "B");
 }
   }
 
Index: clangd/Trace.h
===
--- clangd/Trace.h
+++ clangd/Trace.h
@@ -38,11 +38,12 @@
 
   virtual ~EventTracer() = default;
 
-  /// Called when event that has a duration starts. The returned callback will
-  /// be executed when the event ends. \p Name is a descriptive name
-  /// of the event that was passed to Span constructor.
-  virtual EndEventCallback beginSpan(const Context &Ctx,
- llvm::StringRef Name) = 0;
+  /// Called when event that has a duration starts. \p Name describes the event.
+  /// Returns a derived context that will be destroyed when the event ends.
+  /// Usually implementations will store an object in the returned context
+  /// whose destructor records the end of the event.
+  /// The args are spanArgs(Ctx), only complete when the event ends.
+  virtual Context beginSpan(const Context &Ctx, llvm::StringRef Name) = 0;
 
   /// Called for instant events.
   virtual void instant(const Context &Ctx, llvm::StringRef Name,
@@ -69,31 +70,34 @@
 /// Records a single instant event, associated with the current thread.
 void log(const Context &Ctx, const llvm::Twine &Name);
 
-/// Records an event whose duration is the lifetime of the Span object.
+/// Records an event with a duration.
+/// Returns a derived context, the event ends when it is destroyed.
+///
 /// This is the main public interface for producing tracing events.
 ///
 /// Arbitrary JSON metadata can be attached while this span is active:
-///   SPAN_ATTACH(MySpan, "Payload", SomeJSONExpr);
+///   SPAN_ATTACH(spanCtx, "Payload", SomeJSONExpr);
+///
 /// SomeJSONExpr is evaluated and copied only if actually needed.
-class Span {
-public:
-  Span(const Context &Ctx, llvm::StringRef Name);
-  ~Span();
-
-  /// Returns mutable span metadata if this span is interested.
-  /// Prefer to use SPAN_ATTACH rather than accessing this directly.
-  json::obj *args() { return Args.get(); }
-
-private:
-  std::unique_ptr Args;
-  EventTracer::EndEventCallback Callback;
-};
-
-#define SPAN_ATTACH(S, Name, Expr) \
+///
+/// FIXME: this API is awkward to use. Migrate to TLS Context and scoped Span.
+/// Meanwhile, beware of this trap:
+/// foo(const Context &Ctx) {
+///   Context Ctx = trace::span(Ctx /* actually the uninit'd new context! */);
+/// }
+Context span(const Context &Ctx, llvm::StringRef Name);
+
+/// Returns mutable span metadata if this span is interested.
+/// Prefer to use SPAN_ATTACH rather than accessing this directly.
+json::obj *spanArgs(const Context &Ctx);
+
+/// Attach a key-value pair to the current trace span.
+/// Ctx (or some ancestor) must be created by span().
+/// This macro is not safe for use on the same span from multiple threads.
+#define SPAN_ATTACH(Ctx, Name, Expr)   \
   do { \
-if ((S).args() != nullptr) {   \
-  (*((S).args()))[(Name)] = (Expr);\
-}  \
+if (auto *Args = ::clang::clangd::trace::spanArgs(Ctx))\
+  (*Args)[Name] = Expr;\
   } while (0)
 
 } // namespace trace
Index: clangd/Trace.cpp
===

r323373 - [analyzer] Enable c++-allocator-inlining by default.

2018-01-24 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Wed Jan 24 12:59:40 2018
New Revision: 323373

URL: http://llvm.org/viewvc/llvm-project?rev=323373&view=rev
Log:
[analyzer] Enable c++-allocator-inlining by default.

This allows the analyzer to analyze ("inline") custom operator new() calls and,
even more importantly, inline constructors of objects that were allocated
by any operator new() - not necessarily a custom one.

All changes in the tests in the current commit are intended improvements,
even if they didn't carry any explicit FIXME flag.

It is possible to restore the old behavior via

  -analyzer-config c++-allocator-inlining=false

(this flag is supported by scan-build as well, and it can be into a clang
--analyze invocation via -Xclang .. -Xclang ..). There is no intention to
remove the old behavior for now.

Differential Revision: https://reviews.llvm.org/D42219
rdar://problem/12180598

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
cfe/trunk/test/Analysis/NewDelete-custom.cpp
cfe/trunk/test/Analysis/ctor.mm
cfe/trunk/test/Analysis/new.cpp
cfe/trunk/test/Analysis/virtualcall.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp?rev=323373&r1=323372&r2=323373&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp Wed Jan 24 12:59:40 
2018
@@ -203,7 +203,7 @@ bool AnalyzerOptions::mayInlineTemplateF
 bool AnalyzerOptions::mayInlineCXXAllocator() {
   return getBooleanOption(InlineCXXAllocator,
   "c++-allocator-inlining",
-  /*Default=*/false);
+  /*Default=*/true);
 }
 
 bool AnalyzerOptions::mayInlineCXXContainerMethods() {

Modified: cfe/trunk/test/Analysis/NewDelete-custom.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/NewDelete-custom.cpp?rev=323373&r1=323372&r2=323373&view=diff
==
--- cfe/trunk/test/Analysis/NewDelete-custom.cpp (original)
+++ cfe/trunk/test/Analysis/NewDelete-custom.cpp Wed Jan 24 12:59:40 2018
@@ -1,7 +1,7 @@
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks 
-verify %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc 
-std=c++11 -DLEAKS=1 -fblocks -verify %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 
-analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks 
-verify %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc 
-std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 
-DALLOCATOR_INLINING=1 -fblocks -verify %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 
-analyzer-config c++-allocator-inlining=false -fblocks -verify %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc 
-std=c++11 -analyzer-config c++-allocator-inlining=false -DLEAKS=1 -fblocks 
-verify %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 
-DALLOCATOR_INLINING=1 -fblocks -verify %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc 
-std=c++11 -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s
 #include "Inputs/system-header-simulator-cxx.h"
 
 #if !(LEAKS && !ALLOCATOR_INLINING)

Modified: cfe/trunk/test/Analysis/ctor.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ctor.mm?rev=323373&r1=323372&r2=323373&view=diff
==
--- cfe/trunk/test/Analysis/ctor.mm (original)
+++ cfe/trunk/test/Analysis/ctor.mm Wed Jan 24 12:59:40 2018
@@ -572,10 +572,9 @@ namespace ZeroInitialization {
   }
 
   void testNew() {
-// FIXME: Pending proper implementation of constructors for 'new'.
 raw_pair *pp = new raw_pair();
-clang_analyzer_eval(pp->p1 == 0); // expected-warning{{UNKNOWN}}
-clang_analyzer_eval(pp->p2 == 0); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(pp->p1 == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(pp->p2 == 0); // expected-warning{{TRUE}}
   }
 
   void testArrayNew() {
@@ -679,8 +678,7 @@ namespace InitializerList {
 
   void testDynamic() {
 List *list = new List{1, 2};
-// FIXME: When we handle constructors with 'new', this will be TRUE.
-clang_analyzer_eval(list->usedInitializerList); // 
expected-warning{{UNKNOWN}}
+clang_analyzer_eval(list->usedInitializerList); // expected-warning{{TRUE}}
   }
 }
 

Modified: cfe/trunk/test/Analysis/new.cp

[PATCH] D42219: [analyzer] Enable c++-allocator-inlining by default?

2018-01-24 Thread Phabricator via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323373: [analyzer] Enable c++-allocator-inlining by default. 
(authored by dergachev, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42219?vs=130326&id=131331#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42219

Files:
  cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  cfe/trunk/test/Analysis/NewDelete-custom.cpp
  cfe/trunk/test/Analysis/ctor.mm
  cfe/trunk/test/Analysis/new.cpp
  cfe/trunk/test/Analysis/virtualcall.cpp


Index: cfe/trunk/test/Analysis/NewDelete-custom.cpp
===
--- cfe/trunk/test/Analysis/NewDelete-custom.cpp
+++ cfe/trunk/test/Analysis/NewDelete-custom.cpp
@@ -1,7 +1,7 @@
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks 
-verify %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc 
-std=c++11 -DLEAKS=1 -fblocks -verify %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 
-analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks 
-verify %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc 
-std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 
-DALLOCATOR_INLINING=1 -fblocks -verify %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 
-analyzer-config c++-allocator-inlining=false -fblocks -verify %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc 
-std=c++11 -analyzer-config c++-allocator-inlining=false -DLEAKS=1 -fblocks 
-verify %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 
-DALLOCATOR_INLINING=1 -fblocks -verify %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc 
-std=c++11 -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s
 #include "Inputs/system-header-simulator-cxx.h"
 
 #if !(LEAKS && !ALLOCATOR_INLINING)
Index: cfe/trunk/test/Analysis/ctor.mm
===
--- cfe/trunk/test/Analysis/ctor.mm
+++ cfe/trunk/test/Analysis/ctor.mm
@@ -572,10 +572,9 @@
   }
 
   void testNew() {
-// FIXME: Pending proper implementation of constructors for 'new'.
 raw_pair *pp = new raw_pair();
-clang_analyzer_eval(pp->p1 == 0); // expected-warning{{UNKNOWN}}
-clang_analyzer_eval(pp->p2 == 0); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(pp->p1 == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(pp->p2 == 0); // expected-warning{{TRUE}}
   }
 
   void testArrayNew() {
@@ -679,8 +678,7 @@
 
   void testDynamic() {
 List *list = new List{1, 2};
-// FIXME: When we handle constructors with 'new', this will be TRUE.
-clang_analyzer_eval(list->usedInitializerList); // 
expected-warning{{UNKNOWN}}
+clang_analyzer_eval(list->usedInitializerList); // expected-warning{{TRUE}}
   }
 }
 
Index: cfe/trunk/test/Analysis/virtualcall.cpp
===
--- cfe/trunk/test/Analysis/virtualcall.cpp
+++ cfe/trunk/test/Analysis/virtualcall.cpp
@@ -262,6 +262,9 @@
//expected-note-re@-2 ^}}Calling default constructor for 'M'}}
 #endif
   Y *y = new Y;
+#if !PUREONLY
+  //expected-note-re@-2 ^}}Calling default constructor for 'Y'}}
+#endif
   delete y;
   header::Z z;
 #if !PUREONLY
Index: cfe/trunk/test/Analysis/new.cpp
===
--- cfe/trunk/test/Analysis/new.cpp
+++ cfe/trunk/test/Analysis/new.cpp
@@ -34,7 +34,7 @@
 
   void *y = new (x) int;
   clang_analyzer_eval(x == y); // expected-warning{{TRUE}};
-  clang_analyzer_eval(*x == 1); // expected-warning{{UNKNOWN}};
+  clang_analyzer_eval(*x == 1); // expected-warning{{TRUE}};
 
   return y;
 }
@@ -200,8 +200,7 @@
   int n;
   new (&n) int;
 
-  // Should warn that n is uninitialized.
-  if (n) { // no-warning
+  if (n) { // expected-warning{{Branch condition evaluates to a garbage value}}
 return 0;
   }
   return 1;
Index: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
@@ -203,7 +203,7 @@
 bool AnalyzerOptions::mayInlineCXXAllocator() {
   return getBooleanOption(InlineCXXAllocator,
   "c++-allocator-inlining",
-  /*Default=*/false);
+  /*Default=*/true);
 }
 
 bool AnalyzerOptions::mayInlineCXXContainer

[PATCH] D42500: [clang-format] Fixes indentation of inner text proto messages

2018-01-24 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.
krasimir added a reviewer: djasper.
Herald added a subscriber: klimek.

Consider the text proto:

  message {
sub { key: value }
  }

Previously the first `{` was TT_Unknown, which caused the inner message to be
indented by the continuation width. This didn't happen for:

  message {
sub: { key: value }
  }

This is because the code to mark the first `{` as a TT_DictLiteral was only
considering the case where it marches forward and reaches a `:`.

This patch updates this by looking not only for `:`, but also for `<` and `{`.


Repository:
  rC Clang

https://reviews.llvm.org/D42500

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestTextProto.cpp


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -289,6 +289,10 @@
"  headheadheadheadheadhead_id: 1\n"
"  product_data \n"
">");
+
+  verifyFormat("dcccwrnfioeruvginerurneitinfo {\n"
+   "  exte3nsionrnfvui {key: value}\n"
+   "}");
 }
 
 TEST_F(FormatTestTextProto, DiscardsUnbreakableTailIfCanBreakAfter) {
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -462,13 +462,15 @@
   FormatToken *Previous = CurrentToken->getPreviousNonComment();
   if (Previous->is(TT_JsTypeOptionalQuestion))
 Previous = Previous->getPreviousNonComment();
-  if (((CurrentToken->is(tok::colon) &&
-(!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
-   Style.Language == FormatStyle::LK_Proto ||
-   Style.Language == FormatStyle::LK_TextProto) &&
-  (Previous->Tok.getIdentifierInfo() ||
-   Previous->is(tok::string_literal)))
-Previous->Type = TT_SelectorName;
+  if ((CurrentToken->is(tok::colon) &&
+   (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
+  Style.Language == FormatStyle::LK_Proto ||
+  Style.Language == FormatStyle::LK_TextProto) {
+Left->Type = TT_DictLiteral;
+if (Previous->Tok.getIdentifierInfo() ||
+Previous->is(tok::string_literal))
+  Previous->Type = TT_SelectorName;
+  }
   if (CurrentToken->is(tok::colon) ||
   Style.Language == FormatStyle::LK_JavaScript)
 Left->Type = TT_DictLiteral;


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -289,6 +289,10 @@
"  headheadheadheadheadhead_id: 1\n"
"  product_data \n"
">");
+
+  verifyFormat("dcccwrnfioeruvginerurneitinfo {\n"
+   "  exte3nsionrnfvui {key: value}\n"
+   "}");
 }
 
 TEST_F(FormatTestTextProto, DiscardsUnbreakableTailIfCanBreakAfter) {
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -462,13 +462,15 @@
   FormatToken *Previous = CurrentToken->getPreviousNonComment();
   if (Previous->is(TT_JsTypeOptionalQuestion))
 Previous = Previous->getPreviousNonComment();
-  if (((CurrentToken->is(tok::colon) &&
-(!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
-   Style.Language == FormatStyle::LK_Proto ||
-   Style.Language == FormatStyle::LK_TextProto) &&
-  (Previous->Tok.getIdentifierInfo() ||
-   Previous->is(tok::string_literal)))
-Previous->Type = TT_SelectorName;
+  if ((CurrentToken->is(tok::colon) &&
+   (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
+  Style.Language == FormatStyle::LK_Proto ||
+  Style.Language == FormatStyle::LK_TextProto) {
+Left->Type = TT_DictLiteral;
+if (Previous->Tok.getIdentifierInfo() ||
+Previous->is(tok::string_literal))
+  Previous->Type = TT_SelectorName;
+  }
   if (CurrentToken->is(tok::colon) ||
   Style.Language == FormatStyle::LK_JavaScript)
 Left->Type = TT_DictLiteral;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42499: [clangd] Modify the Span API so that Spans propagate with contexts.

2018-01-24 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 131335.
sammccall added a comment.

Remove obsolete typedef


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42499

Files:
  clangd/ClangdUnit.cpp
  clangd/Context.h
  clangd/Function.h
  clangd/JSONRPCDispatcher.cpp
  clangd/Trace.cpp
  clangd/Trace.h
  unittests/clangd/TraceTests.cpp

Index: unittests/clangd/TraceTests.cpp
===
--- unittests/clangd/TraceTests.cpp
+++ unittests/clangd/TraceTests.cpp
@@ -78,8 +78,8 @@
 auto JSONTracer = trace::createJSONTracer(OS);
 trace::Session Session(*JSONTracer);
 {
-  trace::Span S(Context::empty(), "A");
-  trace::log(Context::empty(), "B");
+  Context Ctx = trace::span(Context::empty(), "A");
+  trace::log(Ctx, "B");
 }
   }
 
Index: clangd/Trace.h
===
--- clangd/Trace.h
+++ clangd/Trace.h
@@ -32,17 +32,14 @@
 /// Implmentations of this interface must be thread-safe.
 class EventTracer {
 public:
-  /// A callback executed when an event with duration ends. Args represent data
-  /// that was attached to the event via SPAN_ATTACH.
-  using EndEventCallback = UniqueFunction;
-
   virtual ~EventTracer() = default;
 
-  /// Called when event that has a duration starts. The returned callback will
-  /// be executed when the event ends. \p Name is a descriptive name
-  /// of the event that was passed to Span constructor.
-  virtual EndEventCallback beginSpan(const Context &Ctx,
- llvm::StringRef Name) = 0;
+  /// Called when event that has a duration starts. \p Name describes the event.
+  /// Returns a derived context that will be destroyed when the event ends.
+  /// Usually implementations will store an object in the returned context
+  /// whose destructor records the end of the event.
+  /// The args are spanArgs(Ctx), only complete when the event ends.
+  virtual Context beginSpan(const Context &Ctx, llvm::StringRef Name) = 0;
 
   /// Called for instant events.
   virtual void instant(const Context &Ctx, llvm::StringRef Name,
@@ -69,31 +66,34 @@
 /// Records a single instant event, associated with the current thread.
 void log(const Context &Ctx, const llvm::Twine &Name);
 
-/// Records an event whose duration is the lifetime of the Span object.
+/// Records an event with a duration.
+/// Returns a derived context, the event ends when it is destroyed.
+///
 /// This is the main public interface for producing tracing events.
 ///
 /// Arbitrary JSON metadata can be attached while this span is active:
-///   SPAN_ATTACH(MySpan, "Payload", SomeJSONExpr);
+///   SPAN_ATTACH(spanCtx, "Payload", SomeJSONExpr);
+///
 /// SomeJSONExpr is evaluated and copied only if actually needed.
-class Span {
-public:
-  Span(const Context &Ctx, llvm::StringRef Name);
-  ~Span();
-
-  /// Returns mutable span metadata if this span is interested.
-  /// Prefer to use SPAN_ATTACH rather than accessing this directly.
-  json::obj *args() { return Args.get(); }
-
-private:
-  std::unique_ptr Args;
-  EventTracer::EndEventCallback Callback;
-};
-
-#define SPAN_ATTACH(S, Name, Expr) \
+///
+/// FIXME: this API is awkward to use. Migrate to TLS Context and scoped Span.
+/// Meanwhile, beware of this trap:
+/// foo(const Context &Ctx) {
+///   Context Ctx = trace::span(Ctx /* actually the uninit'd new context! */);
+/// }
+Context span(const Context &Ctx, llvm::StringRef Name);
+
+/// Returns mutable span metadata if this span is interested.
+/// Prefer to use SPAN_ATTACH rather than accessing this directly.
+json::obj *spanArgs(const Context &Ctx);
+
+/// Attach a key-value pair to the current trace span.
+/// Ctx (or some ancestor) must be created by span().
+/// This macro is not safe for use on the same span from multiple threads.
+#define SPAN_ATTACH(Ctx, Name, Expr)   \
   do { \
-if ((S).args() != nullptr) {   \
-  (*((S).args()))[(Name)] = (Expr);\
-}  \
+if (auto *Args = ::clang::clangd::trace::spanArgs(Ctx))\
+  (*Args)[Name] = Expr;\
   } while (0)
 
 } // namespace trace
Index: clangd/Trace.cpp
===
--- clangd/Trace.cpp
+++ clangd/Trace.cpp
@@ -7,6 +7,8 @@
 //
 //===--===//
 
+#include "Context.h"
+#include "Function.h"
 #include "Trace.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/Support/Chrono.h"
@@ -43,14 +45,12 @@
 Out.flush();
   }
 
-  EndEventCallback beginSpan(const Context &Ctx,
-

[PATCH] D42343: [coroutines] Fix application of NRVO to Coroutine "Gro" or return object.

2018-01-24 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF updated this revision to Diff 131334.
EricWF edited the summary of this revision.
EricWF added a comment.

- Use a better formulation for detecting when the Gro should be an NRVO 
variable.


https://reviews.llvm.org/D42343

Files:
  lib/Sema/SemaCoroutine.cpp
  test/CodeGenCoroutines/coro-alloc.cpp
  test/CodeGenCoroutines/coro-gro-nrvo.cpp

Index: test/CodeGenCoroutines/coro-gro-nrvo.cpp
===
--- /dev/null
+++ test/CodeGenCoroutines/coro-gro-nrvo.cpp
@@ -0,0 +1,80 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fcoroutines-ts -std=c++14 -emit-llvm %s -o - -disable-llvm-passes | FileCheck %s
+
+#include "Inputs/coroutine.h"
+
+using namespace std::experimental;
+
+namespace std {
+
+struct nothrow_t {};
+constexpr nothrow_t nothrow = {};
+
+} // end namespace std
+
+// Required when get_return_object_on_allocation_failure() is defined by
+// the promise.
+void* operator new(__SIZE_TYPE__ __sz, const std::nothrow_t&) noexcept;
+void  operator delete(void* __p, const std::nothrow_t&) noexcept;
+
+
+template 
+struct promise_type {
+RetObject get_return_object();
+suspend_always initial_suspend();
+suspend_never final_suspend();
+void return_void();
+static void unhandled_exception();
+};
+
+struct coro {
+  using promise_type = promise_type;
+  coro(coro const&);
+  struct Impl;
+  Impl *impl;
+};
+
+// Verify that the NRVO is applied to the Gro object.
+// CHECK-LABEL: define void @_Z1fi(%struct.coro* noalias sret %agg.result, i32)
+coro f(int) {
+// CHECK: coro.init:
+// CHECK: store i1 false, i1* %gro.active
+// CHECK-NEXT: call void @{{.*get_return_objectEv}}(%struct.coro* sret %agg.result
+// CHECK-NEXT: store i1 true, i1* %gro.active
+  co_return;
+}
+
+
+template 
+struct promise_type_with_on_alloc_failure {
+static RetObject get_return_object_on_allocation_failure();
+RetObject get_return_object();
+suspend_always initial_suspend();
+suspend_never final_suspend();
+void return_void();
+static void unhandled_exception();
+};
+
+struct coro_two {
+  using promise_type = promise_type_with_on_alloc_failure;
+  coro_two(coro_two const&);
+  struct Impl;
+  Impl *impl;
+};
+
+// Verify that the NRVO is applied to the Gro object.
+// CHECK-LABEL: define void @_Z1hi(%struct.coro_two* noalias sret %agg.result, i32)
+ coro_two h(int) {
+
+// CHECK: coro.ret.on.failure:
+// CHECK-NEXT: call void @{{.*get_return_object_on_allocation_failureEv}}(%struct.coro_two* sret %agg.result
+// CHECK-NEXT: br label %[[RetLabel:.*]]
+
+// CHECK: coro.init:
+// CHECK: store i1 false, i1* %gro.active
+// CHECK-NEXT: call void @{{.*get_return_objectEv}}(%struct.coro_two* sret %agg.result
+// CHECK-NEXT: store i1 true, i1* %gro.active
+
+// CHECK: [[RetLabel]]:
+// CHECK-NEXT: ret void
+  co_return;
+}
Index: test/CodeGenCoroutines/coro-alloc.cpp
===
--- test/CodeGenCoroutines/coro-alloc.cpp
+++ test/CodeGenCoroutines/coro-alloc.cpp
@@ -173,6 +173,7 @@
 // CHECK-LABEL: f4(
 extern "C" int f4(promise_on_alloc_failure_tag) {
   // CHECK: %[[RetVal:.+]] = alloca i32
+  // CHECK: %[[Gro:.+]] = alloca i32
   // CHECK: %[[ID:.+]] = call token @llvm.coro.id(i32 16
   // CHECK: %[[SIZE:.+]] = call i64 @llvm.coro.size.i64()
   // CHECK: %[[MEM:.+]] = call i8* @_ZnwmRKSt9nothrow_t(i64 %[[SIZE]], %"struct.std::nothrow_t"* dereferenceable(1) @_ZStL7nothrow)
@@ -186,7 +187,12 @@
 
   // CHECK: [[OKBB]]:
   // CHECK:   %[[OkRet:.+]] = call i32 @_ZNSt12experimental16coroutine_traitsIJi28promise_on_alloc_failure_tagEE12promise_type17get_return_objectEv(
-  // CHECK:   store i32 %[[OkRet]], i32* %[[RetVal]]
+  // CHECK:   store i32 %[[OkRet]], i32* %[[Gro]]
+
+  // CHECK: coro.ret:
+  // CHECK: %[[Tmp1:.*]] = load i32, i32* %[[Gro]]
+  // CHECK-NEXT: store i32 %[[Tmp1]], i32* %[[RetVal]]
+  // CHECK-NEXT: br label %[[RetBB]]
 
   // CHECK: [[RetBB]]:
   // CHECK:   %[[LoadRet:.+]] = load i32, i32* %[[RetVal]], align 4
Index: lib/Sema/SemaCoroutine.cpp
===
--- lib/Sema/SemaCoroutine.cpp
+++ lib/Sema/SemaCoroutine.cpp
@@ -1256,10 +1256,6 @@
   if (Res.isInvalid())
 return false;
 
-  if (GroType == FnRetType) {
-GroDecl->setNRVOVariable(true);
-  }
-
   S.AddInitializerToDecl(GroDecl, Res.get(),
  /*DirectInit=*/false);
 
@@ -1283,6 +1279,8 @@
 noteMemberDeclaredHere(S, ReturnValue, Fn);
 return false;
   }
+  if (cast(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
+GroDecl->setNRVOVariable(true);
 
   this->ReturnStmt = ReturnStmt.get();
   return true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42301: [ASTImporter] Support LambdaExprs and improve template support

2018-01-24 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

In https://reviews.llvm.org/D42301#986583, @a.sidorin wrote:

> I'd rather create a separate patch - this one is already large enough. Is it 
> OK?


Yeah, that is fine by me.


Repository:
  rC Clang

https://reviews.llvm.org/D42301



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


r323376 - [analyzer] NFC: Run many existing C++ tests with a custom operator new().

2018-01-24 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Wed Jan 24 13:24:10 2018
New Revision: 323376

URL: http://llvm.org/viewvc/llvm-project?rev=323376&view=rev
Log:
[analyzer] NFC: Run many existing C++ tests with a custom operator new().

In order to provide more test coverage for inlined operator new(), add more
run-lines to existing test cases, which would trigger our fake header
to provide a body for operator new(). Most of the code should still behave
reasonably. When behavior intentionally changes, #ifs are provided.

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

Modified:
cfe/trunk/test/Analysis/Inputs/system-header-simulator-cxx.h
cfe/trunk/test/Analysis/MismatchedDeallocator-checker-test.mm
cfe/trunk/test/Analysis/NewDelete-checker-test.cpp
cfe/trunk/test/Analysis/NewDelete-intersections.mm
cfe/trunk/test/Analysis/ctor.mm
cfe/trunk/test/Analysis/diagnostics/implicit-cxx-std-suppression.cpp
cfe/trunk/test/Analysis/initializer.cpp
cfe/trunk/test/Analysis/inlining/containers.cpp
cfe/trunk/test/Analysis/malloc.cpp
cfe/trunk/test/Analysis/new.cpp
cfe/trunk/test/Analysis/uninit-const.cpp

Modified: cfe/trunk/test/Analysis/Inputs/system-header-simulator-cxx.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/Inputs/system-header-simulator-cxx.h?rev=323376&r1=323375&r2=323376&view=diff
==
--- cfe/trunk/test/Analysis/Inputs/system-header-simulator-cxx.h (original)
+++ cfe/trunk/test/Analysis/Inputs/system-header-simulator-cxx.h Wed Jan 24 
13:24:10 2018
@@ -584,10 +584,21 @@ namespace std {
 
 }
 
+#ifdef TEST_INLINABLE_ALLOCATORS
+namespace std {
+  void *malloc(size_t);
+  void free(void *);
+}
+void* operator new(std::size_t size, const std::nothrow_t&) throw() { return 
std::malloc(size); }
+void* operator new[](std::size_t size, const std::nothrow_t&) throw() { return 
std::malloc(size); }
+void operator delete(void* ptr, const std::nothrow_t&) throw() { 
std::free(ptr); }
+void operator delete[](void* ptr, const std::nothrow_t&) throw() { 
std::free(ptr); }
+#else
 void* operator new(std::size_t, const std::nothrow_t&) throw();
 void* operator new[](std::size_t, const std::nothrow_t&) throw();
 void operator delete(void*, const std::nothrow_t&) throw();
 void operator delete[](void*, const std::nothrow_t&) throw();
+#endif
 
 void* operator new (std::size_t size, void* ptr) throw() { return ptr; };
 void* operator new[] (std::size_t size, void* ptr) throw() { return ptr; };

Modified: cfe/trunk/test/Analysis/MismatchedDeallocator-checker-test.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/MismatchedDeallocator-checker-test.mm?rev=323376&r1=323375&r2=323376&view=diff
==
--- cfe/trunk/test/Analysis/MismatchedDeallocator-checker-test.mm (original)
+++ cfe/trunk/test/Analysis/MismatchedDeallocator-checker-test.mm Wed Jan 24 
13:24:10 2018
@@ -1,4 +1,5 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.MismatchedDeallocator 
-fblocks -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.MismatchedDeallocator 
-fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
 
 #include "Inputs/system-header-simulator-objc.h"
 #include "Inputs/system-header-simulator-cxx.h"

Modified: cfe/trunk/test/Analysis/NewDelete-checker-test.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/NewDelete-checker-test.cpp?rev=323376&r1=323375&r2=323376&view=diff
==
--- cfe/trunk/test/Analysis/NewDelete-checker-test.cpp (original)
+++ cfe/trunk/test/Analysis/NewDelete-checker-test.cpp Wed Jan 24 13:24:10 2018
@@ -2,6 +2,11 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks 
-DLEAKS -std=c++11 -fblocks -verify %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete 
-std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -verify %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks 
-DLEAKS -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true 
-verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete 
-std=c++11 -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks 
-DLEAKS -std=c++11 -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete 
-std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true 
-DTEST_INLINABLE_ALLOCATORS -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks 
-DLEAKS -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true 
-DTEST_INLINABLE_ALLOCATORS -verify %s
+
 #include "Inputs/system-header-simulator-cxx.h"
 
 typedef __typeof__(sizeof(int)) size_t;
@@ -47,14 +52,18 @@ void testGlobalNoThrowPlaceme

[PATCH] D42221: [analyzer] NFC: See if existing C++ tests work with custom operator new().

2018-01-24 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323376: [analyzer] NFC: Run many existing C++ tests with a 
custom operator new(). (authored by dergachev, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D42221

Files:
  test/Analysis/Inputs/system-header-simulator-cxx.h
  test/Analysis/MismatchedDeallocator-checker-test.mm
  test/Analysis/NewDelete-checker-test.cpp
  test/Analysis/NewDelete-intersections.mm
  test/Analysis/ctor.mm
  test/Analysis/diagnostics/implicit-cxx-std-suppression.cpp
  test/Analysis/initializer.cpp
  test/Analysis/inlining/containers.cpp
  test/Analysis/malloc.cpp
  test/Analysis/new.cpp
  test/Analysis/uninit-const.cpp

Index: test/Analysis/NewDelete-checker-test.cpp
===
--- test/Analysis/NewDelete-checker-test.cpp
+++ test/Analysis/NewDelete-checker-test.cpp
@@ -2,6 +2,11 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -verify %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -verify %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -DTEST_INLINABLE_ALLOCATORS -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -DTEST_INLINABLE_ALLOCATORS -verify %s
+
 #include "Inputs/system-header-simulator-cxx.h"
 
 typedef __typeof__(sizeof(int)) size_t;
@@ -47,14 +52,18 @@
   void *p = operator new(0, std::nothrow);
 }
 #ifdef LEAKS
-// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
+#ifndef TEST_INLINABLE_ALLOCATORS
+// expected-warning@-3{{Potential leak of memory pointed to by 'p'}}
+#endif
 #endif
 
 void testGlobalNoThrowPlacementExprNewBeforeOverload() {
   int *p = new(std::nothrow) int;
 }
 #ifdef LEAKS
-// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
+#ifndef TEST_INLINABLE_ALLOCATORS
+// expected-warning@-3{{Potential leak of memory pointed to by 'p'}}
+#endif
 #endif
 
 //- Standard pointer placement operators
@@ -188,7 +197,10 @@
 
 void testAllocDeallocNames() {
   int *p = new(std::nothrow) int[1];
-  delete[] (++p); // expected-warning{{Argument to 'delete[]' is offset by 4 bytes from the start of memory allocated by 'new[]'}}
+  delete[] (++p);
+#ifndef TEST_INLINABLE_ALLOCATORS
+  // expected-warning@-2{{Argument to 'delete[]' is offset by 4 bytes from the start of memory allocated by 'new[]'}}
+#endif
 }
 
 //
Index: test/Analysis/MismatchedDeallocator-checker-test.mm
===
--- test/Analysis/MismatchedDeallocator-checker-test.mm
+++ test/Analysis/MismatchedDeallocator-checker-test.mm
@@ -1,4 +1,5 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.MismatchedDeallocator -fblocks -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.MismatchedDeallocator -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
 
 #include "Inputs/system-header-simulator-objc.h"
 #include "Inputs/system-header-simulator-cxx.h"
Index: test/Analysis/NewDelete-intersections.mm
===
--- test/Analysis/NewDelete-intersections.mm
+++ test/Analysis/NewDelete-intersections.mm
@@ -1,5 +1,7 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -verify %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks -std=c++11 -DLEAKS -fblocks -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks -std=c++11 -DLEAKS -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
 #include "Inputs/system-header-simulator-cxx.h"
 #include "Inputs/system-header-simulator-objc.h"
 
Index: test/Analysis/malloc.cpp
===
--- test/Analysis/malloc.cpp
+++ test/Analysis/malloc.cpp
@@ -1,5 +1,7 @@
 // RUN: %clang_analyze_cc1 -w -analyzer-checker=core,alpha.deadcode.UnreachableCode,alpha.core.CastSize,unix.Malloc,cplusplus.NewDelete -analyzer-store=region -verify %s
 // RUN: %clang_analyze_cc1 -triple i386-unknown-linux-gnu -

[PATCH] D42500: [clang-format] Fixes indentation of inner text proto messages

2018-01-24 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

Looks good


Repository:
  rC Clang

https://reviews.llvm.org/D42500



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


[PATCH] D42396: [analyzer] Do not attempt to get the pointee of void* .

2018-01-24 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Yeah, i guess that'd work as well :)


Repository:
  rL LLVM

https://reviews.llvm.org/D42396



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


[libcxx] r323380 - [libc++] Fix PR20855 -- libc++ incorrectly diagnoses illegal reference binding in std::tuple.

2018-01-24 Thread Eric Fiselier via cfe-commits
Author: ericwf
Date: Wed Jan 24 14:14:01 2018
New Revision: 323380

URL: http://llvm.org/viewvc/llvm-project?rev=323380&view=rev
Log:
[libc++] Fix PR20855 -- libc++ incorrectly diagnoses illegal reference binding 
in std::tuple.

Summary:
See https://bugs.llvm.org/show_bug.cgi?id=20855

Libc++ goes out of it's way to diagnose `std::tuple` constructions which are UB 
due to lifetime bugs caused by reference creation. For example:

```
// The 'const std::string&' is created *inside* the tuple constructor, and its 
lifetime is over before the end of the constructor call.
std::tuple t(std::make_tuple(42, "abc"));
```

However, we are over-aggressive and we incorrectly diagnose cases such as:

```
void foo(std::tuple const&);
foo(std::make_tuple(42, 42));
```

This patch fixes the incorrectly diagnosed cases, as well as converting the 
diagnostic to use the newly added Clang trait `__reference_binds_to_temporary`. 
The new trait allows us to diagnose cases we previously couldn't such as:

```
std::tuple t(42, "abc");
```

Reviewers: rsmith, mclow.lists

Reviewed By: rsmith

Subscribers: cfe-commits

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

Added:

libcxx/trunk/test/libcxx/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.fail.cpp

libcxx/trunk/test/std/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.pass.cpp
Removed:

libcxx/trunk/test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.fail.cpp

libcxx/trunk/test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.pass.cpp
Modified:
libcxx/trunk/include/tuple

Modified: libcxx/trunk/include/tuple
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/tuple?rev=323380&r1=323379&r2=323380&view=diff
==
--- libcxx/trunk/include/tuple (original)
+++ libcxx/trunk/include/tuple Wed Jan 24 14:14:01 2018
@@ -173,16 +173,9 @@ class __tuple_leaf
 
 template 
 static constexpr bool __can_bind_reference() {
-using _RawTp = typename remove_reference<_Tp>::type;
-using _RawHp = typename remove_reference<_Hp>::type;
-using _CheckLValueArg = integral_constant::value
-||  is_same<_RawTp, reference_wrapper<_RawHp>>::value
-||  is_same<_RawTp, reference_wrapper::type>>::value
->;
-return  !is_reference<_Hp>::value
-|| (is_lvalue_reference<_Hp>::value && _CheckLValueArg::value)
-|| (is_rvalue_reference<_Hp>::value && 
!is_lvalue_reference<_Tp>::value);
+#if __has_keyword(__reference_binds_to_temporary)
+  return !__reference_binds_to_temporary(_Hp, _Tp);
+#endif
 }
 
 __tuple_leaf& operator=(const __tuple_leaf&);
@@ -224,15 +217,15 @@ public:
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 explicit __tuple_leaf(_Tp&& __t) 
_NOEXCEPT_((is_nothrow_constructible<_Hp, _Tp>::value))
 : __value_(_VSTD::forward<_Tp>(__t))
-{static_assert(__can_bind_reference<_Tp>(),
-   "Attempted to construct a reference element in a tuple with an 
rvalue");}
+{static_assert(__can_bind_reference<_Tp&&>(),
+   "Attempted construction of reference element binds to a temporary whose 
lifetime has ended");}
 
 template 
 _LIBCPP_INLINE_VISIBILITY
 explicit __tuple_leaf(integral_constant, const _Alloc&, _Tp&& 
__t)
 : __value_(_VSTD::forward<_Tp>(__t))
-{static_assert(__can_bind_reference<_Tp>(),
-   "Attempted to construct a reference element in a tuple with an 
rvalue");}
+{static_assert(__can_bind_reference<_Tp&&>(),
+   "Attempted construction of reference element binds to a temporary whose 
lifetime has ended");}
 
 template 
 _LIBCPP_INLINE_VISIBILITY

Removed: 
libcxx/trunk/test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.fail.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.fail.cpp?rev=323379&view=auto
==
--- 
libcxx/trunk/test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.fail.cpp
 (original)
+++ 
libcxx/trunk/test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.fail.cpp
 (removed)
@@ -1,40 +0,0 @@
-//===--===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is dual licensed under the MIT and the University of Illinois Open
-// Source Licenses. See LICENSE.TXT for details.
-//
-//===--===//
-
-// UNSUPPORTED: c++98, c++03
-
-// 
-
-// Test the diagnostics libc++ generates for invalid reference binding.
-// Libc++ attempts to diagnose the following cases:
-//  * Constructing an lvalue reference from an rvalue.
-//  * C

[PATCH] D41977: [libc++] Fix PR20855 -- libc++ incorrectly diagnoses illegal reference binding in std::tuple.

2018-01-24 Thread Eric Fiselier via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCXX323380: [libc++] Fix PR20855 -- libc++ incorrectly 
diagnoses illegal reference binding… (authored by EricWF, committed by ).

Repository:
  rCXX libc++

https://reviews.llvm.org/D41977

Files:
  include/tuple
  test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.fail.cpp
  test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.pass.cpp
  
test/libcxx/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.fail.cpp
  
test/std/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.pass.cpp

Index: include/tuple
===
--- include/tuple
+++ include/tuple
@@ -173,16 +173,9 @@
 
 template 
 static constexpr bool __can_bind_reference() {
-using _RawTp = typename remove_reference<_Tp>::type;
-using _RawHp = typename remove_reference<_Hp>::type;
-using _CheckLValueArg = integral_constant::value
-||  is_same<_RawTp, reference_wrapper<_RawHp>>::value
-||  is_same<_RawTp, reference_wrapper::type>>::value
->;
-return  !is_reference<_Hp>::value
-|| (is_lvalue_reference<_Hp>::value && _CheckLValueArg::value)
-|| (is_rvalue_reference<_Hp>::value && !is_lvalue_reference<_Tp>::value);
+#if __has_keyword(__reference_binds_to_temporary)
+  return !__reference_binds_to_temporary(_Hp, _Tp);
+#endif
 }
 
 __tuple_leaf& operator=(const __tuple_leaf&);
@@ -224,15 +217,15 @@
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 explicit __tuple_leaf(_Tp&& __t) _NOEXCEPT_((is_nothrow_constructible<_Hp, _Tp>::value))
 : __value_(_VSTD::forward<_Tp>(__t))
-{static_assert(__can_bind_reference<_Tp>(),
-   "Attempted to construct a reference element in a tuple with an rvalue");}
+{static_assert(__can_bind_reference<_Tp&&>(),
+   "Attempted construction of reference element binds to a temporary whose lifetime has ended");}
 
 template 
 _LIBCPP_INLINE_VISIBILITY
 explicit __tuple_leaf(integral_constant, const _Alloc&, _Tp&& __t)
 : __value_(_VSTD::forward<_Tp>(__t))
-{static_assert(__can_bind_reference<_Tp>(),
-   "Attempted to construct a reference element in a tuple with an rvalue");}
+{static_assert(__can_bind_reference<_Tp&&>(),
+   "Attempted construction of reference element binds to a temporary whose lifetime has ended");}
 
 template 
 _LIBCPP_INLINE_VISIBILITY
Index: test/std/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.pass.cpp
===
--- test/std/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.pass.cpp
+++ test/std/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.pass.cpp
@@ -0,0 +1,136 @@
+// -*- C++ -*-
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: c++98, c++03
+
+// 
+
+// See llvm.org/PR20855
+
+#include 
+#include 
+#include "test_macros.h"
+
+#if TEST_HAS_BUILTIN_IDENTIFIER(__reference_binds_to_temporary)
+# define ASSERT_REFERENCE_BINDS_TEMPORARY(...) static_assert(__reference_binds_to_temporary(__VA_ARGS__), "")
+# define ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(...) static_assert(!__reference_binds_to_temporary(__VA_ARGS__), "")
+#else
+# define ASSERT_REFERENCE_BINDS_TEMPORARY(...) static_assert(true, "")
+# define ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(...) static_assert(true, "")
+#endif
+
+template 
+struct ConvertsTo {
+  using RawTp = typename std::remove_cv< typename std::remove_reference::type>::type;
+
+  operator Tp() const {
+return static_cast(value);
+  }
+
+  mutable RawTp value;
+};
+
+struct Base {};
+struct Derived : Base {};
+
+
+static_assert(std::is_same::value, "");
+ASSERT_REFERENCE_BINDS_TEMPORARY(std::string const&, decltype("abc"));
+ASSERT_REFERENCE_BINDS_TEMPORARY(std::string const&, decltype(("abc")));
+ASSERT_REFERENCE_BINDS_TEMPORARY(std::string const&, const char*&&);
+
+ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(int&, const ConvertsTo&);
+ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(const int&, ConvertsTo&);
+ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(Base&, Derived&);
+
+
+static_assert(std::is_constructible>::value, "");
+static_assert(std::is_constructible>::value, "");
+
+template  struct CannotDeduce {
+ using type = T;
+};
+
+template 
+void F(typename CannotDeduce>::type const&) {}
+
+void compile_tests() {
+  {
+F(std::make_tuple(42, 42));
+  }
+  {
+F(std::make_tupl

[PATCH] D41977: [libc++] Fix PR20855 -- libc++ incorrectly diagnoses illegal reference binding in std::tuple.

2018-01-24 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF updated this revision to Diff 131348.
EricWF added a comment.

- Improve diagnostic as per @rsmiths suggestion.


https://reviews.llvm.org/D41977

Files:
  include/tuple
  test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.fail.cpp
  test/libcxx/utilities/tuple/tuple.tuple/diagnose_reference_binding.pass.cpp
  
test/libcxx/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.fail.cpp
  
test/std/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.pass.cpp

Index: test/std/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.pass.cpp
===
--- /dev/null
+++ test/std/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.pass.cpp
@@ -0,0 +1,136 @@
+// -*- C++ -*-
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: c++98, c++03
+
+// 
+
+// See llvm.org/PR20855
+
+#include 
+#include 
+#include "test_macros.h"
+
+#if TEST_HAS_BUILTIN_IDENTIFIER(__reference_binds_to_temporary)
+# define ASSERT_REFERENCE_BINDS_TEMPORARY(...) static_assert(__reference_binds_to_temporary(__VA_ARGS__), "")
+# define ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(...) static_assert(!__reference_binds_to_temporary(__VA_ARGS__), "")
+#else
+# define ASSERT_REFERENCE_BINDS_TEMPORARY(...) static_assert(true, "")
+# define ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(...) static_assert(true, "")
+#endif
+
+template 
+struct ConvertsTo {
+  using RawTp = typename std::remove_cv< typename std::remove_reference::type>::type;
+
+  operator Tp() const {
+return static_cast(value);
+  }
+
+  mutable RawTp value;
+};
+
+struct Base {};
+struct Derived : Base {};
+
+
+static_assert(std::is_same::value, "");
+ASSERT_REFERENCE_BINDS_TEMPORARY(std::string const&, decltype("abc"));
+ASSERT_REFERENCE_BINDS_TEMPORARY(std::string const&, decltype(("abc")));
+ASSERT_REFERENCE_BINDS_TEMPORARY(std::string const&, const char*&&);
+
+ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(int&, const ConvertsTo&);
+ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(const int&, ConvertsTo&);
+ASSERT_NOT_REFERENCE_BINDS_TEMPORARY(Base&, Derived&);
+
+
+static_assert(std::is_constructible>::value, "");
+static_assert(std::is_constructible>::value, "");
+
+template  struct CannotDeduce {
+ using type = T;
+};
+
+template 
+void F(typename CannotDeduce>::type const&) {}
+
+void compile_tests() {
+  {
+F(std::make_tuple(42, 42));
+  }
+  {
+F(std::make_tuple(42, 42));
+std::tuple t(std::make_tuple(42, 42));
+  }
+  {
+auto fn = &F;
+fn(std::tuple(42, std::string("a")));
+fn(std::make_tuple(42, std::string("a")));
+  }
+  {
+Derived d;
+std::tuple t(d, d);
+  }
+  {
+ConvertsTo ct;
+std::tuple t(42, ct);
+  }
+}
+
+void allocator_tests() {
+std::allocator alloc;
+int x = 42;
+{
+std::tuple t(std::ref(x));
+assert(&std::get<0>(t) == &x);
+std::tuple t1(std::allocator_arg, alloc, std::ref(x));
+assert(&std::get<0>(t1) == &x);
+}
+{
+auto r = std::ref(x);
+auto const& cr = r;
+std::tuple t(r);
+assert(&std::get<0>(t) == &x);
+std::tuple t1(cr);
+assert(&std::get<0>(t1) == &x);
+std::tuple t2(std::allocator_arg, alloc, r);
+assert(&std::get<0>(t2) == &x);
+std::tuple t3(std::allocator_arg, alloc, cr);
+assert(&std::get<0>(t3) == &x);
+}
+{
+std::tuple t(std::ref(x));
+assert(&std::get<0>(t) == &x);
+std::tuple t2(std::cref(x));
+assert(&std::get<0>(t2) == &x);
+std::tuple t3(std::allocator_arg, alloc, std::ref(x));
+assert(&std::get<0>(t3) == &x);
+std::tuple t4(std::allocator_arg, alloc, std::cref(x));
+assert(&std::get<0>(t4) == &x);
+}
+{
+auto r = std::ref(x);
+auto cr = std::cref(x);
+std::tuple t(r);
+assert(&std::get<0>(t) == &x);
+std::tuple t2(cr);
+assert(&std::get<0>(t2) == &x);
+std::tuple t3(std::allocator_arg, alloc, r);
+assert(&std::get<0>(t3) == &x);
+std::tuple t4(std::allocator_arg, alloc, cr);
+assert(&std::get<0>(t4) == &x);
+}
+}
+
+
+int main() {
+  compile_tests();
+  allocator_tests();
+}
Index: test/libcxx/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.fail.cpp
===
--- /dev/null
+++ test/libcxx/utilities/tuple/tuple.tuple/tuple.cnstr/PR20855_tuple_ref_binding_diagnostics.fail.cpp
@@ -0,0 +1,80 @@
+// -*- C++ -*-
+//===--

r323381 - [coroutines] Pass coro func args to promise ctor

2018-01-24 Thread Brian Gesiak via cfe-commits
Author: modocache
Date: Wed Jan 24 14:15:42 2018
New Revision: 323381

URL: http://llvm.org/viewvc/llvm-project?rev=323381&view=rev
Log:
[coroutines] Pass coro func args to promise ctor

Summary:
Use corutine function arguments to initialize a promise type, but only
if the promise type defines a constructor that takes those arguments.
Otherwise, fall back to the default constructor.

Test Plan: check-clang

Reviewers: rsmith, GorNishanov, eric_niebler

Reviewed By: GorNishanov

Subscribers: toby-allsopp, lewissbaker, EricWF, cfe-commits

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

Modified:
cfe/trunk/include/clang/Sema/ScopeInfo.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/CoroutineStmtBuilder.h
cfe/trunk/lib/Sema/ScopeInfo.cpp
cfe/trunk/lib/Sema/SemaCoroutine.cpp
cfe/trunk/lib/Sema/TreeTransform.h
cfe/trunk/test/CodeGenCoroutines/coro-params.cpp
cfe/trunk/test/SemaCXX/coroutines.cpp

Modified: cfe/trunk/include/clang/Sema/ScopeInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/ScopeInfo.h?rev=323381&r1=323380&r2=323381&view=diff
==
--- cfe/trunk/include/clang/Sema/ScopeInfo.h (original)
+++ cfe/trunk/include/clang/Sema/ScopeInfo.h Wed Jan 24 14:15:42 2018
@@ -22,6 +22,7 @@
 #include "clang/Sema/CleanupInfo.h"
 #include "clang/Sema/Ownership.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringSwitch.h"
@@ -172,6 +173,10 @@ public:
   /// \brief The promise object for this coroutine, if any.
   VarDecl *CoroutinePromise = nullptr;
 
+  /// \brief A mapping between the coroutine function parameters that were 
moved
+  /// to the coroutine frame, and their move statements.
+  llvm::SmallMapVector CoroutineParameterMoves;
+
   /// \brief The initial and final coroutine suspend points.
   std::pair CoroutineSuspends;
 

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=323381&r1=323380&r2=323381&view=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Wed Jan 24 14:15:42 2018
@@ -8478,6 +8478,7 @@ public:
   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
+  bool buildCoroutineParameterMoves(SourceLocation Loc);
   VarDecl *buildCoroutinePromise(SourceLocation Loc);
   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
 

Modified: cfe/trunk/lib/Sema/CoroutineStmtBuilder.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/CoroutineStmtBuilder.h?rev=323381&r1=323380&r2=323381&view=diff
==
--- cfe/trunk/lib/Sema/CoroutineStmtBuilder.h (original)
+++ cfe/trunk/lib/Sema/CoroutineStmtBuilder.h Wed Jan 24 14:15:42 2018
@@ -51,9 +51,6 @@ public:
   /// name lookup.
   bool buildDependentStatements();
 
-  /// \brief Build just parameter moves. To use for rebuilding in 
TreeTransform.
-  bool buildParameterMoves();
-
   bool isInvalid() const { return !this->IsValid; }
 
 private:
@@ -65,7 +62,6 @@ private:
   bool makeReturnObject();
   bool makeGroDeclAndReturnStmt();
   bool makeReturnOnAllocFailure();
-  bool makeParamMoves();
 };
 
 } // end namespace clang

Modified: cfe/trunk/lib/Sema/ScopeInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/ScopeInfo.cpp?rev=323381&r1=323380&r2=323381&view=diff
==
--- cfe/trunk/lib/Sema/ScopeInfo.cpp (original)
+++ cfe/trunk/lib/Sema/ScopeInfo.cpp Wed Jan 24 14:15:42 2018
@@ -43,6 +43,7 @@ void FunctionScopeInfo::Clear() {
   // Coroutine state
   FirstCoroutineStmtLoc = SourceLocation();
   CoroutinePromise = nullptr;
+  CoroutineParameterMoves.clear();
   NeedsCoroutineSuspends = true;
   CoroutineSuspends.first = nullptr;
   CoroutineSuspends.second = nullptr;

Modified: cfe/trunk/lib/Sema/SemaCoroutine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCoroutine.cpp?rev=323381&r1=323380&r2=323381&view=diff
==
--- cfe/trunk/lib/Sema/SemaCoroutine.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCoroutine.cpp Wed Jan 24 14:15:42 2018
@@ -494,9 +494,67 @@ VarDecl *Sema::buildCoroutinePromise(Sou
   CheckVariableDeclarationType(VD);
   if (VD->isInvalidDecl())
 return nullptr;
-  ActOnUninitializedDecl(VD);
+
+  auto *ScopeInfo = getCurFunction();
+  // Build a list of arguments, based on the coroutine functions arguments,
+  // that will be passed to the promise type's constructor.
+  llvm::SmallVector 

r323382 - [analyzer] Do not attempt to get the pointee of void*

2018-01-24 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Wed Jan 24 14:17:30 2018
New Revision: 323382

URL: http://llvm.org/viewvc/llvm-project?rev=323382&view=rev
Log:
[analyzer] Do not attempt to get the pointee of void*

Do not attempt to get the pointee of void* while generating a bug report 
(otherwise it will trigger an assert inside RegionStoreManager::getBinding 
assert(!T->isVoidType() && "Attempting to dereference a void pointer!")).

Test plan: make check-all

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
cfe/trunk/test/Analysis/malloc.c

Modified: cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp?rev=323382&r1=323381&r2=323382&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp Wed Jan 24 14:17:30 
2018
@@ -1211,6 +1211,9 @@ std::string StackHintGeneratorForSymbol:
 
 // Check if the parameter is a pointer to the symbol.
 if (Optional Reg = SV.getAs()) {
+  // Do not attempt to dereference void*.
+  if ((*I)->getType()->isVoidPointerType())
+continue;
   SVal PSV = N->getState()->getSVal(Reg->getRegion());
   SymbolRef AS = PSV.getAsLocSymbol();
   if (AS == Sym) {

Modified: cfe/trunk/test/Analysis/malloc.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/malloc.c?rev=323382&r1=323381&r2=323382&view=diff
==
--- cfe/trunk/test/Analysis/malloc.c (original)
+++ cfe/trunk/test/Analysis/malloc.c Wed Jan 24 14:17:30 2018
@@ -1786,6 +1786,18 @@ void cstringchecker_bounds_nocrash() {
   free(p);
 }
 
+void allocateSomeMemory(void *offendingParameter, void **ptr) {
+  *ptr = malloc(1);
+}
+
+void testNoCrashOnOffendingParameter() {
+  // "extern" is necessary to avoid unrelated warnings 
+  // on passing uninitialized value.
+  extern void *offendingParameter;
+  void* ptr;
+  allocateSomeMemory(offendingParameter, &ptr);
+} // expected-warning {{Potential leak of memory pointed to by 'ptr'}}
+
 // 
 // False negatives.
 


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


[PATCH] D41820: [coroutines] Pass coro func args to promise ctor

2018-01-24 Thread Brian Gesiak via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323381: [coroutines] Pass coro func args to promise ctor 
(authored by modocache, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41820?vs=129785&id=131351#toc

Repository:
  rC Clang

https://reviews.llvm.org/D41820

Files:
  include/clang/Sema/ScopeInfo.h
  include/clang/Sema/Sema.h
  lib/Sema/CoroutineStmtBuilder.h
  lib/Sema/ScopeInfo.cpp
  lib/Sema/SemaCoroutine.cpp
  lib/Sema/TreeTransform.h
  test/CodeGenCoroutines/coro-params.cpp
  test/SemaCXX/coroutines.cpp

Index: test/SemaCXX/coroutines.cpp
===
--- test/SemaCXX/coroutines.cpp
+++ test/SemaCXX/coroutines.cpp
@@ -1171,4 +1171,73 @@
 
 template CoroMemberTag DepTestType::test_static_template(const char *volatile &, unsigned);
 
+struct bad_promise_deleted_constructor {
+  // expected-note@+1 {{'bad_promise_deleted_constructor' has been explicitly marked deleted here}}
+  bad_promise_deleted_constructor() = delete;
+  coro get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend();
+  void return_void();
+  void unhandled_exception();
+};
+
+coro
+bad_coroutine_calls_deleted_promise_constructor() {
+  // expected-error@-1 {{call to deleted constructor of 'std::experimental::coroutine_traits>::promise_type' (aka 'CoroHandleMemberFunctionTest::bad_promise_deleted_constructor')}}
+  co_return;
+}
+
+// Test that, when the promise type has a constructor whose signature matches
+// that of the coroutine function, that constructor is used. If no matching
+// constructor exists, the default constructor is used as a fallback. If no
+// matching constructors exist at all, an error is emitted. This is an
+// experimental feature that will be proposed for the Coroutines TS.
+
+struct good_promise_default_constructor {
+  good_promise_default_constructor(double, float, int);
+  good_promise_default_constructor() = default;
+  coro get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend();
+  void return_void();
+  void unhandled_exception();
+};
+
+coro
+good_coroutine_calls_default_constructor() {
+  co_return;
+}
+
+struct good_promise_custom_constructor {
+  good_promise_custom_constructor(double, float, int);
+  good_promise_custom_constructor() = delete;
+  coro get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend();
+  void return_void();
+  void unhandled_exception();
+};
+
+coro
+good_coroutine_calls_custom_constructor(double, float, int) {
+  co_return;
+}
+
+struct bad_promise_no_matching_constructor {
+  bad_promise_no_matching_constructor(int, int, int);
+  // expected-note@+1 {{'bad_promise_no_matching_constructor' has been explicitly marked deleted here}}
+  bad_promise_no_matching_constructor() = delete;
+  coro get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend();
+  void return_void();
+  void unhandled_exception();
+};
+
+coro
+bad_coroutine_calls_with_no_matching_constructor(int, int) {
+  // expected-error@-1 {{call to deleted constructor of 'std::experimental::coroutine_traits, int, int>::promise_type' (aka 'CoroHandleMemberFunctionTest::bad_promise_no_matching_constructor')}}
+  co_return;
+}
+
 } // namespace CoroHandleMemberFunctionTest
Index: test/CodeGenCoroutines/coro-params.cpp
===
--- test/CodeGenCoroutines/coro-params.cpp
+++ test/CodeGenCoroutines/coro-params.cpp
@@ -1,6 +1,7 @@
 // Verifies that parameters are copied with move constructors
 // Verifies that parameter copies are destroyed
 // Vefifies that parameter copies are used in the body of the coroutine
+// Verifies that parameter copies are used to construct the promise type, if that type has a matching constructor
 // RUN: %clang_cc1 -std=c++1z -fcoroutines-ts -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s -disable-llvm-passes -fexceptions | FileCheck %s
 
 namespace std::experimental {
@@ -127,3 +128,31 @@
 void call_dependent_params() {
   dependent_params(A{}, B{}, B{});
 }
+
+// Test that, when the promise type has a constructor whose signature matches
+// that of the coroutine function, that constructor is used. This is an
+// experimental feature that will be proposed for the Coroutines TS.
+
+struct promise_matching_constructor {};
+
+template<>
+struct std::experimental::coroutine_traits {
+  struct promise_type {
+promise_type(promise_matching_constructor, int, float, double) {}
+promise_type() = delete;
+void get_return_object() {}
+suspend_always initial_suspend() { return {}; }
+suspend_always final_suspend() { return {}; }
+void return_void() {}
+void unhandled_exception() {}
+  };
+};
+
+// CHECK-LABEL: void @_Z38coroutine_matching_promise_constructor28promise_matching_constructorifd(i32, float, double)
+void coroutine_matching_promise_constructo

[PATCH] D41820: [coroutines] Pass coro func args to promise ctor

2018-01-24 Thread Brian Gesiak via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323381: [coroutines] Pass coro func args to promise ctor 
(authored by modocache, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D41820

Files:
  cfe/trunk/include/clang/Sema/ScopeInfo.h
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/lib/Sema/CoroutineStmtBuilder.h
  cfe/trunk/lib/Sema/ScopeInfo.cpp
  cfe/trunk/lib/Sema/SemaCoroutine.cpp
  cfe/trunk/lib/Sema/TreeTransform.h
  cfe/trunk/test/CodeGenCoroutines/coro-params.cpp
  cfe/trunk/test/SemaCXX/coroutines.cpp

Index: cfe/trunk/include/clang/Sema/Sema.h
===
--- cfe/trunk/include/clang/Sema/Sema.h
+++ cfe/trunk/include/clang/Sema/Sema.h
@@ -8478,6 +8478,7 @@
   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
+  bool buildCoroutineParameterMoves(SourceLocation Loc);
   VarDecl *buildCoroutinePromise(SourceLocation Loc);
   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
 
Index: cfe/trunk/include/clang/Sema/ScopeInfo.h
===
--- cfe/trunk/include/clang/Sema/ScopeInfo.h
+++ cfe/trunk/include/clang/Sema/ScopeInfo.h
@@ -22,6 +22,7 @@
 #include "clang/Sema/CleanupInfo.h"
 #include "clang/Sema/Ownership.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringSwitch.h"
@@ -172,6 +173,10 @@
   /// \brief The promise object for this coroutine, if any.
   VarDecl *CoroutinePromise = nullptr;
 
+  /// \brief A mapping between the coroutine function parameters that were moved
+  /// to the coroutine frame, and their move statements.
+  llvm::SmallMapVector CoroutineParameterMoves;
+
   /// \brief The initial and final coroutine suspend points.
   std::pair CoroutineSuspends;
 
Index: cfe/trunk/test/SemaCXX/coroutines.cpp
===
--- cfe/trunk/test/SemaCXX/coroutines.cpp
+++ cfe/trunk/test/SemaCXX/coroutines.cpp
@@ -1171,4 +1171,73 @@
 
 template CoroMemberTag DepTestType::test_static_template(const char *volatile &, unsigned);
 
+struct bad_promise_deleted_constructor {
+  // expected-note@+1 {{'bad_promise_deleted_constructor' has been explicitly marked deleted here}}
+  bad_promise_deleted_constructor() = delete;
+  coro get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend();
+  void return_void();
+  void unhandled_exception();
+};
+
+coro
+bad_coroutine_calls_deleted_promise_constructor() {
+  // expected-error@-1 {{call to deleted constructor of 'std::experimental::coroutine_traits>::promise_type' (aka 'CoroHandleMemberFunctionTest::bad_promise_deleted_constructor')}}
+  co_return;
+}
+
+// Test that, when the promise type has a constructor whose signature matches
+// that of the coroutine function, that constructor is used. If no matching
+// constructor exists, the default constructor is used as a fallback. If no
+// matching constructors exist at all, an error is emitted. This is an
+// experimental feature that will be proposed for the Coroutines TS.
+
+struct good_promise_default_constructor {
+  good_promise_default_constructor(double, float, int);
+  good_promise_default_constructor() = default;
+  coro get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend();
+  void return_void();
+  void unhandled_exception();
+};
+
+coro
+good_coroutine_calls_default_constructor() {
+  co_return;
+}
+
+struct good_promise_custom_constructor {
+  good_promise_custom_constructor(double, float, int);
+  good_promise_custom_constructor() = delete;
+  coro get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend();
+  void return_void();
+  void unhandled_exception();
+};
+
+coro
+good_coroutine_calls_custom_constructor(double, float, int) {
+  co_return;
+}
+
+struct bad_promise_no_matching_constructor {
+  bad_promise_no_matching_constructor(int, int, int);
+  // expected-note@+1 {{'bad_promise_no_matching_constructor' has been explicitly marked deleted here}}
+  bad_promise_no_matching_constructor() = delete;
+  coro get_return_object();
+  suspend_always initial_suspend();
+  suspend_always final_suspend();
+  void return_void();
+  void unhandled_exception();
+};
+
+coro
+bad_coroutine_calls_with_no_matching_constructor(int, int) {
+  // expected-error@-1 {{call to deleted constructor of 'std::experimental::coroutine_traits, int, int>::promise_type' (aka 'CoroHandleMemberFunctionTest::bad_promise_no_matching_constructor')}}
+  co_return;
+}
+
 } // namespace CoroHandleMemberFunctionTest
Index: cfe/trunk/test/CodeGenCoroutines/coro-params.cpp
==

[PATCH] D42396: [analyzer] Do not attempt to get the pointee of void* .

2018-01-24 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323382: [analyzer] Do not attempt to get the pointee of 
void* (authored by alexshap, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42396?vs=130979&id=131352#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42396

Files:
  cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  cfe/trunk/test/Analysis/malloc.c


Index: cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
@@ -1211,6 +1211,9 @@
 
 // Check if the parameter is a pointer to the symbol.
 if (Optional Reg = SV.getAs()) {
+  // Do not attempt to dereference void*.
+  if ((*I)->getType()->isVoidPointerType())
+continue;
   SVal PSV = N->getState()->getSVal(Reg->getRegion());
   SymbolRef AS = PSV.getAsLocSymbol();
   if (AS == Sym) {
Index: cfe/trunk/test/Analysis/malloc.c
===
--- cfe/trunk/test/Analysis/malloc.c
+++ cfe/trunk/test/Analysis/malloc.c
@@ -1786,6 +1786,18 @@
   free(p);
 }
 
+void allocateSomeMemory(void *offendingParameter, void **ptr) {
+  *ptr = malloc(1);
+}
+
+void testNoCrashOnOffendingParameter() {
+  // "extern" is necessary to avoid unrelated warnings 
+  // on passing uninitialized value.
+  extern void *offendingParameter;
+  void* ptr;
+  allocateSomeMemory(offendingParameter, &ptr);
+} // expected-warning {{Potential leak of memory pointed to by 'ptr'}}
+
 // 
 // False negatives.
 


Index: cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
@@ -1211,6 +1211,9 @@
 
 // Check if the parameter is a pointer to the symbol.
 if (Optional Reg = SV.getAs()) {
+  // Do not attempt to dereference void*.
+  if ((*I)->getType()->isVoidPointerType())
+continue;
   SVal PSV = N->getState()->getSVal(Reg->getRegion());
   SymbolRef AS = PSV.getAsLocSymbol();
   if (AS == Sym) {
Index: cfe/trunk/test/Analysis/malloc.c
===
--- cfe/trunk/test/Analysis/malloc.c
+++ cfe/trunk/test/Analysis/malloc.c
@@ -1786,6 +1786,18 @@
   free(p);
 }
 
+void allocateSomeMemory(void *offendingParameter, void **ptr) {
+  *ptr = malloc(1);
+}
+
+void testNoCrashOnOffendingParameter() {
+  // "extern" is necessary to avoid unrelated warnings 
+  // on passing uninitialized value.
+  extern void *offendingParameter;
+  void* ptr;
+  allocateSomeMemory(offendingParameter, &ptr);
+} // expected-warning {{Potential leak of memory pointed to by 'ptr'}}
+
 // 
 // False negatives.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41820: [coroutines] Pass coro func args to promise ctor

2018-01-24 Thread Brian Gesiak via Phabricator via cfe-commits
modocache added a comment.

Great, thanks for the reviews!


Repository:
  rC Clang

https://reviews.llvm.org/D41820



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


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 131356.

Repository:
  rC Clang

https://reviews.llvm.org/D42467

Files:
  lib/Driver/ToolChains/CommonArgs.cpp


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -549,14 +549,17 @@
   TC.getTriple().getOS() != llvm::Triple::NetBSD &&
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
-  // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  // Required for functions like forktpy on some OSes
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lkvm");
 }
 


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -549,14 +549,17 @@
   TC.getTriple().getOS() != llvm::Triple::NetBSD &&
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
-  // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  // Required for functions like forktpy on some OSes
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lkvm");
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread Kamil Rytarowski via Phabricator via cfe-commits
krytarowski added a comment.

I propose to skip now `-lkvm` and `-lutil` for FreeBSD. I'm researching now an 
option to rebuild these libraries against sanitizers and so stop teaching the 
world how to handle its API.

Please keep these patches locally for now.


Repository:
  rC Clang

https://reviews.llvm.org/D42467



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


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 131358.

Repository:
  rC Clang

https://reviews.llvm.org/D42467

Files:
  lib/Driver/ToolChains/CommonArgs.cpp


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -549,14 +549,17 @@
   TC.getTriple().getOS() != llvm::Triple::NetBSD &&
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
-  // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  // Required for functions like forkpty on some OSes
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lkvm");
 }
 


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -549,14 +549,17 @@
   TC.getTriple().getOS() != llvm::Triple::NetBSD &&
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
-  // Required for forkpty on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  // Required for functions like forkpty on some OSes
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lkvm");
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen added a comment.

In https://reviews.llvm.org/D42467#987140, @krytarowski wrote:

> I propose to skip now `-lkvm` and `-lutil` for FreeBSD. I'm researching now 
> an option to rebuild these libraries against sanitizers and so stop teaching 
> the world how to handle its API.
>
> Please keep these patches locally for now.


Ok patches updated.


Repository:
  rC Clang

https://reviews.llvm.org/D42467



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


[PATCH] D42467: FreeBSD needs also execinfo, libutil and libkvm

2018-01-24 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 131359.
devnexen edited the summary of this revision.

Repository:
  rC Clang

https://reviews.llvm.org/D42467

Files:
  lib/Driver/ToolChains/CommonArgs.cpp


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -549,11 +549,12 @@
   TC.getTriple().getOS() != llvm::Triple::NetBSD &&
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
-  // Required for forkpty on some OSes
+  // Required for functions like forkpty on some OSes
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -549,11 +549,12 @@
   TC.getTriple().getOS() != llvm::Triple::NetBSD &&
   TC.getTriple().getOS() != llvm::Triple::RTEMS)
 CmdArgs.push_back("-ldl");
-  // Required for forkpty on some OSes
+  // Required for functions like forkpty on some OSes
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
 CmdArgs.push_back("-lutil");
   // Required for backtrace on some OSes
-  if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
+  if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
+  TC.getTriple().getOS() == llvm::Triple::FreeBSD)
 CmdArgs.push_back("-lexecinfo");
   // Required for kvm (kernel memory interface) on some OSes
   if (TC.getTriple().getOS() == llvm::Triple::NetBSD)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] r323385 - Implement LWG2783: stack::emplace() and queue::emplace() should return decltype(auto)

2018-01-24 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Wed Jan 24 14:42:25 2018
New Revision: 323385

URL: http://llvm.org/viewvc/llvm-project?rev=323385&view=rev
Log:
Implement LWG2783: stack::emplace() and queue::emplace() should return 
decltype(auto)

Modified:
libcxx/trunk/include/queue
libcxx/trunk/include/stack

libcxx/trunk/test/std/containers/container.adaptors/queue/queue.defn/emplace.pass.cpp

libcxx/trunk/test/std/containers/container.adaptors/stack/stack.defn/emplace.pass.cpp
libcxx/trunk/www/cxx2a_status.html

Modified: libcxx/trunk/include/queue
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/queue?rev=323385&r1=323384&r2=323385&view=diff
==
--- libcxx/trunk/include/queue (original)
+++ libcxx/trunk/include/queue Wed Jan 24 14:42:25 2018
@@ -290,7 +290,7 @@ public:
 template 
 _LIBCPP_INLINE_VISIBILITY
 #if _LIBCPP_STD_VER > 14
-reference emplace(_Args&&... __args)
+decltype(auto) emplace(_Args&&... __args)
 { return c.emplace_back(_VSTD::forward<_Args>(__args)...);}
 #else
 void emplace(_Args&&... __args)

Modified: libcxx/trunk/include/stack
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/stack?rev=323385&r1=323384&r2=323385&view=diff
==
--- libcxx/trunk/include/stack (original)
+++ libcxx/trunk/include/stack Wed Jan 24 14:42:25 2018
@@ -199,7 +199,7 @@ public:
 template 
 _LIBCPP_INLINE_VISIBILITY
 #if _LIBCPP_STD_VER > 14
-reference emplace(_Args&&... __args)
+decltype(auto) emplace(_Args&&... __args)
 { return c.emplace_back(_VSTD::forward<_Args>(__args)...);}
 #else
 void  emplace(_Args&&... __args)

Modified: 
libcxx/trunk/test/std/containers/container.adaptors/queue/queue.defn/emplace.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/containers/container.adaptors/queue/queue.defn/emplace.pass.cpp?rev=323385&r1=323384&r2=323385&view=diff
==
--- 
libcxx/trunk/test/std/containers/container.adaptors/queue/queue.defn/emplace.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/containers/container.adaptors/queue/queue.defn/emplace.pass.cpp
 Wed Jan 24 14:42:25 2018
@@ -1,6 +1,6 @@
 
//===--===//
 //
-// The LLVM Compiler Infrastructure
+//The LLVM Compiler Infrastructure
 //
 // This file is dual licensed under the MIT and the University of Illinois Open
 // Source Licenses. See LICENSE.TXT for details.
@@ -11,36 +11,55 @@
 
 // 
 
-// template  reference emplace(Args&&... args);
-// return type is 'reference' in C++17; 'void' before
+// template  decltype(auto) emplace(Args&&... args);
+// return type is 'decltype(auto)' in C++17; 'void' before
+// whatever the return type of the underlying container's emplace_back() 
returns.
 
 
 #include 
 #include 
+#include 
 
 #include "test_macros.h"
 
 #include "../../../Emplaceable.h"
 
+template 
+void test_return_type() {
+   typedef typename Queue::container_type Container;
+   typedef typename Container::value_type value_type;
+   typedef decltype(std::declval().emplace(std::declval())) queue_return_type;
+   
+#if TEST_STD_VER > 14
+   typedef 
decltype(std::declval().emplace_back(std::declval())) 
container_return_type;
+   static_assert(std::is_same::value, "");
+#else
+   static_assert(std::is_same::value, "");
+#endif
+}
+
 int main()
 {
-typedef Emplaceable T;
-std::queue q;
+   test_return_type > ();
+   test_return_type > > ();
+   
+   typedef Emplaceable T;
+   std::queue q;
 #if TEST_STD_VER > 14
-T& r1 = q.emplace(1, 2.5);
-assert(&r1 == &q.back());
-T& r2 = q.emplace(2, 3.5);
-assert(&r2 == &q.back());
-T& r3 = q.emplace(3, 4.5);
-assert(&r3 == &q.back());
-assert(&r1 == &q.front());
+   T& r1 = q.emplace(1, 2.5);
+   assert(&r1 == &q.back());
+   T& r2 = q.emplace(2, 3.5);
+   assert(&r2 == &q.back());
+   T& r3 = q.emplace(3, 4.5);
+   assert(&r3 == &q.back());
+   assert(&r1 == &q.front());
 #else
-q.emplace(1, 2.5);
-q.emplace(2, 3.5);
-q.emplace(3, 4.5);
+   q.emplace(1, 2.5);
+   q.emplace(2, 3.5);
+   q.emplace(3, 4.5);
 #endif
 
-assert(q.size() == 3);
-assert(q.front() == Emplaceable(1, 2.5));
-assert(q.back() == Emplaceable(3, 4.5));
+   assert(q.size() == 3);
+   assert(q.front() == Emplaceable(1, 2.5));
+   assert(q.back() == Emplaceable(3, 4.5));
 }

Modified: 
libcxx/trunk/test/std/containers/container.adaptors/stack/stack.defn/emplace.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/containers/container.adaptors/stack/stack.defn/emplace.pass.c

  1   2   >