Re: r320942 - [ASTImporter] Support importing FunctionTemplateDecl and CXXDependentScopeMemberExpr

2017-12-20 Thread Aleksei Sidorin via cfe-commits
Thank you, Peter! I'll take a look.
Unfortunately, there were no any buildbot e-mail complains about it so I 
didn't even notice the issue.


20.12.2017 04:48, Peter Collingbourne пишет:

Hi,

I reverted this change in r321139 because it causes a test failure on 
Windows.
e.g. 
https://logs.chromium.org/v/?s=chromium%2Fbb%2Ftryserver.chromium.win%2Fwin_upload_clang%2F277%2F%2B%2Frecipes%2Fsteps%2Fpackage_clang%2F0%2Fstdout

Please let me know if you have trouble reproducing.

Thanks,
Peter

On Sun, Dec 17, 2017 at 6:16 AM, Aleksei Sidorin via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:


Author: a.sidorin
Date: Sun Dec 17 06:16:17 2017
New Revision: 320942

URL: http://llvm.org/viewvc/llvm-project?rev=320942&view=rev

Log:
[ASTImporter] Support importing FunctionTemplateDecl and
CXXDependentScopeMemberExpr

* Also introduces ImportTemplateArgumentListInfo facility (A. Sidorin)

Patch by Peter Szecsi!

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


Modified:
    cfe/trunk/lib/AST/ASTImporter.cpp
    cfe/trunk/unittests/AST/ASTImporterTest.cpp

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL:

http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=320942&r1=320941&r2=320942&view=diff



==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Sun Dec 17 06:16:17 2017
@@ -134,12 +134,17 @@ namespace clang {
     bool ImportTemplateArguments(const TemplateArgument *FromArgs,
                                  unsigned NumFromArgs,
                                SmallVectorImpl
&ToArgs);
+    template 
+    bool ImportTemplateArgumentListInfo(const InContainerTy
&Container,
+ TemplateArgumentListInfo &ToTAInfo);
     bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl
*ToRecord,
                            bool Complain = true);
     bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
                            bool Complain = true);
     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
     bool IsStructuralMatch(EnumConstantDecl *FromEC,
EnumConstantDecl *ToEC);
+    bool IsStructuralMatch(FunctionTemplateDecl *From,
+                           FunctionTemplateDecl *To);
     bool IsStructuralMatch(ClassTemplateDecl *From,
ClassTemplateDecl *To);
     bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl
*To);
     Decl *VisitDecl(Decl *D);
@@ -195,6 +200,7 @@ namespace clang {
 ClassTemplateSpecializationDecl *D);
     Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
     Decl
*VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
+    Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);

     // Importing statements
     DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
@@ -280,6 +286,7 @@ namespace clang {
     Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E);
     Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
     Expr *VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
+    Expr
*VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
     Expr *VisitExprWithCleanups(ExprWithCleanups *EWC);
     Expr *VisitCXXThisExpr(CXXThisExpr *E);
     Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
@@ -1247,6 +1254,18 @@ bool ASTNodeImporter::ImportTemplateArgu
   return false;
 }

+template 
+bool ASTNodeImporter::ImportTemplateArgumentListInfo(
+    const InContainerTy &Container, TemplateArgumentListInfo
&ToTAInfo) {
+  for (const auto &FromLoc : Container) {
+    if (auto ToLoc = ImportTemplateArgumentLoc(FromLoc))
+      ToTAInfo.addArgument(*ToLoc);
+    else
+      return true;
+  }
+  return false;
+}
+
 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
                                         RecordDecl *ToRecord,
bool Complain) {
   // Eliminate a potential failure point where we attempt to
re-import
@@ -1280,6 +1299,14 @@ bool ASTNodeImporter::IsStructuralMatch(
   return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
 }

+bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
+ FunctionTemplateDecl *To) {
+  StructuralEquivalenceContext Ctx(
+      Importer.getFromContext(), Importer.getToContext(),
+      Importer.getNonEquivalentDecls(), false, false);
+  return Ctx.IsStructurallyEquivalent(From, To);
+}
+
 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
                

[clang-tools-extra] r321156 - [clangd] Add "../" to Logger.h included from parent directory.

2017-12-20 Thread Martin Bohme via cfe-commits
Author: mboehme
Date: Wed Dec 20 01:17:31 2017
New Revision: 321156

URL: http://llvm.org/viewvc/llvm-project?rev=321156&view=rev
Log:
[clangd] Add "../" to Logger.h included from parent directory.

Modified:
clang-tools-extra/trunk/clangd/index/MemIndex.cpp

Modified: clang-tools-extra/trunk/clangd/index/MemIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/MemIndex.cpp?rev=321156&r1=321155&r2=321156&view=diff
==
--- clang-tools-extra/trunk/clangd/index/MemIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/MemIndex.cpp Wed Dec 20 01:17:31 2017
@@ -8,7 +8,7 @@
 //===---===//
 
 #include "MemIndex.h"
-#include "Logger.h"
+#include "../Logger.h"
 
 namespace clang {
 namespace clangd {


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


[clang-tools-extra] r321157 - [clangd] Igore cases in index fuzzy find.

2017-12-20 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Wed Dec 20 01:29:54 2017
New Revision: 321157

URL: http://llvm.org/viewvc/llvm-project?rev=321157&view=rev
Log:
[clangd] Igore cases in index fuzzy find.

Modified:
clang-tools-extra/trunk/clangd/index/MemIndex.cpp
clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/MemIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/MemIndex.cpp?rev=321157&r1=321156&r2=321157&view=diff
==
--- clang-tools-extra/trunk/clangd/index/MemIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/MemIndex.cpp Wed Dec 20 01:29:54 2017
@@ -49,7 +49,7 @@ bool MemIndex::fuzzyFind(const Context &
 continue;
 
   // FIXME(ioeric): use fuzzy matcher.
-  if (StringRef(StringRef(Sym->Name).lower()).contains(Req.Query)) {
+  if (StringRef(Sym->Name).find_lower(Req.Query) != StringRef::npos) {
 if (++Matched > Req.MaxCandidateCount)
   return false;
 Callback(*Sym);

Modified: clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp?rev=321157&r1=321156&r2=321157&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/IndexTests.cpp Wed Dec 20 01:29:54 
2017
@@ -178,6 +178,16 @@ TEST(MemIndexTest, NoMatchNestedScopes)
   EXPECT_THAT(match(I, Req), UnorderedElementsAre("a::xyz"));
 }
 
+TEST(MemIndexTest, IgnoreCases) {
+  MemIndex I;
+  I.build(generateSymbols({"ns::ABC", "ns::abc"}));
+  FuzzyFindRequest Req;
+  Req.Query = "AB";
+  Req.Scopes = {"ns"};
+  auto Matches = match(I, Req);
+  EXPECT_THAT(match(I, Req), UnorderedElementsAre("ns::ABC", "ns::abc"));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


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


[PATCH] D41432: [clangd] Switch xrefs and documenthighlight to annotated-code unit tests. NFC

2017-12-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ioeric.
Herald added subscribers: cfe-commits, ilya-biryukov, mgorny, klimek.

The goal here is again to make it easier to read and write the tests.

I've extracted `parseTextMarker` from CodeCompleteTests into an `Annotations`
class, adding features to it:

- as well as points `^s` it allows ranges `[[...]]`
- multiple points and ranges are supported
- points and ranges may be named: `$name^` and `$name[[...]]`

These features are used for the xrefs tests. This also paves the way for
replacing the lit diagnostics.test with more readable unit tests, using named
ranges.

Alternative considered: `TestSelectionRange` in clang-refactor/TestSupport
Main problems were:

- delimiting the end of ranges is awkward, requiring counting
- comment syntax is long and at least as cryptic for most cases
- no separate syntax for point vs range, which keeps xrefs tests concise
- Still need to convert to Position everywhere
- Still need helpers for common case of expecting exactly one point/range

(I'll probably promote the extra `PrintTo`s from some of the core Protocol types
into `operator<<` in `Protocol.h` itself in a separate, prior patch...)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41432

Files:
  test/clangd/definitions.test
  test/clangd/documenthighlight.test
  test/clangd/xrefs.test
  unittests/clangd/Annotations.cpp
  unittests/clangd/Annotations.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/Matchers.h
  unittests/clangd/XRefsTests.cpp

Index: unittests/clangd/XRefsTests.cpp
===
--- /dev/null
+++ unittests/clangd/XRefsTests.cpp
@@ -0,0 +1,222 @@
+//===-- XRefsTests.cpp  ---*- C++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "Annotations.h"
+#include "ClangdUnit.h"
+#include "Matchers.h"
+#include "XRefs.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/PCHContainerOperations.h"
+#include "clang/Frontend/Utils.h"
+#include "llvm/Support/Path.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+using namespace llvm;
+
+void PrintTo(const DocumentHighlight &V, std::ostream *O) {
+  PrintTo(V.range, O);
+  if (V.kind == DocumentHighlightKind::Read)
+*O << "(r)";
+  if (V.kind == DocumentHighlightKind::Write)
+*O << "(w)";
+}
+void PrintTo(const Location &V, std::ostream *O) {
+  PrintTo(V.range, O);
+  raw_os_ostream OS(*O);
+  OS << "@" << V.uri.file;
+}
+
+namespace {
+using testing::ElementsAre;
+using testing::Field;
+using testing::Matcher;
+using testing::UnorderedElementsAreArray;
+
+// FIXME: this is duplicated with FileIndexTests. Share it.
+ParsedAST build(StringRef Code) {
+  auto CI = createInvocationFromCommandLine({"clang", "-xc++", "Foo.cpp"});
+  auto Buf = MemoryBuffer::getMemBuffer(Code);
+  auto AST = ParsedAST::Build(
+  Context::empty(), std::move(CI), nullptr, std::move(Buf),
+  std::make_shared(), vfs::getRealFileSystem());
+  assert(AST.hasValue());
+  return std::move(*AST);
+}
+
+// Extracts ranges from an annotated example, and constructs a matcher for a
+// highlight set. Ranges should be named $read/$write as appropriate.
+Matcher &>
+HighlightsFrom(const Annotations &Test) {
+  std::vector Expected;
+  auto Add = [&](const Range &R, DocumentHighlightKind K) {
+Expected.emplace_back();
+Expected.back().range = R;
+Expected.back().kind = K;
+  };
+  for (const auto &Range : Test.ranges())
+Add(Range, DocumentHighlightKind::Text);
+  for (const auto &Range : Test.ranges("read"))
+Add(Range, DocumentHighlightKind::Read);
+  for (const auto &Range : Test.ranges("write"))
+Add(Range, DocumentHighlightKind::Write);
+  return UnorderedElementsAreArray(Expected);
+}
+
+TEST(HighlightsTest, All) {
+  const char *Tests[] = {
+  R"cpp(// Local variable
+int main() {
+  int [[bonjour]];
+  $write[[^bonjour]] = 2;
+  int test1 = $read[[bonjour]];
+}
+  )cpp",
+
+  R"cpp(// Struct
+namespace ns1 {
+struct [[MyClass]] {
+  static void foo([[MyClass]]*) {}
+};
+} // namespace ns1
+int main() {
+  ns1::[[My^Class]]* Params;
+}
+  )cpp",
+
+  R"cpp(// Function
+int [[^foo]](int) {}
+int main() {
+  [[foo]]([[foo]](42));
+  auto *X = &[[foo]];
+}
+  )cpp",
+  };
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto AST = build(T.code());
+EXPECT_THAT(findDocumentHighlights(Context::empty(), AST, T.point()),
+HighlightsFrom(T))
+

[clang-tools-extra] r321161 - [clangd] Add debug printers for basic protocol types. NFC

2017-12-20 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Wed Dec 20 02:26:53 2017
New Revision: 321161

URL: http://llvm.org/viewvc/llvm-project?rev=321161&view=rev
Log:
[clangd] Add debug printers for basic protocol types. NFC

Modified:
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp

Modified: clang-tools-extra/trunk/clangd/Protocol.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.cpp?rev=321161&r1=321160&r2=321161&view=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.cpp (original)
+++ clang-tools-extra/trunk/clangd/Protocol.cpp Wed Dec 20 02:26:53 2017
@@ -59,6 +59,10 @@ bool fromJSON(const json::Expr &E, URI &
 
 json::Expr toJSON(const URI &U) { return U.uri; }
 
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const URI &U) {
+  return OS << U.uri;
+}
+
 bool fromJSON(const json::Expr &Params, TextDocumentIdentifier &R) {
   json::ObjectMapper O(Params);
   return O && O.map("uri", R.uri);
@@ -76,6 +80,10 @@ json::Expr toJSON(const Position &P) {
   };
 }
 
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Position &P) {
+  return OS << P.line << ':' << P.character;
+}
+
 bool fromJSON(const json::Expr &Params, Range &R) {
   json::ObjectMapper O(Params);
   return O && O.map("start", R.start) && O.map("end", R.end);
@@ -88,6 +96,10 @@ json::Expr toJSON(const Range &P) {
   };
 }
 
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Range &R) {
+  return OS << R.start << '-' << R.end;
+}
+
 json::Expr toJSON(const Location &P) {
   return json::obj{
   {"uri", P.uri},
@@ -95,6 +107,10 @@ json::Expr toJSON(const Location &P) {
   };
 }
 
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Location &L) {
+  return OS << L.range << '@' << L.uri;
+}
+
 bool fromJSON(const json::Expr &Params, TextDocumentItem &R) {
   json::ObjectMapper O(Params);
   return O && O.map("uri", R.uri) && O.map("languageId", R.languageId) &&

Modified: clang-tools-extra/trunk/clangd/Protocol.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.h?rev=321161&r1=321160&r2=321161&view=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.h (original)
+++ clang-tools-extra/trunk/clangd/Protocol.h Wed Dec 20 02:26:53 2017
@@ -16,6 +16,9 @@
 // Each struct has a toJSON and fromJSON function, that converts between
 // the struct and a JSON representation. (See JSONExpr.h)
 //
+// Some structs also have operator<< serialization. This is for debugging and
+// tests, and is not generally machine-readable.
+//
 
//===--===//
 
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_PROTOCOL_H
@@ -65,6 +68,7 @@ struct URI {
 };
 json::Expr toJSON(const URI &U);
 bool fromJSON(const json::Expr &, URI &);
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, const URI &);
 
 struct TextDocumentIdentifier {
   /// The text document's URI.
@@ -90,6 +94,7 @@ struct Position {
 };
 bool fromJSON(const json::Expr &, Position &);
 json::Expr toJSON(const Position &);
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Position &);
 
 struct Range {
   /// The range's start position.
@@ -107,6 +112,7 @@ struct Range {
 };
 bool fromJSON(const json::Expr &, Range &);
 json::Expr toJSON(const Range &);
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Range &);
 
 struct Location {
   /// The text document's URI.
@@ -126,6 +132,7 @@ struct Location {
   }
 };
 json::Expr toJSON(const Location &);
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Location &);
 
 struct Metadata {
   std::vector extraFlags;

Modified: clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp?rev=321161&r1=321160&r2=321161&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp Wed Dec 20 
02:26:53 2017
@@ -13,10 +13,6 @@
 
 namespace clang{
 namespace clangd {
-void PrintTo(const Position &P, std::ostream *O) {
-  llvm::raw_os_ostream OS(*O);
-  OS << toJSON(P);
-}
 namespace {
 
 MATCHER_P2(Pos, Line, Col, "") {


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


[PATCH] D41432: [clangd] Switch xrefs and documenthighlight to annotated-code unit tests. NFC

2017-12-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 127674.
sammccall added a comment.

Remove test PrintTos for basic types after r321161.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41432

Files:
  test/clangd/definitions.test
  test/clangd/documenthighlight.test
  test/clangd/xrefs.test
  unittests/clangd/Annotations.cpp
  unittests/clangd/Annotations.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/Matchers.h
  unittests/clangd/SourceCodeTests.cpp
  unittests/clangd/XRefsTests.cpp

Index: unittests/clangd/XRefsTests.cpp
===
--- /dev/null
+++ unittests/clangd/XRefsTests.cpp
@@ -0,0 +1,217 @@
+//===-- XRefsTests.cpp  ---*- C++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "Annotations.h"
+#include "ClangdUnit.h"
+#include "Matchers.h"
+#include "XRefs.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/PCHContainerOperations.h"
+#include "clang/Frontend/Utils.h"
+#include "llvm/Support/Path.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+using namespace llvm;
+
+void PrintTo(const DocumentHighlight &V, std::ostream *O) {
+  PrintTo(V.range, O);
+  if (V.kind == DocumentHighlightKind::Read)
+*O << "(r)";
+  if (V.kind == DocumentHighlightKind::Write)
+*O << "(w)";
+}
+
+namespace {
+using testing::ElementsAre;
+using testing::Field;
+using testing::Matcher;
+using testing::UnorderedElementsAreArray;
+
+// FIXME: this is duplicated with FileIndexTests. Share it.
+ParsedAST build(StringRef Code) {
+  auto CI = createInvocationFromCommandLine({"clang", "-xc++", "Foo.cpp"});
+  auto Buf = MemoryBuffer::getMemBuffer(Code);
+  auto AST = ParsedAST::Build(
+  Context::empty(), std::move(CI), nullptr, std::move(Buf),
+  std::make_shared(), vfs::getRealFileSystem());
+  assert(AST.hasValue());
+  return std::move(*AST);
+}
+
+// Extracts ranges from an annotated example, and constructs a matcher for a
+// highlight set. Ranges should be named $read/$write as appropriate.
+Matcher &>
+HighlightsFrom(const Annotations &Test) {
+  std::vector Expected;
+  auto Add = [&](const Range &R, DocumentHighlightKind K) {
+Expected.emplace_back();
+Expected.back().range = R;
+Expected.back().kind = K;
+  };
+  for (const auto &Range : Test.ranges())
+Add(Range, DocumentHighlightKind::Text);
+  for (const auto &Range : Test.ranges("read"))
+Add(Range, DocumentHighlightKind::Read);
+  for (const auto &Range : Test.ranges("write"))
+Add(Range, DocumentHighlightKind::Write);
+  return UnorderedElementsAreArray(Expected);
+}
+
+TEST(HighlightsTest, All) {
+  const char *Tests[] = {
+  R"cpp(// Local variable
+int main() {
+  int [[bonjour]];
+  $write[[^bonjour]] = 2;
+  int test1 = $read[[bonjour]];
+}
+  )cpp",
+
+  R"cpp(// Struct
+namespace ns1 {
+struct [[MyClass]] {
+  static void foo([[MyClass]]*) {}
+};
+} // namespace ns1
+int main() {
+  ns1::[[My^Class]]* Params;
+}
+  )cpp",
+
+  R"cpp(// Function
+int [[^foo]](int) {}
+int main() {
+  [[foo]]([[foo]](42));
+  auto *X = &[[foo]];
+}
+  )cpp",
+  };
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto AST = build(T.code());
+EXPECT_THAT(findDocumentHighlights(Context::empty(), AST, T.point()),
+HighlightsFrom(T))
+<< Test;
+  }
+}
+
+MATCHER_P(RangeIs, R, "") { return arg.range == R; }
+
+TEST(GoToDefinition, All) {
+  const char *Tests[] = {
+  R"cpp(// Local variable
+int main() {
+  [[int bonjour]];
+  ^bonjour = 2;
+  int test1 = bonjour;
+}
+  )cpp",
+
+  R"cpp(// Struct
+namespace ns1 {
+[[struct MyClass {}]];
+} // namespace ns1
+int main() {
+  ns1::My^Class* Params;
+}
+  )cpp",
+
+  R"cpp(// Function definition via pointer
+[[int foo(int) {}]]
+int main() {
+  auto *X = &^foo;
+}
+  )cpp",
+
+  R"cpp(// Function declaration via call
+[[int foo(int)]];
+int main() {
+  return ^foo(42);
+}
+  )cpp",
+
+  R"cpp(// Field
+struct Foo { [[int x]]; };
+int main() {
+  Foo bar;
+  bar.^x;
+}
+  )cpp",
+
+  R"cpp(// Field, member initializer
+struct Foo {
+  [[int x]];
+  Foo() : ^x(0) {}
+};
+  )cpp",
+
+  R"cpp(// Field, GNU old-style field designator
+struct Foo { [[int x]]; 

[PATCH] D41433: Unit tests for TBAA metadata generation.

2017-12-20 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff created this revision.
sepavloff added reviewers: rjmccall, hfinkel.
Herald added subscribers: kosarev, mgorny.

Now tests for metadata created by clang involve compiling code snippets
placed into c/c++ source files and matching interesting patterns in the
obtained textual representation of IR. Writting such tests is a painful
process as metadata often form complex tree-like structures but textual
representation of IR contains only a pile of metadata at the module end.

This change implements IR matchers that may be used to match required
patterns in the binary IR representation. In this case the metadata
structure is not broken and creation of match patterns is easier.

The change adds unit tests for TBAA metadata generation.


Repository:
  rC Clang

https://reviews.llvm.org/D41433

Files:
  unittests/CodeGen/CMakeLists.txt
  unittests/CodeGen/IRMatchers.h
  unittests/CodeGen/TBAAMetadataTest.cpp

Index: unittests/CodeGen/TBAAMetadataTest.cpp
===
--- /dev/null
+++ unittests/CodeGen/TBAAMetadataTest.cpp
@@ -0,0 +1,1299 @@
+//=== unittests/CodeGen/TBAAMetadataTest.cpp - Checks metadata generation -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "IRMatchers.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/CodeGen/ModuleBuilder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Parse/ParseAST.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Constants.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "gtest/gtest.h"
+#include 
+
+using namespace llvm;
+
+namespace {
+
+struct TestCompiler {
+  LLVMContext Context;
+  clang::CompilerInstance compiler;
+  clang::CodeGenerator *CG = nullptr;
+  llvm::Module *M = nullptr;
+  unsigned PtrSize = 0;
+
+  void init(const char *TestProgram) {
+compiler.createDiagnostics();
+compiler.getCodeGenOpts().StructPathTBAA = 1;
+compiler.getCodeGenOpts().OptimizationLevel = 1;
+
+std::string TrStr = llvm::Triple::normalize(llvm::sys::getProcessTriple());
+llvm::Triple Tr(TrStr);
+Tr.setOS(Triple::Linux);
+Tr.setVendor(Triple::VendorType::UnknownVendor);
+Tr.setEnvironment(Triple::EnvironmentType::UnknownEnvironment);
+compiler.getTargetOpts().Triple = Tr.getTriple();
+compiler.setTarget(clang::TargetInfo::CreateTargetInfo(
+compiler.getDiagnostics(),
+std::make_shared(compiler.getTargetOpts(;
+
+const clang::TargetInfo &TInfo = compiler.getTarget();
+PtrSize = TInfo.getPointerWidth(0) / 8;
+
+compiler.createFileManager();
+compiler.createSourceManager(compiler.getFileManager());
+compiler.createPreprocessor(clang::TU_Prefix);
+
+compiler.createASTContext();
+
+CG = CreateLLVMCodeGen(
+compiler.getDiagnostics(),
+"main-module",
+compiler.getHeaderSearchOpts(),
+compiler.getPreprocessorOpts(),
+compiler.getCodeGenOpts(),
+Context);
+compiler.setASTConsumer(std::unique_ptr(CG));
+
+compiler.createSema(clang::TU_Prefix, nullptr);
+
+clang::SourceManager &sm = compiler.getSourceManager();
+sm.setMainFileID(sm.createFileID(
+llvm::MemoryBuffer::getMemBuffer(TestProgram), clang::SrcMgr::C_User));
+  }
+
+  const BasicBlock *compile() {
+clang::ParseAST(compiler.getSema(), false, false);
+M = CG->GetModule();
+
+// Do not expect more than one function definition.
+auto FuncPtr = M->begin();
+for (; FuncPtr != M->end(); ++FuncPtr)
+  if (!FuncPtr->isDeclaration())
+break;
+assert(FuncPtr != M->end());
+const llvm::Function &Func = *FuncPtr;
+++FuncPtr;
+for (; FuncPtr != M->end(); ++FuncPtr)
+  if (!FuncPtr->isDeclaration())
+break;
+assert(FuncPtr == M->end());
+
+// The function must consist of single basic block.
+auto BBPtr = Func.begin();
+assert(Func.begin() != Func.end());
+const BasicBlock &BB = *BBPtr;
+++BBPtr;
+assert(BBPtr == Func.end());
+
+return &BB;
+  }
+};
+
+
+auto OmnipotentCharC = MMTuple(
+  MMString("omnipotent char"),
+  MMTuple(
+MMString("Simple C/C++ TBAA")),
+  MConstInt(0, 64)
+);
+
+
+auto OmnipotentCharCXX = MMTuple(
+  MMString("omnipotent char"),
+  MMTuple(
+MMString("Simple C++ TBAA")),
+  MConstInt(0, 64)
+);
+
+
+TEST(TBAAMetadataTest, BasicTypes) {
+  const char TestProgram[] = R"**(
+void func(char *CP, short *SP, int *IP, long long *LP, void **VPP,
+  int **IPP) {
+  *CP = 4;
+  *SP = 11;
+  *IP = 601;
+  *LP = 604;
+  *VPP = CP;
+  *IPP = IP;
+}
+  )**";
+
+  TestCompiler Compiler;
+  Compiler.compiler.getLangOpts().C1

[PATCH] D40295: -fsanitize=vptr warnings on bad static types in dynamic_cast and typeid

2017-12-20 Thread Stephan Bergmann via Phabricator via cfe-commits
sberg updated this revision to Diff 127676.
sberg added a comment.

added a small IR test


https://reviews.llvm.org/D40295

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGenCXX/ubsan-vtable-checks.cpp
  compiler-rt/lib/ubsan/ubsan_handlers.cc
  compiler-rt/test/ubsan/TestCases/TypeCheck/vptr.cpp

Index: compiler-rt/test/ubsan/TestCases/TypeCheck/vptr.cpp
===
--- compiler-rt/test/ubsan/TestCases/TypeCheck/vptr.cpp
+++ compiler-rt/test/ubsan/TestCases/TypeCheck/vptr.cpp
@@ -1,41 +1,53 @@
-// RUN: %clangxx -frtti -fsanitize=null,vptr -fno-sanitize-recover=null,vptr -g %s -O3 -o %t -mllvm -enable-tail-merge=false
-// RUN: %run %t rT && %run %t mT && %run %t fT && %run %t cT
-// RUN: %run %t rU && %run %t mU && %run %t fU && %run %t cU
-// RUN: %run %t rS && %run %t rV && %run %t oV
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t mS 2>&1 | FileCheck %s --check-prefix=CHECK-MEMBER --check-prefix=CHECK-%os-MEMBER --strict-whitespace
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t fS 2>&1 | FileCheck %s --check-prefix=CHECK-MEMFUN --strict-whitespace
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t cS 2>&1 | FileCheck %s --check-prefix=CHECK-DOWNCAST --check-prefix=CHECK-%os-DOWNCAST --strict-whitespace
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t mV 2>&1 | FileCheck %s --check-prefix=CHECK-MEMBER --check-prefix=CHECK-%os-MEMBER --strict-whitespace
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t fV 2>&1 | FileCheck %s --check-prefix=CHECK-MEMFUN --strict-whitespace
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t cV 2>&1 | FileCheck %s --check-prefix=CHECK-DOWNCAST --check-prefix=CHECK-%os-DOWNCAST --strict-whitespace
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t oU 2>&1 | FileCheck %s --check-prefix=CHECK-OFFSET --check-prefix=CHECK-%os-OFFSET --strict-whitespace
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t m0 2>&1 | FileCheck %s --check-prefix=CHECK-INVALID-MEMBER --check-prefix=CHECK-%os-NULL-MEMBER --strict-whitespace
-// RUN: %env_ubsan_opts=print_stacktrace=1 not %run %t m0 2>&1 | FileCheck %s --check-prefix=CHECK-INVALID-MEMBER --check-prefix=CHECK-%os-NULL-MEMBER --strict-whitespace
-// RUN: not %run %t nN 2>&1 | FileCheck %s --check-prefix=CHECK-NULL-MEMFUN --strict-whitespace
+// RUN: %clangxx -frtti -fsanitize=null,vptr -g %s -O3 -o %t -mllvm -enable-tail-merge=false
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t rT
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t mT
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t fT
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t cT
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t rU
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t mU
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t fU
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t cU
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t rS
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t rV
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t oV
+// RUN: %env_ubsan_opts=halt_on_error=1 %run %t zN
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t mS 2>&1 | FileCheck %s --check-prefix=CHECK-MEMBER --check-prefix=CHECK-%os-MEMBER --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t fS 2>&1 | FileCheck %s --check-prefix=CHECK-MEMFUN --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t cS 2>&1 | FileCheck %s --check-prefix=CHECK-DOWNCAST --check-prefix=CHECK-%os-DOWNCAST --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t mV 2>&1 | FileCheck %s --check-prefix=CHECK-MEMBER --check-prefix=CHECK-%os-MEMBER --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t fV 2>&1 | FileCheck %s --check-prefix=CHECK-MEMFUN --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t cV 2>&1 | FileCheck %s --check-prefix=CHECK-DOWNCAST --check-prefix=CHECK-%os-DOWNCAST --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t oU 2>&1 | FileCheck %s --check-prefix=CHECK-OFFSET --check-prefix=CHECK-%os-OFFSET --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t m0 2>&1 | FileCheck %s --check-prefix=CHECK-INVALID-MEMBER --check-prefix=CHECK-%os-NULL-MEMBER --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1:print_stacktrace=1 not %run %t m0 2>&1 | FileCheck %s --check-prefix=CHECK-INVALID-MEMBER --check-prefix=CHECK-%os-NULL-MEMBER --strict-whitespace
+// RUN: %env_ubsan_opts=halt_on_error=1 not %run %t nN 2>&1 | FileCheck %s --check-prefix=CHECK-NULL-MEMFUN --strict-whitespace
+// RUN: %env_ubsan_opts=print_stacktrace=1 %run %t dT 2>&1 | FileCheck %s --check-prefix=CHECK-DYNAMIC --check-prefix=CHECK-%os-DYNAMIC --strict-whitespace
 
 // RUN: (echo 

[PATCH] D41237: [Frontend] Handle skipped bodies in template instantiations

2017-12-20 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff accepted this revision.
sepavloff added a comment.
This revision is now accepted and ready to land.

LGTM.

Thanks!


Repository:
  rC Clang

https://reviews.llvm.org/D41237



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


[PATCH] D41432: [clangd] Switch xrefs and documenthighlight to annotated-code unit tests. NFC

2017-12-20 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added a comment.
This revision is now accepted and ready to land.

lgtm! This is amazing!




Comment at: unittests/clangd/Annotations.h:12
+//
+//Annotations Example(R"cpp(
+//   int complete() { x.pri^ }  // ^ indicates a point

Does this support overlapping annotations like (named) points in (named) ranges?



Comment at: unittests/clangd/Annotations.h:45
+  // Crashes if there isn't exactly one.
+  Position point(llvm::StringRef Name = "") const;
+  // Returns the position of all points marked by ^ (or $name^) in the text.

Is this the position in the stripped code or the original text?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41432



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


[PATCH] D41409: [analyzer] Fix intermediate diagnostics on paths that go through operator new().

2017-12-20 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin accepted this revision.
a.sidorin added a comment.
This revision is now accepted and ready to land.

Looks good!


Repository:
  rC Clang

https://reviews.llvm.org/D41409



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


r321167 - Remove llvm::MemoryBuffer const_casts

2017-12-20 Thread Pavel Labath via cfe-commits
Author: labath
Date: Wed Dec 20 03:34:38 2017
New Revision: 321167

URL: http://llvm.org/viewvc/llvm-project?rev=321167&view=rev
Log:
Remove llvm::MemoryBuffer const_casts

Summary:
llvm has grown a WritableMemoryBuffer class, which is convertible
(inherits from) a MemoryBuffer. We can use it to avoid conts_casting the
buffer contents when we want to write to it.

Reviewers: dblaikie, rsmith

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Basic/SourceManager.cpp
cfe/trunk/lib/Lex/Preprocessor.cpp

Modified: cfe/trunk/lib/Basic/SourceManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/SourceManager.cpp?rev=321167&r1=321166&r2=321167&view=diff
==
--- cfe/trunk/lib/Basic/SourceManager.cpp (original)
+++ cfe/trunk/lib/Basic/SourceManager.cpp Wed Dec 20 03:34:38 2017
@@ -125,11 +125,12 @@ llvm::MemoryBuffer *ContentCache::getBuf
   // possible.
   if (!BufferOrError) {
 StringRef FillStr("<<>>\n");
-Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
-  ContentsEntry->getSize(), "").release());
-char *Ptr = const_cast(Buffer.getPointer()->getBufferStart());
+auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
+ContentsEntry->getSize(), "");
+char *Ptr = BackupBuffer->getBufferStart();
 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
   Ptr[i] = FillStr[i % FillStr.size()];
+Buffer.setPointer(BackupBuffer.release());
 
 if (Diag.isDiagnosticInFlight())
   Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,

Modified: cfe/trunk/lib/Lex/Preprocessor.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/Preprocessor.cpp?rev=321167&r1=321166&r2=321167&view=diff
==
--- cfe/trunk/lib/Lex/Preprocessor.cpp (original)
+++ cfe/trunk/lib/Lex/Preprocessor.cpp Wed Dec 20 03:34:38 2017
@@ -420,10 +420,9 @@ bool Preprocessor::SetCodeCompletionPoin
   CodeCompletionFile = File;
   CodeCompletionOffset = Position - Buffer->getBufferStart();
 
-  std::unique_ptr NewBuffer =
-  MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
-  Buffer->getBufferIdentifier());
-  char *NewBuf = const_cast(NewBuffer->getBufferStart());
+  auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
+  Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
+  char *NewBuf = NewBuffer->getBufferStart();
   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
   *NewPos = '\0';
   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);


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


[PATCH] D41387: Remove llvm::MemoryBuffer const_casts

2017-12-20 Thread Pavel Labath via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL321167: Remove llvm::MemoryBuffer const_casts (authored by 
labath, committed by ).

Repository:
  rL LLVM

https://reviews.llvm.org/D41387

Files:
  cfe/trunk/lib/Basic/SourceManager.cpp
  cfe/trunk/lib/Lex/Preprocessor.cpp


Index: cfe/trunk/lib/Lex/Preprocessor.cpp
===
--- cfe/trunk/lib/Lex/Preprocessor.cpp
+++ cfe/trunk/lib/Lex/Preprocessor.cpp
@@ -420,10 +420,9 @@
   CodeCompletionFile = File;
   CodeCompletionOffset = Position - Buffer->getBufferStart();
 
-  std::unique_ptr NewBuffer =
-  MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
-  Buffer->getBufferIdentifier());
-  char *NewBuf = const_cast(NewBuffer->getBufferStart());
+  auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
+  Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
+  char *NewBuf = NewBuffer->getBufferStart();
   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
   *NewPos = '\0';
   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
Index: cfe/trunk/lib/Basic/SourceManager.cpp
===
--- cfe/trunk/lib/Basic/SourceManager.cpp
+++ cfe/trunk/lib/Basic/SourceManager.cpp
@@ -125,11 +125,12 @@
   // possible.
   if (!BufferOrError) {
 StringRef FillStr("<<>>\n");
-Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
-  ContentsEntry->getSize(), "").release());
-char *Ptr = const_cast(Buffer.getPointer()->getBufferStart());
+auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
+ContentsEntry->getSize(), "");
+char *Ptr = BackupBuffer->getBufferStart();
 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
   Ptr[i] = FillStr[i % FillStr.size()];
+Buffer.setPointer(BackupBuffer.release());
 
 if (Diag.isDiagnosticInFlight())
   Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,


Index: cfe/trunk/lib/Lex/Preprocessor.cpp
===
--- cfe/trunk/lib/Lex/Preprocessor.cpp
+++ cfe/trunk/lib/Lex/Preprocessor.cpp
@@ -420,10 +420,9 @@
   CodeCompletionFile = File;
   CodeCompletionOffset = Position - Buffer->getBufferStart();
 
-  std::unique_ptr NewBuffer =
-  MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
-  Buffer->getBufferIdentifier());
-  char *NewBuf = const_cast(NewBuffer->getBufferStart());
+  auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
+  Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
+  char *NewBuf = NewBuffer->getBufferStart();
   char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
   *NewPos = '\0';
   std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
Index: cfe/trunk/lib/Basic/SourceManager.cpp
===
--- cfe/trunk/lib/Basic/SourceManager.cpp
+++ cfe/trunk/lib/Basic/SourceManager.cpp
@@ -125,11 +125,12 @@
   // possible.
   if (!BufferOrError) {
 StringRef FillStr("<<>>\n");
-Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
-  ContentsEntry->getSize(), "").release());
-char *Ptr = const_cast(Buffer.getPointer()->getBufferStart());
+auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
+ContentsEntry->getSize(), "");
+char *Ptr = BackupBuffer->getBufferStart();
 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
   Ptr[i] = FillStr[i % FillStr.size()];
+Buffer.setPointer(BackupBuffer.release());
 
 if (Diag.isDiagnosticInFlight())
   Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41408: [analyzer] NFC: Fix nothrow operator new definition in a test.

2017-12-20 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin accepted this revision.
a.sidorin added a comment.
This revision is now accepted and ready to land.

Looks good, just a minor nit.




Comment at: test/Analysis/NewDelete-custom.cpp:7
 
-#if !LEAKS
+#if !(LEAKS && !ALLOCATOR_INLINING)
 // expected-no-diagnostics

Double negation can be simplified a bit: `#if !LEAKS || ALLOCATOR_INLINING`


Repository:
  rC Clang

https://reviews.llvm.org/D41408



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


[PATCH] D39239: [AST] Incorrectly qualified unscoped enumeration as template actual parameter.

2017-12-20 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
CarlosAlbertoEnciso added a comment.

In https://reviews.llvm.org/D39239#912837, @probinson wrote:

> Have you tried the GDB suite yet?  If it has no problems, and we can make 
> LLDB happy, I'm okay with it.


Hi Paul,

Following the instructions from David Blaikie on how to build/run the GDB suite:

"Directions for how to run it would be divined from the buildbot configuration.

https://github.com/llvm-mirror/zorg/blob/master/zorg/buildbot/builders/ClangBuilder.py#L883";

1. I have managed to build the GDB suite using clang as the default compiler.
2. Run the test before and after my changes and the results are the same.



=== gdb Summary ===
  
  # of expected passes  20501
  # of unexpected failures  1481
  # of expected failures262
  # of unknown successes2
  # of known failures   78
  # of unresolved testcases 9
  # of untested testcases   48
  # of unsupported tests36

The unexpected failures falls into the categories:

- Invalid option '-w' to the ADA compiler
- Timeout issues
- Threading and attaching issues

Possible incorrect settings for the GDB suite.


https://reviews.llvm.org/D39239



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


[clang-tools-extra] r321168 - [clang-tidy] Misc redundant expression checker updated for ineffective bitwise operator expressions

2017-12-20 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Dec 20 04:22:16 2017
New Revision: 321168

URL: http://llvm.org/viewvc/llvm-project?rev=321168&view=rev
Log:
[clang-tidy] Misc redundant expression checker updated for ineffective bitwise 
operator expressions

Examples:
* Always evaluates to 0:

```
  int X;
  if (0 & X) return;
```

* Always evaluates to ~0:

```
  int Y;
  if (Y | ~0) return;
```

* The symbol is unmodified:

```
  int Z;
  Z &= ~0;
```

Patch by: Lilla Barancsuk!

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

Modified:
clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp

Modified: clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp?rev=321168&r1=321167&r2=321168&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp Wed 
Dec 20 04:22:16 2017
@@ -22,6 +22,7 @@
 #include "llvm/Support/Casting.h"
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -198,7 +199,7 @@ static bool areExclusiveRanges(BinaryOpe
 }
 
 // Returns whether the ranges covered by the union of both relational
-// expressions covers the whole domain (i.e. x < 10  and  x > 0).
+// expressions cover the whole domain (i.e. x < 10  and  x > 0).
 static bool rangesFullyCoverDomain(BinaryOperatorKind OpcodeLHS,
const APSInt &ValueLHS,
BinaryOperatorKind OpcodeRHS,
@@ -519,6 +520,9 @@ static bool retrieveRelationalIntegerCon
 if (canOverloadedOperatorArgsBeModified(OverloadedFunctionDecl, false))
   return false;
 
+if (canOverloadedOperatorArgsBeModified(OverloadedFunctionDecl, false))
+  return false;
+
 if (!OverloadedOperatorExpr->getArg(1)->isIntegerConstantExpr(
 Value, *Result.Context))
   return false;
@@ -559,7 +563,7 @@ static bool areSidesBinaryConstExpressio
 }
 
 // Retrieves integer constant subexpressions from binary operator expressions
-// that have two equivalent sides
+// that have two equivalent sides.
 // E.g.: from (X == 5) && (X == 5) retrieves 5 and 5.
 static bool retrieveConstExprFromBothSides(const BinaryOperator *&BinOp,
BinaryOperatorKind &MainOpcode,
@@ -675,6 +679,33 @@ void RedundantExpressionCheck::registerM
   .bind("call"),
   this);
 
+  // Match expressions like: !(1 | 2 | 3)
+  Finder->addMatcher(
+  implicitCastExpr(
+  hasImplicitDestinationType(isInteger()),
+  has(unaryOperator(
+  hasOperatorName("!"),
+  hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
+  anyOf(hasOperatorName("|"), hasOperatorName("&")),
+  hasLHS(anyOf(binaryOperator(anyOf(hasOperatorName("|"),
+hasOperatorName("&"))),
+   integerLiteral())),
+  hasRHS(integerLiteral())
+  .bind("logical-bitwise-confusion"))),
+  this);
+
+  // Match expressions like: (X << 8) & 0xFF
+  Finder->addMatcher(
+  binaryOperator(hasOperatorName("&"),
+ hasEitherOperand(ignoringParenImpCasts(binaryOperator(
+ hasOperatorName("<<"),
+ hasRHS(ignoringParenImpCasts(
+ integerLiteral().bind("shift-const")),
+ hasEitherOperand(ignoringParenImpCasts(
+ integerLiteral().bind("and-const"
+  .bind("left-right-shift-confusion"),
+  this);
+
   // Match common expressions and apply more checks to find redundant
   // sub-expressions.
   //   a) Expr  K1 == K2
@@ -783,6 +814,21 @@ void RedundantExpressionCheck::checkArit
   }
 }
 
+static bool exprEvaluatesToZero(BinaryOperatorKind Opcode, APSInt Value) {
+  return (Opcode == BO_And || Opcode == BO_AndAssign) && Value == 0;
+}
+
+static bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode,
+  APSInt Value) {
+  return (Opcode == BO_Or || Opcode == BO_OrAssign) && ~Value == 0;
+}
+
+static bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode, APSInt Value) {
+  return ((Opcode == BO_Or || Opcode == BO_OrAssign) && Value == 0) ||
+ ((Opcode == BO_And || Opcode == BO_AndAssign) && ~Value == 0);
+}
+
+
 void RedundantExpressionCheck::checkBitwiseExpr(
 const MatchFinder::MatchResult &Result) {
   if (const auto *ComparisonOperator = Result.Nodes.getNodeAs(
@@ -816,6 +862,43 @@ void RedundantExpressionCheck::checkBitw
   else if 

[clang-tools-extra] r321169 - Fix an error in the release notes.

2017-12-20 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Dec 20 04:30:27 2017
New Revision: 321169

URL: http://llvm.org/viewvc/llvm-project?rev=321169&view=rev
Log:
Fix an error in the release notes.

Modified:
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=321169&r1=321168&r2=321169&view=diff
==
--- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original)
+++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Wed Dec 20 04:30:27 2017
@@ -269,7 +269,7 @@ Improvements to clang-tidy
 - Added the ability to suppress specific checks (or all checks) in a 
``NOLINT`` or ``NOLINTNEXTLINE`` comment.
 
 - Added new functionality to `misc-redundant-expression
-  
http://clang.llvm.org/extra/clang-tidy/checks/misc-redundant-expression.html`_ 
check
+  
`_
 check
 
   Finds redundant binary operator expressions where the operators are 
overloaded,
   and ones that contain the same macros twice.


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


[PATCH] D35181: Defer addition of keywords to identifier table when loading AST

2017-12-20 Thread Johann Klähn via Phabricator via cfe-commits
jklaehn updated this revision to Diff 127685.
jklaehn added a project: clang.
jklaehn added a comment.

ping (rebased)


https://reviews.llvm.org/D35181

Files:
  include/clang/Basic/IdentifierTable.h
  lib/Basic/IdentifierTable.cpp
  lib/Lex/Preprocessor.cpp
  unittests/libclang/LibclangTest.cpp

Index: unittests/libclang/LibclangTest.cpp
===
--- unittests/libclang/LibclangTest.cpp
+++ unittests/libclang/LibclangTest.cpp
@@ -572,3 +572,67 @@
   EXPECT_EQ(0U, clang_getNumDiagnostics(ClangTU));
   DisplayDiagnostics();
 }
+
+class LibclangSerializationTest : public LibclangParseTest {
+public:
+  bool SaveAndLoadTU(const std::string &Filename) {
+unsigned options = clang_defaultSaveOptions(ClangTU);
+if (clang_saveTranslationUnit(ClangTU, Filename.c_str(), options) !=
+CXSaveError_None) {
+  DEBUG(llvm::dbgs() << "Saving failed\n");
+  return false;
+}
+
+clang_disposeTranslationUnit(ClangTU);
+
+ClangTU = clang_createTranslationUnit(Index, Filename.c_str());
+
+if (!ClangTU) {
+  DEBUG(llvm::dbgs() << "Loading failed\n");
+  return false;
+}
+
+return true;
+  }
+};
+
+TEST_F(LibclangSerializationTest, TokenKindsAreCorrectAfterLoading) {
+  // Ensure that "class" is recognized as a keyword token after serializing
+  // and reloading the AST, as it is not a keyword for the default LangOptions.
+  std::string HeaderName = "test.h";
+  WriteFile(HeaderName, "enum class Something {};");
+
+  const char *Argv[] = {"-xc++-header", "-std=c++11"};
+
+  ClangTU = clang_parseTranslationUnit(Index, HeaderName.c_str(), Argv,
+   sizeof(Argv) / sizeof(Argv[0]), nullptr,
+   0, TUFlags);
+
+  auto CheckTokenKinds = [=]() {
+CXSourceRange Range =
+clang_getCursorExtent(clang_getTranslationUnitCursor(ClangTU));
+
+CXToken *Tokens;
+unsigned int NumTokens;
+clang_tokenize(ClangTU, Range, &Tokens, &NumTokens);
+
+ASSERT_EQ(6u, NumTokens);
+EXPECT_EQ(CXToken_Keyword, clang_getTokenKind(Tokens[0]));
+EXPECT_EQ(CXToken_Keyword, clang_getTokenKind(Tokens[1]));
+EXPECT_EQ(CXToken_Identifier, clang_getTokenKind(Tokens[2]));
+EXPECT_EQ(CXToken_Punctuation, clang_getTokenKind(Tokens[3]));
+EXPECT_EQ(CXToken_Punctuation, clang_getTokenKind(Tokens[4]));
+EXPECT_EQ(CXToken_Punctuation, clang_getTokenKind(Tokens[5]));
+
+clang_disposeTokens(ClangTU, Tokens, NumTokens);
+  };
+
+  CheckTokenKinds();
+
+  std::string ASTName = "test.ast";
+  WriteFile(ASTName, "");
+
+  ASSERT_TRUE(SaveAndLoadTU(ASTName));
+
+  CheckTokenKinds();
+}
Index: lib/Lex/Preprocessor.cpp
===
--- lib/Lex/Preprocessor.cpp
+++ lib/Lex/Preprocessor.cpp
@@ -85,12 +85,14 @@
IdentifierInfoLookup *IILookup, bool OwnsHeaders,
TranslationUnitKind TUKind)
 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
-  FileMgr(Headers.getFileMgr()), SourceMgr(SM),
-  PCMCache(PCMCache), ScratchBuf(new ScratchBuffer(SourceMgr)),
-  HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
-  ExternalSource(nullptr), Identifiers(opts, IILookup),
-  PragmaHandlers(new PragmaNamespace(StringRef())), TUKind(TUKind),
-  SkipMainFilePreamble(0, true),
+  FileMgr(Headers.getFileMgr()), SourceMgr(SM), PCMCache(PCMCache),
+  ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
+  TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
+  // As the language options may have not been loaded yet (when
+  // deserializing an ASTUnit), adding keywords to the identifier table is
+  // deferred to Preprocessor::Initialize().
+  Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
+  TUKind(TUKind), SkipMainFilePreamble(0, true),
   CurSubmoduleState(&NullSubmoduleState) {
   OwnsHeaderSearch = OwnsHeaders;
   
@@ -190,6 +192,9 @@
   // Initialize information about built-ins.
   BuiltinInfo.InitializeTarget(Target, AuxTarget);
   HeaderInfo.setTarget(Target);
+
+  // Populate the identifier table with info about keywords for the current language.
+  Identifiers.AddKeywords(LangOpts);
 }
 
 void Preprocessor::InitializeForModelFile() {
Index: lib/Basic/IdentifierTable.cpp
===
--- lib/Basic/IdentifierTable.cpp
+++ lib/Basic/IdentifierTable.cpp
@@ -79,16 +79,16 @@
   return new EmptyLookupIterator();
 }
 
+IdentifierTable::IdentifierTable(IdentifierInfoLookup *externalLookup)
+: HashTable(8192), // Start with space for 8K identifiers.
+  ExternalLookup(externalLookup) {}
+
 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
- IdentifierInfoLookup* externalLookup)
-  : HashTable(8192), // Start with space for 8K identifiers.
-  

[PATCH] D39239: [AST] Incorrectly qualified unscoped enumeration as template actual parameter.

2017-12-20 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
CarlosAlbertoEnciso added a comment.

In https://reviews.llvm.org/D39239#912837, @probinson wrote:

> Have you tried the GDB suite yet?  If it has no problems, and we can make 
> LLDB happy, I'm okay with it.


These are the results when using GCC as the default compiler:

=== gdb Summary ===
  
  # of expected passes  21368
  # of unexpected failures  1788
  # of expected failures213
  # of unknown successes2
  # of known failures   75
  # of unresolved testcases 10
  # of untested testcases   29
  # of unsupported tests34

The unexpected failures falls into the categories (same as with clang):

- Invalid option '-w' to the ADA compiler
- Timeout issues
- Threading and attaching issues


https://reviews.llvm.org/D39239



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


[PATCH] D41384: [analyzer] Suppress false positive warnings form security.insecureAPI.strcpy

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added reviewers: NoQ, george.karpenkov.
xazax.hun added a comment.

In the tests there are multiple variants of the strcpy function guarded by 
macros. Maybe we should run the tests multiple times to test all variants with 
different defines?


https://reviews.llvm.org/D41384



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


Re: [clang-tools-extra] r320591 - [clangd] Fix bool conversion operator of UniqueFunction

2017-12-20 Thread Ilya Biryukov via cfe-commits
Thanks. Fixed in r321173. Should've been explicit from the start.

On Mon, Dec 18, 2017 at 7:25 PM, David Blaikie  wrote:

> This operator bool should probably be explicit (as most/all of them should
> be - and most of them in LLVM are) - to avoid undue implicit conversion to
> other int types.
>
> On Wed, Dec 13, 2017 at 7:43 AM Ilya Biryukov via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: ibiryukov
>> Date: Wed Dec 13 07:42:59 2017
>> New Revision: 320591
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=320591&view=rev
>> Log:
>> [clangd] Fix bool conversion operator of UniqueFunction
>>
>> Usages of it were giving compiler errors because of the missing
>> explicit conversion.
>>
>> Modified:
>> clang-tools-extra/trunk/clangd/Function.h
>>
>> Modified: clang-tools-extra/trunk/clangd/Function.h
>> URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/
>> trunk/clangd/Function.h?rev=320591&r1=320590&r2=320591&view=diff
>> 
>> ==
>> --- clang-tools-extra/trunk/clangd/Function.h (original)
>> +++ clang-tools-extra/trunk/clangd/Function.h Wed Dec 13 07:42:59 2017
>> @@ -49,7 +49,7 @@ public:
>>  FunctionCallImpl> std::decay::type>>(
>>  std::forward(Func))) {}
>>
>> -  operator bool() { return CallablePtr; }
>> +  operator bool() { return bool(CallablePtr); }
>>
>>Ret operator()(Args... As) {
>>  assert(CallablePtr);
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>
>


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


[clang-tools-extra] r321173 - [clangd] Made UniqueFunction's bool conversion explicit

2017-12-20 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Dec 20 06:06:05 2017
New Revision: 321173

URL: http://llvm.org/viewvc/llvm-project?rev=321173&view=rev
Log:
[clangd] Made UniqueFunction's bool conversion explicit

Modified:
clang-tools-extra/trunk/clangd/Function.h

Modified: clang-tools-extra/trunk/clangd/Function.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Function.h?rev=321173&r1=321172&r2=321173&view=diff
==
--- clang-tools-extra/trunk/clangd/Function.h (original)
+++ clang-tools-extra/trunk/clangd/Function.h Wed Dec 20 06:06:05 2017
@@ -49,7 +49,7 @@ public:
 FunctionCallImpl::type>>(
 std::forward(Func))) {}
 
-  operator bool() { return bool(CallablePtr); }
+  explicit operator bool() { return bool(CallablePtr); }
 
   Ret operator()(Args... As) {
 assert(CallablePtr);


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


[PATCH] D40705: [Parser] Diagnose storage classes in template parameter declarations

2017-12-20 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki added a comment.

I would appreciate, if you make those changes (because I'm very new to Clang 
and I'm not sure that I understand how to move these checks to Sema correctly).


https://reviews.llvm.org/D40705



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


[PATCH] D41406: [analyzer] Add a new checker callback, check::NewAllocator.

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Maybe `debug.AnalysisOrder` could be used to test the callback order 
explicitly. This way the test could also serve as a documentation for the 
callback order.


https://reviews.llvm.org/D41406



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


[PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin created this revision.
a.sidorin added reviewers: NoQ, xazax.hun, szepet.
Herald added subscribers: cfe-commits, rnkovacs.

While running ASTImporterTests, we often forget about Windows MSVC buildbots 
which enable '-fdelayed-template-parsing' by default. It takes reviewing time 
to find such issues as well as unexpected buildbot failures. To solve this 
issue, I suggest making '-fdelayed-template-parsing' mandatory so this problem 
can be caught during development.


Repository:
  rC Clang

https://reviews.llvm.org/D41444

Files:
  unittests/AST/ASTImporterTest.cpp


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -33,10 +33,10 @@
 Args.insert(Args.end(), { "-x", "c", "-std=c89" });
 break;
   case Lang_CXX:
-Args.push_back("-std=c++98");
+Args.insert(Args.end(), {"-std=c++98", "-fdelayed-template-parsing"});
 break;
   case Lang_CXX11:
-Args.push_back("-std=c++11");
+Args.insert(Args.end(), {"-std=c++11", "-fdelayed-template-parsing"});
 break;
   case Lang_OpenCL:
   case Lang_OBJCXX:


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -33,10 +33,10 @@
 Args.insert(Args.end(), { "-x", "c", "-std=c89" });
 break;
   case Lang_CXX:
-Args.push_back("-std=c++98");
+Args.insert(Args.end(), {"-std=c++98", "-fdelayed-template-parsing"});
 break;
   case Lang_CXX11:
-Args.push_back("-std=c++11");
+Args.insert(Args.end(), {"-std=c++11", "-fdelayed-template-parsing"});
 break;
   case Lang_OpenCL:
   case Lang_OBJCXX:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Is it possible that this will hide other problems? Wouldn't it be better to run 
the tests twice once with this argument and once without it?


Repository:
  rC Clang

https://reviews.llvm.org/D41444



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


r321174 - [Frontend] Handle skipped bodies in template instantiations

2017-12-20 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Dec 20 06:32:38 2017
New Revision: 321174

URL: http://llvm.org/viewvc/llvm-project?rev=321174&view=rev
Log:
[Frontend] Handle skipped bodies in template instantiations

Summary:
- Fixed an assert in Sema::InstantiateFunctionDefinition and added
  support for instantiating a function template with skipped body.
- Properly call setHasSkippedBody for FunctionTemplateDecl passed to
  Sema::ActOnSkippedFunctionBody.

Reviewers: sepavloff, bkramer

Reviewed By: sepavloff

Subscribers: klimek, cfe-commits

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

Added:
cfe/trunk/test/Index/skipped-bodies-templates.cpp
Modified:
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=321174&r1=321173&r2=321174&view=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Wed Dec 20 06:32:38 2017
@@ -12179,9 +12179,11 @@ bool Sema::canSkipFunctionBody(Decl *D)
 }
 
 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
-  if (FunctionDecl *FD = dyn_cast_or_null(Decl))
+  if (!Decl)
+return nullptr;
+  if (FunctionDecl *FD = Decl->getAsFunction())
 FD->setHasSkippedBody();
-  else if (ObjCMethodDecl *MD = dyn_cast_or_null(Decl))
+  else if (ObjCMethodDecl *MD = dyn_cast(Decl))
 MD->setHasSkippedBody();
   return Decl;
 }

Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp?rev=321174&r1=321173&r2=321174&view=diff
==
--- cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp Wed Dec 20 06:32:38 2017
@@ -3855,7 +3855,8 @@ void Sema::InstantiateFunctionDefinition
   }
 
   // Note, we should never try to instantiate a deleted function template.
-  assert((Pattern || PatternDecl->isDefaulted()) &&
+  assert((Pattern || PatternDecl->isDefaulted() ||
+  PatternDecl->hasSkippedBody()) &&
  "unexpected kind of function template definition");
 
   // C++1y [temp.explicit]p10:
@@ -3940,16 +3941,20 @@ void Sema::InstantiateFunctionDefinition
   }
 }
 
-// Instantiate the function body.
-StmtResult Body = SubstStmt(Pattern, TemplateArgs);
-
-if (Body.isInvalid())
-  Function->setInvalidDecl();
-
-// FIXME: finishing the function body while in an expression evaluation
-// context seems wrong. Investigate more.
-ActOnFinishFunctionBody(Function, Body.get(),
-/*IsInstantiation=*/true);
+if (PatternDecl->hasSkippedBody()) {
+  ActOnSkippedFunctionBody(Function);
+} else {
+  // Instantiate the function body.
+  StmtResult Body = SubstStmt(Pattern, TemplateArgs);
+
+  if (Body.isInvalid())
+Function->setInvalidDecl();
+
+  // FIXME: finishing the function body while in an expression evaluation
+  // context seems wrong. Investigate more.
+  ActOnFinishFunctionBody(Function, Body.get(),
+  /*IsInstantiation=*/true);
+}
 
 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
 

Added: cfe/trunk/test/Index/skipped-bodies-templates.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/skipped-bodies-templates.cpp?rev=321174&view=auto
==
--- cfe/trunk/test/Index/skipped-bodies-templates.cpp (added)
+++ cfe/trunk/test/Index/skipped-bodies-templates.cpp Wed Dec 20 06:32:38 2017
@@ -0,0 +1,27 @@
+// RUN: env CINDEXTEST_SKIP_FUNCTION_BODIES=1 c-index-test -test-load-source 
all %s 2>&1 \
+// RUN: | FileCheck %s
+
+
+template 
+struct Foo {
+  inline int with_body() {
+return 100;
+  }
+
+  inline int without_body();
+};
+
+
+int bar = Foo().with_body() + Foo().without_body();
+// CHECK-NOT: warning: inline function 'Foo::with_body' is not defined
+// CHECK: warning: inline function 'Foo::without_body' is not defined
+
+template 
+inline int with_body() { return 10; }
+
+template 
+inline int without_body();
+
+int baz = with_body() + without_body();
+// CHECK-NOT: warning: inline function 'with_body' is not defined
+// CHECK: warning: inline function 'without_body' is not defined


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


[PATCH] D41237: [Frontend] Handle skipped bodies in template instantiations

2017-12-20 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL321174: [Frontend] Handle skipped bodies in template 
instantiations (authored by ibiryukov, committed by ).

Repository:
  rL LLVM

https://reviews.llvm.org/D41237

Files:
  cfe/trunk/lib/Sema/SemaDecl.cpp
  cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
  cfe/trunk/test/Index/skipped-bodies-templates.cpp


Index: cfe/trunk/lib/Sema/SemaDecl.cpp
===
--- cfe/trunk/lib/Sema/SemaDecl.cpp
+++ cfe/trunk/lib/Sema/SemaDecl.cpp
@@ -12179,9 +12179,11 @@
 }
 
 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
-  if (FunctionDecl *FD = dyn_cast_or_null(Decl))
+  if (!Decl)
+return nullptr;
+  if (FunctionDecl *FD = Decl->getAsFunction())
 FD->setHasSkippedBody();
-  else if (ObjCMethodDecl *MD = dyn_cast_or_null(Decl))
+  else if (ObjCMethodDecl *MD = dyn_cast(Decl))
 MD->setHasSkippedBody();
   return Decl;
 }
Index: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -3855,7 +3855,8 @@
   }
 
   // Note, we should never try to instantiate a deleted function template.
-  assert((Pattern || PatternDecl->isDefaulted()) &&
+  assert((Pattern || PatternDecl->isDefaulted() ||
+  PatternDecl->hasSkippedBody()) &&
  "unexpected kind of function template definition");
 
   // C++1y [temp.explicit]p10:
@@ -3940,16 +3941,20 @@
   }
 }
 
-// Instantiate the function body.
-StmtResult Body = SubstStmt(Pattern, TemplateArgs);
+if (PatternDecl->hasSkippedBody()) {
+  ActOnSkippedFunctionBody(Function);
+} else {
+  // Instantiate the function body.
+  StmtResult Body = SubstStmt(Pattern, TemplateArgs);
 
-if (Body.isInvalid())
-  Function->setInvalidDecl();
+  if (Body.isInvalid())
+Function->setInvalidDecl();
 
-// FIXME: finishing the function body while in an expression evaluation
-// context seems wrong. Investigate more.
-ActOnFinishFunctionBody(Function, Body.get(),
-/*IsInstantiation=*/true);
+  // FIXME: finishing the function body while in an expression evaluation
+  // context seems wrong. Investigate more.
+  ActOnFinishFunctionBody(Function, Body.get(),
+  /*IsInstantiation=*/true);
+}
 
 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
 
Index: cfe/trunk/test/Index/skipped-bodies-templates.cpp
===
--- cfe/trunk/test/Index/skipped-bodies-templates.cpp
+++ cfe/trunk/test/Index/skipped-bodies-templates.cpp
@@ -0,0 +1,27 @@
+// RUN: env CINDEXTEST_SKIP_FUNCTION_BODIES=1 c-index-test -test-load-source 
all %s 2>&1 \
+// RUN: | FileCheck %s
+
+
+template 
+struct Foo {
+  inline int with_body() {
+return 100;
+  }
+
+  inline int without_body();
+};
+
+
+int bar = Foo().with_body() + Foo().without_body();
+// CHECK-NOT: warning: inline function 'Foo::with_body' is not defined
+// CHECK: warning: inline function 'Foo::without_body' is not defined
+
+template 
+inline int with_body() { return 10; }
+
+template 
+inline int without_body();
+
+int baz = with_body() + without_body();
+// CHECK-NOT: warning: inline function 'with_body' is not defined
+// CHECK: warning: inline function 'without_body' is not defined


Index: cfe/trunk/lib/Sema/SemaDecl.cpp
===
--- cfe/trunk/lib/Sema/SemaDecl.cpp
+++ cfe/trunk/lib/Sema/SemaDecl.cpp
@@ -12179,9 +12179,11 @@
 }
 
 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
-  if (FunctionDecl *FD = dyn_cast_or_null(Decl))
+  if (!Decl)
+return nullptr;
+  if (FunctionDecl *FD = Decl->getAsFunction())
 FD->setHasSkippedBody();
-  else if (ObjCMethodDecl *MD = dyn_cast_or_null(Decl))
+  else if (ObjCMethodDecl *MD = dyn_cast(Decl))
 MD->setHasSkippedBody();
   return Decl;
 }
Index: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -3855,7 +3855,8 @@
   }
 
   // Note, we should never try to instantiate a deleted function template.
-  assert((Pattern || PatternDecl->isDefaulted()) &&
+  assert((Pattern || PatternDecl->isDefaulted() ||
+  PatternDecl->hasSkippedBody()) &&
  "unexpected kind of function template definition");
 
   // C++1y [temp.explicit]p10:
@@ -3940,16 +3941,20 @@
   }
 }
 
-// Instantiate the function body.
-StmtResult Body = SubstStmt(Pattern, TemplateArgs);
+if (PatternDecl->hasSkippedBody()) {
+  ActOnSkippedFunctionBody(Function);
+} else {
+  // Instantiate the function body.
+  StmtResul

[PATCH] D41365: [clang] Add BeforeExecute method to PrecompiledPreamble

2017-12-20 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov requested changes to this revision.
ilya-biryukov added a comment.
This revision now requires changes to proceed.

LGTM modulo the comment. Should I land this for you?




Comment at: include/clang/Frontend/PrecompiledPreamble.h:247
 
+  /// Can be used to store references to various CompilerInstance fields
+  /// (e.g. SourceManager) that may be interesting to the consumers of other 
callbacks.

Please add that the following information to the comment:
```
/// Called before FrontendAction::BeginSourceFile .
/// Can be used 
```


Repository:
  rC Clang

https://reviews.llvm.org/D41365



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


[PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

In https://reviews.llvm.org/D41444#960841, @xazax.hun wrote:

> Is it possible that this will hide other problems? Wouldn't it be better to 
> run the tests twice once with this argument and once without it?


I don't think so. In fact, without instantiation, we are not even able to check 
semantic code correctness inside templates. So, we are solving this problem as 
well.


Repository:
  rC Clang

https://reviews.llvm.org/D41444



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


[PATCH] D41448: Fix counting parameters/arguments for ObjC.

2017-12-20 Thread Jacek Olesiak via Phabricator via cfe-commits
jolesiak created this revision.
jolesiak added a reviewer: krasimir.
Herald added a subscriber: klimek.

[clang-format] Fix ParameterCount for ObjC.


Repository:
  rC Clang

https://reviews.llvm.org/D41448

Files:
  lib/Format/TokenAnnotator.cpp


Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -414,6 +414,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 +487,11 @@
   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/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -414,6 +414,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 +487,11 @@
   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));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

In https://reviews.llvm.org/D41444#960848, @a.sidorin wrote:

> In https://reviews.llvm.org/D41444#960841, @xazax.hun wrote:
>
> > Is it possible that this will hide other problems? Wouldn't it be better to 
> > run the tests twice once with this argument and once without it?
>
>
> I don't think so. In fact, without instantiation, we are not even able to 
> check semantic code correctness inside templates. So, we are solving this 
> problem as well.


E.g. the following code only compiles with `-fdelayed-template-parsing` flag 
added:

  template
  struct Base {
int x;
  };
  
  
  template
  struct Derived : Base {
int f() {
  return x;
}
  };

But yeah, maybe it is not very likely that we hit such issues.


Repository:
  rC Clang

https://reviews.llvm.org/D41444



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


[PATCH] D41365: [clang] Add BeforeExecute method to PrecompiledPreamble

2017-12-20 Thread William Enright via Phabricator via cfe-commits
Nebiroth updated this revision to Diff 127715.
Nebiroth added a comment.

Updated BeforeExecute comment


Repository:
  rC Clang

https://reviews.llvm.org/D41365

Files:
  include/clang/Frontend/PrecompiledPreamble.h
  lib/Frontend/PrecompiledPreamble.cpp


Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -348,6 +348,7 @@
   std::unique_ptr Act;
   Act.reset(new PrecompilePreambleAction(
   StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
+  Callbacks.BeforeExecute(*Clang);
   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
 return BuildPreambleError::BeginSourceFileFailed;
 
@@ -704,6 +705,7 @@
   }
 }
 
+void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
Index: include/clang/Frontend/PrecompiledPreamble.h
===
--- include/clang/Frontend/PrecompiledPreamble.h
+++ include/clang/Frontend/PrecompiledPreamble.h
@@ -244,6 +244,10 @@
 public:
   virtual ~PreambleCallbacks() = default;
 
+  /// Called before FrontendAction::BeginSourceFile.
+  /// Can be used to store references to various CompilerInstance fields
+  /// (e.g. SourceManager) that may be interesting to the consumers of other 
callbacks.
+  virtual void BeforeExecute(CompilerInstance &CI);
   /// Called after FrontendAction::Execute(), but before
   /// FrontendAction::EndSourceFile(). Can be used to transfer ownership of
   /// various CompilerInstance fields before they are destroyed.


Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -348,6 +348,7 @@
   std::unique_ptr Act;
   Act.reset(new PrecompilePreambleAction(
   StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
+  Callbacks.BeforeExecute(*Clang);
   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
 return BuildPreambleError::BeginSourceFileFailed;
 
@@ -704,6 +705,7 @@
   }
 }
 
+void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
Index: include/clang/Frontend/PrecompiledPreamble.h
===
--- include/clang/Frontend/PrecompiledPreamble.h
+++ include/clang/Frontend/PrecompiledPreamble.h
@@ -244,6 +244,10 @@
 public:
   virtual ~PreambleCallbacks() = default;
 
+  /// Called before FrontendAction::BeginSourceFile.
+  /// Can be used to store references to various CompilerInstance fields
+  /// (e.g. SourceManager) that may be interesting to the consumers of other callbacks.
+  virtual void BeforeExecute(CompilerInstance &CI);
   /// Called after FrontendAction::Execute(), but before
   /// FrontendAction::EndSourceFile(). Can be used to transfer ownership of
   /// various CompilerInstance fields before they are destroyed.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Zachary Turner via cfe-commits
On the other hand, it doesn’t hurt anything to run the tests twice does it?
I’d feel better if this patch were *adding* test coverage as opposed to
changing coverage
On Wed, Dec 20, 2017 at 6:50 AM Gábor Horváth via Phabricator <
revi...@reviews.llvm.org> wrote:

> xazax.hun added a comment.
>
> In https://reviews.llvm.org/D41444#960848, @a.sidorin wrote:
>
> > In https://reviews.llvm.org/D41444#960841, @xazax.hun wrote:
> >
> > > Is it possible that this will hide other problems? Wouldn't it be
> better to run the tests twice once with this argument and once without it?
> >
> >
> > I don't think so. In fact, without instantiation, we are not even able
> to check semantic code correctness inside templates. So, we are solving
> this problem as well.
>
>
> E.g. the following code only compiles with `-fdelayed-template-parsing`
> flag added:
>
>   template
>   struct Base {
> int x;
>   };
>
>
>   template
>   struct Derived : Base {
> int f() {
>   return x;
> }
>   };
>
> But yeah, maybe it is not very likely that we hit such issues.
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D41444
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41365: [clang] Add BeforeExecute method to PrecompiledPreamble

2017-12-20 Thread William Enright via Phabricator via cfe-commits
Nebiroth added a comment.

Yes please land this.


Repository:
  rC Clang

https://reviews.llvm.org/D41365



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


[PATCH] D40299: [Complex] Don't use __div?c3 when building with fast-math.

2017-12-20 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

I'll commit this for you Paul


https://reviews.llvm.org/D40299



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


[PATCH] D41450: [clangd] Pull CodeCompletionString handling logic into its own file and add unit test.

2017-12-20 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added a reviewer: sammccall.
Herald added subscribers: cfe-commits, ilya-biryukov, mgorny, klimek.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41450

Files:
  clangd/CMakeLists.txt
  clangd/CodeComplete.cpp
  clangd/CompletionString.cpp
  clangd/CompletionString.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/CompletionStringTests.cpp

Index: unittests/clangd/CompletionStringTests.cpp
===
--- /dev/null
+++ unittests/clangd/CompletionStringTests.cpp
@@ -0,0 +1,130 @@
+//===-- CompletionStringTests.cpp ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "CompletionString.h"
+#include "clang/Sema/CodeCompleteConsumer.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+class CompletionStringTest : public ::testing::Test {
+public:
+  CompletionStringTest()
+  : Allocator(std::make_shared()),
+CCTUInfo(Allocator), Builder(*Allocator, CCTUInfo) {}
+
+protected:
+  std::shared_ptr Allocator;
+  CodeCompletionTUInfo CCTUInfo;
+  CodeCompletionBuilder Builder;
+};
+
+TEST_F(CompletionStringTest, Detail) {
+  Builder.AddResultTypeChunk("result");
+  Builder.AddResultTypeChunk("redundant result no no");
+  EXPECT_EQ(getDetail(*Builder.TakeString()), "result");
+}
+
+TEST_F(CompletionStringTest, FilterText) {
+  Builder.AddTypedTextChunk("typed");
+  Builder.AddTypedTextChunk("redundant typed no no");
+  auto *S = Builder.TakeString();
+  EXPECT_EQ(getFilterText(*S), "typed");
+}
+
+TEST_F(CompletionStringTest, Documentation) {
+  Builder.addBriefComment("Is this brief?");
+  EXPECT_EQ(getDocumentation(*Builder.TakeString()), "Is this brief?");
+}
+
+TEST_F(CompletionStringTest, DocumentationWithAnnotation) {
+  Builder.addBriefComment("Is this brief?");
+  Builder.AddAnnotation("Ano");
+  EXPECT_EQ(getDocumentation(*Builder.TakeString()),
+"Annotation: Ano\n\nIs this brief?");
+}
+
+TEST_F(CompletionStringTest, MultipleAnnotations) {
+  Builder.AddAnnotation("Ano1");
+  Builder.AddAnnotation("Ano2");
+  Builder.AddAnnotation("Ano3");
+
+  EXPECT_EQ(getDocumentation(*Builder.TakeString()),
+"Annotations: Ano1 Ano2 Ano3\n");
+}
+
+TEST_F(CompletionStringTest, SimpleLabelAndInsert) {
+  Builder.AddTypedTextChunk("X");
+  Builder.AddResultTypeChunk("result no no");
+  auto Pair = getLabelAndInsertText(*Builder.TakeString());
+  EXPECT_EQ(Pair.first, "X");
+  EXPECT_EQ(Pair.second, "X");
+}
+
+TEST_F(CompletionStringTest, FunctionPlainText) {
+  Builder.AddResultTypeChunk("result no no");
+  Builder.AddTypedTextChunk("Foo");
+  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
+  Builder.AddPlaceholderChunk("p1");
+  Builder.AddChunk(CodeCompletionString::CK_Comma);
+  Builder.AddPlaceholderChunk("p2");
+  Builder.AddChunk(CodeCompletionString::CK_RightParen);
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddInformativeChunk("const");
+
+  auto Pair = getLabelAndInsertText(*Builder.TakeString());
+  EXPECT_EQ(Pair.first, "Foo(p1, p2) const");
+  EXPECT_EQ(Pair.second, "Foo");
+}
+
+TEST_F(CompletionStringTest, FunctionSnippet) {
+  Builder.AddResultTypeChunk("result no no");
+  Builder.AddTypedTextChunk("Foo");
+  Builder.AddTextChunk("d");
+  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
+  Builder.AddPlaceholderChunk("p1");
+  Builder.AddChunk(CodeCompletionString::CK_Comma);
+  Builder.AddPlaceholderChunk("p2");
+  Builder.AddChunk(CodeCompletionString::CK_RightParen);
+
+  bool IsSnippet = false;
+  auto Pair = getLabelAndInsertText(*Builder.TakeString(), &IsSnippet);
+  EXPECT_TRUE(IsSnippet);
+  EXPECT_EQ(Pair.first, "Food(p1, p2)");
+  EXPECT_EQ(Pair.second, "Food(${1:p1}, ${2:p2})");
+}
+
+TEST_F(CompletionStringTest, EscapeSnippet) {
+  Builder.AddTypedTextChunk("Foo");
+  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
+  Builder.AddPlaceholderChunk("$p}1\\");
+  Builder.AddChunk(CodeCompletionString::CK_RightParen);
+
+  bool IsSnippet = false;
+  auto Pair = getLabelAndInsertText(*Builder.TakeString(), &IsSnippet);
+  EXPECT_TRUE(IsSnippet);
+  EXPECT_EQ(Pair.first, "Foo($p}1\\)");
+  EXPECT_EQ(Pair.second, "Foo(${1:\\$p\\}1})");
+}
+
+TEST_F(CompletionStringTest, IgnoreInformativeQualifier) {
+  Builder.AddTypedTextChunk("X");
+  Builder.AddInformativeChunk("info ok");
+  Builder.AddInformativeChunk("info no no::");
+  auto Pair = getLabelAndInsertText(*Builder.TakeString());
+  EXPECT_EQ(Pair.first, "Xinfo ok");
+  EXPECT_EQ(Pair.second, "X");
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: unittests/clangd/CMakeLists.txt
===

r321183 - [Complex] Don't use __div?c3 when building with fast-math.

2017-12-20 Thread Florian Hahn via cfe-commits
Author: fhahn
Date: Wed Dec 20 07:50:52 2017
New Revision: 321183

URL: http://llvm.org/viewvc/llvm-project?rev=321183&view=rev
Log:
[Complex] Don't use __div?c3 when building with fast-math.

Summary: Plant an inline version of "((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))" 
instead.

Patch by Paul Walker.

Reviewed By: hfinkel

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

Modified:
cfe/trunk/lib/CodeGen/CGExprComplex.cpp
cfe/trunk/test/CodeGen/complex-math.c

Modified: cfe/trunk/lib/CodeGen/CGExprComplex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprComplex.cpp?rev=321183&r1=321182&r2=321183&view=diff
==
--- cfe/trunk/lib/CodeGen/CGExprComplex.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprComplex.cpp Wed Dec 20 07:50:52 2017
@@ -761,15 +761,16 @@ ComplexPairTy ComplexExprEmitter::EmitBi
   llvm::Value *LHSr = Op.LHS.first, *LHSi = Op.LHS.second;
   llvm::Value *RHSr = Op.RHS.first, *RHSi = Op.RHS.second;
 
-
   llvm::Value *DSTr, *DSTi;
   if (LHSr->getType()->isFloatingPointTy()) {
-// If we have a complex operand on the RHS, we delegate to a libcall to
-// handle all of the complexities and minimize underflow/overflow cases.
+// If we have a complex operand on the RHS and FastMath is not allowed, we
+// delegate to a libcall to handle all of the complexities and minimize
+// underflow/overflow cases. When FastMath is allowed we construct the
+// divide inline using the same algorithm as for integer operands.
 //
 // FIXME: We would be able to avoid the libcall in many places if we
 // supported imaginary types in addition to complex types.
-if (RHSi) {
+if (RHSi && !CGF.getLangOpts().FastMath) {
   BinOpInfo LibCallOp = Op;
   // If LHS was a real, supply a null imaginary part.
   if (!LHSi)
@@ -791,11 +792,31 @@ ComplexPairTy ComplexExprEmitter::EmitBi
   case llvm::Type::FP128TyID:
 return EmitComplexBinOpLibCall("__divtc3", LibCallOp);
   }
-}
-assert(LHSi && "Can have at most one non-complex operand!");
+} else if (RHSi) {
+  if (!LHSi)
+LHSi = llvm::Constant::getNullValue(RHSi->getType());
+
+  // (a+ib) / (c+id) = ((ac+bd)/(cc+dd)) + i((bc-ad)/(cc+dd))
+  llvm::Value *AC = Builder.CreateFMul(LHSr, RHSr); // a*c
+  llvm::Value *BD = Builder.CreateFMul(LHSi, RHSi); // b*d
+  llvm::Value *ACpBD = Builder.CreateFAdd(AC, BD); // ac+bd
 
-DSTr = Builder.CreateFDiv(LHSr, RHSr);
-DSTi = Builder.CreateFDiv(LHSi, RHSr);
+  llvm::Value *CC = Builder.CreateFMul(RHSr, RHSr); // c*c
+  llvm::Value *DD = Builder.CreateFMul(RHSi, RHSi); // d*d
+  llvm::Value *CCpDD = Builder.CreateFAdd(CC, DD); // cc+dd
+
+  llvm::Value *BC = Builder.CreateFMul(LHSi, RHSr); // b*c
+  llvm::Value *AD = Builder.CreateFMul(LHSr, RHSi); // a*d
+  llvm::Value *BCmAD = Builder.CreateFSub(BC, AD); // bc-ad
+
+  DSTr = Builder.CreateFDiv(ACpBD, CCpDD);
+  DSTi = Builder.CreateFDiv(BCmAD, CCpDD);
+} else {
+  assert(LHSi && "Can have at most one non-complex operand!");
+
+  DSTr = Builder.CreateFDiv(LHSr, RHSr);
+  DSTi = Builder.CreateFDiv(LHSi, RHSr);
+}
   } else {
 assert(Op.LHS.second && Op.RHS.second &&
"Both operands of integer complex operators must be complex!");

Modified: cfe/trunk/test/CodeGen/complex-math.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/complex-math.c?rev=321183&r1=321182&r2=321183&view=diff
==
--- cfe/trunk/test/CodeGen/complex-math.c (original)
+++ cfe/trunk/test/CodeGen/complex-math.c Wed Dec 20 07:50:52 2017
@@ -5,6 +5,7 @@
 // RUN %clang_cc1 %s -O1 -emit-llvm -triple armv7-none-linux-gnueabi -o - | 
FileCheck %s --check-prefix=ARM
 // RUN: %clang_cc1 %s -O1 -emit-llvm -triple armv7-none-linux-gnueabihf -o - | 
FileCheck %s --check-prefix=ARMHF
 // RUN: %clang_cc1 %s -O1 -emit-llvm -triple thumbv7k-apple-watchos2.0 -o - 
-target-abi aapcs16 | FileCheck %s --check-prefix=ARM7K
+// RUN: %clang_cc1 %s -O1 -emit-llvm -triple aarch64-unknown-unknown 
-ffast-math -o - | FileCheck %s --check-prefix=AARCH64-FASTMATH
 
 float _Complex add_float_rr(float a, float b) {
   // X86-LABEL: @add_float_rr(
@@ -128,6 +129,29 @@ float _Complex div_float_rc(float a, flo
   // X86-NOT: fdiv
   // X86: call {{.*}} @__divsc3(
   // X86: ret
+
+  // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD))
+  // AARCH64-FASTMATH-LABEL: @div_float_rc(float %a, [2 x float] %b.coerce)
+  // A = a
+  // B = 0
+  // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x float] %b.coerce, 0
+  // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x float] %b.coerce, 1
+  //
+  // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast float [[C]], %a
+  // BD = 0
+  // ACpBD = AC
+  //
+  // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast float [[C]], [[C]]
+  // AARC

[PATCH] D40299: [Complex] Don't use __div?c3 when building with fast-math.

2017-12-20 Thread Florian Hahn via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC321183: [Complex] Don't use __div?c3 when building with 
fast-math. (authored by fhahn, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D40299

Files:
  lib/CodeGen/CGExprComplex.cpp
  test/CodeGen/complex-math.c

Index: test/CodeGen/complex-math.c
===
--- test/CodeGen/complex-math.c
+++ test/CodeGen/complex-math.c
@@ -5,6 +5,7 @@
 // RUN %clang_cc1 %s -O1 -emit-llvm -triple armv7-none-linux-gnueabi -o - | FileCheck %s --check-prefix=ARM
 // RUN: %clang_cc1 %s -O1 -emit-llvm -triple armv7-none-linux-gnueabihf -o - | FileCheck %s --check-prefix=ARMHF
 // RUN: %clang_cc1 %s -O1 -emit-llvm -triple thumbv7k-apple-watchos2.0 -o - -target-abi aapcs16 | FileCheck %s --check-prefix=ARM7K
+// RUN: %clang_cc1 %s -O1 -emit-llvm -triple aarch64-unknown-unknown -ffast-math -o - | FileCheck %s --check-prefix=AARCH64-FASTMATH
 
 float _Complex add_float_rr(float a, float b) {
   // X86-LABEL: @add_float_rr(
@@ -128,13 +129,59 @@
   // X86-NOT: fdiv
   // X86: call {{.*}} @__divsc3(
   // X86: ret
+
+  // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD))
+  // AARCH64-FASTMATH-LABEL: @div_float_rc(float %a, [2 x float] %b.coerce)
+  // A = a
+  // B = 0
+  // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x float] %b.coerce, 0
+  // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x float] %b.coerce, 1
+  //
+  // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast float [[C]], %a
+  // BD = 0
+  // ACpBD = AC
+  //
+  // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast float [[C]], [[C]]
+  // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast float [[D]], [[D]]
+  // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast float [[CC]], [[DD]]
+  //
+  // BC = 0
+  // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast float [[D]], %a
+  // AARCH64-FASTMATH: [[BCmAD:%.*]] = fsub fast float -0.00e+00, [[AD]]
+  //
+  // AARCH64-FASTMATH: fdiv fast float [[AC]], [[CCpDD]]
+  // AARCH64-FASTMATH: fdiv fast float [[BCmAD]], [[CCpDD]]
+  // AARCH64-FASTMATH: ret
   return a / b;
 }
 float _Complex div_float_cc(float _Complex a, float _Complex b) {
   // X86-LABEL: @div_float_cc(
   // X86-NOT: fdiv
   // X86: call {{.*}} @__divsc3(
   // X86: ret
+
+  // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD))
+  // AARCH64-FASTMATH-LABEL: @div_float_cc([2 x float] %a.coerce, [2 x float] %b.coerce)
+  // AARCH64-FASTMATH: [[A:%.*]] = extractvalue [2 x float] %a.coerce, 0
+  // AARCH64-FASTMATH: [[B:%.*]] = extractvalue [2 x float] %a.coerce, 1
+  // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x float] %b.coerce, 0
+  // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x float] %b.coerce, 1
+  //
+  // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast float [[C]], [[A]]
+  // AARCH64-FASTMATH: [[BD:%.*]] = fmul fast float [[D]], [[B]]
+  // AARCH64-FASTMATH: [[ACpBD:%.*]] = fadd fast float [[AC]], [[BD]]
+  //
+  // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast float [[C]], [[C]]
+  // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast float [[D]], [[D]]
+  // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast float [[CC]], [[DD]]
+  //
+  // AARCH64-FASTMATH: [[BC:%.*]] = fmul fast float [[C]], [[B]]
+  // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast float [[D]], [[A]]
+  // AARCH64-FASTMATH: [[BCmAD:%.*]] = fsub fast float [[BC]], [[AD]]
+  //
+  // AARCH64-FASTMATH: fdiv fast float [[ACpBD]], [[CCpDD]]
+  // AARCH64-FASTMATH: fdiv fast float [[BCmAD]], [[CCpDD]]
+  // AARCH64-FASTMATH: ret
   return a / b;
 }
 
@@ -260,13 +307,59 @@
   // X86-NOT: fdiv
   // X86: call {{.*}} @__divdc3(
   // X86: ret
+
+  // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD))
+  // AARCH64-FASTMATH-LABEL: @div_double_rc(double %a, [2 x double] %b.coerce)
+  // A = a
+  // B = 0
+  // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x double] %b.coerce, 0
+  // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x double] %b.coerce, 1
+  //
+  // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast double [[C]], %a
+  // BD = 0
+  // ACpBD = AC
+  //
+  // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast double [[C]], [[C]]
+  // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast double [[D]], [[D]]
+  // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast double [[CC]], [[DD]]
+  //
+  // BC = 0
+  // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast double [[D]], %a
+  // AARCH64-FASTMATH: [[BCmAD:%.*]] = fsub fast double -0.00e+00, [[AD]]
+  //
+  // AARCH64-FASTMATH: fdiv fast double [[AC]], [[CCpDD]]
+  // AARCH64-FASTMATH: fdiv fast double [[BCmAD]], [[CCpDD]]
+  // AARCH64-FASTMATH: ret
   return a / b;
 }
 double _Complex div_double_cc(double _Complex a, double _Complex b) {
   // X86-LABEL: @div_double_cc(
   // X86-NOT: fdiv
   // X86: call {{.*}} @__divdc3(
   // X86: ret
+
+  // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD))
+  // AARCH64-FASTMATH-LABEL: @div_double_cc([2 x double] %a.coerce, [2 x double] %b.coerce)
+  // AARCH64-FASTMATH: [[

[PATCH] D41394: [CodeGen] Support generation of TBAA info in the new format

2017-12-20 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev updated this revision to Diff 127722.
kosarev added a comment.

Added tests.


https://reviews.llvm.org/D41394

Files:
  lib/CodeGen/CodeGenTBAA.cpp
  test/CodeGen/tbaa.cpp

Index: test/CodeGen/tbaa.cpp
===
--- test/CodeGen/tbaa.cpp
+++ test/CodeGen/tbaa.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -no-struct-path-tbaa -disable-llvm-passes %s -emit-llvm -o - | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -disable-llvm-passes %s -emit-llvm -o - | FileCheck %s -check-prefix=PATH
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -new-struct-path-tbaa -disable-llvm-passes %s -emit-llvm -o - | FileCheck %s -check-prefix=NEW-PATH
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -O0 -disable-llvm-passes %s -emit-llvm -o - | FileCheck %s -check-prefix=NO-TBAA
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -relaxed-aliasing -disable-llvm-passes %s -emit-llvm -o - | FileCheck %s -check-prefix=NO-TBAA
 // Test TBAA metadata generated by front-end.
@@ -55,6 +56,9 @@
 // PATH-LABEL: define i32 @_Z1g
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_i32:!.*]]
 // PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z1g
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_i32:!.*]]
+// NEW-PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32:!.*]]
   *s = 1;
   A->f32 = 4;
   return *s;
@@ -67,6 +71,9 @@
 // PATH-LABEL: define i32 @_Z2g2
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_i32]]
 // PATH: store i16 4, i16* %{{.*}}, align 4, !tbaa [[TAG_A_f16:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z2g2
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// NEW-PATH: store i16 4, i16* %{{.*}}, align 4, !tbaa [[TAG_A_f16:!.*]]
   *s = 1;
   A->f16 = 4;
   return *s;
@@ -79,6 +86,9 @@
 // PATH-LABEL: define i32 @_Z2g3
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
 // PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_B_a_f32:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z2g3
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
+// NEW-PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_B_a_f32:!.*]]
   A->f32 = 1;
   B->a.f32 = 4;
   return A->f32;
@@ -91,6 +101,9 @@
 // PATH-LABEL: define i32 @_Z2g4
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
 // PATH: store i16 4, i16* %{{.*}}, align 4, !tbaa [[TAG_B_a_f16:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z2g4
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
+// NEW-PATH: store i16 4, i16* %{{.*}}, align 4, !tbaa [[TAG_B_a_f16:!.*]]
   A->f32 = 1;
   B->a.f16 = 4;
   return A->f32;
@@ -103,6 +116,9 @@
 // PATH-LABEL: define i32 @_Z2g5
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
 // PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_B_f32:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z2g5
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
+// NEW-PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_B_f32:!.*]]
   A->f32 = 1;
   B->f32 = 4;
   return A->f32;
@@ -115,6 +131,9 @@
 // PATH-LABEL: define i32 @_Z2g6
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
 // PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_B_a_f32_2:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z2g6
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
+// NEW-PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_B_a_f32_2:!.*]]
   A->f32 = 1;
   B->a.f32_2 = 4;
   return A->f32;
@@ -127,6 +146,9 @@
 // PATH-LABEL: define i32 @_Z2g7
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
 // PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_S_f32:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z2g7
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
+// NEW-PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_S_f32:!.*]]
   A->f32 = 1;
   S->f32 = 4;
   return A->f32;
@@ -139,6 +161,9 @@
 // PATH-LABEL: define i32 @_Z2g8
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
 // PATH: store i16 4, i16* %{{.*}}, align 4, !tbaa [[TAG_S_f16:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z2g8
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_A_f32]]
+// NEW-PATH: store i16 4, i16* %{{.*}}, align 4, !tbaa [[TAG_S_f16:!.*]]
   A->f32 = 1;
   S->f16 = 4;
   return A->f32;
@@ -151,6 +176,9 @@
 // PATH-LABEL: define i32 @_Z2g9
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_S_f32]]
 // PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_S2_f32:!.*]]
+// NEW-PATH-LABEL: define i32 @_Z2g9
+// NEW-PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_S_f32]]
+// NEW-PATH: store i32 4, i32* %{{.*}}, align 4, !tbaa [[TAG_S2_f32:!.*]]
   S->f32 = 1;
   S2->f32 = 4;
   return S->f32;
@@ -163,6 +191,9 @@
 // PATH-LABEL: define i32 @_Z3g10
 // PATH: store i32 1, i32* %{{.*}}, align 4, !tbaa [[TAG_S_f32]]
 // PATH: store i16 

[PATCH] D41451: Make DiagnosticIDs::getAllDiagnostics use std::vector

2017-12-20 Thread András Leitereg via Phabricator via cfe-commits
leanil created this revision.
leanil added reviewers: rsmith, xazax.hun.
Herald added a subscriber: rnkovacs.

The size of the result vector is currently around 4600 with 
Flavor::WarningOrError, which makes std::vector a better candidate than 
llvm::SmallVector.


https://reviews.llvm.org/D41451

Files:
  include/clang/Basic/DiagnosticIDs.h
  lib/Basic/Diagnostic.cpp
  lib/Basic/DiagnosticIDs.cpp


Index: lib/Basic/DiagnosticIDs.cpp
===
--- lib/Basic/DiagnosticIDs.cpp
+++ lib/Basic/DiagnosticIDs.cpp
@@ -583,7 +583,7 @@
 }
 
 void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
-  SmallVectorImpl &Diags) {
+  std::vector &Diags) {
   for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
 if (StaticDiagInfo[i].getFlavor() == Flavor)
   Diags.push_back(StaticDiagInfo[i].DiagID);
Index: lib/Basic/Diagnostic.cpp
===
--- lib/Basic/Diagnostic.cpp
+++ lib/Basic/Diagnostic.cpp
@@ -363,7 +363,7 @@
   diag::Severity Map,
   SourceLocation Loc) {
   // Get all the diagnostics.
-  SmallVector AllDiags;
+  std::vector AllDiags;
   DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
 
   // Set the mapping.
Index: include/clang/Basic/DiagnosticIDs.h
===
--- include/clang/Basic/DiagnosticIDs.h
+++ include/clang/Basic/DiagnosticIDs.h
@@ -297,7 +297,7 @@
 
   /// \brief Get the set of all diagnostic IDs.
   static void getAllDiagnostics(diag::Flavor Flavor,
-SmallVectorImpl &Diags);
+std::vector &Diags);
 
   /// \brief Get the diagnostic option with the closest edit distance to the
   /// given group name.


Index: lib/Basic/DiagnosticIDs.cpp
===
--- lib/Basic/DiagnosticIDs.cpp
+++ lib/Basic/DiagnosticIDs.cpp
@@ -583,7 +583,7 @@
 }
 
 void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
-  SmallVectorImpl &Diags) {
+  std::vector &Diags) {
   for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
 if (StaticDiagInfo[i].getFlavor() == Flavor)
   Diags.push_back(StaticDiagInfo[i].DiagID);
Index: lib/Basic/Diagnostic.cpp
===
--- lib/Basic/Diagnostic.cpp
+++ lib/Basic/Diagnostic.cpp
@@ -363,7 +363,7 @@
   diag::Severity Map,
   SourceLocation Loc) {
   // Get all the diagnostics.
-  SmallVector AllDiags;
+  std::vector AllDiags;
   DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
 
   // Set the mapping.
Index: include/clang/Basic/DiagnosticIDs.h
===
--- include/clang/Basic/DiagnosticIDs.h
+++ include/clang/Basic/DiagnosticIDs.h
@@ -297,7 +297,7 @@
 
   /// \brief Get the set of all diagnostic IDs.
   static void getAllDiagnostics(diag::Flavor Flavor,
-SmallVectorImpl &Diags);
+std::vector &Diags);
 
   /// \brief Get the diagnostic option with the closest edit distance to the
   /// given group name.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41451: Make DiagnosticIDs::getAllDiagnostics use std::vector

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.
This revision is now accepted and ready to land.

LGTM!


https://reviews.llvm.org/D41451



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


[PATCH] D41432: [clangd] Switch xrefs and documenthighlight to annotated-code unit tests. NFC

2017-12-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: unittests/clangd/Annotations.h:12
+//
+//Annotations Example(R"cpp(
+//   int complete() { x.pri^ }  // ^ indicates a point

ioeric wrote:
> Does this support overlapping annotations like (named) points in (named) 
> ranges?
Yes - ranges can be nested, but not "overlapping" like `[a(b]c)`.
Added a comment.



Comment at: unittests/clangd/Annotations.h:45
+  // Crashes if there isn't exactly one.
+  Position point(llvm::StringRef Name = "") const;
+  // Returns the position of all points marked by ^ (or $name^) in the text.

ioeric wrote:
> Is this the position in the stripped code or the original text?
In the stripped code, which is what you'll feed to the compiler. Added a 
comment.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41432



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


[PATCH] D41452: [CodeGen] Fix access sizes in new-format TBAA tags

2017-12-20 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev created this revision.
kosarev added reviewers: rjmccall, hfinkel.
kosarev added a project: clang.

The new format requires to specify both the type of the access and its size. 
This patch fixes setting access sizes for TBAA tags that denote accesses to 
structure members. This fix affects all future TBAA metadata tests for the new 
format, so I guess we don't need any special tests for this fix.


Repository:
  rL LLVM

https://reviews.llvm.org/D41452

Files:
  lib/CodeGen/CGExpr.cpp


Index: lib/CodeGen/CGExpr.cpp
===
--- lib/CodeGen/CGExpr.cpp
+++ lib/CodeGen/CGExpr.cpp
@@ -3790,8 +3790,10 @@
   FieldTBAAInfo.Offset +=
   Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
 
-// Update the final access type.
+// Update the final access type and size.
 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
+FieldTBAAInfo.Size =
+getContext().getTypeSizeInChars(FieldType).getQuantity();
   }
 
   Address addr = base.getAddress();


Index: lib/CodeGen/CGExpr.cpp
===
--- lib/CodeGen/CGExpr.cpp
+++ lib/CodeGen/CGExpr.cpp
@@ -3790,8 +3790,10 @@
   FieldTBAAInfo.Offset +=
   Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
 
-// Update the final access type.
+// Update the final access type and size.
 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
+FieldTBAAInfo.Size =
+getContext().getTypeSizeInChars(FieldType).getQuantity();
   }
 
   Address addr = base.getAddress();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r321184 - [clangd] Switch xrefs and documenthighlight to annotated-code unit tests. NFC

2017-12-20 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Wed Dec 20 08:06:05 2017
New Revision: 321184

URL: http://llvm.org/viewvc/llvm-project?rev=321184&view=rev
Log:
[clangd] Switch xrefs and documenthighlight to annotated-code unit tests. NFC

Summary:
The goal here is again to make it easier to read and write the tests.

I've extracted `parseTextMarker` from CodeCompleteTests into an `Annotations`
class, adding features to it:
  - as well as points `^s` it allows ranges `[[...]]`
  - multiple points and ranges are supported
  - points and ranges may be named: `$name^` and `$name[[...]]`

These features are used for the xrefs tests. This also paves the way for
replacing the lit diagnostics.test with more readable unit tests, using named
ranges.

Alternative considered: `TestSelectionRange` in clang-refactor/TestSupport
Main problems were:
 - delimiting the end of ranges is awkward, requiring counting
 - comment syntax is long and at least as cryptic for most cases
 - no separate syntax for point vs range, which keeps xrefs tests concise
 - Still need to convert to Position everywhere
 - Still need helpers for common case of expecting exactly one point/range

(I'll probably promote the extra `PrintTo`s from some of the core Protocol types
into `operator<<` in `Protocol.h` itself in a separate, prior patch...)

Reviewers: ioeric

Subscribers: klimek, mgorny, ilya-biryukov, cfe-commits

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

Added:
clang-tools-extra/trunk/test/clangd/xrefs.test
clang-tools-extra/trunk/unittests/clangd/Annotations.cpp
clang-tools-extra/trunk/unittests/clangd/Annotations.h
clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp
Removed:
clang-tools-extra/trunk/test/clangd/definitions.test
clang-tools-extra/trunk/test/clangd/documenthighlight.test
Modified:
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
clang-tools-extra/trunk/unittests/clangd/Matchers.h

Removed: clang-tools-extra/trunk/test/clangd/definitions.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/definitions.test?rev=321183&view=auto
==
--- clang-tools-extra/trunk/test/clangd/definitions.test (original)
+++ clang-tools-extra/trunk/test/clangd/definitions.test (removed)
@@ -1,421 +0,0 @@
-# RUN: clangd -pretty -run-synchronously < %s | FileCheck -strict-whitespace %s
-# It is absolutely vital that this file has CRLF line endings.
-#
-Content-Length: 125
-
-{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
-
-Content-Length: 172
-
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"int
 main() {\nint a;\na;\n}\n"}}}
-
-Content-Length: 148
-
-{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":2,"character":0}}}
-# Go to local variable
-#  CHECK:  "id": 1,
-# CHECK-NEXT:  "jsonrpc": "2.0",
-# CHECK-NEXT:  "result": [
-# CHECK-NEXT:{
-# CHECK-NEXT:  "range": {
-# CHECK-NEXT:"end": {
-# CHECK-NEXT:  "character": 5,
-# CHECK-NEXT:  "line": 1
-# CHECK-NEXT:},
-# CHECK-NEXT:"start": {
-# CHECK-NEXT:  "character": 0,
-# CHECK-NEXT:  "line": 1
-# CHECK-NEXT:}
-# CHECK-NEXT:  },
-# CHECK-NEXT:  "uri": "file:///{{([A-Z]:/)?}}main.cpp"
-# CHECK-NEXT:}
-# CHECK-NEXT:  ]
-Content-Length: 148
-
-{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":2,"character":1}}}
-# Go to local variable, end of token
-#  CHECK:  "id": 1,
-# CHECK-NEXT:  "jsonrpc": "2.0",
-# CHECK-NEXT:  "result": [
-# CHECK-NEXT:{
-# CHECK-NEXT:  "range": {
-# CHECK-NEXT:"end": {
-# CHECK-NEXT:  "character": 5,
-# CHECK-NEXT:  "line": 1
-# CHECK-NEXT:},
-# CHECK-NEXT:"start": {
-# CHECK-NEXT:  "character": 0,
-# CHECK-NEXT:  "line": 1
-# CHECK-NEXT:}
-# CHECK-NEXT:  },
-# CHECK-NEXT:  "uri": "file:///{{([A-Z]:/)?}}main.cpp"
-# CHECK-NEXT:}
-# CHECK-NEXT:  ]
-Content-Length: 214
-
-{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"file:///main.cpp","version":2},"contentChanges":[{"text":"struct
 Foo {\nint x;\n};\nint main() {\n  Foo bar = { x : 1 };\n}\n"}]}}
-
-Content-Length: 149
-
-{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":4,"character":14}}}
-# Go to field, GNU old-style field designator 
-#  CHECK:  "id": 1,
-# CHECK-NEXT:  "jsonrpc": "2.0",
-# CHECK-NEXT:  "result": [
-# CHECK-NEXT:{
-# CHECK-NEXT:  "range": {
-# CHECK-NEXT:"end": {
-# CHECK-NEX

[PATCH] D41432: [clangd] Switch xrefs and documenthighlight to annotated-code unit tests. NFC

2017-12-20 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked 2 inline comments as done.
Closed by commit rL321184: [clangd] Switch xrefs and documenthighlight to 
annotated-code unit tests. NFC (authored by sammccall, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41432?vs=127674&id=127728#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D41432

Files:
  clang-tools-extra/trunk/test/clangd/definitions.test
  clang-tools-extra/trunk/test/clangd/documenthighlight.test
  clang-tools-extra/trunk/test/clangd/xrefs.test
  clang-tools-extra/trunk/unittests/clangd/Annotations.cpp
  clang-tools-extra/trunk/unittests/clangd/Annotations.h
  clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
  clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
  clang-tools-extra/trunk/unittests/clangd/Matchers.h
  clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp

Index: clang-tools-extra/trunk/test/clangd/xrefs.test
===
--- clang-tools-extra/trunk/test/clangd/xrefs.test
+++ clang-tools-extra/trunk/test/clangd/xrefs.test
@@ -0,0 +1,67 @@
+# RUN: clangd -pretty -run-synchronously < %s | FileCheck -strict-whitespace %s
+# It is absolutely vital that this file has CRLF line endings.
+#
+Content-Length: 125
+
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+
+Content-Length: 165
+
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
+
+Content-Length: 148
+
+{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":8}}}
+#  CHECK:  "id": 1,
+# CHECK-NEXT:  "jsonrpc": "2.0",
+# CHECK-NEXT:  "result": [
+# CHECK-NEXT:{
+# CHECK-NEXT:  "range": {
+# CHECK-NEXT:"end": {
+# CHECK-NEXT:  "character": 9,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:},
+# CHECK-NEXT:"start": {
+# CHECK-NEXT:  "character": 0,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:}
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "uri": "file:///{{([A-Z]:/)?}}main.cpp"
+# CHECK-NEXT:}
+# CHECK-NEXT:  ]
+Content-Length: 155
+
+{"jsonrpc":"2.0","id":1,"method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":8}}}
+#  CHECK: "id": 1
+# CHECK-NEXT: "jsonrpc": "2.0",
+# CHECK-NEXT: "result": [
+# CHECK-NEXT:   {
+# CHECK-NEXT: "kind": 1,
+# CHECK-NEXT: "range": {
+# CHECK-NEXT:   "end": {
+# CHECK-NEXT: "character": 5,
+# CHECK-NEXT: "line": 0
+# CHECK-NEXT:   },
+# CHECK-NEXT:   "start": {
+# CHECK-NEXT: "character": 4,
+# CHECK-NEXT: "line": 0
+# CHECK-NEXT:   }
+# CHECK-NEXT: }
+# CHECK-NEXT:   },
+# CHECK-NEXT:   {
+# CHECK-NEXT: "kind": 2,
+# CHECK-NEXT: "range": {
+# CHECK-NEXT:   "end": {
+# CHECK-NEXT: "character": 9,
+# CHECK-NEXT: "line": 1
+# CHECK-NEXT:   },
+# CHECK-NEXT:   "start": {
+# CHECK-NEXT: "character": 8,
+# CHECK-NEXT: "line": 1
+# CHECK-NEXT:   }
+# CHECK-NEXT: }
+# CHECK-NEXT:   }
+# CHECK-NEXT: ]
+Content-Length: 48
+
+{"jsonrpc":"2.0","id":1,"method":"shutdown"}
Index: clang-tools-extra/trunk/unittests/clangd/Matchers.h
===
--- clang-tools-extra/trunk/unittests/clangd/Matchers.h
+++ clang-tools-extra/trunk/unittests/clangd/Matchers.h
@@ -13,6 +13,7 @@
 
 #ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_MATCHERS_H
 #define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_MATCHERS_H
+#include "Protocol.h"
 #include "gmock/gmock.h"
 
 namespace clang {
Index: clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/XRefsTests.cpp
@@ -0,0 +1,218 @@
+//===-- XRefsTests.cpp  ---*- C++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "Annotations.h"
+#include "ClangdUnit.h"
+#include "Matchers.h"
+#include "XRefs.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/PCHContainerOperations.h"
+#include "clang/Frontend/Utils.h"
+#include "llvm/Support/Path.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+using namespace llvm;
+
+void PrintTo(const DocumentHighlight &V, std::ostream *O) {
+  llvm::raw_os_ostream OS(*O);
+  OS << 

[PATCH] D41399: [CodeGen] Represent array members in new-format TBAA type descriptors

2017-12-20 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev added inline comments.



Comment at: test/CodeGen/tbaa-array.cpp:24
+// CHECK-DAG: [[TAG_A_i]] = !{[[TYPE_A:!.*]], [[TYPE_int:!.*]], i64 0, i64 4}
+// CHECK-DAG: [[TAG_C_i]] = !{[[TYPE_C:!.*]], [[TYPE_int:!.*]], i64 0, i64 16}
+// CHECK-DAG: [[TYPE_A]] = !{[[TYPE_char:!.*]], i64 4, !"_ZTS1A", 
[[TYPE_int]], i64 0, i64 4}

hfinkel wrote:
> Shouldn't this access have a size of 4, and an access for c->x[2] have a size 
> of 4 and a specific offset and c->x[j] have a size of 12 and an offset of 
> zero? Why does this list a size of 16?
> 
> In any case, please add tests for:
> 
>   int *bar2(C *c) {
> return c->x;
>   }
> 
>   int bar3(C *c) {
> return c->x[2];
>   }
> 
>   int bar4(C *c, int j) {
> return c->x[j];
>   }
> 
Indeed, the access size is wrong as we mistakenly inherit it from the base 
type. D41452 fixes this. Thanks for catching.


Repository:
  rL LLVM

https://reviews.llvm.org/D41399



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


[PATCH] D41345: [clangd] Add more symbol information for code completion.

2017-12-20 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 127730.
ioeric marked 4 inline comments as done.
ioeric added a comment.

- Merge with origin/master
- Fixed an error in merge
- Make documentation etc optional in symbols
- Merge remote-tracking branch 'origin/master' into symbol
- Merge branch 'index-completion' into symbol
- Address review comments; merge with https://reviews.llvm.org/D41450.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41345

Files:
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/CodeComplete.cpp
  clangd/index/FileIndex.cpp
  clangd/index/Index.h
  clangd/index/SymbolCollector.cpp
  clangd/index/SymbolCollector.h
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -9,7 +9,6 @@
 
 #include "index/SymbolCollector.h"
 #include "index/SymbolYAML.h"
-#include "clang/Index/IndexingAction.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Basic/VirtualFileSystem.h"
@@ -26,11 +25,25 @@
 #include 
 #include 
 
+using testing::AllOf;
 using testing::Eq;
 using testing::Field;
 using testing::UnorderedElementsAre;
 
 // GMock helpers for matching Symbol.
+MATCHER_P(Labeled, Label, "") { return arg.second.CompletionLabel == Label; }
+MATCHER_P(Detail, D, "") {
+  return arg.second.Detail && arg.second.Detail->CompletionDetail == D;
+}
+MATCHER_P(Doc, D, "") {
+  return arg.second.Detail && arg.second.Detail->Documentation == D;
+}
+MATCHER_P(Plain, Text, "") {
+  return arg.second.CompletionPlainInsertText == Text;
+}
+MATCHER_P(Snippet, S, "") {
+  return arg.second.CompletionSnippetInsertText == S;
+}
 MATCHER_P(QName, Name, "") {
   return (arg.second.Scope + (arg.second.Scope.empty() ? "" : "::") +
   arg.second.Name) == Name;
@@ -110,6 +123,38 @@
 QName("f1"), QName("f2")));
 }
 
+TEST_F(SymbolCollectorTest, SymbolWithDocumentation) {
+  const std::string Main = R"(
+namespace nx {
+/// Foo comment.
+int ff(int x, double y) { return 0; }
+}
+  )";
+  runSymbolCollector(/*Header=*/"", Main);
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("nx"),
+   AllOf(QName("nx::ff"),
+ Labeled("ff(int x, double y)"),
+ Detail("int"), Doc("Foo comment.";
+}
+
+TEST_F(SymbolCollectorTest, PlainAndSnippet) {
+  const std::string Main = R"(
+namespace nx {
+void f() {}
+int ff(int x, double y) { return 0; }
+}
+  )";
+  runSymbolCollector(/*Header=*/"", Main);
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  QName("nx"),
+  AllOf(QName("nx::f"), Labeled("f()"), Plain("f()"), Snippet("")),
+  AllOf(QName("nx::ff"), Labeled("ff(int x, double y)"), Plain("ff"),
+Snippet("ff(${1:int x}, ${2:double y})";
+}
+
 TEST_F(SymbolCollectorTest, YAMLConversions) {
   const std::string YAML1 = R"(
 ---
Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -86,6 +86,8 @@
 MATCHER_P(Labeled, Label, "") { return arg.label == Label; }
 MATCHER_P(Kind, K, "") { return arg.kind == K; }
 MATCHER_P(Filter, F, "") { return arg.filterText == F; }
+MATCHER_P(Doc, D, "") { return arg.documentation == D; }
+MATCHER_P(Detail, D, "") { return arg.detail == D; }
 MATCHER_P(PlainText, Text, "") {
   return arg.insertTextFormat == clangd::InsertTextFormat::PlainText &&
  arg.insertText == Text;
@@ -480,6 +482,7 @@
   Sym.Name = QName.substr(Pos + 2);
   Sym.Scope = QName.substr(0, Pos);
 }
+Sym.CompletionPlainInsertText = Sym.Name;
 Sym.SymInfo.Kind = Pair.second;
 Snap->Slab.insert(std::move(Sym));
   }
@@ -530,7 +533,7 @@
   void f() { ns::x^ }
   )cpp",
  Opts);
-  EXPECT_THAT(Results.items, Contains(AllOf(Named("XYZ"), Filter("x";
+  EXPECT_THAT(Results.items, Contains(Named("XYZ")));
   EXPECT_THAT(Results.items, Not(Has("foo")));
 }
 
@@ -568,13 +571,17 @@
 
   Server
   .addDocument(Context::empty(), getVirtualTestFilePath("foo.cpp"), R"cpp(
-  namespace ns { class XYZ {}; void foo() {} }
+  namespace ns { class XYZ {}; void foo(int x) {} }
   )cpp")
   .wait();
 
   auto File = getVirtualTestFilePath("bar.cpp");
   auto Test = parseTextMarker(R"cpp(
-  namespace ns { class XXX {}; void fo() {} }
+  namespace ns {
+  class XXX {};
+  /// Doooc
+  void fo() {}
+  }
   void f() { ns::^ }
   )cpp");
   Server.addDocument(Context::empty(), File, Test.Text).wait();
@@ -587,7 +594,9 @@
   EXPECT_TH

[PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

In case of `-fdelayed-template-parsing`, this code won't be even visible to the 
Importer. In my opinion, we shouldn't care about code we're not going to 
import. If we want to import it, we should make it visible and instantiate it. 
In this case it will not compile.
However, I completely agree with the statement that testing of two options is 
better. The question is how to design unit testing for different command line 
options. I'll make a try and update the patch. Unfortunately, the new version 
is much bigger than the source patch. I'm not also sure that new design is 
scalable if we want to introduce more options in future. Any suggestions on 
this are welcome.
Also, I still think we should rather not apply template-related patches until 
this testing is implemented. Gabor, Peter, do you agree?


Repository:
  rC Clang

https://reviews.llvm.org/D41444



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


[PATCH] D41345: [clangd] Add more symbol information for code completion.

2017-12-20 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

Thanks for the review!

Logic around CodeCompletionString is pulled into a separate file in 
https://reviews.llvm.org/D41450.

I also propagate the new completion info to completion code. I am happy to 
split it out if it adds too much noise for the review.




Comment at: clangd/index/Index.h:92
 
+  // Documentation including comment for the symbol declaration.
+  std::string Documentation;

sammccall wrote:
> AFAIK this information isn't needed for retrieval/scoring, just for display.
> 
> LSP has `completionItem/resolve` that adds additional info to a completion 
> item. This allows us to avoid sending a bunch of bulky comments, most of 
> which will never be looked at.
> 
> In practice, there's nothing we particularly want to do differently for the 
> memory index: we have to load the data into memory, and so including a 
> pointer to it right away is no extra work.
> 
> However Symbol has two roles, and being the in-memory representation for 
> MemIndex is only secondary. Its primary role is defining the protocol between 
> indexes and clangd, including remote indexes where returning all 
> documentation *is* expensive.
> 
> One option is to have Symbol just have the "core stuff" that's suitable for 
> returning in bulk, and have an index method to retrieve more details that 
> would be a point lookup only. (Maybe this is just the getSymbol method we've 
> thought about). I'm not sure what it means for the data structure. OK if we 
> discuss offline?
As discussed offline, putting non-core stuff in an optional structure.



Comment at: clangd/index/Index.h:100
+  std::string CompletionDetail;
+  // The placeholder text for function parameters in order.
+  std::vector Params;

sammccall wrote:
> How are you planning to use this?
> 
> This seems to be related to the completion text/edits. We had some early 
> discussions about whether we'd encode something like CodeCompletionString, or 
> LSP snippets, or something else entirely.
> Honestly it would be great to have a doc describing this mapping between 
> source -> index -> LSP for completion data.
As discussed offline, we now store the whole snippet in the insertion text.



Comment at: clangd/index/SymbolCollector.cpp:61
+
+std::string getDocumentation(const CodeCompletionString &CCS) {
+  // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this

sammccall wrote:
> it seems we'll want to share the(some?) doc logic between hover, AST-based 
> complete, and indexing... See D35894 (which is ... complicated, no idea if 
> it'll land soon).
> 
> Among other things:
>  - we may not want to make the logic too elaborate until we're able to merge 
> interfaces
>  - we may want to consume AST nodes rather than CCS in the long run
I pulled `CodeCompletionString` handling logic into a separate file in `D41450`.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41345



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


[PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

In https://reviews.llvm.org/D41444#960999, @a.sidorin wrote:

> Also, I still think we should rather not apply template-related patches until 
> this testing is implemented. Gabor, Peter, do you agree?


Sure, I am fine with that.


Repository:
  rC Clang

https://reviews.llvm.org/D41444



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


[PATCH] D41365: [clang] Add BeforeExecute method to PrecompiledPreamble

2017-12-20 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.

LG


Repository:
  rC Clang

https://reviews.llvm.org/D41365



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


[PATCH] D41450: [clangd] Pull CodeCompletionString handling logic into its own file and add unit test.

2017-12-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clangd/CompletionString.cpp:51
+  std::string Result;
+  Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare.
+  for (const auto Character : Text) {

if you actually care about performance, escapeSnippet should take the string to 
append to as a parameter



Comment at: clangd/CompletionString.cpp:67
+  for (const auto &Chunk : CCS) {
+// Informative qualifier chunks only clutter completion results, skip
+// them.

these comments are just copies of the enum documentation, mind removing them 
while here?



Comment at: clangd/CompletionString.cpp:118
+  break;
+case CodeCompletionString::CK_LeftParen:
+  // A left parenthesis ('(').

you've grouped these into a default case above - do the same here?



Comment at: clangd/CompletionString.h:1
+//===--- CompletionString.h --*- 
C++-*-===//
+//

nit: `CodeCompletionStrings`?

plural because it doesn't define the type, but operations on it.
Full name because we have too many ways to spell things already...



Comment at: clangd/CompletionString.h:25
+///
+/// If \p IsSnippet is not nullptr, this will try to use snippet for the insert
+/// text and sets `IsSnippet` to true when a snippet is created. Otherwise, the

This IsSnippet signature is clever, and matches the existing behavior (even if 
snippets are supported, we send plaintext if possible).

However that doesn't seem important to preserve - either snippets are supported 
or they're not, and the logic is simpler if we just tell getLabelAndInsertText 
what style we want.



Comment at: clangd/CompletionString.h:28
+/// insert text will always be plain text.
+std::pair
+getLabelAndInsertText(const CodeCompletionString &CCS,

nit: std::pair is always hard to remember - can we take two out-params so 
code-completion can help us?



Comment at: clangd/CompletionString.h:34
+/// a class declaration.
+std::string getDocumentation(const CodeCompletionString &CCS);
+

I'm skeptical that CodeCompletionString is actually where we want to be 
generating documentation in the long run, vs something like Decl which will 
give us more flexibility. But this matches what we currently do and seems fine 
for now.



Comment at: clangd/CompletionString.h:37
+/// Gets detail to be used as the detail field in an LSP completion item. This
+/// is usually the result of a function.
+std::string getDetail(const CodeCompletionString &CCS);

nit: result -> return type



Comment at: unittests/clangd/CompletionStringTests.cpp:89
+
+TEST_F(CompletionStringTest, FunctionSnippet) {
+  Builder.AddResultTypeChunk("result no no");

I like the fine-grained tests of the features, but I'd also like to be able to 
see how these strings compare for more typical examples, like the one in this 
test.

Could you have a test (maybe this one or maybe a new one) where you build a 
typical function CCS, and then assert all the strings: label, insert text, 
filter text, with and without snippets...


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41450



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


[PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Zachary Turner via Phabricator via cfe-commits
zturner added a comment.

Can you just have `getLangArgs` return a vector of vectors, and then in 
`testImport` run it in a loop over all sets of args?


Repository:
  rC Clang

https://reviews.llvm.org/D41444



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


[PATCH] D38171: [clang-tidy] Implement clang-tidy check aliases

2017-12-20 Thread András Leitereg via Phabricator via cfe-commits
leanil updated this revision to Diff 127736.
leanil added a comment.

Remove redundant empty lines.
Make list-clang-diagnostics test less strict.
Update getAllDiagnostics to use std::vector.


https://reviews.llvm.org/D38171

Files:
  clang-tidy/ClangTidy.cpp
  clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tidy/ClangTidyModule.h
  clang-tidy/cert/CERTTidyModule.cpp
  clang-tidy/tool/ClangTidyMain.cpp
  test/clang-tidy/cert-exp59-cpp.cpp
  test/clang-tidy/custom-diagnostics.cpp
  test/clang-tidy/diagnostic.cpp
  test/clang-tidy/list-clang-diagnostics.cpp
  test/clang-tidy/misc-suspicious-semicolon-fail.cpp
  test/clang-tidy/validate-check-names.cpp
  test/clang-tidy/warning-check-aliases.cpp
  test/clang-tidy/werrors-diagnostics.cpp

Index: test/clang-tidy/werrors-diagnostics.cpp
===
--- test/clang-tidy/werrors-diagnostics.cpp
+++ test/clang-tidy/werrors-diagnostics.cpp
@@ -1,11 +1,10 @@
-// RUN: clang-tidy %s -checks='-*,llvm-namespace-comment,clang-diagnostic*' \
-// RUN:   -- -Wunused-variable 2>&1 \
+// RUN: clang-tidy %s -checks='-*,llvm-namespace-comment,clang-diagnostic-unused-variable' -- 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-WARN -implicit-check-not='{{warning|error}}:'
-// RUN: not clang-tidy %s -checks='-*,llvm-namespace-comment,clang-diagnostic*' \
-// RUN:   -warnings-as-errors='clang-diagnostic*' -- -Wunused-variable 2>&1 \
+// RUN: not clang-tidy %s -checks='-*,llvm-namespace-comment,clang-diagnostic-unused-variable' \
+// RUN:   -warnings-as-errors='clang-diagnostic*' -- 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-WERR -implicit-check-not='{{warning|error}}:'
-// RUN: not clang-tidy %s -checks='-*,llvm-namespace-comment,clang-diagnostic*' \
-// RUN:   -warnings-as-errors='clang-diagnostic*' -quiet -- -Wunused-variable 2>&1 \
+// RUN: not clang-tidy %s -checks='-*,llvm-namespace-comment,clang-diagnostic-unused-variable' \
+// RUN:   -warnings-as-errors='clang-diagnostic*' -quiet -- 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-WERR-QUIET -implicit-check-not='{{warning|error}}:'
 
 void f() { int i; }
Index: test/clang-tidy/warning-check-aliases.cpp
===
--- /dev/null
+++ test/clang-tidy/warning-check-aliases.cpp
@@ -0,0 +1,19 @@
+// RUN: clang-tidy %s -checks='-*,clang-diagnostic-exceptions' -- 2>&1 | FileCheck -implicit-check-not='{{warning:|error:}}' %s
+// RUN: clang-tidy %s -checks='-*,cert-err54-cpp' -- 2>&1 | FileCheck -implicit-check-not='{{warning:|error:}}' -check-prefix=CHECK2 %s
+// RUN: clang-tidy %s -- 2>&1 | FileCheck -allow-empty -implicit-check-not='{{warning:|error:}}' -check-prefix=CHECK3 %s
+
+class B {};
+class D : public B {};
+
+void f() {
+  try {
+  } catch (B &X) {
+  } catch (D &Y) {
+  }
+}
+
+//CHECK: :11:12: warning: exception of type 'D &' will be caught by earlier handler [clang-diagnostic-exceptions]
+//CHECK: :10:12: note: for type 'B &'
+
+//CHECK2: :11:12: warning: exception of type 'D &' will be caught by earlier handler [cert-err54-cpp]
+//CHECK2: :10:12: note: for type 'B &'
Index: test/clang-tidy/validate-check-names.cpp
===
--- test/clang-tidy/validate-check-names.cpp
+++ test/clang-tidy/validate-check-names.cpp
@@ -1,2 +1,2 @@
 // Check names may only contain alphanumeric characters, '-', '_', and '.'.
-// RUN: clang-tidy -checks=* -list-checks | grep '^' | cut -b5- | not grep -v '^[a-zA-Z0-9_.\-]\+$'
+// RUN: clang-tidy -checks=*,-clang-diagnostic* -list-checks | grep '^' | cut -b5- | not grep -v '^[a-zA-Z0-9_.\-]\+$'
Index: test/clang-tidy/misc-suspicious-semicolon-fail.cpp
===
--- test/clang-tidy/misc-suspicious-semicolon-fail.cpp
+++ test/clang-tidy/misc-suspicious-semicolon-fail.cpp
@@ -1,8 +1,8 @@
 // RUN: clang-tidy %s -checks="-*,misc-suspicious-semicolon" -- -DERROR 2>&1 \
 // RUN:   | FileCheck %s -check-prefix=CHECK-ERROR \
 // RUN:   -implicit-check-not="{{warning|error}}:"
-// RUN: clang-tidy %s -checks="-*,misc-suspicious-semicolon,clang-diagnostic*" \
-// RUN:-- -DWERROR -Wno-everything -Werror=unused-variable 2>&1 \
+// RUN: not clang-tidy %s -checks="-*,misc-suspicious-semicolon,clang-diagnostic-unused-variable" \
+// RUN:   -warnings-as-errors=clang-diagnostic-unused-variable -- -DWERROR 2>&1 \
 // RUN:   | FileCheck %s -check-prefix=CHECK-WERROR \
 // RUN:   -implicit-check-not="{{warning|error}}:"
 
@@ -19,7 +19,7 @@
   // CHECK-ERROR: :[[@LINE-1]]:8: error: expected ';' at end of declaration [clang-diagnostic-error]
 #elif WERROR
   int a;
-  // CHECK-WERROR: :[[@LINE-1]]:7: error: unused variable 'a' [clang-diagnostic-unused-variable]
+  // CHECK-WERROR: :[[@LINE-1]]:7: error: unused variable 'a' [clang-diagnostic-unused-variable,-warnings-as-errors]
 #else
 #error "One of ERROR o

[libcxx] r321188 - Fix the definitions of 'reference' and 'pointer' in string_view that no one uses :-). Thanks to K-ballo for the catch.

2017-12-20 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Wed Dec 20 08:31:40 2017
New Revision: 321188

URL: http://llvm.org/viewvc/llvm-project?rev=321188&view=rev
Log:
Fix the definitions of 'reference' and 'pointer' in string_view that no one 
uses :-). Thanks to K-ballo for the catch.

Added:
libcxx/trunk/test/std/strings/string.view/types.pass.cpp
Modified:
libcxx/trunk/include/string_view

Modified: libcxx/trunk/include/string_view
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/string_view?rev=321188&r1=321187&r2=321188&view=diff
==
--- libcxx/trunk/include/string_view (original)
+++ libcxx/trunk/include/string_view Wed Dec 20 08:31:40 2017
@@ -196,9 +196,9 @@ public:
 // types
 typedef _Traitstraits_type;
 typedef _CharT value_type;
-typedef const _CharT*  pointer;
+typedef _CharT*pointer;
 typedef const _CharT*  const_pointer;
-typedef const _CharT&  reference;
+typedef _CharT&reference;
 typedef const _CharT&  const_reference;
 typedef const_pointer  const_iterator; // See 
[string.view.iterators]
 typedef const_iterator iterator;

Added: libcxx/trunk/test/std/strings/string.view/types.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/strings/string.view/types.pass.cpp?rev=321188&view=auto
==
--- libcxx/trunk/test/std/strings/string.view/types.pass.cpp (added)
+++ libcxx/trunk/test/std/strings/string.view/types.pass.cpp Wed Dec 20 
08:31:40 2017
@@ -0,0 +1,77 @@
+//===--===//
+//
+// 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.
+//
+//===--===//
+
+// 
+
+// Test nested types and default template args:
+
+// template>
+// {
+// public:
+// // types:
+// using traits_type   = traits;
+// using value_type= charT;
+// using pointer   = value_type*;
+// using const_pointer = const value_type*;
+// using reference = value_type&;
+// using const_reference   = const value_type&;
+// using const_iterator= implementation-defined ; // see 
24.4.2.2
+// using iterator  = const_iterator;
+// using const_reverse_iterator= reverse_iterator;
+// using iterator  = const_reverse_iterator;
+// using size_type = size_t;
+// using difference_type   = ptrdiff_t;
+// static constexpr size_type npos = size_type(-1);
+// 
+// };
+
+#include 
+#include 
+#include 
+
+#include "test_macros.h"
+
+template 
+void
+test()
+{
+typedef std::basic_string_view S;
+
+static_assert((std::is_same::value), 
"");
+static_assert((std::is_same::value), "");
+static_assert((std::is_same::value), "");
+static_assert((std::is_same::value), "");
+static_assert((std::is_same::value), "");
+static_assert((std::is_same::value), "");
+static_assert((std::is_same::value), "");
+static_assert((std::is_same::value), "");
+static_assert((std::is_same<
+typename std::iterator_traits::iterator_category,
+std::random_access_iterator_tag>::value), "");
+static_assert((std::is_same<
+typename std::iterator_traits::iterator_category,
+std::random_access_iterator_tag>::value), "");
+static_assert((std::is_same<
+typename S::reverse_iterator,
+std::reverse_iterator >::value), "");
+static_assert((std::is_same<
+typename S::const_reverse_iterator,
+std::reverse_iterator >::value), "");
+static_assert(S::npos == -1, "");
+static_assert((std::is_same::value), "");
+static_assert((std::is_same::value), "");
+}
+
+int main()
+{
+test >();
+test >();
+static_assert((std::is_same::traits_type,
+std::char_traits >::value), "");
+}


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


[PATCH] D38171: [clang-tidy] Implement clang-tidy check aliases

2017-12-20 Thread András Leitereg via Phabricator via cfe-commits
leanil marked 2 inline comments as done.
leanil added a comment.

Does anyone have any more thoughts about this?


https://reviews.llvm.org/D38171



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


[PATCH] D30691: [analyzer] Support for naive cross translational unit analysis

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun marked 6 inline comments as done.
xazax.hun added inline comments.



Comment at: lib/StaticAnalyzer/Core/CallEvent.cpp:372
+
+  cross_tu::CrossTranslationUnitContext &CTUCtx =
+  Engine->getCrossTranslationUnitContext();

dcoughlin wrote:
> Can this logic be moved to AnalysisDeclContext->getBody()?
> 
> CallEvent::getRuntimeDefinition() is really all about modeling function 
> dispatch at run time. It seems odd to have the cross-translation-unit loading 
> (which is about compiler book-keeping rather than semantics) here.
I just tried that and unfortunately, that introduces cyclic dependencies. 
CrossTU depends on Frontend. Frontend depends on Sema. Sema depends on 
Analysis. Making Analysis depending on CrossTU introduces the cycle.



Comment at: lib/StaticAnalyzer/Core/CallEvent.cpp:382
+[&](const cross_tu::IndexError &IE) {
+  CTUCtx.emitCrossTUDiagnostics(IE);
+});

dcoughlin wrote:
> I don't think it makes sense to diagnose index errors here.
> 
> Doing it when during analysis means that, for example, the parse error could 
> be emitted or not emitted depending on whether the analyzer thinks a 
> particular call site is reached.
> 
> It would be better to validate/parse the index before starting analysis 
> rather than during analysis itself.
> 
> 
While I agree, right now this validation is not the part of the analyzer but 
the responsibility of the "driver" script for example CodeChecker. It is useful 
to have this diagnostics to catch bugs in the driver. 


https://reviews.llvm.org/D30691



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


[PATCH] D30691: [analyzer] Support for naive cross translational unit analysis

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 127525.
xazax.hun marked an inline comment as not done.
xazax.hun added a comment.

- Address some review comments
- Rebased on ToT


https://reviews.llvm.org/D30691

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/CMakeLists.txt
  lib/StaticAnalyzer/Core/CallEvent.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  lib/StaticAnalyzer/Frontend/CMakeLists.txt
  test/Analysis/Inputs/ctu-chain.cpp
  test/Analysis/Inputs/ctu-other.cpp
  test/Analysis/Inputs/externalFnMap.txt
  test/Analysis/ctu-main.cpp
  tools/scan-build-py/libscanbuild/__init__.py
  tools/scan-build-py/libscanbuild/analyze.py
  tools/scan-build-py/libscanbuild/arguments.py
  tools/scan-build-py/libscanbuild/clang.py
  tools/scan-build-py/libscanbuild/report.py
  tools/scan-build-py/tests/unit/test_analyze.py
  tools/scan-build-py/tests/unit/test_clang.py

Index: tools/scan-build-py/tests/unit/test_clang.py
===
--- tools/scan-build-py/tests/unit/test_clang.py
+++ tools/scan-build-py/tests/unit/test_clang.py
@@ -92,3 +92,15 @@
 self.assertEqual('Checker One description', result.get('checker.one'))
 self.assertTrue('checker.two' in result)
 self.assertEqual('Checker Two description', result.get('checker.two'))
+
+
+class ClangIsCtuCapableTest(unittest.TestCase):
+def test_ctu_not_found(self):
+is_ctu = sut.is_ctu_capable('not-found-clang-func-mapping')
+self.assertFalse(is_ctu)
+
+
+class ClangGetTripleArchTest(unittest.TestCase):
+def test_arch_is_not_empty(self):
+arch = sut.get_triple_arch(['clang', '-E', '-'], '.')
+self.assertTrue(len(arch) > 0)
Index: tools/scan-build-py/tests/unit/test_analyze.py
===
--- tools/scan-build-py/tests/unit/test_analyze.py
+++ tools/scan-build-py/tests/unit/test_analyze.py
@@ -4,12 +4,12 @@
 # This file is distributed under the University of Illinois Open Source
 # License. See LICENSE.TXT for details.
 
-import libear
-import libscanbuild.analyze as sut
 import unittest
 import re
 import os
 import os.path
+import libear
+import libscanbuild.analyze as sut
 
 
 class ReportDirectoryTest(unittest.TestCase):
@@ -333,3 +333,83 @@
 
 def test_method_exception_not_caught(self):
 self.assertRaises(Exception, method_exception_from_inside, dict())
+
+
+class PrefixWithTest(unittest.TestCase):
+
+def test_gives_empty_on_empty(self):
+res = sut.prefix_with(0, [])
+self.assertFalse(res)
+
+def test_interleaves_prefix(self):
+res = sut.prefix_with(0, [1, 2, 3])
+self.assertListEqual([0, 1, 0, 2, 0, 3], res)
+
+
+class MergeCtuMapTest(unittest.TestCase):
+
+def test_no_map_gives_empty(self):
+pairs = sut.create_global_ctu_function_map([])
+self.assertFalse(pairs)
+
+def test_multiple_maps_merged(self):
+concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
+  'c:@F@fun2#I# ast/fun2.c.ast',
+  'c:@F@fun3#I# ast/fun3.c.ast']
+pairs = sut.create_global_ctu_function_map(concat_map)
+self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
+self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
+self.assertTrue(('c:@F@fun3#I#', 'ast/fun3.c.ast') in pairs)
+self.assertEqual(3, len(pairs))
+
+def test_not_unique_func_left_out(self):
+concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
+  'c:@F@fun2#I# ast/fun2.c.ast',
+  'c:@F@fun1#I# ast/fun7.c.ast']
+pairs = sut.create_global_ctu_function_map(concat_map)
+self.assertFalse(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
+self.assertFalse(('c:@F@fun1#I#', 'ast/fun7.c.ast') in pairs)
+self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
+self.assertEqual(1, len(pairs))
+
+def test_duplicates_are_kept(self):
+concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
+  'c:@F@fun2#I# ast/fun2.c.ast',
+  'c:@F@fun1#I# ast/fun1.c.ast']
+pairs = sut.create_global_ctu_function_map(concat_map)
+self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
+self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
+self.assertEqual(2, len(pairs))
+
+def test_space_handled_in_source(self):
+concat_map = ['c:@F@fun1#I# ast/f un.c.ast']
+pairs = sut.create_global_ctu_function_map(concat_map)
+self.assertTrue(('c:@F@fun1#I#', 'ast/f un.c.ast') in pairs)
+self.assertEqual(1, len(pairs))
+
+
+class FuncMapSrcToAstTest(unittest.TestCase):
+
+def test_empty_gives_empty(se

[PATCH] D30691: [analyzer] Support for naive cross translational unit analysis

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: lib/StaticAnalyzer/Core/AnalyzerOptions.cpp:407
+  if (!NaiveCTU.hasValue()) {
+NaiveCTU = getBooleanOption("experimental-enable-naive-ctu-analysis",
+/*Default=*/false);

This option might not be the most readable but this way experimental is a 
prefix. Do you prefer this way or something like 
`enable-experimental-naive-ctu-analysis`?


https://reviews.llvm.org/D30691



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


[PATCH] D41384: [analyzer] Suppress false positive warnings form security.insecureAPI.strcpy

2017-12-20 Thread András Leitereg via Phabricator via cfe-commits
leanil updated this revision to Diff 127739.
leanil added a comment.

Move negative test next to the positive ones, because the necessary macros and 
run-lines are already defined there.


https://reviews.llvm.org/D41384

Files:
  lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
  test/Analysis/security-syntax-checks.m


Index: test/Analysis/security-syntax-checks.m
===
--- test/Analysis/security-syntax-checks.m
+++ test/Analysis/security-syntax-checks.m
@@ -146,6 +146,11 @@
   strcpy(x, y); //expected-warning{{Call to function 'strcpy' is insecure as 
it does not provide bounding of the memory buffer. Replace unbounded copy 
functions with analogous functions that support length arguments such as 
'strlcpy'. CWE-119}}
 }
 
+void test_strcpy_safe() {
+  char x[5];
+  strcpy(x, "abcd");
+}
+
 //===--===
 // strcat()
 //===--===
Index: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
===
--- lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -510,6 +510,18 @@
   if (!checkCall_strCommon(CE, FD))
 return;
 
+  int ArraySize = -1, StrLen = -1;
+  const auto *Target = CE->getArg(0)->IgnoreImpCasts(),
+ *Source = CE->getArg(1)->IgnoreImpCasts();
+  if (const auto *DeclRef = dyn_cast(Target))
+if (const auto *Array = dyn_cast(
+DeclRef->getDecl()->getType().getTypePtr()))
+  ArraySize = Array->getSize().getLimitedValue();
+  if (const auto *String = dyn_cast(Source))
+StrLen = String->getLength();
+  if (StrLen != -1 && ArraySize >= StrLen + 1)
+return;
+
   // Issue a warning.
   PathDiagnosticLocation CELoc =
 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);


Index: test/Analysis/security-syntax-checks.m
===
--- test/Analysis/security-syntax-checks.m
+++ test/Analysis/security-syntax-checks.m
@@ -146,6 +146,11 @@
   strcpy(x, y); //expected-warning{{Call to function 'strcpy' is insecure as it does not provide bounding of the memory buffer. Replace unbounded copy functions with analogous functions that support length arguments such as 'strlcpy'. CWE-119}}
 }
 
+void test_strcpy_safe() {
+  char x[5];
+  strcpy(x, "abcd");
+}
+
 //===--===
 // strcat()
 //===--===
Index: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
===
--- lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -510,6 +510,18 @@
   if (!checkCall_strCommon(CE, FD))
 return;
 
+  int ArraySize = -1, StrLen = -1;
+  const auto *Target = CE->getArg(0)->IgnoreImpCasts(),
+ *Source = CE->getArg(1)->IgnoreImpCasts();
+  if (const auto *DeclRef = dyn_cast(Target))
+if (const auto *Array = dyn_cast(
+DeclRef->getDecl()->getType().getTypePtr()))
+  ArraySize = Array->getSize().getLimitedValue();
+  if (const auto *String = dyn_cast(Source))
+StrLen = String->getLength();
+  if (StrLen != -1 && ArraySize >= StrLen + 1)
+return;
+
   // Issue a warning.
   PathDiagnosticLocation CELoc =
 PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41399: [CodeGen] Represent array members in new-format TBAA type descriptors

2017-12-20 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev added inline comments.



Comment at: test/CodeGen/tbaa-array.cpp:24
+// CHECK-DAG: [[TAG_A_i]] = !{[[TYPE_A:!.*]], [[TYPE_int:!.*]], i64 0, i64 4}
+// CHECK-DAG: [[TAG_C_i]] = !{[[TYPE_C:!.*]], [[TYPE_int:!.*]], i64 0, i64 16}
+// CHECK-DAG: [[TYPE_A]] = !{[[TYPE_char:!.*]], i64 4, !"_ZTS1A", 
[[TYPE_int]], i64 0, i64 4}

kosarev wrote:
> hfinkel wrote:
> > Shouldn't this access have a size of 4, and an access for c->x[2] have a 
> > size of 4 and a specific offset and c->x[j] have a size of 12 and an offset 
> > of zero? Why does this list a size of 16?
> > 
> > In any case, please add tests for:
> > 
> >   int *bar2(C *c) {
> > return c->x;
> >   }
> > 
> >   int bar3(C *c) {
> > return c->x[2];
> >   }
> > 
> >   int bar4(C *c, int j) {
> > return c->x[j];
> >   }
> > 
> Indeed, the access size is wrong as we mistakenly inherit it from the base 
> type. D41452 fixes this. Thanks for catching.
Hal, in bar2() we don't really access memory. What do we want to check with it?


Repository:
  rL LLVM

https://reviews.llvm.org/D41399



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


[PATCH] D41365: [clang] Add BeforeExecute method to PrecompiledPreamble

2017-12-20 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC321189: [clang] Add BeforeExecute method to 
PrecompiledPreamble (authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41365?vs=127715&id=127740#toc

Repository:
  rC Clang

https://reviews.llvm.org/D41365

Files:
  include/clang/Frontend/PrecompiledPreamble.h
  lib/Frontend/PrecompiledPreamble.cpp


Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -333,6 +333,7 @@
   std::unique_ptr Act;
   Act.reset(new PrecompilePreambleAction(
   StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
+  Callbacks.BeforeExecute(*Clang);
   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
 return BuildPreambleError::BeginSourceFileFailed;
 
@@ -694,6 +695,7 @@
   }
 }
 
+void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
Index: include/clang/Frontend/PrecompiledPreamble.h
===
--- include/clang/Frontend/PrecompiledPreamble.h
+++ include/clang/Frontend/PrecompiledPreamble.h
@@ -244,6 +244,10 @@
 public:
   virtual ~PreambleCallbacks() = default;
 
+  /// Called before FrontendAction::BeginSourceFile.
+  /// Can be used to store references to various CompilerInstance fields
+  /// (e.g. SourceManager) that may be interesting to the consumers of other 
callbacks.
+  virtual void BeforeExecute(CompilerInstance &CI);
   /// Called after FrontendAction::Execute(), but before
   /// FrontendAction::EndSourceFile(). Can be used to transfer ownership of
   /// various CompilerInstance fields before they are destroyed.


Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -333,6 +333,7 @@
   std::unique_ptr Act;
   Act.reset(new PrecompilePreambleAction(
   StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
+  Callbacks.BeforeExecute(*Clang);
   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
 return BuildPreambleError::BeginSourceFileFailed;
 
@@ -694,6 +695,7 @@
   }
 }
 
+void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
Index: include/clang/Frontend/PrecompiledPreamble.h
===
--- include/clang/Frontend/PrecompiledPreamble.h
+++ include/clang/Frontend/PrecompiledPreamble.h
@@ -244,6 +244,10 @@
 public:
   virtual ~PreambleCallbacks() = default;
 
+  /// Called before FrontendAction::BeginSourceFile.
+  /// Can be used to store references to various CompilerInstance fields
+  /// (e.g. SourceManager) that may be interesting to the consumers of other callbacks.
+  virtual void BeforeExecute(CompilerInstance &CI);
   /// Called after FrontendAction::Execute(), but before
   /// FrontendAction::EndSourceFile(). Can be used to transfer ownership of
   /// various CompilerInstance fields before they are destroyed.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r321189 - [clang] Add BeforeExecute method to PrecompiledPreamble

2017-12-20 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Dec 20 08:48:56 2017
New Revision: 321189

URL: http://llvm.org/viewvc/llvm-project?rev=321189&view=rev
Log:
[clang] Add BeforeExecute method to PrecompiledPreamble

Summary: Adds BeforeExecute method to PrecompiledPreamble to be called
before Execute(). This method can be overriden.

Patch by William Enright.

Reviewers: malaperle, ilya-biryukov

Reviewed By: ilya-biryukov

Subscribers: arphaman, cfe-commits, ilya-biryukov

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

Modified:
cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h
cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp

Modified: cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h?rev=321189&r1=321188&r2=321189&view=diff
==
--- cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h (original)
+++ cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h Wed Dec 20 08:48:56 
2017
@@ -244,6 +244,10 @@ class PreambleCallbacks {
 public:
   virtual ~PreambleCallbacks() = default;
 
+  /// Called before FrontendAction::BeginSourceFile.
+  /// Can be used to store references to various CompilerInstance fields
+  /// (e.g. SourceManager) that may be interesting to the consumers of other 
callbacks.
+  virtual void BeforeExecute(CompilerInstance &CI);
   /// Called after FrontendAction::Execute(), but before
   /// FrontendAction::EndSourceFile(). Can be used to transfer ownership of
   /// various CompilerInstance fields before they are destroyed.

Modified: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp?rev=321189&r1=321188&r2=321189&view=diff
==
--- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp (original)
+++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp Wed Dec 20 08:48:56 2017
@@ -333,6 +333,7 @@ llvm::ErrorOr Preco
   std::unique_ptr Act;
   Act.reset(new PrecompilePreambleAction(
   StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
+  Callbacks.BeforeExecute(*Clang);
   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
 return BuildPreambleError::BeginSourceFileFailed;
 
@@ -694,6 +695,7 @@ void PrecompiledPreamble::setupPreambleS
   }
 }
 
+void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}


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


r321190 - Make DiagnosticIDs::getAllDiagnostics use std::vector. NFC.

2017-12-20 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Dec 20 08:55:41 2017
New Revision: 321190

URL: http://llvm.org/viewvc/llvm-project?rev=321190&view=rev
Log:
Make DiagnosticIDs::getAllDiagnostics use std::vector. NFC.

The size of the result vector is currently around 4600 with
Flavor::WarningOrError, which makes std::vector a better candidate than
llvm::SmallVector.

Patch by: Andras Leitereg!

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticIDs.h
cfe/trunk/lib/Basic/Diagnostic.cpp
cfe/trunk/lib/Basic/DiagnosticIDs.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticIDs.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticIDs.h?rev=321190&r1=321189&r2=321190&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticIDs.h (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticIDs.h Wed Dec 20 08:55:41 2017
@@ -297,7 +297,7 @@ public:
 
   /// \brief Get the set of all diagnostic IDs.
   static void getAllDiagnostics(diag::Flavor Flavor,
-SmallVectorImpl &Diags);
+std::vector &Diags);
 
   /// \brief Get the diagnostic option with the closest edit distance to the
   /// given group name.

Modified: cfe/trunk/lib/Basic/Diagnostic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Diagnostic.cpp?rev=321190&r1=321189&r2=321190&view=diff
==
--- cfe/trunk/lib/Basic/Diagnostic.cpp (original)
+++ cfe/trunk/lib/Basic/Diagnostic.cpp Wed Dec 20 08:55:41 2017
@@ -363,7 +363,7 @@ void DiagnosticsEngine::setSeverityForAl
   diag::Severity Map,
   SourceLocation Loc) {
   // Get all the diagnostics.
-  SmallVector AllDiags;
+  std::vector AllDiags;
   DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
 
   // Set the mapping.

Modified: cfe/trunk/lib/Basic/DiagnosticIDs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/DiagnosticIDs.cpp?rev=321190&r1=321189&r2=321190&view=diff
==
--- cfe/trunk/lib/Basic/DiagnosticIDs.cpp (original)
+++ cfe/trunk/lib/Basic/DiagnosticIDs.cpp Wed Dec 20 08:55:41 2017
@@ -583,7 +583,7 @@ DiagnosticIDs::getDiagnosticsInGroup(dia
 }
 
 void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
-  SmallVectorImpl &Diags) {
+  std::vector &Diags) {
   for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
 if (StaticDiagInfo[i].getFlavor() == Flavor)
   Diags.push_back(StaticDiagInfo[i].DiagID);


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


[PATCH] D41451: Make DiagnosticIDs::getAllDiagnostics use std::vector

2017-12-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun closed this revision.
xazax.hun added a comment.

Committed in https://reviews.llvm.org/rL321190


https://reviews.llvm.org/D41451



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


[PATCH] D41399: [CodeGen] Represent array members in new-format TBAA type descriptors

2017-12-20 Thread Hal Finkel via Phabricator via cfe-commits
hfinkel added inline comments.



Comment at: test/CodeGen/tbaa-array.cpp:24
+// CHECK-DAG: [[TAG_A_i]] = !{[[TYPE_A:!.*]], [[TYPE_int:!.*]], i64 0, i64 4}
+// CHECK-DAG: [[TAG_C_i]] = !{[[TYPE_C:!.*]], [[TYPE_int:!.*]], i64 0, i64 16}
+// CHECK-DAG: [[TYPE_A]] = !{[[TYPE_char:!.*]], i64 4, !"_ZTS1A", 
[[TYPE_int]], i64 0, i64 4}

kosarev wrote:
> kosarev wrote:
> > hfinkel wrote:
> > > Shouldn't this access have a size of 4, and an access for c->x[2] have a 
> > > size of 4 and a specific offset and c->x[j] have a size of 12 and an 
> > > offset of zero? Why does this list a size of 16?
> > > 
> > > In any case, please add tests for:
> > > 
> > >   int *bar2(C *c) {
> > > return c->x;
> > >   }
> > > 
> > >   int bar3(C *c) {
> > > return c->x[2];
> > >   }
> > > 
> > >   int bar4(C *c, int j) {
> > > return c->x[j];
> > >   }
> > > 
> > Indeed, the access size is wrong as we mistakenly inherit it from the base 
> > type. D41452 fixes this. Thanks for catching.
> Hal, in bar2() we don't really access memory. What do we want to check with 
> it?
> Hal, in bar2() we don't really access memory. What do we want to check with 
> it?

Ah, good point. Ignore that one.


Repository:
  rL LLVM

https://reviews.llvm.org/D41399



___
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.

2017-12-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, mgorny, klimek.

This adds checks that our diagnostics emit correct ranges in a bunch of cases,
as promised in https://reviews.llvm.org/D41118.

The diagnostics-preamble test is also converted and extended to be a little more
precise.

diagnostics.test stays around as the smoke test for this feature.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41454

Files:
  clangd/Protocol.cpp
  clangd/Protocol.h
  test/clangd/diagnostics-preamble.test
  unittests/clangd/CMakeLists.txt
  unittests/clangd/ClangdUnitTests.cpp

Index: unittests/clangd/ClangdUnitTests.cpp
===
--- /dev/null
+++ unittests/clangd/ClangdUnitTests.cpp
@@ -0,0 +1,124 @@
+//===-- ClangdUnitTests.cpp - ClangdUnit tests --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ClangdUnit.h"
+#include "Annotations.h"
+#include "TestFS.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/PCHContainerOperations.h"
+#include "clang/Frontend/Utils.h"
+#include "llvm/Support/ScopedPrinter.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+using namespace llvm;
+void PrintTo(const DiagWithFixIts &D, std::ostream *O) {
+  llvm::raw_os_ostream OS(*O);
+  OS << D.Diag;
+  if (!D.FixIts.empty()) {
+OS << " {";
+const char *Sep = "";
+for (const auto &F : D.FixIts) {
+  OS << Sep << F;
+  Sep = ", ";
+}
+OS << "}";
+  }
+}
+
+namespace {
+using testing::ElementsAre;
+
+// FIXME: this is duplicated with FileIndexTests. Share it.
+ParsedAST build(StringRef Code, std::vector Flags = {}) {
+  std::vector Cmd = {"clang", "main.cpp"};
+  Cmd.insert(Cmd.begin() + 1, Flags.begin(), Flags.end());
+  auto CI = createInvocationFromCommandLine(Cmd);
+  auto Buf = MemoryBuffer::getMemBuffer(Code);
+  auto AST = ParsedAST::Build(
+  Context::empty(), std::move(CI), nullptr, std::move(Buf),
+  std::make_shared(), vfs::getRealFileSystem());
+  assert(AST.hasValue());
+  return std::move(*AST);
+}
+
+MATCHER_P2(Diag, Range, Message,
+   "Diagnostic at " + llvm::to_string(Range) + " = [" + Message + "]") {
+  return arg.Diag.range == Range && arg.Diag.message == Message &&
+ arg.FixIts.empty();
+}
+
+MATCHER_P3(Fix, Range, Replacement, Message,
+   "Fix " + llvm::to_string(Range) + " => " +
+   testing::PrintToString(Replacement) + " = [" + Message + "]") {
+  return arg.Diag.range == Range && arg.Diag.message == Message &&
+ arg.FixIts.size() == 1 && arg.FixIts[0].range == Range &&
+ arg.FixIts[0].newText == Replacement;
+}
+
+TEST(DiagnosticsTest, DiagnosticRanges) {
+  // Check we report correct ranges, including those that are zero-width, at
+  // the end of a line, or span multiple lines.
+  Annotations Test(R"cpp(
+void $decl[[foo]]();
+int main() {
+  $typo[[go\
+o]]();
+  foo()$semicolon[[]]
+}
+  )cpp");
+  llvm::errs() << Test.code();
+  EXPECT_THAT(
+  build(Test.code()).getDiagnostics(),
+  ElementsAre(
+  Fix(Test.range("typo"), "foo",
+  "use of undeclared identifier 'goo'; did you mean 'foo'?"),
+  Diag(Test.range("decl"), "'foo' declared here"),
+  Fix(Test.range("semicolon"), ";",
+  "expected ';' after expression")));
+}
+
+TEST(DiagnosticsTest, FlagsMatter) {
+  Annotations Test("[[void]] main() {}");
+  EXPECT_THAT(
+  build(Test.code()).getDiagnostics(),
+  ElementsAre(Fix(Test.range(), "int", "'main' must return 'int'")));
+  // Same code built as C gets different diagnostics.
+  EXPECT_THAT(
+  build(Test.code(), {"-x", "c"}).getDiagnostics(),
+  ElementsAre(
+  // FIXME: ideally this would be one diagnostic with a named FixIt.
+  Diag(Test.range(), "return type of 'main' is not 'int'"),
+  Fix(Test.range(), "int", "change return type to 'int'")));
+}
+
+TEST(DiagnosticsTest, Preprocessor) {
+  // This looks like a preamble, but there's an #else in the middle!
+  // Check that:
+  //  - the #else doesn't generate diagnostics (we had this bug)
+  //  - we get diagnostics from the taken branch
+  //  - we get no diagnostics from the not taken branch
+  Annotations Test(R"cpp(
+#ifndef FOO
+#define FOO
+  int a = [[b]];
+#else
+  int x = y;
+#endif
+)cpp");
+  EXPECT_THAT(
+  build(Test.code()).getDiagnostics(),
+  ElementsAre(Diag(Test.range(), "use of undeclared identifier 'b'")));
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: unittests/clangd/

[clang-tools-extra] r321192 - [clangd] Remove an unused lambda capture.

2017-12-20 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Wed Dec 20 09:22:56 2017
New Revision: 321192

URL: http://llvm.org/viewvc/llvm-project?rev=321192&view=rev
Log:
[clangd] Remove an unused lambda capture.

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

Modified: clang-tools-extra/trunk/unittests/clangd/Annotations.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/Annotations.cpp?rev=321192&r1=321191&r2=321192&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/Annotations.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/Annotations.cpp Wed Dec 20 
09:22:56 2017
@@ -24,7 +24,7 @@ static void require(bool Assertion, cons
 
 Annotations::Annotations(StringRef Text) {
   auto Here = [this] { return offsetToPosition(Code, Code.size()); };
-  auto Require = [this, Text](bool Assertion, const char *Msg) {
+  auto Require = [Text](bool Assertion, const char *Msg) {
 require(Assertion, Msg, Text);
   };
   Optional Name;


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


[clang-tools-extra] r321193 - [clangd] Pull CodeCompletionString handling logic into its own file and add unit test.

2017-12-20 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Wed Dec 20 09:24:31 2017
New Revision: 321193

URL: http://llvm.org/viewvc/llvm-project?rev=321193&view=rev
Log:
[clangd] Pull CodeCompletionString handling logic into its own file and add 
unit test.

Reviewers: sammccall

Subscribers: klimek, mgorny, ilya-biryukov, cfe-commits

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

Added:
clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp
clang-tools-extra/trunk/clangd/CodeCompletionStrings.h
clang-tools-extra/trunk/unittests/clangd/CodeCompletionStringsTests.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=321193&r1=321192&r2=321193&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Wed Dec 20 09:24:31 2017
@@ -8,6 +8,7 @@ add_clang_library(clangDaemon
   ClangdUnit.cpp
   ClangdUnitStore.cpp
   CodeComplete.cpp
+  CodeCompletionStrings.cpp
   Context.cpp
   Compiler.cpp
   DraftStore.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=321193&r1=321192&r2=321193&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Wed Dec 20 09:24:31 2017
@@ -15,6 +15,7 @@
 //===-===//
 
 #include "CodeComplete.h"
+#include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Logger.h"
 #include "index/Index.h"
@@ -144,46 +145,6 @@ CompletionItemKind toCompletionItemKind(
   llvm_unreachable("Unhandled clang::index::SymbolKind.");
 }
 
-std::string escapeSnippet(const llvm::StringRef Text) {
-  std::string Result;
-  Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare.
-  for (const auto Character : Text) {
-if (Character == '$' || Character == '}' || Character == '\\')
-  Result.push_back('\\');
-Result.push_back(Character);
-  }
-  return Result;
-}
-
-std::string getDocumentation(const CodeCompletionString &CCS) {
-  // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
-  // information in the documentation field.
-  std::string Result;
-  const unsigned AnnotationCount = CCS.getAnnotationCount();
-  if (AnnotationCount > 0) {
-Result += "Annotation";
-if (AnnotationCount == 1) {
-  Result += ": ";
-} else /* AnnotationCount > 1 */ {
-  Result += "s: ";
-}
-for (unsigned I = 0; I < AnnotationCount; ++I) {
-  Result += CCS.getAnnotation(I);
-  Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
-}
-  }
-  // Add brief documentation (if there is any).
-  if (CCS.getBriefComment() != nullptr) {
-if (!Result.empty()) {
-  // This means we previously added annotations. Add an extra newline
-  // character to make the annotations stand out.
-  Result.push_back('\n');
-}
-Result += CCS.getBriefComment();
-  }
-  return Result;
-}
-
 /// Get the optional chunk as a string. This function is possibly recursive.
 ///
 /// The parameter info for each parameter is appended to the Parameters.
@@ -320,7 +281,8 @@ public:
  /*OutputIsBinary=*/false),
 ClangdOpts(CodeCompleteOpts), Items(Items),
 Allocator(std::make_shared()),
-CCTUInfo(Allocator), CompletedName(CompletedName) {}
+CCTUInfo(Allocator), CompletedName(CompletedName),
+EnableSnippets(CodeCompleteOpts.EnableSnippets) {}
 
   void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
   CodeCompletionResult *Results,
@@ -402,14 +364,16 @@ private:
 // Adjust this to InsertTextFormat::Snippet iff we encounter a
 // CK_Placeholder chunk in SnippetCompletionItemsCollector.
 CompletionItem Item;
-Item.insertTextFormat = InsertTextFormat::PlainText;
 
 Item.documentation = getDocumentation(CCS);
 Item.sortText = Candidate.sortText();
 
-// Fill in the label, detail, insertText and filterText fields of the
-// CompletionItem.
-ProcessChunks(CCS, Item);
+Item.detail = getDetail(CCS);
+Item.filterText = getFilterText(CCS);
+getLabelAndInsertText(CCS, &Item.label, &Item.insertText, EnableSnippets);
+
+Item.insertTextFormat = EnableSnippets ? InsertTextFormat::Snippet
+   : InsertTextFormat::PlainText;
 
 // Fill in the kind field of the CompletionItem.
 Item.ki

[PATCH] D41450: [clangd] Pull CodeCompletionString handling logic into its own file and add unit test.

2017-12-20 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
ioeric marked 7 inline comments as done.
Closed by commit rCTE321193: [clangd] Pull CodeCompletionString handling logic 
into its own file and add… (authored by ioeric, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41450?vs=127718&id=127745#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41450

Files:
  clangd/CMakeLists.txt
  clangd/CodeComplete.cpp
  clangd/CodeCompletionStrings.cpp
  clangd/CodeCompletionStrings.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/CodeCompletionStringsTests.cpp

Index: clangd/CodeCompletionStrings.cpp
===
--- clangd/CodeCompletionStrings.cpp
+++ clangd/CodeCompletionStrings.cpp
@@ -0,0 +1,188 @@
+//===--- CodeCompletionStrings.cpp ---*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===-===//
+
+#include "CodeCompletionStrings.h"
+#include 
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
+  return Chunk.Kind == CodeCompletionString::CK_Informative &&
+ StringRef(Chunk.Text).endswith("::");
+}
+
+void processPlainTextChunks(const CodeCompletionString &CCS,
+std::string *LabelOut, std::string *InsertTextOut) {
+  std::string &Label = *LabelOut;
+  std::string &InsertText = *InsertTextOut;
+  for (const auto &Chunk : CCS) {
+// Informative qualifier chunks only clutter completion results, skip
+// them.
+if (isInformativeQualifierChunk(Chunk))
+  continue;
+
+switch (Chunk.Kind) {
+case CodeCompletionString::CK_ResultType:
+case CodeCompletionString::CK_Optional:
+  break;
+case CodeCompletionString::CK_TypedText:
+  InsertText += Chunk.Text;
+  Label += Chunk.Text;
+  break;
+default:
+  Label += Chunk.Text;
+  break;
+}
+  }
+}
+
+void appendEscapeSnippet(const llvm::StringRef Text, std::string *Out) {
+  for (const auto Character : Text) {
+if (Character == '$' || Character == '}' || Character == '\\')
+  Out->push_back('\\');
+Out->push_back(Character);
+  }
+}
+
+void processSnippetChunks(const CodeCompletionString &CCS,
+  std::string *LabelOut, std::string *InsertTextOut) {
+  std::string &Label = *LabelOut;
+  std::string &InsertText = *InsertTextOut;
+
+  unsigned ArgCount = 0;
+  for (const auto &Chunk : CCS) {
+// Informative qualifier chunks only clutter completion results, skip
+// them.
+if (isInformativeQualifierChunk(Chunk))
+  continue;
+
+switch (Chunk.Kind) {
+case CodeCompletionString::CK_TypedText:
+case CodeCompletionString::CK_Text:
+  Label += Chunk.Text;
+  InsertText += Chunk.Text;
+  break;
+case CodeCompletionString::CK_Optional:
+  // FIXME: Maybe add an option to allow presenting the optional chunks?
+  break;
+case CodeCompletionString::CK_Placeholder:
+  ++ArgCount;
+  InsertText += "${" + std::to_string(ArgCount) + ':';
+  appendEscapeSnippet(Chunk.Text, &InsertText);
+  InsertText += '}';
+  Label += Chunk.Text;
+  break;
+case CodeCompletionString::CK_Informative:
+  // For example, the word "const" for a const method, or the name of
+  // the base class for methods that are part of the base class.
+  Label += Chunk.Text;
+  // Don't put the informative chunks in the insertText.
+  break;
+case CodeCompletionString::CK_ResultType:
+  // This is retrieved as detail.
+  break;
+case CodeCompletionString::CK_CurrentParameter:
+  // This should never be present while collecting completion items,
+  // only while collecting overload candidates.
+  llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
+   "CompletionItems");
+  break;
+case CodeCompletionString::CK_LeftParen:
+case CodeCompletionString::CK_RightParen:
+case CodeCompletionString::CK_LeftBracket:
+case CodeCompletionString::CK_RightBracket:
+case CodeCompletionString::CK_LeftBrace:
+case CodeCompletionString::CK_RightBrace:
+case CodeCompletionString::CK_LeftAngle:
+case CodeCompletionString::CK_RightAngle:
+case CodeCompletionString::CK_Comma:
+case CodeCompletionString::CK_Colon:
+case CodeCompletionString::CK_SemiColon:
+case CodeCompletionString::CK_Equal:
+case CodeCompletionString::CK_HorizontalSpace:
+  InsertText += Chunk.Text;
+  Label += Chunk.Text;
+  break;
+case CodeCompletionString::CK_VerticalSpace:
+  InsertText += Chunk.Text;
+  // Don'

[PATCH] D41345: [clangd] Add more symbol information for code completion.

2017-12-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/index/Index.h:105
+  /// What to insert when completing this symbol (plain text version).
+  std::string CompletionPlainInsertText;
+  /// What to insert when completing this symbol (snippet version).

insert texts can be in details I think? They're not required for completion 
until after resolve.



Comment at: clangd/index/Index.h:122
+
+  llvm::Optional Detail;
+

I think you probably want a raw pointer rather than optional:
 - reduce the size of the struct when it's absent
 - make it inheritance-friendly so we can hang index-specific info off it
(raw pointer rather than unique_ptr because it's owned by a slab not by malloc, 
but unique_ptr is ok for now)




Comment at: clangd/index/SymbolCollector.cpp:65
+  CodeCompletionResult SymbolCompletion(ND, 0);
+  auto Allocator = std::make_shared();
+  CodeCompletionTUInfo TUInfo(Allocator);

this doesn't seem like the kind of thing we should be allocating per-symbol!
You can use a single one and Reset() it, I think

also why globalcodecompletionallocator, vs just codecompletionallocator?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41345



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


[PATCH] D41444: [ASTImporterTest] Make testing under '-fdelayed-template-parsing' mandatory

2017-12-20 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin updated this revision to Diff 127748.
a.sidorin added a comment.

Test both with and without '-fdelayed-template-parsing' in C++ mode.


Repository:
  rC Clang

https://reviews.llvm.org/D41444

Files:
  unittests/AST/ASTImporterTest.cpp

Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -22,38 +22,50 @@
 namespace clang {
 namespace ast_matchers {
 
-typedef std::vector StringVector;
+typedef std::vector ArgVector;
+typedef std::vector RunOptions;
 
-void getLangArgs(Language Lang, StringVector &Args) {
+static bool isCXX(Language Lang) {
+  return Lang == Lang_CXX || Lang == Lang_CXX11;
+}
+
+static RunOptions getRunOptionsForLanguage(Language Lang) {
+  ArgVector BasicArgs;
+  // Test with basic arguments.
   switch (Lang) {
   case Lang_C:
-Args.insert(Args.end(), { "-x", "c", "-std=c99" });
+BasicArgs = {"-x", "c", "-std=c99"};
 break;
   case Lang_C89:
-Args.insert(Args.end(), { "-x", "c", "-std=c89" });
+BasicArgs = {"-x", "c", "-std=c89"};
 break;
   case Lang_CXX:
-Args.push_back("-std=c++98");
+BasicArgs = {"-std=c++98"};
 break;
   case Lang_CXX11:
-Args.push_back("-std=c++11");
+BasicArgs = {"-std=c++11"};
 break;
   case Lang_OpenCL:
   case Lang_OBJCXX:
-break;
+llvm_unreachable("Not implemented yet!");
   }
+
+  // For C++, test with "-fdelayed-template-parsing" enabled to handle MSVC
+  // default behaviour.
+  if (isCXX(Lang)) {
+ArgVector ArgsForDelayedTemplateParse = BasicArgs;
+ArgsForDelayedTemplateParse.emplace_back("-fdelayed-template-parsing");
+return {BasicArgs, ArgsForDelayedTemplateParse};
+  }
+
+  return {BasicArgs};
 }
 
 template
 testing::AssertionResult
-testImport(const std::string &FromCode, Language FromLang,
-   const std::string &ToCode, Language ToLang,
-   MatchVerifier &Verifier,
-   const MatcherType &AMatcher) {
-  StringVector FromArgs, ToArgs;
-  getLangArgs(FromLang, FromArgs);
-  getLangArgs(ToLang, ToArgs);
-
+testImport(const ArgVector &FromArgs, const ArgVector &ToArgs,
+   const std::string &FromCode, const std::string &ToCode,
+   MatchVerifier &Verifier, const MatcherType &AMatcher) {
   const char *const InputFileName = "input.cc";
   const char *const OutputFileName = "output.cc";
 
@@ -92,7 +104,7 @@
 return testing::AssertionFailure() << "Import failed, nullptr returned!";
 
   // This should dump source locations and assert if some source locations
-  // were not imported
+  // were not imported.
   SmallString<1024> ImportChecker;
   llvm::raw_svector_ostream ToNothing(ImportChecker);
   ToCtx.getTranslationUnitDecl()->print(ToNothing);
@@ -104,148 +116,154 @@
   return Verifier.match(Imported, AMatcher);
 }
 
+template
+void testImport(const std::string &FromCode, Language FromLang,
+const std::string &ToCode, Language ToLang,
+MatchVerifier &Verifier,
+const MatcherType &AMatcher) {
+  auto RunOptsFrom = getRunOptionsForLanguage(FromLang);
+  auto RunOptsTo = getRunOptionsForLanguage(ToLang);
+  for (const auto &FromArgs : RunOptsFrom)
+for (const auto &ToArgs : RunOptsTo)
+  EXPECT_TRUE(testImport(FromArgs, ToArgs, FromCode, ToCode,
+ Verifier, AMatcher));
+}
+
+
 TEST(ImportExpr, ImportStringLiteral) {
   MatchVerifier Verifier;
-  EXPECT_TRUE(testImport("void declToImport() { \"foo\"; }",
- Lang_CXX, "", Lang_CXX, Verifier,
- functionDecl(
-   hasBody(
- compoundStmt(
-   has(
- stringLiteral(
-   hasType(
- asString("const char [4]");
-  EXPECT_TRUE(testImport("void declToImport() { L\"foo\"; }",
- Lang_CXX, "", Lang_CXX, Verifier,
- functionDecl(
-   hasBody(
- compoundStmt(
-   has(
- stringLiteral(
-   hasType(
- asString("const wchar_t [4]");
-  EXPECT_TRUE(testImport("void declToImport() { \"foo\" \"bar\"; }",
- Lang_CXX, "", Lang_CXX, Verifier,
- functionDecl(
-   hasBody(
- compoundStmt(
-   has(
- stringLiteral(
-   hasType(
- asString("const char [7]");
+  testImport("void declToImport() { \"foo\"; }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(
+   hasBody(

[PATCH] D41399: [CodeGen] Represent array members in new-format TBAA type descriptors

2017-12-20 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev updated this revision to Diff 127742.
kosarev added a comment.

- Fixed the access size.
- Added the suggested tests.


https://reviews.llvm.org/D41399

Files:
  lib/CodeGen/CodeGenTBAA.cpp
  test/CodeGen/tbaa-array.cpp


Index: test/CodeGen/tbaa-array.cpp
===
--- test/CodeGen/tbaa-array.cpp
+++ test/CodeGen/tbaa-array.cpp
@@ -1,18 +1,52 @@
 // RUN: %clang_cc1 -triple x86_64-linux -O1 -disable-llvm-passes %s \
 // RUN: -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux -O1 -disable-llvm-passes %s \
+// RUN: -new-struct-path-tbaa -emit-llvm -o - | \
+// RUN: FileCheck -check-prefix=CHECK-NEW %s
 //
 // Check that we generate correct TBAA information for accesses to array
 // elements.
 
 struct A { int i; };
 struct B { A a[1]; };
+struct C { int i; int x[3]; };
 
 int foo(B *b) {
 // CHECK-LABEL: _Z3fooP1B
 // CHECK: load i32, {{.*}}, !tbaa [[TAG_A_i:!.*]]
+// CHECK-NEW-LABEL: _Z3fooP1B
+// CHECK-NEW: load i32, {{.*}}, !tbaa [[TAG_A_i:!.*]]
   return b->a->i;
 }
 
+// Check that members of array types are represented correctly.
+int bar(C *c) {
+// CHECK-NEW-LABEL: _Z3barP1C
+// CHECK-NEW: load i32, {{.*}}, !tbaa [[TAG_C_i:!.*]]
+  return c->i;
+}
+
+int bar2(C *c) {
+// CHECK-NEW-LABEL: _Z4bar2P1C
+// CHECK-NEW: load i32, {{.*}}, !tbaa [[TAG_int:!.*]]
+  return c->x[2];
+}
+
+int bar3(C *c, int j) {
+// CHECK-NEW-LABEL: _Z4bar3P1Ci
+// CHECK-NEW: load i32, {{.*}}, !tbaa [[TAG_int:!.*]]
+  return c->x[j];
+}
+
 // CHECK-DAG: [[TAG_A_i]] = !{[[TYPE_A:!.*]], [[TYPE_int:!.*]], i64 0}
 // CHECK-DAG: [[TYPE_A]] = !{!"_ZTS1A", !{{.*}}, i64 0}
 // CHECK-DAG: [[TYPE_int]] = !{!"int", !{{.*}}, i64 0}
+
+// CHECK-NEW-DAG: [[TYPE_char:!.*]] = !{{{.*}}, i64 1, !"omnipotent char"}
+// CHECK-NEW-DAG: [[TYPE_int:!.*]] = !{[[TYPE_char]], i64 4, !"int"}
+// CHECK-NEW-DAG: [[TAG_int]] = !{[[TYPE_int]], [[TYPE_int]], i64 0, i64 4}
+// CHECK-NEW-DAG: [[TYPE_pointer:!.*]] = !{[[TYPE_char]], i64 8, !"any 
pointer"}
+// CHECK-NEW-DAG: [[TYPE_A:!.*]] = !{[[TYPE_char]], i64 4, !"_ZTS1A", 
[[TYPE_int]], i64 0, i64 4}
+// CHECK-NEW-DAG: [[TAG_A_i]] = !{[[TYPE_A]], [[TYPE_int]], i64 0, i64 4}
+// CHECK-NEW-DAG: [[TYPE_C:!.*]] = !{[[TYPE_char]], i64 16, !"_ZTS1C", 
[[TYPE_int]], i64 0, i64 4, [[TYPE_int]], i64 4, i64 12}
+// CHECK-NEW-DAG: [[TAG_C_i]] = !{[[TYPE_C:!.*]], [[TYPE_int:!.*]], i64 0, i64 
4}
Index: lib/CodeGen/CodeGenTBAA.cpp
===
--- lib/CodeGen/CodeGenTBAA.cpp
+++ lib/CodeGen/CodeGenTBAA.cpp
@@ -161,6 +161,10 @@
   if (Ty->isPointerType() || Ty->isReferenceType())
 return createScalarTypeNode("any pointer", getChar(), Size);
 
+  // Accesses to arrays are accesses to objects of their element types.
+  if (CodeGenOpts.NewStructPathTBAA && Ty->isArrayType())
+return getTypeInfo(cast(Ty)->getElementType());
+
   // Enum types are distinct types. In C++ they have "underlying types",
   // however they aren't related for TBAA.
   if (const EnumType *ETy = dyn_cast(Ty)) {


Index: test/CodeGen/tbaa-array.cpp
===
--- test/CodeGen/tbaa-array.cpp
+++ test/CodeGen/tbaa-array.cpp
@@ -1,18 +1,52 @@
 // RUN: %clang_cc1 -triple x86_64-linux -O1 -disable-llvm-passes %s \
 // RUN: -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux -O1 -disable-llvm-passes %s \
+// RUN: -new-struct-path-tbaa -emit-llvm -o - | \
+// RUN: FileCheck -check-prefix=CHECK-NEW %s
 //
 // Check that we generate correct TBAA information for accesses to array
 // elements.
 
 struct A { int i; };
 struct B { A a[1]; };
+struct C { int i; int x[3]; };
 
 int foo(B *b) {
 // CHECK-LABEL: _Z3fooP1B
 // CHECK: load i32, {{.*}}, !tbaa [[TAG_A_i:!.*]]
+// CHECK-NEW-LABEL: _Z3fooP1B
+// CHECK-NEW: load i32, {{.*}}, !tbaa [[TAG_A_i:!.*]]
   return b->a->i;
 }
 
+// Check that members of array types are represented correctly.
+int bar(C *c) {
+// CHECK-NEW-LABEL: _Z3barP1C
+// CHECK-NEW: load i32, {{.*}}, !tbaa [[TAG_C_i:!.*]]
+  return c->i;
+}
+
+int bar2(C *c) {
+// CHECK-NEW-LABEL: _Z4bar2P1C
+// CHECK-NEW: load i32, {{.*}}, !tbaa [[TAG_int:!.*]]
+  return c->x[2];
+}
+
+int bar3(C *c, int j) {
+// CHECK-NEW-LABEL: _Z4bar3P1Ci
+// CHECK-NEW: load i32, {{.*}}, !tbaa [[TAG_int:!.*]]
+  return c->x[j];
+}
+
 // CHECK-DAG: [[TAG_A_i]] = !{[[TYPE_A:!.*]], [[TYPE_int:!.*]], i64 0}
 // CHECK-DAG: [[TYPE_A]] = !{!"_ZTS1A", !{{.*}}, i64 0}
 // CHECK-DAG: [[TYPE_int]] = !{!"int", !{{.*}}, i64 0}
+
+// CHECK-NEW-DAG: [[TYPE_char:!.*]] = !{{{.*}}, i64 1, !"omnipotent char"}
+// CHECK-NEW-DAG: [[TYPE_int:!.*]] = !{[[TYPE_char]], i64 4, !"int"}
+// CHECK-NEW-DAG: [[TAG_int]] = !{[[TYPE_int]], [[TYPE_int]], i64 0, i64 4}
+// CHECK-NEW-DAG: [[TYPE_pointer:!.*]] = !{[[TYPE_char]], i64 8, !"any pointer"}
+// CHECK-NEW-DAG: [[TYPE_A:!.*]] = !{[[TYPE_char]], i64 4, !"_ZTS1A", [[TYPE_int]], i64 0, i64 4}
+// CHECK-NEW-DAG

[PATCH] D41455: [ASTMatchers] Add isNoReturn() match narrower for FunctionDeclarations

2017-12-20 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added a reviewer: aaron.ballman.
lebedev.ri added a project: clang.
Herald added a subscriber: klimek.

How to regenerate LibASTMatchersReference.html ?


Repository:
  rC Clang

https://reviews.llvm.org/D41455

Files:
  include/clang/ASTMatchers/ASTMatchers.h
  lib/ASTMatchers/Dynamic/Registry.cpp
  unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Index: unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -1770,6 +1770,69 @@
 functionDecl(isExplicitTemplateSpecialization(;
 }
 
+TEST(TypeMatching, MatchesNoReturn) {
+  EXPECT_TRUE(notMatches("void func();", functionDecl(isNoReturn(;
+  EXPECT_TRUE(notMatches("void func() {};", functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(
+  notMatches("struct S { void func(); };", functionDecl(isNoReturn(;
+  EXPECT_TRUE(
+  notMatches("struct S { void func() {}; };", functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(notMatches("struct S { static void func(); };",
+ functionDecl(isNoReturn(;
+  EXPECT_TRUE(notMatches("struct S { static void func() {}; };",
+ functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(notMatches("struct S { S(); };", functionDecl(isNoReturn(;
+  EXPECT_TRUE(notMatches("struct S { S() {}; };", functionDecl(isNoReturn(;
+
+  // ---
+
+  EXPECT_TRUE(matches("[[noreturn]] void func();", functionDecl(isNoReturn(;
+  EXPECT_TRUE(
+  matches("[[noreturn]] void func() {};", functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(matches("struct S { [[noreturn]] void func(); };",
+  functionDecl(isNoReturn(;
+  EXPECT_TRUE(matches("struct S { [[noreturn]] void func() {}; };",
+  functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(matches("struct S { [[noreturn]] static void func(); };",
+  functionDecl(isNoReturn(;
+  EXPECT_TRUE(matches("struct S { [[noreturn]] static void func() {}; };",
+  functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(
+  matches("struct S { [[noreturn]] S(); };", functionDecl(isNoReturn(;
+  EXPECT_TRUE(matches("struct S { [[noreturn]] S() {}; };",
+  functionDecl(isNoReturn(;
+
+  // ---
+
+  EXPECT_TRUE(matches("__attribute__((noreturn)) void func();",
+  functionDecl(isNoReturn(;
+  EXPECT_TRUE(matches("__attribute__((noreturn)) void func() {};",
+  functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) void func(); };",
+  functionDecl(isNoReturn(;
+  EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) void func() {}; };",
+  functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(
+  matches("struct S { __attribute__((noreturn)) static void func(); };",
+  functionDecl(isNoReturn(;
+  EXPECT_TRUE(
+  matches("struct S { __attribute__((noreturn)) static void func() {}; };",
+  functionDecl(isNoReturn(;
+
+  EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) S(); };",
+  functionDecl(isNoReturn(;
+  EXPECT_TRUE(matches("struct S { __attribute__((noreturn)) S() {}; };",
+  functionDecl(isNoReturn(;
+}
+
 TEST(TypeMatching, MatchesBool) {
   EXPECT_TRUE(matches("struct S { bool func(); };",
   cxxMethodDecl(returns(booleanType();
Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -354,6 +354,7 @@
   REGISTER_MATCHER(isMemberInitializer);
   REGISTER_MATCHER(isMoveAssignmentOperator);
   REGISTER_MATCHER(isMoveConstructor);
+  REGISTER_MATCHER(isNoReturn);
   REGISTER_MATCHER(isNoThrow);
   REGISTER_MATCHER(isOverride);
   REGISTER_MATCHER(isPrivate);
Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -3567,6 +3567,32 @@
   return Node.getNumParams() == N;
 }
 
+/// \brief Matches \c FunctionDecls that have a noreturn attribute.
+///
+/// Given
+/// \code
+///   void nope();
+///   [[noreturn]] void a0();
+///   [[noreturn]] void a1() {};
+///   __attribute__((noreturn)) void a2();
+///   __attribute__((noreturn)) void a3() {};
+///   struct b0 { [[noreturn]] b0(); };
+///   struct b1 { [[noreturn]] b1() {}; };
+///   struct b2 { __attribute__((noreturn)) b2(); };
+///   struct b3 { __attribute__((noreturn)) b3() {}; };
+///   struct c0 { [[noreturn]] int A(); };
+///   struct c1 { [[noreturn]] int A() {}; };
+///   struct c2 { __attribute__((noreturn)) int A(); };
+///   struct c3 { __att

[PATCH] D40705: [Parser] Diagnose storage classes in template parameter declarations

2017-12-20 Thread Faisal Vali via Phabricator via cfe-commits
faisalv added a comment.

Sounds good - if I don't get this done over the next seven days - would you 
mind just pinging me!

Thanks!


https://reviews.llvm.org/D40705



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


[PATCH] D41456: [clang-tidy] readability-else-after-return: also diagnose noreturn function calls.

2017-12-20 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added reviewers: aaron.ballman, alexfh, djasper, malcolm.parsons.
lebedev.ri added a project: clang-tools-extra.
Herald added a subscriber: xazax.hun.

The readability-else-after-return check was not warning about  an else after a 
call to the function that will not return. In particular, marker with a 
noreturn attribute, be it either C++11 `[[noreturn]]`, or the 
`__attribute__((noreturn))`.
This differential adds support to diagnose normal function calls, and calls to 
member functions; but not constructors, destructors and special member 
functions.

A follow-up for https://reviews.llvm.org/D40505.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41456

Files:
  clang-tidy/readability/ElseAfterReturnCheck.cpp
  docs/ReleaseNotes.rst
  test/clang-tidy/readability-else-after-return.cpp

Index: test/clang-tidy/readability-else-after-return.cpp
===
--- test/clang-tidy/readability-else-after-return.cpp
+++ test/clang-tidy/readability-else-after-return.cpp
@@ -11,6 +11,28 @@
   my_exception(const std::string &s);
 };
 
+__attribute__((noreturn)) void my_noreturn();
+[[noreturn]] void my_noreturn2();
+[[noreturn]] __attribute__((noreturn)) void my_noreturn3();
+struct my_struct {
+  [[noreturn]] static void test();
+  [[noreturn]] void test_2();
+};
+struct my_assign {
+  my_assign();
+  [[noreturn]] my_assign& operator=(const my_assign& c);
+};
+struct my_copy {
+  my_copy();
+  [[noreturn]] my_copy(const my_copy& c);
+};
+struct noreturn_ctor {
+  [[noreturn]] noreturn_ctor();
+};
+struct noreturn_dtor {
+  [[noreturn]] noreturn_dtor();
+};
+
 void f(int a) {
   if (a > 0)
 return;
@@ -103,5 +125,69 @@
 // CHECK-FIXES: {{^}}} // comment-10
   x++;
 }
+if (x) {
+  my_noreturn();
+} else { // comment-11
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use 'else' after 'noreturn call'
+// CHECK-FIXES: {{^}}} // comment-11
+  x++;
+}
+if (x) {
+  my_noreturn2();
+} else { // comment-12
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use 'else' after 'noreturn call'
+// CHECK-FIXES: {{^}}} // comment-12
+  x++;
+}
+if (x) {
+  my_noreturn3();
+} else { // comment-13
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use 'else' after 'noreturn call'
+// CHECK-FIXES: {{^}}} // comment-13
+  x++;
+}
+if (x) {
+  my_struct::test();
+} else { // comment-14
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use 'else' after 'noreturn call'
+// CH1ECK-FIXES: {{^}}} // comment-14
+  x++;
+}
+if (x) {
+  my_struct s;
+  s.test_2();
+} else { // comment-15
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use 'else' after 'noreturn call'
+// CHECK-FIXES: {{^}}} // comment-15
+  x++;
+}
+if (x) {
+  my_assign a0;
+  my_assign a1;
+  a1 = a0;
+} else { // comment-16
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use 'else' after 'noreturn call'
+// CHECK-FIXES: {{^}}} // comment-16
+  x++;
+}
+if (x) {
+  // FIXME
+  my_copy c0;
+  my_copy c1(c0);
+} else { // comment-17
+  x++;
+}
+if (x) {
+  // FIXME
+  noreturn_ctor n;
+} else { // comment-18
+  x++;
+}
+if (x) {
+  // FIXME
+  noreturn_dtor n;
+} else { // comment-19
+  x++;
+}
   }
 }
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -186,6 +186,8 @@
   Finds property declarations in Objective-C files that do not follow the
   pattern of property names in Apple's programming guide.
 
+- The 'readability-else-after-return' check was adjusted to handle throw expressions that require cleanups, calls to functions marked with noreturn attribute.
+
 - New `readability-static-accessed-through-instance
   `_ check
 
Index: clang-tidy/readability/ElseAfterReturnCheck.cpp
===
--- clang-tidy/readability/ElseAfterReturnCheck.cpp
+++ clang-tidy/readability/ElseAfterReturnCheck.cpp
@@ -22,7 +22,9 @@
   const auto ControlFlowInterruptorMatcher =
   stmt(anyOf(returnStmt().bind("return"), continueStmt().bind("continue"),
  breakStmt().bind("break"),
- expr(ignoringImplicit(cxxThrowExpr().bind("throw");
+ expr(ignoringImplicit(cxxThrowExpr().bind("throw"))),
+ callExpr(hasDeclaration(functionDecl(isNoReturn(
+ .bind("noreturn call")));
   Finder->addMatcher(
   compoundStmt(forEach(
   ifStmt(hasThen(stmt(
@@ -37,7 +39,8 @@
   const auto *If = Result.Nodes.getNodeAs("if");
   SourceLocat

[PATCH] D41456: [clang-tidy] readability-else-after-return: also diagnose noreturn function calls.

2017-12-20 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Depends on https://reviews.llvm.org/D41455.
I'm open to suggestions re diagnostic wording.
The current `'noreturn call'` seems lazy, and is basically a placeholder.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41456



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


[PATCH] D38639: [clangd] #include statements support for Open definition

2017-12-20 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov requested changes to this revision.
ilya-biryukov added a comment.
This revision now requires changes to proceed.

Another round of review




Comment at: clangd/ClangdUnit.cpp:113
 
+  CppFilePreambleCallbacks(IncludeReferenceMap &IRM)
+  : IRM(IRM) {}

ilya-biryukov wrote:
> Let's create a new empty map inside this class and have a 
> `takeIncludeReferences` method (similar to `TopLevelDeclIDs` and 
> `takeTopLevelDeclIDs`)
This comment is not addressed yet, but marked as done.



Comment at: clangd/ClangdUnit.cpp:147
+  IncludeReferenceMap &IRM;
+  std::vector> 
TempPreambleIncludeLocations;
 };

Nebiroth wrote:
> ilya-biryukov wrote:
> > We should have `SourceMgr` at all the proper places now, let's store 
> > `IncludeReferenceMap` directly
> The idea was to pass a single map around to fill with every reference instead 
> of having separate maps being merged together.
You copy the map for preamble and then append to it in 
`CppFilePreambleCallbacks`? That also LG, we should not have many references 
there anyway.



Comment at: clangd/ClangdUnit.cpp:281
+ IntrusiveRefCntPtr VFS,
+ IncludeReferenceMap IRM) {
 

Nebiroth wrote:
> ilya-biryukov wrote:
> > What reference does this `IncludeReferenceMap` contain? Includes from the 
> > preamble? 
> This should contain every reference available for one file.
Thanks for clarifying, LG.



Comment at: clangd/ClangdUnit.cpp:141
+  std::unique_ptr createPPCallbacks() {
+return llvm::make_unique(*SourceMgr, IRM);
+  }

Maybe add `assert(SourceMgr && "SourceMgr must be set at this point")` here?



Comment at: clangd/ClangdUnit.cpp:281
+std::shared_ptr PCHs,
+IntrusiveRefCntPtr VFS, IncludeReferenceMap IRM) {
 

Don't we already store the map we need in `PreambleData`? Why do we need an 
extra `IRM` parameter?



Comment at: clangd/ClangdUnit.h:276
+std::vector
+findDefinitions(const Context &Ctx, ParsedAST &AST, Position Pos);
+

ilya-biryukov wrote:
> This function moved without need and lost a comment.
Now we have duplicated definitions here. Bad merge?



Comment at: clangd/CodeComplete.cpp:328
   unsigned NumResults) override final {
-if (auto SS = Context.getCXXScopeSpecifier())
-  CompletedName.SSInfo = extraCompletionScope(S, **SS);
+//if (auto SS = Context.getCXXScopeSpecifier())
+//  CompletedName.SSInfo = extraCompletionScope(S, **SS);

Accidental change?



Comment at: clangd/CodeComplete.cpp:807
   // Enable index-based code completion when Index is provided.
-  Result.IncludeNamespaceLevelDecls = !Index;
+  // Result.IncludeNamespaceLevelDecls = !Index;
 

Accidental change?



Comment at: clangd/XRefs.cpp:41
 
+  std::vector takeLocations() {
+// Don't keep the same location multiple times.

We don't need locations anymore. Remove them.



Comment at: clangd/XRefs.cpp:177
 
+  std::vector IRMResult;
+  if (!AST.getIRM().empty()) {

Probably a good place for a comment. Also, maybe rename local var to something 
easier to understand like `IncludeDefinitions`
```
/// Process targets for paths inside #include directive.
std::vector IncludeTargets;
```



Comment at: clangd/XRefs.cpp:178
+  std::vector IRMResult;
+  if (!AST.getIRM().empty()) {
+for (auto &IncludeLoc : AST.getIRM()) {

No need to special case empty maps, remove the if altogether.



Comment at: clangd/XRefs.cpp:183
+  unsigned CharNumber = SourceMgr.getSpellingColumnNumber(
+  DeclMacrosFinder->getSearchedLocation());
+

Replace with `DeclMacrosFinder->getSearchedLocation()` `SourceLocationBeg`, it 
makes the code easier to read.



Comment at: clangd/XRefs.cpp:185
+
+  if ((unsigned)R.start.line ==
+  SourceMgr.getSpellingLineNumber(

why do we need to convert to unsigned? To slience compiler warnings?



Comment at: clangd/XRefs.cpp:188
+  DeclMacrosFinder->getSearchedLocation()) &&
+  ((unsigned)R.start.character >= CharNumber &&
+   CharNumber <= (unsigned)R.end.character)) {

this should be `R.start.charater <= CharNumber && CharNumber <= R.end.character`


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D38639



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


[PATCH] D41303: Add support for ObjectFormat to TargetSpecificAttr

2017-12-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

Aside from some minor nits, LGTM. Thanks!




Comment at: include/clang/Basic/Attr.td:281
   list CXXABIs;
+  // Specifies Object Formats  for which the target applies, based off the
+  // ObjectFormatType enumeration in Triple.h

Extra space after "Formats"



Comment at: utils/TableGen/ClangAttrEmitter.cpp:2665
+  // If one or more architectures is specified, check those.  Arches are 
handled
+  // differently because GenerateTargetRequiresments needs to combine the list
+  // with ParseKind.

Typo: GenerateTargetRequiresments 


Repository:
  rC Clang

https://reviews.llvm.org/D41303



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


[PATCH] D41363: [clang-tidy] Adding Fuchsia checker for overloaded operators

2017-12-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/fuchsia/OverloadedOperatorCheck.cpp:18
+
+AST_MATCHER(CXXMethodDecl, hasOverloadedOperator) {
+  if (Node.isCopyAssignmentOperator() || Node.isMoveAssignmentOperator())

JonasToth wrote:
> I think `isOverloadedOperator` is a better name.
I think `isFuchsiaOverloadedOperator()` is even better because of the extra 
work done by the checker (otherwise, it might be tempting to put this into 
ASTMatchers.h).



Comment at: clang-tidy/fuchsia/OverloadedOperatorCheck.cpp:30
+  if (const auto *D = Result.Nodes.getNodeAs("decl"))
+diag(D->getLocStart(), "operator overloading is disallowed");
+}

I think this could be better stated as "cannot overload %0" and pass in `D` 
(which should expand to something reasonable).



Comment at: test/clang-tidy/fuchsia-overloaded-operator.cpp:11
+public:
+  B &operator=(B other);
+  // CHECK-MESSAGES-NOT: [[@LINE-1]]:3: warning: operator overloading is 
disallowed [fuchsia-overloaded-operator]

While this is an overloaded assignment operator, it's grating for it not to 
accept a `const B&`.


https://reviews.llvm.org/D41363



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


r321201 - Add support for ObjectFormat to TargetSpecificAttr

2017-12-20 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Wed Dec 20 10:51:08 2017
New Revision: 321201

URL: http://llvm.org/viewvc/llvm-project?rev=321201&view=rev
Log:
Add support for ObjectFormat to TargetSpecificAttr

Looking through the code, I saw a FIXME on IFunc to switch it
to a target specific attribute. In looking through it, i saw that
the no-longer-appropriately-named TargetArch didn't support ObjectFormat
checking.

This patch changes the name of TargetArch to TargetSpecific
(since it checks much more than just Arch), makes "Arch" optional, adds
support for ObjectFormat, better documents the TargetSpecific type, and
changes IFunc over to a TargetSpecificAttr.

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

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/test/Sema/attr-ifunc.c
cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=321201&r1=321200&r2=321201&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed Dec 20 10:51:08 2017
@@ -267,13 +267,24 @@ def RenderScript : LangOpt<"RenderScript
 def ObjC : LangOpt<"ObjC1">;
 def BlocksSupported : LangOpt<"Blocks">;
 
-// Defines targets for target-specific attributes. The list of strings should
-// specify architectures for which the target applies, based off the ArchType
-// enumeration in Triple.h.
-class TargetArch arches> {
-  list Arches = arches;
+// Defines targets for target-specific attributes. Empty lists are unchecked.
+class TargetSpec {
+  // Specifies Architectures for which the target applies, based off the
+  // ArchType enumeration in Triple.h.
+  list Arches = [];
+  // Specifies Operating Systems for which the target applies, based off the
+  // OSType enumeration in Triple.h
   list OSes;
+  // Specifies the C++ ABIs for which the target applies, based off the
+  // TargetCXXABI::Kind in TargetCXXABI.h.
   list CXXABIs;
+  // Specifies Object Formats for which the target applies, based off the
+  // ObjectFormatType enumeration in Triple.h
+  list ObjectFormats;
+}
+
+class TargetArch arches> : TargetSpec {
+  let Arches = arches;
 }
 def TargetARM : TargetArch<["arm", "thumb", "armeb", "thumbeb"]>;
 def TargetAVR : TargetArch<["avr"]>;
@@ -288,6 +299,9 @@ def TargetWindows : TargetArch<["x86", "
 def TargetMicrosoftCXXABI : TargetArch<["x86", "x86_64", "arm", "thumb", 
"aarch64"]> {
   let CXXABIs = ["Microsoft"];
 }
+def TargetELF : TargetSpec {
+  let ObjectFormats = ["ELF"];
+}
 
 // Attribute subject match rules that are used for #pragma clang attribute.
 //
@@ -465,8 +479,8 @@ class InheritableAttr : Attr;
 
 /// A target-specific attribute.  This class is meant to be used as a mixin
 /// with InheritableAttr or Attr depending on the attribute's needs.
-class TargetSpecificAttr {
-  TargetArch Target = target;
+class TargetSpecificAttr {
+  TargetSpec Target = target;
   // Attributes are generally required to have unique spellings for their names
   // so that the parser can determine what kind of attribute it has parsed.
   // However, target-specific attributes are special in that the attribute only
@@ -1121,7 +1135,7 @@ def IBOutletCollection : InheritableAttr
   let Documentation = [Undocumented];
 }
 
-def IFunc : Attr {
+def IFunc : Attr, TargetSpecificAttr {
   let Spellings = [GCC<"ifunc">];
   let Args = [StringArgument<"Resolver">];
   let Subjects = SubjectList<[Function]>;

Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=321201&r1=321200&r2=321201&view=diff
==
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Wed Dec 20 10:51:08 2017
@@ -1844,12 +1844,6 @@ static void handleIFuncAttr(Sema &S, Dec
 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
 return;
   }
-  // FIXME: it should be handled as a target specific attribute.
-  if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
-  llvm::Triple::ELF) {
-S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
-return;
-  }
 
   D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
  
Attr.getAttributeSpellingListIndex()));

Modified: cfe/trunk/test/Sema/attr-ifunc.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/attr-ifunc.c?rev=321201&r1=321200&r2=321201&view=diff
==
--- cfe/trunk/test/Sema/attr-ifunc.c (original)
+++ cfe/trunk/test/Sema/attr-ifunc.c Wed Dec 20 10:51:08 2017
@@ -5,7 +5,7 @@
 #if defined(_WIN32)
 void foo() {}
 void bar() __attribute__((ifunc("foo

[PATCH] D41303: Add support for ObjectFormat to TargetSpecificAttr

2017-12-20 Thread Erich Keane via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC321201: Add support for ObjectFormat to TargetSpecificAttr 
(authored by erichkeane, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41303?vs=127159&id=127757#toc

Repository:
  rC Clang

https://reviews.llvm.org/D41303

Files:
  include/clang/Basic/Attr.td
  lib/Sema/SemaDeclAttr.cpp
  test/Sema/attr-ifunc.c
  utils/TableGen/ClangAttrEmitter.cpp

Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -1844,12 +1844,6 @@
 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
 return;
   }
-  // FIXME: it should be handled as a target specific attribute.
-  if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
-  llvm::Triple::ELF) {
-S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
-return;
-  }
 
   D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
  Attr.getAttributeSpellingListIndex()));
Index: utils/TableGen/ClangAttrEmitter.cpp
===
--- utils/TableGen/ClangAttrEmitter.cpp
+++ utils/TableGen/ClangAttrEmitter.cpp
@@ -2622,6 +2622,31 @@
   OS << "  }\n";
 }
 
+// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
+// parameter with only a single check type, if applicable.
+static void GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
+std::string *FnName,
+StringRef ListName,
+StringRef CheckAgainst,
+StringRef Scope) {
+  if (!R->isValueUnset(ListName)) {
+Test += " && (";
+std::vector Items = R->getValueAsListOfStrings(ListName);
+for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
+  StringRef Part = *I;
+  Test += CheckAgainst;
+  Test += " == ";
+  Test += Scope;
+  Test += Part;
+  if (I + 1 != E)
+Test += " || ";
+  if (FnName)
+*FnName += Part;
+}
+Test += ")";
+  }
+}
+
 // Generate a conditional expression to check if the current target satisfies
 // the conditions for a TargetSpecificAttr record, and append the code for
 // those checks to the Test string. If the FnName string pointer is non-null,
@@ -2635,29 +2660,15 @@
   // named "T" and a TargetInfo object named "Target" within
   // scope that can be used to determine whether the attribute exists in
   // a given target.
-  Test += "(";
-
-  for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
-StringRef Part = *I;
-Test += "T.getArch() == llvm::Triple::";
-Test += Part;
-if (I + 1 != E)
-  Test += " || ";
-if (FnName)
-  *FnName += Part;
-  }
-  Test += ")";
-
-  // If the attribute is specific to particular OSes, check those.
-  if (!R->isValueUnset("OSes")) {
-// We know that there was at least one arch test, so we need to and in the
-// OS tests.
+  Test += "true";
+  // If one or more architectures is specified, check those.  Arches are handled
+  // differently because GenerateTargetRequirements needs to combine the list
+  // with ParseKind.
+  if (!Arches.empty()) {
 Test += " && (";
-std::vector OSes = R->getValueAsListOfStrings("OSes");
-for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
+for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
   StringRef Part = *I;
-
-  Test += "T.getOS() == llvm::Triple::";
+  Test += "T.getArch() == llvm::Triple::";
   Test += Part;
   if (I + 1 != E)
 Test += " || ";
@@ -2667,21 +2678,17 @@
 Test += ")";
   }
 
+  // If the attribute is specific to particular OSes, check those.
+  GenerateTargetSpecificAttrCheck(R, Test, FnName, "OSes", "T.getOS()",
+  "llvm::Triple::");
+
   // If one or more CXX ABIs are specified, check those as well.
-  if (!R->isValueUnset("CXXABIs")) {
-Test += " && (";
-std::vector CXXABIs = R->getValueAsListOfStrings("CXXABIs");
-for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) {
-  StringRef Part = *I;
-  Test += "Target.getCXXABI().getKind() == TargetCXXABI::";
-  Test += Part;
-  if (I + 1 != E)
-Test += " || ";
-  if (FnName)
-*FnName += Part;
-}
-Test += ")";
-  }
+  GenerateTargetSpecificAttrCheck(R, Test, FnName, "CXXABIs",
+  "Target.getCXXABI().getKind()",
+  "TargetCXXABI::");
+  // If one or more object formats is specified, check those.
+  GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
+  "T.getObjectFormat()", "llvm::Triple::");
 }
 
 stati

r321203 - [hwasan] Implement -fsanitize-recover=hwaddress.

2017-12-20 Thread Evgeniy Stepanov via cfe-commits
Author: eugenis
Date: Wed Dec 20 11:05:44 2017
New Revision: 321203

URL: http://llvm.org/viewvc/llvm-project?rev=321203&view=rev
Log:
[hwasan] Implement -fsanitize-recover=hwaddress.

Summary: Very similar to AddressSanitizer, with the exception of the error type 
encoding.

Reviewers: kcc, alekseyshl

Subscribers: cfe-commits, kubamracek, llvm-commits, hiraditya

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

Modified:
cfe/trunk/lib/CodeGen/BackendUtil.cpp

Modified: cfe/trunk/lib/CodeGen/BackendUtil.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/BackendUtil.cpp?rev=321203&r1=321202&r2=321203&view=diff
==
--- cfe/trunk/lib/CodeGen/BackendUtil.cpp (original)
+++ cfe/trunk/lib/CodeGen/BackendUtil.cpp Wed Dec 20 11:05:44 2017
@@ -239,7 +239,11 @@ static void addKernelAddressSanitizerPas
 
 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
 legacy::PassManagerBase &PM) {
-  PM.add(createHWAddressSanitizerPass());
+  const PassManagerBuilderWrapper &BuilderWrapper =
+  static_cast(Builder);
+  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
+  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
+  PM.add(createHWAddressSanitizerPass(Recover));
 }
 
 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,


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


[PATCH] D41417: [hwasan] Implement -fsanitize-recover=hwaddress.

2017-12-20 Thread Evgenii Stepanov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC321203: [hwasan] Implement -fsanitize-recover=hwaddress. 
(authored by eugenis, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41417?vs=127642&id=127760#toc

Repository:
  rC Clang

https://reviews.llvm.org/D41417

Files:
  lib/CodeGen/BackendUtil.cpp


Index: lib/CodeGen/BackendUtil.cpp
===
--- lib/CodeGen/BackendUtil.cpp
+++ lib/CodeGen/BackendUtil.cpp
@@ -239,7 +239,11 @@
 
 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
 legacy::PassManagerBase &PM) {
-  PM.add(createHWAddressSanitizerPass());
+  const PassManagerBuilderWrapper &BuilderWrapper =
+  static_cast(Builder);
+  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
+  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
+  PM.add(createHWAddressSanitizerPass(Recover));
 }
 
 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,


Index: lib/CodeGen/BackendUtil.cpp
===
--- lib/CodeGen/BackendUtil.cpp
+++ lib/CodeGen/BackendUtil.cpp
@@ -239,7 +239,11 @@
 
 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
 legacy::PassManagerBase &PM) {
-  PM.add(createHWAddressSanitizerPass());
+  const PassManagerBuilderWrapper &BuilderWrapper =
+  static_cast(Builder);
+  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
+  bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
+  PM.add(createHWAddressSanitizerPass(Recover));
 }
 
 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41458: WIP: [libc++][C++17] Elementary string conversions for integral types

2017-12-20 Thread Zhihao Yuan via Phabricator via cfe-commits
lichray created this revision.
lichray added reviewers: mclow.lists, EricWF.
Herald added a subscriber: mgorny.

Progress: std::to_chars for integers
Missing: std::from_chars

References:
 https://wg21.link/p0067r5
 https://wg21.link/p0682r1


Repository:
  rCXX libc++

https://reviews.llvm.org/D41458

Files:
  .gitignore
  include/charconv
  include/support/itoa/
  include/support/itoa/itoa.h
  lib/CMakeLists.txt
  src/support/itoa/
  src/support/itoa/itoa.cpp
  test/std/utilities/charconv/
  test/std/utilities/charconv/charconv.to.chars/
  test/std/utilities/charconv/charconv.to.chars/integral.bool.fail.cpp
  test/std/utilities/charconv/charconv.to.chars/integral.pass.cpp

Index: test/std/utilities/charconv/charconv.to.chars/integral.pass.cpp
===
--- /dev/null
+++ test/std/utilities/charconv/charconv.to.chars/integral.pass.cpp
@@ -0,0 +1,87 @@
+//===--===//
+//
+// 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
+// 
+
+// to_chars_result to_chars(char* first, char* last, Integral value,
+//  int base = 10)
+
+#include "charconv_test_helpers.h"
+
+template 
+struct test_basics : to_chars_test_base
+{
+using to_chars_test_base::test;
+using to_chars_test_base::test_value;
+
+void operator()()
+{
+
+test(0, "0");
+test(42, "42");
+test(32768, "32768");
+test(0, "0", 10);
+test(42, "42", 10);
+test(32768, "32768", 10);
+test(0xf, "f", 16);
+test(0xdeadbeaf, "deadbeaf", 16);
+test(0755, "755", 8);
+
+for (int b = 2; b < 37; ++b)
+{
+using xl = std::numeric_limits;
+
+test_value(1, b);
+test_value(xl::lowest(), b);
+test_value((xl::max)(), b);
+test_value((xl::max)() / 2, b);
+}
+}
+};
+
+template 
+struct test_signed : to_chars_test_base
+{
+using to_chars_test_base::test;
+using to_chars_test_base::test_value;
+
+void operator()()
+{
+test(-1, "-1");
+test(-12, "-12");
+test(-1, "-1", 10);
+test(-12, "-12", 10);
+test(-21734634, "-21734634", 10);
+test(-2647, "-101001010111", 2);
+test(-0xcc1, "-cc1", 16);
+
+for (int b = 2; b < 37; ++b)
+{
+using xl = std::numeric_limits;
+
+test_value(0, b);
+test_value(xl::lowest(), b);
+test_value((xl::max)(), b);
+}
+}
+};
+
+int
+main()
+{
+auto all_signed =
+type_list();
+auto all_unsigned = type_list();
+auto integrals = concat(all_signed, all_unsigned);
+
+run(integrals);
+run(all_signed);
+}
Index: test/std/utilities/charconv/charconv.to.chars/integral.bool.fail.cpp
===
--- /dev/null
+++ test/std/utilities/charconv/charconv.to.chars/integral.bool.fail.cpp
@@ -0,0 +1,30 @@
+//===--===//
+//
+// 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
+// 
+
+// In
+//
+// to_chars_result to_chars(char* first, char* last, Integral value,
+//  int base = 10)
+//
+// Integral cannot be bool.
+
+#include 
+
+int main()
+{
+using std::to_chars;
+char buf[10];
+bool lv = true;
+
+to_chars(buf, buf + sizeof(buf), false);   // expected-error {{call to deleted function}}
+to_chars(buf, buf + sizeof(buf), lv, 16);  // expected-error {{call to deleted function}}
+}
Index: src/support/itoa/itoa.cpp
===
--- /dev/null
+++ src/support/itoa/itoa.cpp
@@ -0,0 +1,296 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limi

[PATCH] D41408: [analyzer] NFC: Fix nothrow operator new definition in a test.

2017-12-20 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: test/Analysis/NewDelete-custom.cpp:7
 
-#if !LEAKS
+#if !(LEAKS && !ALLOCATOR_INLINING)
 // expected-no-diagnostics

a.sidorin wrote:
> Double negation can be simplified a bit: `#if !LEAKS || ALLOCATOR_INLINING`
The rest of the `#if`s in this file look like `#if LEAKS && 
!ALLOCATOR_INLINING`, so i wanted this to look similarly.


Repository:
  rC Clang

https://reviews.llvm.org/D41408



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


[PATCH] D41406: [analyzer] Add a new checker callback, check::NewAllocator.

2017-12-20 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

In https://reviews.llvm.org/D41406#960824, @xazax.hun wrote:

> Maybe `debug.AnalysisOrder` could be used to test the callback order 
> explicitly. This way the test could also serve as a documentation for the 
> callback order.


Yep, totally, will do.


https://reviews.llvm.org/D41406



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


[PATCH] D41405: Fix an assertion failure regression in isDesignatorAtObjectEnd for __builtin_object_size with incomplete array type in struct

2017-12-20 Thread George Burgess IV via Phabricator via cfe-commits
george.burgess.iv added inline comments.



Comment at: test/Sema/builtin-object-size.c:105
+void rd36094951_IAS_builtin_object_size_assertion(IncompleteArrayStruct* p) {
+   __builtin___strlcpy_chk (p->session[0].string, "ab", 2, 
__builtin_object_size(p->session[0].string, 1));
+}

vsapsai wrote:
> Do we execute significantly different code paths when the second 
> `__builtin_object_size` argument is 0, 2, 3? I think it is worth checking 
> locally if these values aren't causing an assertion. Not sure about having 
> such tests permanently, I'll leave it to you as you are more familiar with 
> the code.
In this case, only 1 and 3 should be touching the buggy codepath, and they 
should execute it identically. If 0 and 2 reach there, we have bigger problems, 
since they shouldn't really be poking around in the designator of the given 
LValue.

Since it's presumably only ~10 seconds of copy-pasting, I'd be happy if we 
added sanity checks for other modes, as well. :)


Repository:
  rC Clang

https://reviews.llvm.org/D41405



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


[PATCH] D40295: -fsanitize=vptr warnings on bad static types in dynamic_cast and typeid

2017-12-20 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added reviewers: vsk, thakis.
vsk accepted this revision.
vsk added a comment.
This revision is now accepted and ready to land.

Thanks, lgtm. Could you wait a day or two before committing? IIRC Richard or 
Nico have a -fsanitize=vptr Chromium bot, and they may have further comments.


https://reviews.llvm.org/D40295



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


[PATCH] D41311: [CodeGen] Fix crash when a function taking transparent union is redeclared.

2017-12-20 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:2321
+  !isa(ConvertType(Arg->getType())) &&
   ArgI.getCoerceToType() == ConvertType(Ty) &&
   ArgI.getDirectOffset() == 0) {

vsapsai wrote:
> rjmccall wrote:
> > I think the right fix is to change the second clause to 
> > ArgI.getCoerceToType() == ConvertType(Arg->getType()).  The point of this 
> > special case is to catch the common case that the natural way that IRGen 
> > wants to emit the argument expression is by producing a single scalar of 
> > exactly the right IR type; it seems to me that that condition would capture 
> > that correctly.
> I've tried that and it almost works. There are 4 failing tests
> Clang :: CodeGen/kr-func-promote.c
> Clang :: CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
> Clang :: CodeGenCXX/microsoft-abi-virtual-inheritance-vtordisps.cpp
> Clang :: CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
> 
> In a couple of places the problem is that expected function `i32 @a(i32)` but 
> received `i32 @a(i32 %x.coerce)`.
> 
> As for me, parameter naming is not really a problem and can be fixed by 
> making tests less specific. What is more interesting, with the change we 
> started adding extra store and load. For example, for 
> CodeGen/kr-func-promote.c IR was
> 
> ```
> define i32 @a(i32) #0 {
>   %x.addr = alloca i16, align 2
>   %x = trunc i32 %0 to i16
>   store i16 %x, i16* %x.addr, align 2
>   %2 = load i16, i16* %x.addr, align 2
>   %conv = sext i16 %2 to i32
>   ret i32 %conv
> }
> ```
> 
> and with type comparison change IR becomes
> ```
> define i32 @a(i32 %x.coerce) #0 {
> entry:
>   %x = alloca i16, align 2
>   %x.addr = alloca i16, align 2
>   %coerce.val.ii = trunc i32 %x.coerce to i16
>   store i16 %coerce.val.ii, i16* %x, align 2
>   %x1 = load i16, i16* %x, align 2
>   store i16 %x1, i16* %x.addr, align 2
>   %0 = load i16, i16* %x.addr, align 2
>   %conv = sext i16 %0 to i32
>   ret i32 %conv
> }
> ```
> 
> The same situation is with "microsoft-abi-*" tests where instead of
> ```
>   %this = bitcast i8* %0 to %struct.D*
>   store %struct.D* %this, %struct.D** %this.addr, align 4
>   %this1 = load %struct.D*, %struct.D** %this.addr, align 4
>   %2 = bitcast %struct.D* %this1 to i8*
> ```
> we have
> ```
>   %coerce.val = bitcast i8* %this.coerce to %struct.D*
>   store %struct.D* %coerce.val, %struct.D** %this, align 4
>   %this1 = load %struct.D*, %struct.D** %this, align 4
>   store %struct.D* %this1, %struct.D** %this.addr, align 4
>   %this2 = load %struct.D*, %struct.D** %this.addr, align 4
>   %0 = bitcast %struct.D* %this2 to i8*
> ```
> 
> I'll check where and why we are adding extra store/load.
The last store comes from `CodeGenFunction::EmitParmDecl` where for direct 
arguments we have
```lang=c++
  if (Arg.isIndirect()) {
//...
  } else {
// Otherwise, create a temporary to hold the value.
DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
D.getName() + ".addr");
DoStore = true;
  }
```
We have this store before and after my change, and it doesn't depend on 
comparing `ArgI.getCoerceToType()` to other types.

The extra store+load comes from `CreateCoercedStore` and `EmitLoadOfScalar` a 
few lines lower. I've tried to avoid this store+load for cases where we can use 
only `emitArgumentDemotion` and `CreateBitCast`. But it doesn't look to be 
particularly simple and starts to look like incomplete version of "trivial 
case, handle it with no muss and fuss".

Knowing the cause of the extra store+load I don't think it is crucial to avoid 
it. I'll update the patch with `ArgI.getCoerceToType() == 
ConvertType(Arg->getType())` comparison and fixed tests.



Comment at: clang/lib/CodeGen/CGCall.cpp:2461
 AI->setName(Arg->getName() + ".coerce");
 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
   }

Here is where we add the extra store.


https://reviews.llvm.org/D41311



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


[PATCH] D41455: [ASTMatchers] Add isNoReturn() match narrower for FunctionDeclarations

2017-12-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

You regenerate the HTML by running `clang/docs/tools/dump_ast_matchers.py`.




Comment at: unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp:1775
+  EXPECT_TRUE(notMatches("void func();", functionDecl(isNoReturn(;
+  EXPECT_TRUE(notMatches("void func() {};", functionDecl(isNoReturn(;
+

Spurious semicolon, which happens elsewhere in the tests as well -- please 
clean them all.



Comment at: unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp:1834
+  functionDecl(isNoReturn(;
+}
+

For fun, I'd like to see a `matchesC` test for `_Noreturn` as well, just to be 
extra sure. :-)


Repository:
  rC Clang

https://reviews.llvm.org/D41455



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


[PATCH] D41456: [clang-tidy] readability-else-after-return: also diagnose noreturn function calls.

2017-12-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/readability/ElseAfterReturnCheck.cpp:43
+  for (const auto *BindingName :
+   {"return", "continue", "break", "throw", "noreturn call"})
 if (Result.Nodes.getNodeAs(BindingName))

You've spotted the downside to this clever construct -- it is hard to make the 
wording not terrible here. :-)

I think the diagnostic should read `do no use 'else' after a call to a function 
that does not return`. This is trickier because the current `%0` is always 
quoted.



Comment at: docs/ReleaseNotes.rst:189
 
+- The 'readability-else-after-return' check was adjusted to handle throw 
expressions that require cleanups, calls to functions marked with noreturn 
attribute.
+

This seems to be > 80 cols, so please reformat. Also, it should be "that 
require cleanups and calls to functions marked with the noreturn attribute" 
(fixes a few grammatical issues at once).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41456



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


[PATCH] D23934: Add a -ffixed-date-time= flag that sets the initial value of __DATE__, __TIME__, __TIMESTAMP__

2017-12-20 Thread Ed Maste via Phabricator via cfe-commits
emaste added a comment.

Ping?


https://reviews.llvm.org/D23934



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


[PATCH] D39239: [AST] Incorrectly qualified unscoped enumeration as template actual parameter.

2017-12-20 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a project: debug-info.
probinson accepted this revision.
probinson added a comment.
This revision is now accepted and ready to land.

With the GDB test results and LLDB able to handle it, this LGTM.
Carlos, do you have commit access?


https://reviews.llvm.org/D39239



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


[PATCH] D41405: Fix an assertion failure regression in isDesignatorAtObjectEnd for __builtin_object_size with incomplete array type in struct

2017-12-20 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

In https://reviews.llvm.org/D41405#960008, @george.burgess.iv wrote:

> LGTM assuming my nit gets addressed.
>
> Thank you!
>
> > Maybe someone who's more familiar with this builtin could point to the 
> > cause of this discrepancy
>
> Yeah, the documentation for this builtin is pretty sparse. My guess: clang 
> assumes that the array's size is unknown because it's both an array and at 
> the end of a struct. This exists because code will do clever things like
>
>   struct string {
> size_t len;
> char buf[1]; // actual string is accessed from here; `string` just gets 
> overallocated to hold it all.
>   };
>
>
> in FreeBSD-land, they also recommend overallocation with sockaddrs, which 
> have a 14-length trailing element: 
> https://www.freebsd.org/doc/en/books/developers-handbook/sockets-essential-functions.html
>
> ...So, the best compatible heuristic we've been able to settle on here, 
> sadly, is "are we touching the final element in a struct, and is that element 
> an array?" On the bright side, clang failing just means LLVM gets to try to 
> figure it out, so only some hope of getting a useful answer is lost. :)
>
> It's interesting that GCC tries to do better here, since AIUI it has a 
> similar heuristic meant to cope with code like the above.


Thanks!




Comment at: test/Sema/builtin-object-size.c:105
+void rd36094951_IAS_builtin_object_size_assertion(IncompleteArrayStruct* p) {
+   __builtin___strlcpy_chk (p->session[0].string, "ab", 2, 
__builtin_object_size(p->session[0].string, 1));
+}

george.burgess.iv wrote:
> vsapsai wrote:
> > Do we execute significantly different code paths when the second 
> > `__builtin_object_size` argument is 0, 2, 3? I think it is worth checking 
> > locally if these values aren't causing an assertion. Not sure about having 
> > such tests permanently, I'll leave it to you as you are more familiar with 
> > the code.
> In this case, only 1 and 3 should be touching the buggy codepath, and they 
> should execute it identically. If 0 and 2 reach there, we have bigger 
> problems, since they shouldn't really be poking around in the designator of 
> the given LValue.
> 
> Since it's presumably only ~10 seconds of copy-pasting, I'd be happy if we 
> added sanity checks for other modes, as well. :)
Sure, I'll test the other modes as well.


Repository:
  rC Clang

https://reviews.llvm.org/D41405



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


r321222 - Fix an assertion failure regression in isDesignatorAtObjectEnd for

2017-12-20 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Dec 20 13:03:38 2017
New Revision: 321222

URL: http://llvm.org/viewvc/llvm-project?rev=321222&view=rev
Log:
Fix an assertion failure regression in isDesignatorAtObjectEnd for
__builtin_object_size with incomplete array type in struct

The commit r316245 introduced a regression that causes an assertion failure when
Clang tries to cast an IncompleteArrayType to a PointerType when evaluating
__builtin_object_size.

rdar://36094951

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

Modified:
cfe/trunk/lib/AST/ExprConstant.cpp
cfe/trunk/test/Sema/builtin-object-size.c

Modified: cfe/trunk/lib/AST/ExprConstant.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=321222&r1=321221&r2=321222&view=diff
==
--- cfe/trunk/lib/AST/ExprConstant.cpp (original)
+++ cfe/trunk/lib/AST/ExprConstant.cpp Wed Dec 20 13:03:38 2017
@@ -7420,7 +7420,10 @@ static bool isDesignatorAtObjectEnd(cons
 // If we don't know the array bound, conservatively assume we're looking at
 // the final array element.
 ++I;
-BaseType = BaseType->castAs()->getPointeeType();
+if (BaseType->isIncompleteArrayType())
+  BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
+else
+  BaseType = BaseType->castAs()->getPointeeType();
   }
 
   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {

Modified: cfe/trunk/test/Sema/builtin-object-size.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/builtin-object-size.c?rev=321222&r1=321221&r2=321222&view=diff
==
--- cfe/trunk/test/Sema/builtin-object-size.c (original)
+++ cfe/trunk/test/Sema/builtin-object-size.c Wed Dec 20 13:03:38 2017
@@ -91,3 +91,22 @@ int pr31843() {
 
   return n;
 }
+
+typedef struct {
+  char string[512];
+} NestedArrayStruct;
+
+typedef struct {
+  int x;
+  NestedArrayStruct session[];
+} IncompleteArrayStruct;
+
+void rd36094951_IAS_builtin_object_size_assertion(IncompleteArrayStruct *p) {
+#define rd36094951_CHECK(mode) 
\
+  __builtin___strlcpy_chk(p->session[0].string, "ab", 2,   
\
+  __builtin_object_size(p->session[0].string, mode))
+  rd36094951_CHECK(0);
+  rd36094951_CHECK(1);
+  rd36094951_CHECK(2);
+  rd36094951_CHECK(3);
+}


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


[PATCH] D41405: Fix an assertion failure regression in isDesignatorAtObjectEnd for __builtin_object_size with incomplete array type in struct

2017-12-20 Thread Alex Lorenz via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
arphaman marked 2 inline comments as done.
Closed by commit rC321222: Fix an assertion failure regression in 
isDesignatorAtObjectEnd for (authored by arphaman, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41405?vs=127438&id=127778#toc

Repository:
  rC Clang

https://reviews.llvm.org/D41405

Files:
  lib/AST/ExprConstant.cpp
  test/Sema/builtin-object-size.c


Index: lib/AST/ExprConstant.cpp
===
--- lib/AST/ExprConstant.cpp
+++ lib/AST/ExprConstant.cpp
@@ -7420,7 +7420,10 @@
 // If we don't know the array bound, conservatively assume we're looking at
 // the final array element.
 ++I;
-BaseType = BaseType->castAs()->getPointeeType();
+if (BaseType->isIncompleteArrayType())
+  BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
+else
+  BaseType = BaseType->castAs()->getPointeeType();
   }
 
   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
Index: test/Sema/builtin-object-size.c
===
--- test/Sema/builtin-object-size.c
+++ test/Sema/builtin-object-size.c
@@ -91,3 +91,22 @@
 
   return n;
 }
+
+typedef struct {
+  char string[512];
+} NestedArrayStruct;
+
+typedef struct {
+  int x;
+  NestedArrayStruct session[];
+} IncompleteArrayStruct;
+
+void rd36094951_IAS_builtin_object_size_assertion(IncompleteArrayStruct *p) {
+#define rd36094951_CHECK(mode) 
\
+  __builtin___strlcpy_chk(p->session[0].string, "ab", 2,   
\
+  __builtin_object_size(p->session[0].string, mode))
+  rd36094951_CHECK(0);
+  rd36094951_CHECK(1);
+  rd36094951_CHECK(2);
+  rd36094951_CHECK(3);
+}


Index: lib/AST/ExprConstant.cpp
===
--- lib/AST/ExprConstant.cpp
+++ lib/AST/ExprConstant.cpp
@@ -7420,7 +7420,10 @@
 // If we don't know the array bound, conservatively assume we're looking at
 // the final array element.
 ++I;
-BaseType = BaseType->castAs()->getPointeeType();
+if (BaseType->isIncompleteArrayType())
+  BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
+else
+  BaseType = BaseType->castAs()->getPointeeType();
   }
 
   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
Index: test/Sema/builtin-object-size.c
===
--- test/Sema/builtin-object-size.c
+++ test/Sema/builtin-object-size.c
@@ -91,3 +91,22 @@
 
   return n;
 }
+
+typedef struct {
+  char string[512];
+} NestedArrayStruct;
+
+typedef struct {
+  int x;
+  NestedArrayStruct session[];
+} IncompleteArrayStruct;
+
+void rd36094951_IAS_builtin_object_size_assertion(IncompleteArrayStruct *p) {
+#define rd36094951_CHECK(mode) \
+  __builtin___strlcpy_chk(p->session[0].string, "ab", 2,   \
+  __builtin_object_size(p->session[0].string, mode))
+  rd36094951_CHECK(0);
+  rd36094951_CHECK(1);
+  rd36094951_CHECK(2);
+  rd36094951_CHECK(3);
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41311: [CodeGen] Fix crash when a function taking transparent union is redeclared.

2017-12-20 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai updated this revision to Diff 127779.
vsapsai added a comment.

- Address review comment, compare ArgI type with Arg type. Update tests to 
account for coerced store when types don't match.


https://reviews.llvm.org/D41311

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/test/CodeGen/kr-func-promote.c
  clang/test/CodeGen/transparent-union-redecl.c
  clang/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
  clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance-vtordisps.cpp
  clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
  clang/test/Sema/transparent-union.c

Index: clang/test/Sema/transparent-union.c
===
--- clang/test/Sema/transparent-union.c
+++ clang/test/Sema/transparent-union.c
@@ -43,6 +43,35 @@
 void fvpp(TU); // expected-note{{previous declaration is here}}
 void fvpp(void **v) {} // expected-error{{conflicting types}}
 
+/* Test redeclaring a function taking a transparent_union arg more than twice.
+   Merging different declarations depends on their order, vary order too. */
+
+void f_triple0(TU tu) {}
+void f_triple0(int *); // expected-note{{previous declaration is here}}
+void f_triple0(float *f); // expected-error{{conflicting types}}
+
+void f_triple1(int *);
+void f_triple1(TU tu) {} // expected-note{{previous definition is here}}
+void f_triple1(float *f); // expected-error{{conflicting types}}
+
+void f_triple2(int *); // expected-note{{previous declaration is here}}
+void f_triple2(float *f); // expected-error{{conflicting types}}
+void f_triple2(TU tu) {}
+
+/* Test calling redeclared function taking a transparent_union arg. */
+
+void f_callee(TU);
+void f_callee(int *i) {} // expected-note{{passing argument to parameter 'i' here}}
+
+void caller(void) {
+  TU tu;
+  f_callee(tu); // expected-error{{passing 'TU' to parameter of incompatible type 'int *'}}
+
+  int *i;
+  f_callee(i);
+}
+
+
 /* FIXME: we'd like to just use an "int" here and align it differently
from the normal "int", but if we do so we lose the alignment
information from the typedef within the compiler. */
Index: clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
===
--- clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
+++ clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
@@ -115,9 +115,15 @@
 // B::foo gets 'this' cast to VBase* in ECX (i.e. this+8) so we
 // need to adjust 'this' before use.
 //
-// Store initial this:
+// Coerce this to correct type:
+// CHECK:   %[[THIS_STORE:.*]] = alloca %struct.B*
 // CHECK:   %[[THIS_ADDR:.*]] = alloca %struct.B*
-// CHECK:   store %struct.B* %{{.*}}, %struct.B** %[[THIS_ADDR]], align 4
+// CHECK:   %[[COERCE_VAL:.*]] = bitcast i8* %{{.*}} to %struct.B*
+// CHECK:   store %struct.B* %[[COERCE_VAL]], %struct.B** %[[THIS_STORE]], align 4
+//
+// Store initial this:
+// CHECK:   %[[THIS_INIT:.*]] = load %struct.B*, %struct.B** %[[THIS_STORE]]
+// CHECK:   store %struct.B* %[[THIS_INIT]], %struct.B** %[[THIS_ADDR]], align 4
 //
 // Reload and adjust the this parameter:
 // CHECK:   %[[THIS_RELOAD:.*]] = load %struct.B*, %struct.B** %[[THIS_ADDR]]
Index: clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance-vtordisps.cpp
===
--- clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance-vtordisps.cpp
+++ clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance-vtordisps.cpp
@@ -25,6 +25,7 @@
 
 // CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01?f@D@@$4PPPM@A@AEXXZ"
 // Note that the vtordisp is applied before really adjusting to D*.
+// CHECK: %[[COERCE_LOAD:.*]] = load %struct.D*, %struct.D** %{{.*}}
 // CHECK: %[[ECX:.*]] = load %struct.D*, %struct.D** %{{.*}}
 // CHECK: %[[ECX_i8:.*]] = bitcast %struct.D* %[[ECX]] to i8*
 // CHECK: %[[VTORDISP_PTR_i8:.*]] = getelementptr inbounds i8, i8* %[[ECX_i8]], i32 -4
@@ -36,6 +37,7 @@
 // CHECK: ret void
 
 // CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01?f@D@@$4PPPI@3AEXXZ"
+// CHECK: %[[COERCE_LOAD:.*]] = load %struct.D*, %struct.D** %{{.*}}
 // CHECK: %[[ECX:.*]] = load %struct.D*, %struct.D** %{{.*}}
 // CHECK: %[[ECX_i8:.*]] = bitcast %struct.D* %[[ECX]] to i8*
 // CHECK: %[[VTORDISP_PTR_i8:.*]] = getelementptr inbounds i8, i8* %[[ECX_i8]], i32 -8
@@ -64,7 +66,8 @@
 
 G::G() {}  // Forces vftable emission.
 
-// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01?f@E@@$R4BA@M@PPPM@7AEXXZ"(i8*)
+// CHECK-LABEL: define linkonce_odr x86_thiscallcc void @"\01?f@E@@$R4BA@M@PPPM@7AEXXZ"(i8*
+// CHECK: %[[COERCE_LOAD:.*]] = load %struct.E*, %struct.E** %{{.*}}
 // CHECK: %[[ECX:.*]] = load %struct.E*, %struct.E** %{{.*}}
 // CHECK: %[[ECX_i8:.*]] = bitcast %struct.E* %[[ECX]] to i8*
 // CHECK: %[[VTORDISP_PTR_i8:.*]] = getelementptr inbounds i8, i8* %[[ECX_i8]], i32 -4
Index: clang/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-in

[PATCH] D40448: Add a printing policy for AST dumping

2017-12-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

P-p-p-power ping! :-)


https://reviews.llvm.org/D40448



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


  1   2   >