[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom created this revision.
jvikstrom added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet.
Herald added a project: clang.

RecursiveASTVisitor was visiting implcit constructor initializers. This caused 
semantic highlighting in clangd to emit error logs. Fixes this by checking if 
the constructor is written or if the visitor should visit implicit decls.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D65735

Files:
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp


Index: clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp
===
--- clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp
@@ -22,11 +22,19 @@
 
   bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
 
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (Init->getSourceLocation().isInvalid())
+  InvalidLocsVisited = true;
+Match("initializer", Init->getSourceLocation());
+return true;
+  }
+
   bool VisitInitListExpr(InitListExpr *ILE) {
 Match(ILE->isSemanticForm() ? "semantic" : "syntactic", 
ILE->getBeginLoc());
 return true;
   }
 
+  bool InvalidLocsVisited = false;
 private:
   bool VisitImplicitCode;
 };
@@ -49,4 +57,22 @@
   InitListExprPreOrderVisitor::Lang_C));
 }
 
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  std::vector Config{true, false};
+  for (bool VisitImplCode : Config) {
+InitListExprPreOrderVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {
+  C() : A() {}
+};
+  )cpp",
+InitListExprPreOrderVisitor::Lang_CXX));
+EXPECT_EQ(Visitor.InvalidLocsVisited, VisitImplCode);
+  }
+}
 } // end anonymous namespace
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -2023,7 +2023,8 @@
   if (CXXConstructorDecl *Ctor = dyn_cast(D)) {
 // Constructor initializers.
 for (auto *I : Ctor->inits()) {
-  TRY_TO(TraverseConstructorInitializer(I));
+  if (I->isWritten() || getDerived().shouldVisitImplicitCode())
+TRY_TO(TraverseConstructorInitializer(I));
 }
   }
 


Index: clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp
===
--- clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp
@@ -22,11 +22,19 @@
 
   bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
 
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (Init->getSourceLocation().isInvalid())
+  InvalidLocsVisited = true;
+Match("initializer", Init->getSourceLocation());
+return true;
+  }
+
   bool VisitInitListExpr(InitListExpr *ILE) {
 Match(ILE->isSemanticForm() ? "semantic" : "syntactic", ILE->getBeginLoc());
 return true;
   }
 
+  bool InvalidLocsVisited = false;
 private:
   bool VisitImplicitCode;
 };
@@ -49,4 +57,22 @@
   InitListExprPreOrderVisitor::Lang_C));
 }
 
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  std::vector Config{true, false};
+  for (bool VisitImplCode : Config) {
+InitListExprPreOrderVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {
+  C() : A() {}
+};
+  )cpp",
+InitListExprPreOrderVisitor::Lang_CXX));
+EXPECT_EQ(Visitor.InvalidLocsVisited, VisitImplCode);
+  }
+}
 } // end anonymous namespace
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -2023,7 +2023,8 @@
   if (CXXConstructorDecl *Ctor = dyn_cast(D)) {
 // Constructor initializers.
 for (auto *I : Ctor->inits()) {
-  TRY_TO(TraverseConstructorInitializer(I));
+  if (I->isWritten() || getDerived().shouldVisitImplicitCode())
+TRY_TO(TraverseConstructorInitializer(I));
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commit

Re: r367520 - Delay emitting dllexport explicitly defaulted members until the class is fully parsed (PR40006)

2019-08-05 Thread Hans Wennborg via cfe-commits
Merged to release_90 in r367804.

On Thu, Aug 1, 2019 at 10:00 AM Hans Wennborg via cfe-commits
 wrote:
>
> Author: hans
> Date: Thu Aug  1 01:01:09 2019
> New Revision: 367520
>
> URL: http://llvm.org/viewvc/llvm-project?rev=367520&view=rev
> Log:
> Delay emitting dllexport explicitly defaulted members until the class is 
> fully parsed (PR40006)
>
> This is similar to r245139, but that only addressed dllexported classes.
> It was still possible to run into the same problem with dllexported
> members in an otherwise normal class (see bug). This uses the same
> strategy to fix: delay defining the method until the whole class has
> been parsed.
>
> (The easiest way to see the ordering problem is in
> Parser::ParseCXXMemberSpecification(): it calls
> ParseLexedMemberInitializers() *after* ActOnFinishCXXMemberDecls(),
> which was trying to define the dllexport method. Now we delay it to
> ActOnFinishCXXNonNestedClass() which is called after both of those.)
>
> Differential revision: https://reviews.llvm.org/D65511
>
> Modified:
> cfe/trunk/include/clang/Sema/Sema.h
> cfe/trunk/lib/Sema/Sema.cpp
> cfe/trunk/lib/Sema/SemaDeclCXX.cpp
> cfe/trunk/test/CodeGenCXX/dllexport.cpp
>
> Modified: cfe/trunk/include/clang/Sema/Sema.h
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=367520&r1=367519&r2=367520&view=diff
> ==
> --- cfe/trunk/include/clang/Sema/Sema.h (original)
> +++ cfe/trunk/include/clang/Sema/Sema.h Thu Aug  1 01:01:09 2019
> @@ -11136,6 +11136,7 @@ public:
>// Emitting members of dllexported classes is delayed until the class
>// (including field initializers) is fully parsed.
>SmallVector DelayedDllExportClasses;
> +  SmallVector DelayedDllExportMemberFunctions;
>
>  private:
>class SavePendingParsedClassStateRAII {
>
> Modified: cfe/trunk/lib/Sema/Sema.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/Sema.cpp?rev=367520&r1=367519&r2=367520&view=diff
> ==
> --- cfe/trunk/lib/Sema/Sema.cpp (original)
> +++ cfe/trunk/lib/Sema/Sema.cpp Thu Aug  1 01:01:09 2019
> @@ -961,6 +961,7 @@ void Sema::ActOnEndOfTranslationUnit() {
>
>// All dllexport classes should have been processed already.
>assert(DelayedDllExportClasses.empty());
> +  assert(DelayedDllExportMemberFunctions.empty());
>
>// Remove file scoped decls that turned out to be used.
>UnusedFileScopedDecls.erase(
>
> Modified: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclCXX.cpp?rev=367520&r1=367519&r2=367520&view=diff
> ==
> --- cfe/trunk/lib/Sema/SemaDeclCXX.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp Thu Aug  1 01:01:09 2019
> @@ -6283,8 +6283,8 @@ void Sema::CheckCompletedCXXClass(CXXRec
>  M->dropAttr();
>
>if (M->hasAttr()) {
> -DefineImplicitSpecialMember(*this, M, M->getLocation());
> -ActOnFinishInlineFunctionDef(M);
> +// Define after any fields with in-class initializers have been 
> parsed.
> +DelayedDllExportMemberFunctions.push_back(M);
>}
>  }
>};
> @@ -11537,6 +11537,15 @@ void Sema::ActOnFinishCXXMemberDecls() {
>
>  void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
>referenceDLLExportedClassMethods();
> +
> +  if (!DelayedDllExportMemberFunctions.empty()) {
> +SmallVector WorkList;
> +std::swap(DelayedDllExportMemberFunctions, WorkList);
> +for (CXXMethodDecl *M : WorkList) {
> +  DefineImplicitSpecialMember(*this, M, M->getLocation());
> +  ActOnFinishInlineFunctionDef(M);
> +}
> +  }
>  }
>
>  void Sema::referenceDLLExportedClassMethods() {
>
> Modified: cfe/trunk/test/CodeGenCXX/dllexport.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/dllexport.cpp?rev=367520&r1=367519&r2=367520&view=diff
> ==
> --- cfe/trunk/test/CodeGenCXX/dllexport.cpp (original)
> +++ cfe/trunk/test/CodeGenCXX/dllexport.cpp Thu Aug  1 01:01:09 2019
> @@ -851,6 +851,15 @@ struct __declspec(dllexport) Baz {
>  // Baz's operator=, causing instantiation of Foo after which
>  // ActOnFinishCXXNonNestedClass is called, and we would bite our own tail.
>  // M32-DAG: define weak_odr dso_local dllexport x86_thiscallcc 
> dereferenceable(1) %"struct.InClassInits::Baz"* 
> @"??4Baz@InClassInits@@QAEAAU01@ABU01@@Z"
> +
> +// Trying to define the explicitly defaulted ctor must be delayed until the
> +// in-class initializer for x has been processed.
> +struct PR40006 {
> +  __declspec(dllexport) PR40006() = default;
> +  int x = 42;
> +};
> +// M32-DAG: define weak_odr dso_local dllexport x86_thiscallcc 
> %"struct.InClassInits::PR40006"* @"??0PR40006@InClassInits@@QAE@XZ"
> +
>  

Re: r367661 - Don't try emitting dllexported explicitly defaulted non-trivial ctors twice during explicit template instantiation definition (PR42857)

2019-08-05 Thread Hans Wennborg via cfe-commits
Merged to release_90 in r367805.

On Fri, Aug 2, 2019 at 9:50 AM Hans Wennborg via cfe-commits
 wrote:
>
> Author: hans
> Date: Fri Aug  2 00:51:41 2019
> New Revision: 367661
>
> URL: http://llvm.org/viewvc/llvm-project?rev=367661&view=rev
> Log:
> Don't try emitting dllexported explicitly defaulted non-trivial ctors twice 
> during explicit template instantiation definition (PR42857)
>
> Trying to emit the definition twice triggers an assert.
>
> Differential revision: https://reviews.llvm.org/D65579
>
> Modified:
> cfe/trunk/lib/Sema/SemaDeclCXX.cpp
> cfe/trunk/test/CodeGenCXX/dllexport.cpp
>
> Modified: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclCXX.cpp?rev=367661&r1=367660&r2=367661&view=diff
> ==
> --- cfe/trunk/lib/Sema/SemaDeclCXX.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp Fri Aug  2 00:51:41 2019
> @@ -11543,7 +11543,13 @@ void Sema::ActOnFinishCXXNonNestedClass(
>  std::swap(DelayedDllExportMemberFunctions, WorkList);
>  for (CXXMethodDecl *M : WorkList) {
>DefineImplicitSpecialMember(*this, M, M->getLocation());
> -  ActOnFinishInlineFunctionDef(M);
> +
> +  // Pass the method to the consumer to get emitted. This is not 
> necessary
> +  // for explicit instantiation definitions, as they will get emitted
> +  // anyway.
> +  if (M->getParent()->getTemplateSpecializationKind() !=
> +  TSK_ExplicitInstantiationDefinition)
> +ActOnFinishInlineFunctionDef(M);
>  }
>}
>  }
>
> Modified: cfe/trunk/test/CodeGenCXX/dllexport.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/dllexport.cpp?rev=367661&r1=367660&r2=367661&view=diff
> ==
> --- cfe/trunk/test/CodeGenCXX/dllexport.cpp (original)
> +++ cfe/trunk/test/CodeGenCXX/dllexport.cpp Fri Aug  2 00:51:41 2019
> @@ -860,6 +860,13 @@ struct PR40006 {
>  };
>  // M32-DAG: define weak_odr dso_local dllexport x86_thiscallcc 
> %"struct.InClassInits::PR40006"* @"??0PR40006@InClassInits@@QAE@XZ"
>
> +// PR42857: Clang would try to emit the non-trivial explicitly defaulted
> +// dllexport ctor twice when doing an explicit instantiation definition.
> +struct Qux { Qux(); };
> +template  struct PR42857 { __declspec(dllexport) PR42857() = 
> default; Qux q; };
> +template struct PR42857;
> +// M32-DAG: define weak_odr dso_local dllexport x86_thiscallcc 
> %"struct.InClassInits::PR42857"* @"??0?$PR42857@H@InClassInits@@QAE@XZ"
> +
>  }
>
>  // We had an issue where instantiating A would force emission of B's delayed
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D65655: [clangd] Fix a crash when presenting values for Hover

2019-08-05 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In D65655#1612392 , @ilya-biryukov 
wrote:

> @hans, could we merge this commit into the release branch?


Sure, merged in r367807.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D65655



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


Re: [clang-tools-extra] r367687 - [clangd] Fix a crash when presenting values for Hover

2019-08-05 Thread Hans Wennborg via cfe-commits
Merged to release_90 in r367807.

On Fri, Aug 2, 2019 at 5:22 PM Ilya Biryukov via cfe-commits
 wrote:
>
> Author: ibiryukov
> Date: Fri Aug  2 08:23:04 2019
> New Revision: 367687
>
> URL: http://llvm.org/viewvc/llvm-project?rev=367687&view=rev
> Log:
> [clangd] Fix a crash when presenting values for Hover
>
> Summary:
> We should pass the expression type, not a variable type when printing
> the resulting value. Variable type may be different from what the
> pretty-printing function expects, e.g. have references.
>
> Reviewers: sammccall
>
> Reviewed By: sammccall
>
> Subscribers: MaskRay, jkorous, arphaman, kadircet, cfe-commits
>
> Tags: #clang
>
> Differential Revision: https://reviews.llvm.org/D65655
>
> Modified:
> clang-tools-extra/trunk/clangd/XRefs.cpp
> clang-tools-extra/trunk/clangd/unittests/XRefsTests.cpp
>
> Modified: clang-tools-extra/trunk/clangd/XRefs.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/XRefs.cpp?rev=367687&r1=367686&r2=367687&view=diff
> ==
> --- clang-tools-extra/trunk/clangd/XRefs.cpp (original)
> +++ clang-tools-extra/trunk/clangd/XRefs.cpp Fri Aug  2 08:23:04 2019
> @@ -715,7 +715,7 @@ static HoverInfo getHoverContents(const
>  HI.Value.emplace();
>  llvm::raw_string_ostream ValueOS(*HI.Value);
>  Result.Val.printPretty(ValueOS, const_cast(Ctx),
> -   Var->getType());
> +   Init->getType());
>}
>  }
>}
>
> Modified: clang-tools-extra/trunk/clangd/unittests/XRefsTests.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/XRefsTests.cpp?rev=367687&r1=367686&r2=367687&view=diff
> ==
> --- clang-tools-extra/trunk/clangd/unittests/XRefsTests.cpp (original)
> +++ clang-tools-extra/trunk/clangd/unittests/XRefsTests.cpp Fri Aug  2 
> 08:23:04 2019
> @@ -1793,6 +1793,16 @@ TEST(Hover, All) {
>"int\n"
>"]",
>},
> +  {
> +  R"cpp(// Should not crash when evaluating the initializer.
> +struct Test {};
> +void test() { Test && te^st = {}; }
> +  )cpp",
> +  "text[Declared in]code[test]\n"
> +  "codeblock(cpp) [\n"
> +  "struct Test &&test = {}\n"
> +  "]",
> +  },
>};
>
>// Create a tiny index, so tests above can verify documentation is fetched.
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

I think this is a reasonable fix, just a few comments on the test.




Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp:26
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (Init->getSourceLocation().isInvalid())
+  InvalidLocsVisited = true;

there may be other reasons to cause an invalid source location. I think we can 
use the `Init->isWritten()` to verify the implicit initializer is being 
visited. 



Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp:37
 
+  bool InvalidLocsVisited = false;
 private:

maybe name it `VisitedImplicitInitializer`?



Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp:62
+  std::vector Config{true, false};
+  for (bool VisitImplCode : Config) {
+InitListExprPreOrderVisitor Visitor(VisitImplCode);

nit: inline the Config.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735



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


r367809 - Adds a warning when an inline Doxygen comment has no argument

2019-08-05 Thread Dmitri Gribenko via cfe-commits
Author: gribozavr
Date: Mon Aug  5 01:05:16 2019
New Revision: 367809

URL: http://llvm.org/viewvc/llvm-project?rev=367809&view=rev
Log:
Adds a warning when an inline Doxygen comment has no argument

Summary:
It warns for for comments like
/** \pre \em */

where \em has no argument

This warning is enabled with the -Wdocumentation option.

Reviewers: gribozavr, rsmith

Reviewed By: gribozavr

Subscribers: cfe-commits

Tags: #clang

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

Patch by Mark de Wever.

Modified:
cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
cfe/trunk/lib/AST/CommentParser.cpp
cfe/trunk/test/Sema/warn-documentation.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td?rev=367809&r1=367808&r2=367809&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td Mon Aug  5 01:05:16 
2019
@@ -153,6 +153,12 @@ def warn_doc_deprecated_not_sync : Warni
 def note_add_deprecation_attr : Note<
   "add a deprecation attribute to the declaration to silence this warning">;
 
+// inline contents commands
+
+def warn_doc_inline_contents_no_argument : Warning<
+  "'%select{\\|@}0%1' command does not have an argument">,
+  InGroup, DefaultIgnore;
+
 // verbatim block commands
 
 def warn_verbatim_block_end_without_start : Warning<

Modified: cfe/trunk/lib/AST/CommentParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/CommentParser.cpp?rev=367809&r1=367808&r2=367809&view=diff
==
--- cfe/trunk/lib/AST/CommentParser.cpp (original)
+++ cfe/trunk/lib/AST/CommentParser.cpp Mon Aug  5 01:05:16 2019
@@ -422,6 +422,12 @@ InlineCommandComment *Parser::parseInlin
 IC = S.actOnInlineCommand(CommandTok.getLocation(),
   CommandTok.getEndLocation(),
   CommandTok.getCommandID());
+
+Diag(CommandTok.getEndLocation().getLocWithOffset(1),
+ diag::warn_doc_inline_contents_no_argument)
+<< CommandTok.is(tok::at_command)
+<< Traits.getCommandInfo(CommandTok.getCommandID())->Name
+<< SourceRange(CommandTok.getLocation(), CommandTok.getEndLocation());
   }
 
   Retokenizer.putBackLeftoverTokens();

Modified: cfe/trunk/test/Sema/warn-documentation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-documentation.cpp?rev=367809&r1=367808&r2=367809&view=diff
==
--- cfe/trunk/test/Sema/warn-documentation.cpp (original)
+++ cfe/trunk/test/Sema/warn-documentation.cpp Mon Aug  5 01:05:16 2019
@@ -1044,6 +1044,48 @@ template <>
 template 
 void test_attach38::test_attach39(int, B);
 
+// The inline comments expect a string after the command.
+// expected-warning@+1 {{'\a' command does not have an argument}}
+/// \a
+int test_inline_no_argument_a_bad(int);
+
+/// \a A
+int test_inline_no_argument_a_good(int);
+
+// expected-warning@+1 {{'@b' command does not have an argument}}
+/// @b
+int test_inline_no_argument_b_bad(int);
+
+/// @b A
+int test_inline_no_argument_b_good(int);
+
+// expected-warning@+1 {{'\c' command does not have an argument}}
+/// \c
+int test_inline_no_argument_c_bad(int);
+
+/// \c A
+int test_inline_no_argument_c_good(int);
+
+// expected-warning@+1 {{'\e' command does not have an argument}}
+/// \e
+int test_inline_no_argument_e_bad(int);
+
+/// \e A
+int test_inline_no_argument_e_good(int);
+
+// expected-warning@+1 {{'\em' command does not have an argument}}
+/// \em
+int test_inline_no_argument_em_bad(int);
+
+/// \em A
+int test_inline_no_argument_em_good(int);
+
+// expected-warning@+1 {{'\p' command does not have an argument}}
+/// \p
+int test_inline_no_argument_p_bad(int);
+
+/// \p A
+int test_inline_no_argument_p_good(int);
 
 // PR13411, reduced.  We used to crash on this.
 /**


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


[PATCH] D64696: Adds a warning when an inline Doxygen comment has no argument

2019-08-05 Thread Dmitri Gribenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL367809: Adds a warning when an inline Doxygen comment has no 
argument (authored by gribozavr, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D64696?vs=211340&id=213287#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D64696

Files:
  cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
  cfe/trunk/lib/AST/CommentParser.cpp
  cfe/trunk/test/Sema/warn-documentation.cpp


Index: cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
===
--- cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
+++ cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
@@ -153,6 +153,12 @@
 def note_add_deprecation_attr : Note<
   "add a deprecation attribute to the declaration to silence this warning">;
 
+// inline contents commands
+
+def warn_doc_inline_contents_no_argument : Warning<
+  "'%select{\\|@}0%1' command does not have an argument">,
+  InGroup, DefaultIgnore;
+
 // verbatim block commands
 
 def warn_verbatim_block_end_without_start : Warning<
Index: cfe/trunk/test/Sema/warn-documentation.cpp
===
--- cfe/trunk/test/Sema/warn-documentation.cpp
+++ cfe/trunk/test/Sema/warn-documentation.cpp
@@ -1044,6 +1044,48 @@
 template 
 void test_attach38::test_attach39(int, B);
 
+// The inline comments expect a string after the command.
+// expected-warning@+1 {{'\a' command does not have an argument}}
+/// \a
+int test_inline_no_argument_a_bad(int);
+
+/// \a A
+int test_inline_no_argument_a_good(int);
+
+// expected-warning@+1 {{'@b' command does not have an argument}}
+/// @b
+int test_inline_no_argument_b_bad(int);
+
+/// @b A
+int test_inline_no_argument_b_good(int);
+
+// expected-warning@+1 {{'\c' command does not have an argument}}
+/// \c
+int test_inline_no_argument_c_bad(int);
+
+/// \c A
+int test_inline_no_argument_c_good(int);
+
+// expected-warning@+1 {{'\e' command does not have an argument}}
+/// \e
+int test_inline_no_argument_e_bad(int);
+
+/// \e A
+int test_inline_no_argument_e_good(int);
+
+// expected-warning@+1 {{'\em' command does not have an argument}}
+/// \em
+int test_inline_no_argument_em_bad(int);
+
+/// \em A
+int test_inline_no_argument_em_good(int);
+
+// expected-warning@+1 {{'\p' command does not have an argument}}
+/// \p
+int test_inline_no_argument_p_bad(int);
+
+/// \p A
+int test_inline_no_argument_p_good(int);
 
 // PR13411, reduced.  We used to crash on this.
 /**
Index: cfe/trunk/lib/AST/CommentParser.cpp
===
--- cfe/trunk/lib/AST/CommentParser.cpp
+++ cfe/trunk/lib/AST/CommentParser.cpp
@@ -422,6 +422,12 @@
 IC = S.actOnInlineCommand(CommandTok.getLocation(),
   CommandTok.getEndLocation(),
   CommandTok.getCommandID());
+
+Diag(CommandTok.getEndLocation().getLocWithOffset(1),
+ diag::warn_doc_inline_contents_no_argument)
+<< CommandTok.is(tok::at_command)
+<< Traits.getCommandInfo(CommandTok.getCommandID())->Name
+<< SourceRange(CommandTok.getLocation(), CommandTok.getEndLocation());
   }
 
   Retokenizer.putBackLeftoverTokens();


Index: cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
===
--- cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
+++ cfe/trunk/include/clang/Basic/DiagnosticCommentKinds.td
@@ -153,6 +153,12 @@
 def note_add_deprecation_attr : Note<
   "add a deprecation attribute to the declaration to silence this warning">;
 
+// inline contents commands
+
+def warn_doc_inline_contents_no_argument : Warning<
+  "'%select{\\|@}0%1' command does not have an argument">,
+  InGroup, DefaultIgnore;
+
 // verbatim block commands
 
 def warn_verbatim_block_end_without_start : Warning<
Index: cfe/trunk/test/Sema/warn-documentation.cpp
===
--- cfe/trunk/test/Sema/warn-documentation.cpp
+++ cfe/trunk/test/Sema/warn-documentation.cpp
@@ -1044,6 +1044,48 @@
 template 
 void test_attach38::test_attach39(int, B);
 
+// The inline comments expect a string after the command.
+// expected-warning@+1 {{'\a' command does not have an argument}}
+/// \a
+int test_inline_no_argument_a_bad(int);
+
+/// \a A
+int test_inline_no_argument_a_good(int);
+
+// expected-warning@+1 {{'@b' command does not have an argument}}
+/// @b
+int test_inline_no_argument_b_bad(int);
+
+/// @b A
+int test_inline_no_argument_b_good(int);
+
+// expected-warning@+1 {{'\c' command does not have an argument}}
+/// \c
+int test_inline_no_argument_c_bad(int);
+
+/// \c A
+int test_inline_no_argument_c_good(int);
+
+// expected-warning

[clang-tools-extra] r367811 - [clangd] Fix error message with incorrect TextDocumentcontentChangeEvent.rangeLength

2019-08-05 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Aug  5 01:14:13 2019
New Revision: 367811

URL: http://llvm.org/viewvc/llvm-project?rev=367811&view=rev
Log:
[clangd] Fix error message with incorrect 
TextDocumentcontentChangeEvent.rangeLength

Modified:
clang-tools-extra/trunk/clangd/DraftStore.cpp

Modified: clang-tools-extra/trunk/clangd/DraftStore.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/DraftStore.cpp?rev=367811&r1=367810&r2=367811&view=diff
==
--- clang-tools-extra/trunk/clangd/DraftStore.cpp (original)
+++ clang-tools-extra/trunk/clangd/DraftStore.cpp Mon Aug  5 01:14:13 2019
@@ -90,7 +90,7 @@ llvm::Expected DraftStore::
   return llvm::make_error(
   llvm::formatv("Change's rangeLength ({0}) doesn't match the "
 "computed range length ({1}).",
-*Change.rangeLength, *EndIndex - *StartIndex),
+*Change.rangeLength, ComputedRangeLength),
   llvm::errc::invalid_argument);
 
 std::string NewContents;


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


[clang-tools-extra] r367812 - [clangd] Expose -offset-encoding=utf-32, which has been implemented for ages

2019-08-05 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Aug  5 01:14:17 2019
New Revision: 367812

URL: http://llvm.org/viewvc/llvm-project?rev=367812&view=rev
Log:
[clangd] Expose -offset-encoding=utf-32, which has been implemented for ages

Modified:
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp

Modified: clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp?rev=367812&r1=367811&r2=367812&view=diff
==
--- clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp (original)
+++ clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp Mon Aug  5 01:14:17 2019
@@ -359,7 +359,9 @@ opt ForceOffsetEncoding{
 values(
 clEnumValN(OffsetEncoding::UTF8, "utf-8", "Offsets are in UTF-8 
bytes"),
 clEnumValN(OffsetEncoding::UTF16, "utf-16",
-   "Offsets are in UTF-16 code units")),
+   "Offsets are in UTF-16 code units"),
+clEnumValN(OffsetEncoding::UTF32, "utf-32",
+   "Offsets are in unicode codepoints")),
 init(OffsetEncoding::UnsupportedEncoding),
 };
 


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


[PATCH] D65637: [clangd] [WIP] Semantic highlighting prototype for the vscode extension.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D65637#1613692 , @nridge wrote:

> Do you plan to support text decoration options other than color, e.g. bold / 
> underline / italic?


I think we'd just support color, and we don't have further plan to support 
richer renderings at the moment -- ideally, vscode should have built-in support 
for semantic highlighting if the proposal is accepted in LSP, this means this 
part of extension code will be removed in the end.

> Are users going to be able to change the color (and other decoration options) 
> for specific highlightings in the VSCode Settings?

vscode seems to provide a mechanism to override the theme settings, like

  "editor.tokenColorCustomizations": {
  "[Visual Studio Dark]": {
  "textMateRules": [
  {
  "scope": "entity.name.type",
  "settings": {
  "foreground": "#FF",
  }
  }
  ]
  }

I think our extension should respect it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65637



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


[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

The fix looks good.




Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrder.cpp:17
 // syntactic and semantic form.
 class InitListExprPreOrderVisitor
 : public ExpectedLocationVisitor {

Could you create a new test?
This test is clearly meant to test only `InitListExpr`, we should keep it 
focused on one thing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735



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


[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 213291.
jvikstrom marked 4 inline comments as done.
jvikstrom added a comment.

Moved test to its own test file (also addressed comments about the test).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735

Files:
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp


Index: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
@@ -0,0 +1,57 @@
+//===- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+// Check to ensure that CXXCtorInitializer is not visited when implicit code
+// should not be visited and that it is visited when implicit code should be
+// visited.
+class CXXCtorInitializerVisitor
+: public ExpectedLocationVisitor {
+public:
+  CXXCtorInitializerVisitor(bool VisitImplicitCode)
+  : VisitImplicitCode(VisitImplicitCode) {}
+
+  bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
+
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return true;
+  }
+
+  bool VisitedImplicitInitializer = false;
+
+private:
+  bool VisitImplicitCode;
+};
+
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  for (bool VisitImplCode : {true, false}) {
+CXXCtorInitializerVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {
+  C() : A() {}
+};
+  )cpp",
+CXXCtorInitializerVisitor::Lang_CXX));
+EXPECT_EQ(Visitor.VisitedImplicitInitializer, VisitImplCode);
+  }
+}
+} // end anonymous namespace
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -2023,7 +2023,8 @@
   if (CXXConstructorDecl *Ctor = dyn_cast(D)) {
 // Constructor initializers.
 for (auto *I : Ctor->inits()) {
-  TRY_TO(TraverseConstructorInitializer(I));
+  if (I->isWritten() || getDerived().shouldVisitImplicitCode())
+TRY_TO(TraverseConstructorInitializer(I));
 }
   }
 


Index: clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
@@ -0,0 +1,57 @@
+//===- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+// Check to ensure that CXXCtorInitializer is not visited when implicit code
+// should not be visited and that it is visited when implicit code should be
+// visited.
+class CXXCtorInitializerVisitor
+: public ExpectedLocationVisitor {
+public:
+  CXXCtorInitializerVisitor(bool VisitImplicitCode)
+  : VisitImplicitCode(VisitImplicitCode) {}
+
+  bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
+
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return true;
+  }
+
+  bool VisitedImplicitInitializer = false;
+
+private:
+  bool VisitImplicitCode;
+};
+
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  for (bool VisitImplCode : {true, false}) {
+CXXCtorInitializerVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {
+  C() : A() {}
+};
+  )cpp",
+CXXCtorInitializerVisitor::Lang_CXX))

[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 213294.
jvikstrom added a comment.

Call the base Traverse.. function in the visitor.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735

Files:
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp


Index: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
@@ -0,0 +1,58 @@
+//===- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+// Check to ensure that CXXCtorInitializer is not visited when implicit code
+// should not be visited and that it is visited when implicit code should be
+// visited.
+class CXXCtorInitializerVisitor
+: public ExpectedLocationVisitor {
+public:
+  CXXCtorInitializerVisitor(bool VisitImplicitCode)
+  : VisitImplicitCode(VisitImplicitCode) {}
+
+  bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
+
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return ExpectedLocationVisitor<
+CXXCtorInitializerVisitor>::TraverseConstructorInitializer(Init);
+  }
+
+  bool VisitedImplicitInitializer = false;
+
+private:
+  bool VisitImplicitCode;
+};
+
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  for (bool VisitImplCode : {true, false}) {
+CXXCtorInitializerVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {
+  C() : A() {}
+};
+  )cpp",
+CXXCtorInitializerVisitor::Lang_CXX));
+EXPECT_EQ(Visitor.VisitedImplicitInitializer, VisitImplCode);
+  }
+}
+} // end anonymous namespace
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -2023,7 +2023,8 @@
   if (CXXConstructorDecl *Ctor = dyn_cast(D)) {
 // Constructor initializers.
 for (auto *I : Ctor->inits()) {
-  TRY_TO(TraverseConstructorInitializer(I));
+  if (I->isWritten() || getDerived().shouldVisitImplicitCode())
+TRY_TO(TraverseConstructorInitializer(I));
 }
   }
 


Index: clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
@@ -0,0 +1,58 @@
+//===- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+// Check to ensure that CXXCtorInitializer is not visited when implicit code
+// should not be visited and that it is visited when implicit code should be
+// visited.
+class CXXCtorInitializerVisitor
+: public ExpectedLocationVisitor {
+public:
+  CXXCtorInitializerVisitor(bool VisitImplicitCode)
+  : VisitImplicitCode(VisitImplicitCode) {}
+
+  bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
+
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return ExpectedLocationVisitor<
+CXXCtorInitializerVisitor>::TraverseConstructorInitializer(Init);
+  }
+
+  bool VisitedImplicitInitializer = false;
+
+private:
+  bool VisitImplicitCode;
+};
+
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  for (bool VisitImplCode : {true, false}) {
+CXXCtorInitializerVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {

[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp:2
+//===- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
+//-===//
+//

we should make them one line even it exceeds 80 columns.



Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp:3
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.

I think you forgot to add the new file to the cmake file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735



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


[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

LGTM from my side, a few optional NITs.
Feel free to land as soon as @hokein stamps.




Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp:16
+
+// Check to ensure that CXXCtorInitializer is not visited when implicit code
+// should not be visited and that it is visited when implicit code should be

NIT: this comment is about the `TEST` rather than the helper class. Maybe move 
it there?



Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp:29
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());

NIT: alternatively use different match identifiers for written and unwritten 
initializers:
```
if (Init->isWritten())
  Match("written-inititiazlier", ...);
else
  Match("implicit-initializer", ...);

...
TEST() {
  Visitor.expectMatch("written-initializer");
  Visitor.disallowMatch("implicit-initializer"); // would that work with 
invalid source locs, though?
}
```

This allows to reuse the mechanism used by other tests without extra code. But 
up to you, definitely not a big deal.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735



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


[PATCH] D64695: [clang-format] Added new style rule: SortNetBSDIncludes

2019-08-05 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Assuming this works and the other unit tests don't show issues then this LGTM. 
Please consider running this on your NetBSD code base before committing, if 
possible please also run on clang code based to ensure existing sorted headers 
aren't sorted unexpectedly.

I do feel like there could be a documentation change missing really to explain 
to people how this really works and what if anything they have to change in 
their existing .clang-format files


Repository:
  rC Clang

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

https://reviews.llvm.org/D64695



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


r367823 - [OpenCL] Fix vector literal test broken in rL367675.

2019-08-05 Thread Anastasia Stulova via cfe-commits
Author: stulova
Date: Mon Aug  5 02:50:28 2019
New Revision: 367823

URL: http://llvm.org/viewvc/llvm-project?rev=367823&view=rev
Log:
[OpenCL] Fix vector literal test broken in rL367675.

Avoid checking alignment unnecessary that is not portable
among targets.


Modified:
cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl

Modified: cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl?rev=367823&r1=367822&r2=367823&view=diff
==
--- cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl (original)
+++ cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl Mon Aug  5 02:50:28 
2019
@@ -51,11 +51,11 @@ void vector_literals_valid() {
   //CHECK: store <4 x i32> , <4 x i32>* %a
   int4 a = (int4)(1);
 
-  //CHECK: load <4 x i32>, <4 x i32>* %a, align 16
+  //CHECK: load <4 x i32>, <4 x i32>* %a
   //CHECK: shufflevector <4 x i32> %{{[0-9]+}}, <4 x i32> undef, <2 x i32> 

   //CHECK: shufflevector <2 x i32> %{{[0-9]+}}, <2 x i32> undef, <8 x i32> 

   //CHECK: shufflevector <8 x i32> , <8 x i32> %{{.+}}, <8 x i32> 
-  //CHECK: load <4 x i32>, <4 x i32>* %a, align 16
+  //CHECK: load <4 x i32>, <4 x i32>* %a
   //CHECK: shufflevector <4 x i32> %{{[0-9]+}}, <4 x i32> undef, <8 x i32> 

   //CHECK: shufflevector <8 x i32> %{{.+}}, <8 x i32> %{{.+}}, <8 x i32> 
   int8 b = (int8)(1, 2, a.xy, a);


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


[PATCH] D65286: [OpenCL] Allow OpenCL C style vector initialization in C++

2019-08-05 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D65286#1614239 , @ebrevnov wrote:

> Please be aware about build bot failure 
> (http://lab.llvm.org:8011/builders/clang-cmake-thumbv7-full-sh/builds/2185) 
> most likely caused by this change.


Thanks! I believe it is now fixed in 
http://llvm.org/viewvc/llvm-project?view=revision&revision=367823.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D65286



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


[PATCH] D65648: [clang-format] Add support to SpacesBeforeTrailingComments to add spaces before Block comments.

2019-08-05 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay requested changes to this revision.
MyDeveloperDay added inline comments.
This revision now requires changes to proceed.



Comment at: lib/Format/TokenAnnotator.cpp:2163
+if (Current->is(TT_BlockComment)){
+  std::cout << "TYPE"isOneOf(TT_TemplateCloser,tok::l_paren) && 
Current->isTrailingComment()){
+  Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;

would a  test that shows why it should not be used after TT_TemplateCloser or 
tok::l_paren help?



Comment at: unittests/Format/FormatTest.cpp:3663
+  FormatStyle Style = getGoogleStyle();
+  Style.SpacesBeforeTrailingComments = 0;
   EXPECT_EQ("#define MACRO() \\\n"

this feels odd, suggesting those using google style will get reformatted 
changes?


Repository:
  rC Clang

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

https://reviews.llvm.org/D65648



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


r367826 - Sidestep false positive due to a matching git repository name

2019-08-05 Thread Roger Ferrer Ibanez via cfe-commits
Author: rogfer01
Date: Mon Aug  5 03:09:06 2019
New Revision: 367826

URL: http://llvm.org/viewvc/llvm-project?rev=367826&view=rev
Log:
Sidestep false positive due to a matching git repository name

I have failures in this test because the grep @b gets confused by the
clang version including a repository name like this

!1 = !{!"clang version 10.0.0 (git@build-machine:llvm/llvm-monorepo.git 
fe958c0e8c89ec663c8e551936778e2cbb460154)"}

I considered something like grep -w but my understanding of the manpages
was that that isn't super portable. So I think it is easier to make
clang not to output that metadata using -fno-ident.

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

Modified:
cfe/trunk/test/CodeGen/constant-comparison.c

Modified: cfe/trunk/test/CodeGen/constant-comparison.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/constant-comparison.c?rev=367826&r1=367825&r2=367826&view=diff
==
--- cfe/trunk/test/CodeGen/constant-comparison.c (original)
+++ cfe/trunk/test/CodeGen/constant-comparison.c Mon Aug  5 03:09:06 2019
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -emit-llvm %s -o - 2>&1 | not grep warning
-// RUN: %clang_cc1 -emit-llvm %s -o - | grep @b | count 1
+// RUN: %clang_cc1 -fno-ident -emit-llvm %s -o - | grep @b | count 1
 
 int a, b;
 int *c1 = 1 < 2 ? &a : &b;


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


[PATCH] D65387: [clangd] Add a callback mechanism for handling responses from client.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

thanks for the detailed comments!




Comment at: clang-tools-extra/clangd/test/request-reply.test:22
+---
+{"jsonrpc":"2.0","id":0,"result":{"applied":false}}
+#  CHECK:  "code": -32001,

sammccall wrote:
> please use increasing IDs and don't reuse them. (In general, but particularly 
> in this test)
I believe `0` is right here, this is a client reply for the server request `0` 
(applyEdit).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65387



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


[PATCH] D65635: Sidestep false positive due to a matching git repository name

2019-08-05 Thread Roger Ferrer Ibanez via Phabricator via cfe-commits
rogfer01 added a comment.

Thanks @efriedma. I will commit this shortly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65635



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


[PATCH] D65387: [clangd] Add a callback mechanism for handling responses from client.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 213304.
hokein marked 24 inline comments as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65387

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/test/fixits-command.test
  clang-tools-extra/clangd/test/request-reply.test

Index: clang-tools-extra/clangd/test/request-reply.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/request-reply.test
@@ -0,0 +1,43 @@
+# RUN: clangd -log=verbose -lit-test < %s | FileCheck -strict-whitespace %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":"auto i = 0;"}}}
+---
+{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{"command":"clangd.applyTweak","arguments":[{"file":"file:///clangd-test/main.cpp","selection":{"end":{"character":4,"line":0},"start":{"character":0,"line":0}},"tweakID":"ExpandAutoType"}]}}
+#  CHECK:  "id": 0,
+#  CHECK:  "method": "workspace/applyEdit",
+#  CHECK:  "newText": "int",
+# CHECK-NEXT:  "range": {
+# CHECK-NEXT:"end": {
+# CHECK-NEXT:  "character": 4,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:},
+# CHECK-NEXT:"start": {
+# CHECK-NEXT:  "character": 0,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:}
+# CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","id":0,"result":{"applied":false}}
+#  CHECK:  "error": {
+# CHECK-NEXT:"code": -32001,
+# CHECK-NEXT:"message": "edits were not applied: unknown reason"
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "id": 4,
+---
+{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{"command":"clangd.applyTweak","arguments":[{"file":"file:///clangd-test/main.cpp","selection":{"end":{"character":4,"line":0},"start":{"character":0,"line":0}},"tweakID":"ExpandAutoType"}]}}
+#  CHECK:  "id": 1,
+#  CHECK:  "method": "workspace/applyEdit",
+---
+{"jsonrpc":"2.0","id":1,"result":{"applied":true}}
+#  CHECK:  "id": 4,
+# CHECK-NEXT:  "jsonrpc": "2.0",
+# CHECK-NEXT:  "result": "Tweak applied."
+---
+# a reply with an invalid id.
+{"jsonrpc":"2.0","id":"invalid","result":{"applied":true}}
+# clangd doesn't reply, just emits an elog.
+---
+{"jsonrpc":"2.0","id":5,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: clang-tools-extra/clangd/test/fixits-command.test
===
--- clang-tools-extra/clangd/test/fixits-command.test
+++ clang-tools-extra/clangd/test/fixits-command.test
@@ -165,10 +165,6 @@
 # CHECK-NEXT:  ]
 ---
 {"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{"command":"clangd.applyFix","arguments":[{"changes":{"test:///foo.c":[{"range":{"start":{"line":0,"character":32},"end":{"line":0,"character":32}},"newText":"("},{"range":{"start":{"line":0,"character":37},"end":{"line":0,"character":37}},"newText":")"}]}}]}}
-#  CHECK:  "id": 4,
-# CHECK-NEXT:  "jsonrpc": "2.0",
-# CHECK-NEXT:  "result": "Fix applied."
-#
 #  CHECK:  "id": 0,
 # CHECK-NEXT:  "jsonrpc": "2.0",
 # CHECK-NEXT:  "method": "workspace/applyEdit",
@@ -207,6 +203,11 @@
 # CHECK-NEXT:}
 # CHECK-NEXT:  }
 ---
+{"jsonrpc":"2.0","id":0,"result":{"applied":true}}
+#  CHECK:  "id": 4,
+# CHECK-NEXT:  "jsonrpc": "2.0",
+# CHECK-NEXT:  "result": "Fix applied."
+---
 {"jsonrpc":"2.0","id":4,"method":"shutdown"}
 ---
 {"jsonrpc":"2.0","method":"exit"}
Index: clang-tools-extra/clangd/Protocol.h
===
--- clang-tools-extra/clangd/Protocol.h
+++ clang-tools-extra/clangd/Protocol.h
@@ -873,6 +873,12 @@
 };
 llvm::json::Value toJSON(const ApplyWorkspaceEditParams &);
 
+struct ApplyWorkspaceEditResponse {
+  bool applied = true;
+  llvm::Optional failureReason;
+};
+bool fromJSON(const llvm::json::Value &, ApplyWorkspaceEditResponse &);
+
 struct TextDocumentPositionParams {
   /// The text document.
   TextDocumentIdentifier textDocument;
Index: clang-tools-extra/clangd/Protocol.cpp
===
--- clang-tools-extra/clangd/Protocol.cpp
+++ clang-tools-extra/clangd/Protocol.cpp
@@ -670,6 +670,15 @@
   return llvm::json::Object{{"edit", Params.edit}};
 }
 
+bool fromJSON(const llvm::json::Value &Response,
+  ApplyWorkspaceEditResponse &R) {
+  llvm::json::ObjectMapper O(Response);
+  if (!O || !O.map("applied", R.applied))
+return false;
+  O.map("failureReason", R.failureReason);
+  return true;
+}
+
 bool fromJSON(const llvm::json::Value

[PATCH] D65635: Sidestep false positive due to a matching git repository name

2019-08-05 Thread Roger Ferrer Ibanez via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL367826: Sidestep false positive due to a matching git 
repository name (authored by rogfer01, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65635?vs=212975&id=213305#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65635

Files:
  cfe/trunk/test/CodeGen/constant-comparison.c


Index: cfe/trunk/test/CodeGen/constant-comparison.c
===
--- cfe/trunk/test/CodeGen/constant-comparison.c
+++ cfe/trunk/test/CodeGen/constant-comparison.c
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -emit-llvm %s -o - 2>&1 | not grep warning
-// RUN: %clang_cc1 -emit-llvm %s -o - | grep @b | count 1
+// RUN: %clang_cc1 -fno-ident -emit-llvm %s -o - | grep @b | count 1
 
 int a, b;
 int *c1 = 1 < 2 ? &a : &b;


Index: cfe/trunk/test/CodeGen/constant-comparison.c
===
--- cfe/trunk/test/CodeGen/constant-comparison.c
+++ cfe/trunk/test/CodeGen/constant-comparison.c
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -emit-llvm %s -o - 2>&1 | not grep warning
-// RUN: %clang_cc1 -emit-llvm %s -o - | grep @b | count 1
+// RUN: %clang_cc1 -fno-ident -emit-llvm %s -o - | grep @b | count 1
 
 int a, b;
 int *c1 = 1 < 2 ? &a : &b;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64696: Adds a warning when an inline Doxygen comment has no argument

2019-08-05 Thread David Zarzycki via Phabricator via cfe-commits
davezarzycki added a comment.

Hello – This change seems to have exposed a bug in -Wdocumentation argument 
parsing. For example, this warns when it shouldn't(?):

  /// \c @foobar


Repository:
  rL LLVM

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

https://reviews.llvm.org/D64696



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


[PATCH] D65589: [clang] Fix mismatched args constructing AddressSpaceAttr.

2019-08-05 Thread Anton Bikineev via Phabricator via cfe-commits
AntonBikineev added a comment.

Ping.


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

https://reviews.llvm.org/D65589



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


[PATCH] D64753: [CrossTU][NFCI] Refactor loadExternalAST function

2019-08-05 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 213311.
gamesh411 added a comment.

- Remove unused member Limit
- Rebase to current master


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D64753

Files:
  clang/include/clang/CrossTU/CrossTranslationUnit.h
  clang/lib/CrossTU/CrossTranslationUnit.cpp

Index: clang/lib/CrossTU/CrossTranslationUnit.cpp
===
--- clang/lib/CrossTU/CrossTranslationUnit.cpp
+++ clang/lib/CrossTU/CrossTranslationUnit.cpp
@@ -188,7 +188,7 @@
 }
 
 CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
-: CI(CI), Context(CI.getASTContext()),
+: CI(CI), Context(CI.getASTContext()), ASTStorage(CI),
   CTULoadThreshold(CI.getAnalyzerOpts()->CTUImportThreshold) {}
 
 CrossTranslationUnitContext::~CrossTranslationUnitContext() {}
@@ -237,8 +237,8 @@
   if (LookupName.empty())
 return llvm::make_error(
 index_error_code::failed_to_generate_usr);
-  llvm::Expected ASTUnitOrError = loadExternalAST(
-  LookupName, CrossTUDir, IndexName, DisplayCTUProgress);
+  llvm::Expected ASTUnitOrError =
+  loadExternalAST(LookupName, CrossTUDir, IndexName, DisplayCTUProgress);
   if (!ASTUnitOrError)
 return ASTUnitOrError.takeError();
   ASTUnit *Unit = *ASTUnitOrError;
@@ -340,6 +340,118 @@
   }
 }
 
+CrossTranslationUnitContext::ASTFileLoader::ASTFileLoader(
+const CompilerInstance &CI)
+: CI(CI) {}
+
+std::unique_ptr
+CrossTranslationUnitContext::ASTFileLoader::operator()(StringRef ASTFilePath) {
+  // Load AST from ast-dump.
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+  TextDiagnosticPrinter *DiagClient =
+  new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr Diags(
+  new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient));
+
+  return ASTUnit::LoadFromASTFile(
+  ASTFilePath, CI.getPCHContainerOperations()->getRawReader(),
+  ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts());
+}
+
+CrossTranslationUnitContext::ASTUnitStorage::ASTUnitStorage(
+const CompilerInstance &CI)
+: FileAccessor(CI) {}
+
+llvm::Expected
+CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(StringRef FileName) {
+  // Try the cache first.
+  auto ASTCacheEntry = FileASTUnitMap.find(FileName);
+  if (ASTCacheEntry == FileASTUnitMap.end()) {
+// Load the ASTUnit from the pre-dumped AST file specified by ASTFileName.
+std::unique_ptr LoadedUnit = FileAccessor(FileName);
+
+// Need the raw pointer and the unique_ptr as well.
+ASTUnit* Unit = LoadedUnit.get();
+
+// Update the cache.
+FileASTUnitMap[FileName] = std::move(LoadedUnit);
+return Unit;
+
+  } else {
+// Found in the cache.
+return ASTCacheEntry->second.get();
+  }
+}
+
+llvm::Expected
+CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFunction(
+StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName) {
+  // Try the cache first.
+  auto ASTCacheEntry = NameASTUnitMap.find(FunctionName);
+  if (ASTCacheEntry == NameASTUnitMap.end()) {
+// Load the ASTUnit from the pre-dumped AST file specified by ASTFileName.
+
+// Ensure that the Index is loaded, as we need to search in it.
+if (llvm::Error IndexLoadError =
+ensureCTUIndexLoaded(CrossTUDir, IndexName))
+  return std::move(IndexLoadError);
+
+// Check if there is and entry in the index for the function.
+if (!NameFileMap.count(FunctionName)) {
+  ++NumNotInOtherTU;
+  return llvm::make_error(index_error_code::missing_definition);
+}
+
+// Search in the index for the filename where the definition of FuncitonName
+// resides.
+if (llvm::Expected FoundForFile =
+getASTUnitForFile(NameFileMap[FunctionName])) {
+
+  // Update the cache.
+  NameASTUnitMap[FunctionName] = *FoundForFile;
+  return *FoundForFile;
+
+} else {
+  return FoundForFile.takeError();
+}
+  } else {
+// Found in the cache.
+return ASTCacheEntry->second;
+  }
+}
+
+llvm::Expected
+CrossTranslationUnitContext::ASTUnitStorage::getFileForFunction(
+StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName) {
+  if (llvm::Error IndexLoadError = ensureCTUIndexLoaded(CrossTUDir, IndexName))
+return std::move(IndexLoadError);
+  return NameFileMap[FunctionName];
+}
+
+llvm::Error CrossTranslationUnitContext::ASTUnitStorage::ensureCTUIndexLoaded(
+StringRef CrossTUDir, StringRef IndexName) {
+  // Dont initialize if the map is filled.
+  if (!NameFileMap.empty())
+return llvm::Error::success();
+
+  // Get the absolute path to the index file.
+  SmallString<256> IndexFile = CrossTUDir;
+  if (llvm::sys::path::is_absolute(IndexName))
+IndexFile = IndexName;
+  else
+llvm::sys::path::append(IndexFile, IndexName);
+
+  if (auto IndexMapping = 

[PATCH] D65234: [CodeGen]: don't treat structures returned in registers as memory inputs

2019-08-05 Thread Alexander Potapenko via Phabricator via cfe-commits
glider added a comment.

Eli, any other comments?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65234



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


r367829 - [CrossTU][NFCI] Refactor loadExternalAST function

2019-08-05 Thread Endre Fulop via cfe-commits
Author: gamesh411
Date: Mon Aug  5 04:06:41 2019
New Revision: 367829

URL: http://llvm.org/viewvc/llvm-project?rev=367829&view=rev
Log:
[CrossTU][NFCI] Refactor loadExternalAST function

Summary:
Refactor loadExternalAST method of CrossTranslationUnitContext in order to
reduce maintenance burden and so that features are easier to add in the future.

Reviewers: martong

Subscribers: rnkovacs, dkrupp, Szelethus, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp

Modified: cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h?rev=367829&r1=367828&r2=367829&view=diff
==
--- cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h (original)
+++ cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h Mon Aug  5 04:06:41 
2019
@@ -192,11 +192,11 @@ private:
   template 
   llvm::Expected importDefinitionImpl(const T *D, ASTUnit *Unit);
 
-  llvm::StringMap> FileASTUnitMap;
-  llvm::StringMap NameASTUnitMap;
-  llvm::StringMap NameFileMap;
-  llvm::DenseMap>
-  ASTUnitImporterMap;
+  using ImporterMapTy =
+  llvm::DenseMap>;
+
+  ImporterMapTy ASTUnitImporterMap;
+
   CompilerInstance &CI;
   ASTContext &Context;
   std::shared_ptr ImporterSharedSt;
@@ -209,10 +209,105 @@ private:
   /// imported the FileID.
   ImportedFileIDMap ImportedFileIDs;
 
+  /// Functor for loading ASTUnits from AST-dump files.
+  class ASTFileLoader {
+  public:
+ASTFileLoader(const CompilerInstance &CI);
+std::unique_ptr operator()(StringRef ASTFilePath);
+
+  private:
+const CompilerInstance &CI;
+  };
+
+  /// Storage for ASTUnits, cached access, and providing searchability are the
+  /// concerns of ASTUnitStorage class.
+  class ASTUnitStorage {
+  public:
+ASTUnitStorage(const CompilerInstance &CI);
+/// Loads an ASTUnit for a function.
+///
+/// \param FuncitionName USR name of the function.
+/// \param CrossTUDir Path to the directory used to store CTU related 
files.
+/// \param IndexName Name of the file inside \p CrossTUDir which maps
+/// function USR names to file paths. These files contain the corresponding
+/// AST-dumps.
+///
+/// \return An Expected instance which contains the ASTUnit pointer or the
+/// error occured during the load.
+llvm::Expected getASTUnitForFunction(StringRef FunctionName,
+StringRef CrossTUDir,
+StringRef IndexName);
+/// Identifies the path of the file which can be used to load the ASTUnit
+/// for a given function.
+///
+/// \param FuncitionName USR name of the function.
+/// \param CrossTUDir Path to the directory used to store CTU related 
files.
+/// \param IndexName Name of the file inside \p CrossTUDir which maps
+/// function USR names to file paths. These files contain the corresponding
+/// AST-dumps.
+///
+/// \return An Expected instance containing the filepath.
+llvm::Expected getFileForFunction(StringRef FunctionName,
+   StringRef CrossTUDir,
+   StringRef IndexName);
+
+  private:
+llvm::Error ensureCTUIndexLoaded(StringRef CrossTUDir, StringRef 
IndexName);
+llvm::Expected getASTUnitForFile(StringRef FileName);
+
+template  using BaseMapTy = llvm::StringMap;
+using OwningMapTy = BaseMapTy>;
+using NonOwningMapTy = BaseMapTy;
+
+OwningMapTy FileASTUnitMap;
+NonOwningMapTy NameASTUnitMap;
+
+using IndexMapTy = BaseMapTy;
+IndexMapTy NameFileMap;
+
+ASTFileLoader FileAccessor;
+  };
+
+  ASTUnitStorage ASTStorage;
+
   /// \p CTULoadTreshold should serve as an upper limit to the number of TUs
   /// imported in order to reduce the memory footprint of CTU analysis.
   const unsigned CTULoadThreshold;
-  unsigned NumASTLoaded{0u};
+
+  /// The number successfully loaded ASTs. Used to indicate, and  - with the
+  /// appropriate threshold value - limit the  memory usage of the
+  /// CrossTranslationUnitContext.
+  unsigned NumASTLoaded;
+
+  /// RAII counter to signal 'threshold reached' condition, and to increment 
the
+  /// NumASTLoaded counter upon a successful load.
+  class LoadGuard {
+  public:
+LoadGuard(unsigned Limit, unsigned &Counter)
+: Counter(Counter), Enabled(Counter < Limit){};
+~LoadGuard() {
+  if (StoreSuccess)
+++Counter;
+}
+/// Flag the LoadGuard instance as successful, meaning that the load
+/// operation succeeded, and the memory footprint of the AST storage
+/// actually increased. In this case, \p Counter should be incremented upon
+/// destructi

[PATCH] D64753: [CrossTU][NFCI] Refactor loadExternalAST function

2019-08-05 Thread Endre Fülöp via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL367829: [CrossTU][NFCI] Refactor loadExternalAST function 
(authored by gamesh411, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D64753?vs=213311&id=213315#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D64753

Files:
  cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
  cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp

Index: cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
===
--- cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
+++ cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
@@ -192,11 +192,11 @@
   template 
   llvm::Expected importDefinitionImpl(const T *D, ASTUnit *Unit);
 
-  llvm::StringMap> FileASTUnitMap;
-  llvm::StringMap NameASTUnitMap;
-  llvm::StringMap NameFileMap;
-  llvm::DenseMap>
-  ASTUnitImporterMap;
+  using ImporterMapTy =
+  llvm::DenseMap>;
+
+  ImporterMapTy ASTUnitImporterMap;
+
   CompilerInstance &CI;
   ASTContext &Context;
   std::shared_ptr ImporterSharedSt;
@@ -209,10 +209,105 @@
   /// imported the FileID.
   ImportedFileIDMap ImportedFileIDs;
 
+  /// Functor for loading ASTUnits from AST-dump files.
+  class ASTFileLoader {
+  public:
+ASTFileLoader(const CompilerInstance &CI);
+std::unique_ptr operator()(StringRef ASTFilePath);
+
+  private:
+const CompilerInstance &CI;
+  };
+
+  /// Storage for ASTUnits, cached access, and providing searchability are the
+  /// concerns of ASTUnitStorage class.
+  class ASTUnitStorage {
+  public:
+ASTUnitStorage(const CompilerInstance &CI);
+/// Loads an ASTUnit for a function.
+///
+/// \param FuncitionName USR name of the function.
+/// \param CrossTUDir Path to the directory used to store CTU related files.
+/// \param IndexName Name of the file inside \p CrossTUDir which maps
+/// function USR names to file paths. These files contain the corresponding
+/// AST-dumps.
+///
+/// \return An Expected instance which contains the ASTUnit pointer or the
+/// error occured during the load.
+llvm::Expected getASTUnitForFunction(StringRef FunctionName,
+StringRef CrossTUDir,
+StringRef IndexName);
+/// Identifies the path of the file which can be used to load the ASTUnit
+/// for a given function.
+///
+/// \param FuncitionName USR name of the function.
+/// \param CrossTUDir Path to the directory used to store CTU related files.
+/// \param IndexName Name of the file inside \p CrossTUDir which maps
+/// function USR names to file paths. These files contain the corresponding
+/// AST-dumps.
+///
+/// \return An Expected instance containing the filepath.
+llvm::Expected getFileForFunction(StringRef FunctionName,
+   StringRef CrossTUDir,
+   StringRef IndexName);
+
+  private:
+llvm::Error ensureCTUIndexLoaded(StringRef CrossTUDir, StringRef IndexName);
+llvm::Expected getASTUnitForFile(StringRef FileName);
+
+template  using BaseMapTy = llvm::StringMap;
+using OwningMapTy = BaseMapTy>;
+using NonOwningMapTy = BaseMapTy;
+
+OwningMapTy FileASTUnitMap;
+NonOwningMapTy NameASTUnitMap;
+
+using IndexMapTy = BaseMapTy;
+IndexMapTy NameFileMap;
+
+ASTFileLoader FileAccessor;
+  };
+
+  ASTUnitStorage ASTStorage;
+
   /// \p CTULoadTreshold should serve as an upper limit to the number of TUs
   /// imported in order to reduce the memory footprint of CTU analysis.
   const unsigned CTULoadThreshold;
-  unsigned NumASTLoaded{0u};
+
+  /// The number successfully loaded ASTs. Used to indicate, and  - with the
+  /// appropriate threshold value - limit the  memory usage of the
+  /// CrossTranslationUnitContext.
+  unsigned NumASTLoaded;
+
+  /// RAII counter to signal 'threshold reached' condition, and to increment the
+  /// NumASTLoaded counter upon a successful load.
+  class LoadGuard {
+  public:
+LoadGuard(unsigned Limit, unsigned &Counter)
+: Counter(Counter), Enabled(Counter < Limit){};
+~LoadGuard() {
+  if (StoreSuccess)
+++Counter;
+}
+/// Flag the LoadGuard instance as successful, meaning that the load
+/// operation succeeded, and the memory footprint of the AST storage
+/// actually increased. In this case, \p Counter should be incremented upon
+/// destruction.
+void storedSuccessfully() { StoreSuccess = true; }
+/// Indicates, whether a new load operation is permitted, it is within the
+/// threshold.
+operator bool() const { return Enabled; };
+
+  private:
+/// The number of ASTs actually imported. LoadGuard does not own the
+/// counter, jus

Re: r367675 - [OpenCL] Allow OpenCL C style vector initialization in C++

2019-08-05 Thread Anastasia Stulova via cfe-commits
Hi Yvan,


Sorry for this, it should now be fixed  in r367823.


Thanks,

Anastasia



From: Yvan Roux 
Sent: 02 August 2019 14:09
To: Anastasia Stulova 
Cc: cfe-commits 
Subject: Re: r367675 - [OpenCL] Allow OpenCL C style vector initialization in 
C++

Hi Anastasia,

This commit broke ARMv8 bots, logs are available here:

http://lab.llvm.org:8011/builders/clang-cmake-armv8-quick/builds/14655/steps/ninja%20check%201/logs/FAIL%3A%20Clang%3A%3Avector_literals_valid.cl

Thanks,
Yvan

On Fri, 2 Aug 2019 at 13:18, Anastasia Stulova via cfe-commits
 wrote:
>
> Author: stulova
> Date: Fri Aug  2 04:19:35 2019
> New Revision: 367675
>
> URL: http://llvm.org/viewvc/llvm-project?rev=367675&view=rev
> Log:
> [OpenCL] Allow OpenCL C style vector initialization in C++
>
> Allow creating vector literals from other vectors.
>
>  float4 a = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
>  float4 v = (float4)(a.s23, a.s01);
>
> Differential revision: https://reviews.llvm.org/D65286
>
>
> Removed:
> cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl
> cfe/trunk/test/SemaOpenCL/vector_literals_const.cl
> Modified:
> cfe/trunk/lib/Sema/SemaInit.cpp
> cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl
> cfe/trunk/test/SemaCXX/vector.cpp
>
> Modified: cfe/trunk/lib/Sema/SemaInit.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=367675&r1=367674&r2=367675&view=diff
> ==
> --- cfe/trunk/lib/Sema/SemaInit.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  2 04:19:35 2019
> @@ -1289,7 +1289,16 @@ void InitListChecker::CheckSubElementTyp
>  // FIXME: Better EqualLoc?
>  InitializationKind Kind =
>  InitializationKind::CreateCopy(expr->getBeginLoc(), 
> SourceLocation());
> -InitializationSequence Seq(SemaRef, Entity, Kind, expr,
> +
> +// Vector elements can be initialized from other vectors in which case
> +// we need initialization entity with a type of a vector (and not a 
> vector
> +// element!) initializing multiple vector elements.
> +auto TmpEntity =
> +(ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
> +? InitializedEntity::InitializeTemporary(ElemType)
> +: Entity;
> +
> +InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
> /*TopLevelOfInitList*/ true);
>
>  // C++14 [dcl.init.aggr]p13:
> @@ -1300,8 +1309,7 @@ void InitListChecker::CheckSubElementTyp
>  // assignment-expression.
>  if (Seq || isa(expr)) {
>if (!VerifyOnly) {
> -ExprResult Result =
> -  Seq.Perform(SemaRef, Entity, Kind, expr);
> +ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
>  if (Result.isInvalid())
>hadError = true;
>
>
> Removed: cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl?rev=367674&view=auto
> ==
> --- cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl (original)
> +++ cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl (removed)
> @@ -1,23 +0,0 @@
> -// RUN: %clang_cc1 %s -emit-llvm -O3 -o - | FileCheck %s
> -
> -typedef int int2 __attribute((ext_vector_type(2)));
> -typedef int int4 __attribute((ext_vector_type(4)));
> -
> -__constant const int4 itest1 = (int4)(1, 2, ((int2)(3, 4)));
> -// CHECK: constant <4 x i32> 
> -__constant const int4 itest2 = (int4)(1, 2, ((int2)(3)));
> -// CHECK: constant <4 x i32> 
> -
> -typedef float float2 __attribute((ext_vector_type(2)));
> -typedef float float4 __attribute((ext_vector_type(4)));
> -
> -void ftest1(float4 *p) {
> -  *p = (float4)(1.1f, 1.2f, ((float2)(1.3f, 1.4f)));
> -// CHECK: store <4 x float>  0x3FF34000, float 0x3FF4C000, float 0x3FF66000>
> -}
> -
> -float4 ftest2(float4 *p) {
> -   *p =  (float4)(1.1f, 1.2f, ((float2)(1.3f)));
> -// CHECK: store <4 x float>  0x3FF34000, float 0x3FF4C000, float 0x3FF4C000>
> -}
> -
>
> Modified: cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl?rev=367675&r1=367674&r2=367675&view=diff
> ==
> --- cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl (original)
> +++ cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl Fri Aug  2 04:19:35 
> 2019
> @@ -1,22 +1,65 @@
> -// RUN: %clang_cc1 -emit-llvm %s -o %t
> +// RUN: %clang_cc1 -emit-llvm %s -o - -O0 | FileCheck %s
> +// RUN: %clang_cc1 -emit-llvm %s -o - -cl-std=clc++ -O0 | FileCheck %s
>
> -typedef __attribute__(( ext_vector_type(2) ))  int int2;
> -typedef __attribute__(( ext_vector_type(3) ))  int int3;
> -typede

[PATCH] D63835: [Syntax] Add nodes for most common statements

2019-08-05 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: clang/include/clang/Tooling/Syntax/Nodes.h:99
 /// An abstract node for C++ statements, e.g. 'while', 'if', etc.
 class Statement : public Tree {
 public:

ilya-biryukov wrote:
> sammccall wrote:
> > Do you want to expose the statement-ending-semicolon here?
> > 
> > (Not all statements have it, but common enough you may want it in the base 
> > class instead of all children)
> Yes, only "leaf" (i.e. the ones not having any statement children) have it.
> I was thinking about:
>   - having a separate class for non-composite statements and providing an 
> accessor there,
>   - providing an accessor in each of the leaf statements (would mean some 
> duplication, but, arguably, better discoverability).
> 
> But, from an offline conversation, we seem to disagree that inheritance is a 
> proper way to model this.
> Would it be ok to do this in a follow-up? I'll add a FIXME for now.
First: yes, let's not do this now.

Second: I'm wary of using standard is-a inheritance to model more than 
alternation in the grammar. That is, ForStatement is-a Statement is fine, 
ForStatement is-a LoopyStatement is suspect. This is to do with the fact that 
LoopyStatement is-a Statement seems obvious, and we may end up with 
diamond-shaped inheritance and some conceptual confusion.

This goes for all traits that aren't natural tree-shaped inheritance: 
HasTrailingSemicolon, LoopyStatement, ...

I think there are two concerns here:
 - we want to be able to get the trailing-semicolon if it exists
 - we want to be able to check if the trailing-semicolon is *expected* 
including via its static type

One way to do this (not the only one...):

```
// generic helper, or callers could even write this directly
Optional trailingSemi(Tree *Node) {
  return firstElement(Node->Children(NodeRole::TrailingSemi));
}

// mixin for trailing semi support. Note: doesn't inherit Statement!
// maybe need/want some CRTP magic
class TrailingSemicolon {
  Optional trailingSemi() const { return trailingSemi((const Node*)this; }
}

// Gets the trailingSemi() accessor.
ExprStmt : public Statement, TrailingSemicolon { ... }

```



Comment at: clang/include/clang/Tooling/Syntax/Nodes.h:193
+  syntax::Statement *thenStatement();
+  syntax::Leaf *elseKeyword();
+  syntax::Statement *elseStatement();

ilya-biryukov wrote:
> sammccall wrote:
> > I think throughout it's important to mark which of these are:
> >  - nullable in correct code
> >  - nullable in code generated by recovery
> I would suggest to only mark the nodes that are nullable in the correct code. 
> For recovery, I would assume the following rule (please tell me if I'm wrong):
> 
> On a construct whose parsing involved recovery:
> - if the node has an introducing token (`if`, `try`, etc.), the corresponding 
> child cannot be null.
> - any other child can be null.
Agree with this strategy, and the fact that it doesn't need to be documented on 
every node/occurrence.

But it should definitely be documented somewhere at a high level! (With clang 
AST, this sort of thing feels like tribal knowledge)



Comment at: clang/include/clang/Tooling/Syntax/Nodes.h:24
 
 /// A kind of a syntax node, used for implementing casts.
 enum class NodeKind : uint16_t {

Can you add a comment here saying the ordering/blocks must correspond to the 
Node inheritance hierarchy? This is *kind of* common knowledge, but I think 
this is normally handled by tablegen.



Comment at: clang/include/clang/Tooling/Syntax/Nodes.h:79
+  ExpressionStatement_expression,
+  CompoundStatement_statement
 };

As discussed offline, there's some options about how abstract/concrete these 
roles should be.

e.g. for a list of function args, this could be 
FunctionOpenParen/FunctionArgExpr/FunctionArgComma/FunctionCloseParam 
(specific) <-> OpenParen/Arg/Comma/CloseParen <-> Open/Item/Separator/Close.

The more specific ones are somewhat redundant with the parent/child type (but 
easy to assign systematically), and the more generic ones are more orthogonal 
(but require more design and may by hard to always make consistent).

The concrete advantage of the generic roles is being able to write code like 
`getTrailingSemicolon(Tree*)` or `findLoopBreak(Stmt*)` or 
`removeListItem(Tree*, int)` in a fairly generic way, without resorting to 
adding a `Loop` base class or handling each case with separate code.

This is up to you, though.



Comment at: clang/include/clang/Tooling/Syntax/Nodes.h:265
+  syntax::Leaf *returnKeyword();
+  syntax::Expression *value();
+};

nullable, marked somehow

Optional is tempting as a systematic and hard-to-ignore way of 
documenting that.
And it reflects the fact that there are three conceptual states for children: 
present, lega

[PATCH] D65738: [clangd] Added a TextMate theme parser that updates when the current theme changes.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom created this revision.
jvikstrom added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Adds a TextMate parser module to the vscode extension. It watches for changes 
to the vscode configuration and updates the colors when the current theme is 
changed.
The colors are saved in a singleton to allow for easy access when doing 
coloring later.

The TMColor class maps all scopes to the clangd TextMate scope indexes and 
discards any theme colors that are not relevant.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D65738

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/package.json
  clang-tools-extra/clangd/clients/clangd-vscode/src/TextMate.ts
  clang-tools-extra/clangd/clients/clangd-vscode/test/TextMate.test.ts

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/TextMate.test.ts
===
--- /dev/null
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/TextMate.test.ts
@@ -0,0 +1,32 @@
+/** The module 'assert' provides assertion methods from node */
+import * as assert from 'assert';
+
+import * as vscode from 'vscode';
+import {SemanticHighlighting} from '../src/TextMate';
+
+// TODO: add tests
+suite("Extension Tests", () => {
+  test('overrides for more specific themes', () => {
+const scopes = [ 'a.b.c.d', 'a.b.f', 'a' ];
+const colorPairs = [
+  [ [ 'a.b.c', 'a.b.d' ], '1' ],
+  [ 'a.b', '2' ],
+  [ 'a.b.c.d', '3' ],
+  [ 'a', '4' ],
+];
+const tm = new SemanticHighlighting.TMColors(scopes);
+colorPairs.forEach((p) => tm.setColor(p[0], p[1] as string));
+assert.deepEqual(tm.getColor(0), '3');
+assert.deepEqual(tm.getColor(1), '2');
+assert.deepEqual(tm.getColor(2), '4');
+  });
+  test('Sets an instance of TMColors on setup.', async () => {
+const scopes = [
+  'variable',
+];
+const disp = await SemanticHighlighting.setupTMScopes(scopes, () => {});
+assert.notEqual(SemanticHighlighting.TMColorProvider.get().getColors(),
+undefined);
+disp.dispose();
+  });
+});
\ No newline at end of file
Index: clang-tools-extra/clangd/clients/clangd-vscode/src/TextMate.ts
===
--- /dev/null
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/TextMate.ts
@@ -0,0 +1,174 @@
+import * as fs from 'fs';
+import * as jsonc from "jsonc-parser";
+import * as path from 'path';
+import * as vscode from 'vscode';
+
+export namespace SemanticHighlighting {
+export class TMColors {
+  // The clangd tm scopes.
+  private scopes: string[];
+  // Mapping from a clangd scope index to a color hex string.
+  private colors: string[];
+  // The current best matching scope for every index.
+  private colorScopes: string[];
+  constructor(scopes: string[]) {
+this.scopes = scopes;
+this.colors = this.scopes.map(() => '#000');
+this.colorScopes = this.scopes.map(() => '');
+  }
+
+  setColor(scope: string|Array, color: string) {
+if (scope instanceof Array) {
+  scope.forEach((s: string) => this.setColor(s, color));
+  return;
+}
+
+// Find the associated clangd scope(s) index for this scope.
+// If "scope" is a candiate for a clangd scope the clangd scope must have
+// "scope" as a prefix.
+const allCandidates =
+this.scopes.map((s, i) => ({s : s, i : i}))
+.filter(({s}) => s.substr(0, scope.length) === scope);
+// If this scope is more specific than any of current scopes for the clangd
+// scopes it should be replaced. As both options are prefixes of the clangd
+// scope it's enough to compare lengths.
+allCandidates.forEach(({i}) => {
+  if (scope.length > this.colorScopes[i].length) {
+this.colorScopes[i] = scope;
+this.colors[i] = color;
+  }
+});
+  }
+
+  getColor(idx: number) { return this.colors[idx]; }
+}
+
+// Singleton for reading/writing TM scopes/colors.
+export class TMColorProvider {
+  private static instance: TMColorProvider = new TMColorProvider();
+  private colors: TMColors = undefined;
+  static get() { return TMColorProvider.instance; }
+
+  setColors(colors: TMColors) { this.colors = colors; }
+  getColors(): TMColors { return this.colors; }
+}
+
+/**
+ * @param scopes The TextMate scopes clangd sends on initialize.
+ * @param cb A callback that is called every time the theme changes and the new
+ * theme has been loaded (not called on the first load).
+ */
+export async function setupTMScopes(scopes: string[],
+cb: Function): Promise {
+  let oldThemeName = '';
+  async function setTMColors() {
+const name =
+vscode.workspace.getConfiguration('workbench').get('colorTheme');
+if (typeof name != 'string') {
+  console.warn('The current theme name is not a string, is: ' +
+   (ty

[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 213323.
jvikstrom marked 3 inline comments as done.
jvikstrom added a comment.
Herald added a subscriber: mgorny.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735

Files:
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp


Index: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
@@ -0,0 +1,57 @@
+//=- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp -=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+class CXXCtorInitializerVisitor
+: public ExpectedLocationVisitor {
+public:
+  CXXCtorInitializerVisitor(bool VisitImplicitCode)
+  : VisitImplicitCode(VisitImplicitCode) {}
+
+  bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
+
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return ExpectedLocationVisitor<
+CXXCtorInitializerVisitor>::TraverseConstructorInitializer(Init);
+  }
+
+  bool VisitedImplicitInitializer = false;
+
+private:
+  bool VisitImplicitCode;
+};
+
+// Check to ensure that CXXCtorInitializer is not visited when implicit code
+// should not be visited and that it is visited when implicit code should be
+// visited.
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  for (bool VisitImplCode : {true, false}) {
+CXXCtorInitializerVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {
+  C() : A() {}
+};
+  )cpp",
+CXXCtorInitializerVisitor::Lang_CXX));
+EXPECT_EQ(Visitor.VisitedImplicitInitializer, VisitImplCode);
+  }
+}
+} // end anonymous namespace
Index: clang/unittests/Tooling/CMakeLists.txt
===
--- clang/unittests/Tooling/CMakeLists.txt
+++ clang/unittests/Tooling/CMakeLists.txt
@@ -31,6 +31,7 @@
   RecursiveASTVisitorTests/CXXOperatorCallExprTraverser.cpp
   RecursiveASTVisitorTests/DeclRefExpr.cpp
   RecursiveASTVisitorTests/ImplicitCtor.cpp
+  RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
   RecursiveASTVisitorTests/InitListExprPostOrder.cpp
   RecursiveASTVisitorTests/InitListExprPostOrderNoQueue.cpp
   RecursiveASTVisitorTests/InitListExprPreOrder.cpp
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -2023,7 +2023,8 @@
   if (CXXConstructorDecl *Ctor = dyn_cast(D)) {
 // Constructor initializers.
 for (auto *I : Ctor->inits()) {
-  TRY_TO(TraverseConstructorInitializer(I));
+  if (I->isWritten() || getDerived().shouldVisitImplicitCode())
+TRY_TO(TraverseConstructorInitializer(I));
 }
   }
 


Index: clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
@@ -0,0 +1,57 @@
+//=- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp -=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+class CXXCtorInitializerVisitor
+: public ExpectedLocationVisitor {
+public:
+  CXXCtorInitializerVisitor(bool VisitImplicitCode)
+  : VisitImplicitCode(VisitImplicitCode) {}
+
+  bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
+
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return ExpectedLocationVisitor<
+CXXCtorInitializerVisitor>::Tr

[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom marked an inline comment as done.
jvikstrom added inline comments.



Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp:29
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());

ilya-biryukov wrote:
> NIT: alternatively use different match identifiers for written and unwritten 
> initializers:
> ```
> if (Init->isWritten())
>   Match("written-inititiazlier", ...);
> else
>   Match("implicit-initializer", ...);
> 
> ...
> TEST() {
>   Visitor.expectMatch("written-initializer");
>   Visitor.disallowMatch("implicit-initializer"); // would that work with 
> invalid source locs, though?
> }
> ```
> 
> This allows to reuse the mechanism used by other tests without extra code. 
> But up to you, definitely not a big deal.
disallowMatch requires a valid SourceLocation otherwise that would definitely 
be the way to do it.

Maybe that is something that should be added (the ability to disallow matches 
no matter what location) to ExpectedLocationVisitor?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735



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


[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp:26
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return ExpectedLocationVisitor<

is it intentional to run for case `!Init->IsWritten()` where the source 
location is invalid?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65735



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


[PATCH] D65387: [clangd] Add a callback mechanism for handling responses from client.

2019-08-05 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: clang-tools-extra/clangd/ClangdLSPServer.cpp:278
 ~ReplyOnce() {
-  if (Server && !Replied) {
+  if (Server && !Server->isDestructing() && !Replied) {
 elog("No reply to message {0}({1})", Method, ID);

sammccall wrote:
> Need a comment about the server being destroyed/unreplied calls case.
You've added a comment that repeats what the code does, please don't do that :-)

Instead, explain the context around this case. e.g.
"There's one legitimate reason to never reply to a request: clangd's request 
handler sent a call to the client (e.g. applyWorkspaceEdit) and the client 
never replied. In this case, the ReplyOnce is owned by ClangdServer's reply 
callback table and is destroyed along with the server. We don't attempt to send 
a reply in this case, there's little to be gained from doing so."



Comment at: clang-tools-extra/clangd/ClangdLSPServer.cpp:205
+  // Return a call id of the request.
+  int bindReply(Callback Reply) {
+llvm::Optional>> OldestCB;

nit: I think this function could return json::Value, encapsulating the fact 
that we use integers inside the MessageHandler class.

(Or does something outside the class depend on this?)



Comment at: clang-tools-extra/clangd/ClangdLSPServer.cpp:228
+OldestCB->first)));
+assert(ID != -1 && "ID must be set");
+return ID;

There's no complicated flow control around this - I'd suggest instead leaving 
ID uninitialized and letting msan flag this if it goes wrong.



Comment at: clang-tools-extra/clangd/ClangdLSPServer.cpp:317
   llvm::StringMap> Calls;
+  // The maximum number of callbacks hold in clangd.
+  //

"held" or "to hold"



Comment at: clang-tools-extra/clangd/ClangdLSPServer.cpp:321
+  // for cases where LSP clients don't reply for the request.
+  static constexpr int MaxCallbacks = 100;
+  mutable std::mutex CallMutex;

more specific name: MaxReplyCallbacks or even better MaxOutstandingCalls?



Comment at: clang-tools-extra/clangd/test/fixits-command.test:206
 ---
+{"jsonrpc":"2.0","id":0,"result":{"applied":true}}
+#  CHECK:  "id": 4,

this ID is reused



Comment at: clang-tools-extra/clangd/test/request-reply.test:28
+---
+{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{"command":"clangd.applyTweak","arguments":[{"file":"file:///clangd-test/main.cpp","selection":{"end":{"character":4,"line":0},"start":{"character":0,"line":0}},"tweakID":"ExpandAutoType"}]}}
+#  CHECK:  "id": 1,

ID reuse here (4 was previously used on line 6)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65387



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


[PATCH] D65665: Support for attributes on @class declarations

2019-08-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I don't think I know enough about ObjC semantics to say much about the language 
design aspects of this patch.




Comment at: clang/include/clang/Parse/Parser.h:1496
+  DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc,
+ ParsedAttributes &Attrs);
   Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,

Slight preference for using `ParsedAttributesWithRange` instead when making new 
interfaces -- we often need the range when trying to prohibit attributes in 
places, or for other diagnostic purposes.

However, this may not be feasible depending on where you're getting the 
attributes from (some parts of the parser are still unfortunately deficient in 
this regard).



Comment at: clang/lib/Parse/ParseObjc.cpp:124
 /// objc-class-declaration:
 ///'@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
 ///

Comment seems out of date now.



Comment at: clang/test/CodeGenObjC/objc-asm-attribute-test.m:78
 // CHECK: [[IVAR:%.*]] = load i64, i64* 
@"OBJC_IVAR_$_MySecretNamespace.Message.MyIVAR"
+

Can probably drop this spurious newline.



Comment at: clang/test/SemaObjC/attr-forward-class.m:11-12
+
+// FIXME: it'd be nice to point to the declaration with the attribute if its
+// inherited.
+@interface FwdDefined // expected-note{{introduced in macOS 1000 here}}

Do you have plans to fix this? If so, I'm fine with a FIXME for now, but I 
think the note is essentially a bug as it stands.



Comment at: clang/test/SemaObjC/attr-forward-class.m:27
+
+// expected-error@+1{{postfix attributes are not allowed on Objective-C 
directives}}
+@class __attribute__((availability(macos, introduced=1000))) InTheMiddle;

What is a "postfix attribute"? I would have assumed this was attempting to add 
a type attribute rather than a declaration attribute (based on the usual C and 
C++ semantics), so this diagnostic is a bit unhelpful.


Repository:
  rC Clang

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

https://reviews.llvm.org/D65665



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


[PATCH] D65735: [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
jvikstrom marked an inline comment as done.
Closed by commit rL367839: [AST] Fix RecursiveASTVisitor visiting implicit 
constructor initializers. (authored by jvikstrom, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65735?vs=213323&id=213329#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65735

Files:
  cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
  cfe/trunk/unittests/Tooling/CMakeLists.txt
  
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp


Index: cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
===
--- cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
+++ cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
@@ -2023,7 +2023,8 @@
   if (CXXConstructorDecl *Ctor = dyn_cast(D)) {
 // Constructor initializers.
 for (auto *I : Ctor->inits()) {
-  TRY_TO(TraverseConstructorInitializer(I));
+  if (I->isWritten() || getDerived().shouldVisitImplicitCode())
+TRY_TO(TraverseConstructorInitializer(I));
 }
   }
 
Index: 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
===
--- 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
+++ 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
@@ -0,0 +1,57 @@
+//=- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp -=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+class CXXCtorInitializerVisitor
+: public ExpectedLocationVisitor {
+public:
+  CXXCtorInitializerVisitor(bool VisitImplicitCode)
+  : VisitImplicitCode(VisitImplicitCode) {}
+
+  bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
+
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return ExpectedLocationVisitor<
+CXXCtorInitializerVisitor>::TraverseConstructorInitializer(Init);
+  }
+
+  bool VisitedImplicitInitializer = false;
+
+private:
+  bool VisitImplicitCode;
+};
+
+// Check to ensure that CXXCtorInitializer is not visited when implicit code
+// should not be visited and that it is visited when implicit code should be
+// visited.
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  for (bool VisitImplCode : {true, false}) {
+CXXCtorInitializerVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {
+  C() : A() {}
+};
+  )cpp",
+CXXCtorInitializerVisitor::Lang_CXX));
+EXPECT_EQ(Visitor.VisitedImplicitInitializer, VisitImplCode);
+  }
+}
+} // end anonymous namespace
Index: cfe/trunk/unittests/Tooling/CMakeLists.txt
===
--- cfe/trunk/unittests/Tooling/CMakeLists.txt
+++ cfe/trunk/unittests/Tooling/CMakeLists.txt
@@ -31,6 +31,7 @@
   RecursiveASTVisitorTests/CXXOperatorCallExprTraverser.cpp
   RecursiveASTVisitorTests/DeclRefExpr.cpp
   RecursiveASTVisitorTests/ImplicitCtor.cpp
+  RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
   RecursiveASTVisitorTests/InitListExprPostOrder.cpp
   RecursiveASTVisitorTests/InitListExprPostOrderNoQueue.cpp
   RecursiveASTVisitorTests/InitListExprPreOrder.cpp


Index: cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
===
--- cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
+++ cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
@@ -2023,7 +2023,8 @@
   if (CXXConstructorDecl *Ctor = dyn_cast(D)) {
 // Constructor initializers.
 for (auto *I : Ctor->inits()) {
-  TRY_TO(TraverseConstructorInitializer(I));
+  if (I->isWritten() || getDerived().shouldVisitImplicitCode())
+TRY_TO(TraverseConstructorInitializer(I));
 }
   }
 
Index: cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
===
--- cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
+++ cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
@@ -0,0

r367839 - [AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

2019-08-05 Thread Johan Vikstrom via cfe-commits
Author: jvikstrom
Date: Mon Aug  5 05:20:43 2019
New Revision: 367839

URL: http://llvm.org/viewvc/llvm-project?rev=367839&view=rev
Log:
[AST] Fix RecursiveASTVisitor visiting implicit constructor initializers.

Summary: RecursiveASTVisitor was visiting implcit constructor initializers. 
This caused semantic highlighting in clangd to emit error logs. Fixes this by 
checking if the constructor is written or if the visitor should visit implicit 
decls.

Reviewers: hokein, ilya-biryukov

Subscribers: kadircet, cfe-commits

Tags: #clang

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

Added:

cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
Modified:
cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
cfe/trunk/unittests/Tooling/CMakeLists.txt

Modified: cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/RecursiveASTVisitor.h?rev=367839&r1=367838&r2=367839&view=diff
==
--- cfe/trunk/include/clang/AST/RecursiveASTVisitor.h (original)
+++ cfe/trunk/include/clang/AST/RecursiveASTVisitor.h Mon Aug  5 05:20:43 2019
@@ -2023,7 +2023,8 @@ bool RecursiveASTVisitor::Trave
   if (CXXConstructorDecl *Ctor = dyn_cast(D)) {
 // Constructor initializers.
 for (auto *I : Ctor->inits()) {
-  TRY_TO(TraverseConstructorInitializer(I));
+  if (I->isWritten() || getDerived().shouldVisitImplicitCode())
+TRY_TO(TraverseConstructorInitializer(I));
 }
   }
 

Modified: cfe/trunk/unittests/Tooling/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/CMakeLists.txt?rev=367839&r1=367838&r2=367839&view=diff
==
--- cfe/trunk/unittests/Tooling/CMakeLists.txt (original)
+++ cfe/trunk/unittests/Tooling/CMakeLists.txt Mon Aug  5 05:20:43 2019
@@ -31,6 +31,7 @@ add_clang_unittest(ToolingTests
   RecursiveASTVisitorTests/CXXOperatorCallExprTraverser.cpp
   RecursiveASTVisitorTests/DeclRefExpr.cpp
   RecursiveASTVisitorTests/ImplicitCtor.cpp
+  RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
   RecursiveASTVisitorTests/InitListExprPostOrder.cpp
   RecursiveASTVisitorTests/InitListExprPostOrderNoQueue.cpp
   RecursiveASTVisitorTests/InitListExprPreOrder.cpp

Added: 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp?rev=367839&view=auto
==
--- 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
 (added)
+++ 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
 Mon Aug  5 05:20:43 2019
@@ -0,0 +1,57 @@
+//=- unittest/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp -=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+class CXXCtorInitializerVisitor
+: public ExpectedLocationVisitor {
+public:
+  CXXCtorInitializerVisitor(bool VisitImplicitCode)
+  : VisitImplicitCode(VisitImplicitCode) {}
+
+  bool shouldVisitImplicitCode() const { return VisitImplicitCode; }
+
+  bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
+if (!Init->isWritten())
+  VisitedImplicitInitializer = true;
+Match("initializer", Init->getSourceLocation());
+return ExpectedLocationVisitor<
+CXXCtorInitializerVisitor>::TraverseConstructorInitializer(Init);
+  }
+
+  bool VisitedImplicitInitializer = false;
+
+private:
+  bool VisitImplicitCode;
+};
+
+// Check to ensure that CXXCtorInitializer is not visited when implicit code
+// should not be visited and that it is visited when implicit code should be
+// visited.
+TEST(RecursiveASTVisitor, CXXCtorInitializerVisitNoImplicit) {
+  for (bool VisitImplCode : {true, false}) {
+CXXCtorInitializerVisitor Visitor(VisitImplCode);
+Visitor.ExpectMatch("initializer", 7, 17);
+EXPECT_TRUE(Visitor.runOver(R"cpp(
+class A {};
+class B : public A {
+  B() {};
+};
+class C : public A {
+  C() : A() {}
+};
+  )cpp",
+CXXCtorInitializerVisitor::Lang_CXX));
+EXPECT_EQ(Visitor.VisitedImplicitInitializer, VisitImplCode);
+  }
+}
+} // end anonymous namespace


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


r367840 - [clang][NFC] Remove unused private variable 'CI' in CrossTranslationUnit.h

2019-08-05 Thread Raphael Isemann via cfe-commits
Author: teemperor
Date: Mon Aug  5 05:23:39 2019
New Revision: 367840

URL: http://llvm.org/viewvc/llvm-project?rev=367840&view=rev
Log:
[clang][NFC] Remove unused private variable 'CI' in CrossTranslationUnit.h

It seems because of the recent refactorings this variable has become unused
and now we get this warning in the build logs:

In file included from llvm/clang/lib/CrossTU/CrossTranslationUnit.cpp:12:
llvm/clang/include/clang/CrossTU/CrossTranslationUnit.h:200:21: warning: 
private field 'CI' is not used [-Wunused-private-field]
  CompilerInstance &CI;
^

I'll remove them for now to get the builds back to green.

Modified:
cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp

Modified: cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h?rev=367840&r1=367839&r2=367840&view=diff
==
--- cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h (original)
+++ cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h Mon Aug  5 05:23:39 
2019
@@ -197,7 +197,6 @@ private:
 
   ImporterMapTy ASTUnitImporterMap;
 
-  CompilerInstance &CI;
   ASTContext &Context;
   std::shared_ptr ImporterSharedSt;
   /// Map of imported FileID's (in "To" context) to FileID in "From" context

Modified: cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp?rev=367840&r1=367839&r2=367840&view=diff
==
--- cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp (original)
+++ cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp Mon Aug  5 05:23:39 2019
@@ -188,7 +188,7 @@ template  static bool hasBod
 }
 
 CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
-: CI(CI), Context(CI.getASTContext()), ASTStorage(CI),
+: Context(CI.getASTContext()), ASTStorage(CI),
   CTULoadThreshold(CI.getAnalyzerOpts()->CTUImportThreshold) {}
 
 CrossTranslationUnitContext::~CrossTranslationUnitContext() {}


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


[PATCH] D65510: [clangd] Fix implicit template instatiations appearing as topLevelDecls.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 213331.
jvikstrom marked an inline comment as done.
jvikstrom added a comment.

Formatted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65510

Files:
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/ClangdUnit.cpp
  clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp


Index: clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
@@ -103,6 +103,20 @@
   EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
 }
 
+TEST(ClangdUnitTest, DoesNotGetImplicitTemplateTopDecls) {
+  TestTU TU;
+  TU.Code = R"cpp(
+template
+void f(T) {}
+void s() {
+  f(10UL);
+}
+  )cpp";
+  auto AST = TU.build();
+  EXPECT_THAT(AST.getLocalTopLevelDecls(),
+  ElementsAre(DeclNamed("f"), DeclNamed("s")));
+}
+
 TEST(ClangdUnitTest, TokensAfterPreamble) {
   TestTU TU;
   TU.AdditionalFiles["foo.h"] = R"(
Index: clang-tools-extra/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/clangd/ClangdUnit.cpp
+++ clang-tools-extra/clangd/ClangdUnit.cpp
@@ -19,8 +19,11 @@
 #include "index/CanonicalIncludes.h"
 #include "index/Index.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
@@ -60,6 +63,12 @@
   return Vec.capacity() * sizeof(T);
 }
 
+template  bool isImplicitTemplateInstantiation(const Decl *D) {
+  if (const auto *TD = dyn_cast(D))
+return TD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
+  return false;
+}
+
 class DeclTrackingASTConsumer : public ASTConsumer {
 public:
   DeclTrackingASTConsumer(std::vector &TopLevelDecls)
@@ -70,6 +79,10 @@
   auto &SM = D->getASTContext().getSourceManager();
   if (!isInsideMainFile(D->getLocation(), SM))
 continue;
+  if (isImplicitTemplateInstantiation(D) ||
+  isImplicitTemplateInstantiation(D) ||
+  isImplicitTemplateInstantiation(D))
+continue;
 
   // ObjCMethodDecl are not actually top-level decls.
   if (isa(D))
Index: clang-tools-extra/clangd/AST.h
===
--- clang-tools-extra/clangd/AST.h
+++ clang-tools-extra/clangd/AST.h
@@ -81,7 +81,7 @@
 /// Example: shortenNamespace("ns1::MyClass", "ns1")
 ///--> "MyClass"
 std::string  shortenNamespace(const llvm::StringRef OriginalName,
-  const llvm::StringRef CurrentNamespace);
+const llvm::StringRef CurrentNamespace);
 
 
 } // namespace clangd


Index: clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
@@ -103,6 +103,20 @@
   EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
 }
 
+TEST(ClangdUnitTest, DoesNotGetImplicitTemplateTopDecls) {
+  TestTU TU;
+  TU.Code = R"cpp(
+template
+void f(T) {}
+void s() {
+  f(10UL);
+}
+  )cpp";
+  auto AST = TU.build();
+  EXPECT_THAT(AST.getLocalTopLevelDecls(),
+  ElementsAre(DeclNamed("f"), DeclNamed("s")));
+}
+
 TEST(ClangdUnitTest, TokensAfterPreamble) {
   TestTU TU;
   TU.AdditionalFiles["foo.h"] = R"(
Index: clang-tools-extra/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/clangd/ClangdUnit.cpp
+++ clang-tools-extra/clangd/ClangdUnit.cpp
@@ -19,8 +19,11 @@
 #include "index/CanonicalIncludes.h"
 #include "index/Index.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
@@ -60,6 +63,12 @@
   return Vec.capacity() * sizeof(T);
 }
 
+template  bool isImplicitTemplateInstantiation(const Decl *D) {
+  if (const auto *TD = dyn_cast(D))
+return TD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
+  return false;
+}
+
 class DeclTrackingASTConsumer : public ASTConsumer {
 public:
   DeclTrackingASTConsumer(std::vector &TopLevelDecls)
@@ -70,6 +79,10 @@
   auto &SM = D->getASTContext().getSourceManager();
   if (!isInsideMainFile(D->getLocation(), SM))
 continue;
+

[PATCH] D65573: Add User docs for ASTImporter

2019-08-05 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 213332.
martong added a comment.

- Add description for `-ast-merge`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65573

Files:
  clang/docs/LibASTImporter.rst
  clang/docs/index.rst

Index: clang/docs/index.rst
===
--- clang/docs/index.rst
+++ clang/docs/index.rst
@@ -61,6 +61,7 @@
RAVFrontendAction
LibASTMatchersTutorial
LibASTMatchers
+   LibASTImporter
HowToSetupToolingForLLVM
JSONCompilationDatabase
RefactoringEngine
Index: clang/docs/LibASTImporter.rst
===
--- /dev/null
+++ clang/docs/LibASTImporter.rst
@@ -0,0 +1,613 @@
+===
+ASTImporter: Merging Clang ASTs
+===
+
+The ``ASTImporter`` class is part of Clang's core library, the AST library.
+It imports nodes of an ``ASTContext`` into another ``ASTContext``.
+
+In this document, we assume basic knowledge about the Clang AST.  See the :doc:`Introduction
+to the Clang AST ` if you want to learn more
+about how the AST is structured.
+Knowledge about :doc:`matching the Clang AST ` and the `reference for the matchers `_ are also useful.
+
+.. contents::
+   :local:
+
+Introduction
+
+
+``ASTContext`` holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic analysis of a file.
+In some cases it is preferable to work with more than one ``ASTContext``.
+For example, we'd like to parse multiple different files inside the same Clang tool.
+It may be convenient if we could view the set of the resulting ASTs as if they were one AST resulting from the parsing of each file together.
+``ASTImporter`` provides the way to copy types or declarations from one ``ASTContext`` to another.
+We refer to the context from which we import as the **"from" context** or *source context*; and the context into which we import as the **"to" context** or *destination context*.
+
+Existing clients of the ``ASTImporter`` library are Cross Translation Unit (CTU) static analysis and the LLDB expression parser.
+CTU static analysis imports a definition of a function if its definition is found in another translation unit (TU).
+This way the analysis can breach out from the single TU limitation.
+LLDB's ``expr`` command parses a user-defined expression, creates an ``ASTContext`` for that and then imports the missing definitions from the AST what we got from the debug information (DWARF, etc).
+
+Algorithm of the import
+---
+
+Importing one AST node copies that node into the destination ``ASTContext``.
+Why do we have to copy the node?
+Isn't enough to insert the pointer to that node into the destination context?
+One reason is that the "from" context may outlive the "to" context.
+Also, the Clang AST consider nodes (or certain properties of nodes) equivalent if they have the same address!
+
+The import algorithm has to ensure that the structurally equivalent nodes in the different translation units are not getting duplicated in the merged AST.
+E.g. if we include the definition of the vector template (``#include ``) in two translation units, then their merged AST should have only one node which represents the template.
+Also, we have to discover *one definition rule* (ODR) violations.
+For instance, if there is a class definition with the same name in both translation units, but one of the definition contains a different number of fields.
+So, we look up existing definitions, and then we check the structural equivalency on those nodes.
+The following pseudo-code demonstrates the basics of the import mechanism:
+
+.. code-block:: cpp
+
+  // Pseudo-code(!) of import:
+  ErrorOrDecl Import(Decl *FromD) {
+Decl *ToDecl = nullptr;
+FoundDeclsList = Look up all Decls in the "to" Ctx with the same name of FromD;
+for (auto FoundDecl : FoundDeclsList) {
+  if (StructurallyEquivalentDecls(FoundDecl, FromD)) {
+ToDecl = FoundDecl;
+Mark FromD as imported;
+break;
+  } else {
+Report ODR violation;
+return error;
+  }
+}
+if (FoundDeclsList is empty) {
+  Import dependent declarations and types of ToDecl;
+  ToDecl = create a new AST node in "to" Ctx;
+  Mark FromD as imported;
+}
+return ToDecl;
+  }
+
+Two AST nodes are *structurally equivalent* if they are
+
+- builtin types and refer to the same type, e.g. ``int`` and ``int`` are structurally equivalent,
+- function types and all their parameters have structurally equivalent types,
+- record types and all their fields in order of their definition have the same identifier names and structurally equivalent types,
+- variable or function declarations and they have the same identifier name and their 

[PATCH] D62829: [clang-tidy] Check for dynamically initialized statics in headers.

2019-08-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp:47
+void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus || getLangOpts().ThreadsafeStatics)
+return;

Why is this check disabled for C++? I would expect dynamic init of a static in 
a C++ header file would be flagged by this check.



Comment at: 
clang-tools-extra/test/clang-tidy/bugprone-dynamic-static-initializers.hpp:1
+// RUN: %check_clang_tidy %s bugprone-dynamic-static-initializers %t
+

I'm a bit confused.

1) Why is this file a .hpp if the check is currently supposed to be C-only?
2) Why are there no `#include` directives in the test if the check is supposed 
to only work on header files?

As best I can tell, this is a moral equivalent to doing: clang -x c whatever.h, 
and so this should be a compilation unit and not a header file. @alexfh, do you 
have thoughts there?


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

https://reviews.llvm.org/D62829



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


[PATCH] D65387: [clangd] Add a callback mechanism for handling responses from client.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 213334.
hokein marked 8 inline comments as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65387

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/test/fixits-command.test
  clang-tools-extra/clangd/test/request-reply.test

Index: clang-tools-extra/clangd/test/request-reply.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/request-reply.test
@@ -0,0 +1,43 @@
+# RUN: clangd -log=verbose -lit-test < %s | FileCheck -strict-whitespace %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":"auto i = 0;"}}}
+---
+{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{"command":"clangd.applyTweak","arguments":[{"file":"file:///clangd-test/main.cpp","selection":{"end":{"character":4,"line":0},"start":{"character":0,"line":0}},"tweakID":"ExpandAutoType"}]}}
+#  CHECK:  "id": 0,
+#  CHECK:  "method": "workspace/applyEdit",
+#  CHECK:  "newText": "int",
+# CHECK-NEXT:  "range": {
+# CHECK-NEXT:"end": {
+# CHECK-NEXT:  "character": 4,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:},
+# CHECK-NEXT:"start": {
+# CHECK-NEXT:  "character": 0,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:}
+# CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","id":0,"result":{"applied":false}}
+#  CHECK:  "error": {
+# CHECK-NEXT:"code": -32001,
+# CHECK-NEXT:"message": "edits were not applied: unknown reason"
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "id": 4,
+---
+{"jsonrpc":"2.0","id":5,"method":"workspace/executeCommand","params":{"command":"clangd.applyTweak","arguments":[{"file":"file:///clangd-test/main.cpp","selection":{"end":{"character":4,"line":0},"start":{"character":0,"line":0}},"tweakID":"ExpandAutoType"}]}}
+#  CHECK:  "id": 1,
+#  CHECK:  "method": "workspace/applyEdit",
+---
+{"jsonrpc":"2.0","id":1,"result":{"applied":true}}
+#  CHECK:  "id": 5,
+# CHECK-NEXT:  "jsonrpc": "2.0",
+# CHECK-NEXT:  "result": "Tweak applied."
+---
+# a reply with an invalid id.
+{"jsonrpc":"2.0","id":"invalid","result":{"applied":true}}
+# clangd doesn't reply, just emits an elog.
+---
+{"jsonrpc":"2.0","id":6,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: clang-tools-extra/clangd/test/fixits-command.test
===
--- clang-tools-extra/clangd/test/fixits-command.test
+++ clang-tools-extra/clangd/test/fixits-command.test
@@ -165,10 +165,6 @@
 # CHECK-NEXT:  ]
 ---
 {"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{"command":"clangd.applyFix","arguments":[{"changes":{"test:///foo.c":[{"range":{"start":{"line":0,"character":32},"end":{"line":0,"character":32}},"newText":"("},{"range":{"start":{"line":0,"character":37},"end":{"line":0,"character":37}},"newText":")"}]}}]}}
-#  CHECK:  "id": 4,
-# CHECK-NEXT:  "jsonrpc": "2.0",
-# CHECK-NEXT:  "result": "Fix applied."
-#
 #  CHECK:  "id": 0,
 # CHECK-NEXT:  "jsonrpc": "2.0",
 # CHECK-NEXT:  "method": "workspace/applyEdit",
@@ -207,6 +203,11 @@
 # CHECK-NEXT:}
 # CHECK-NEXT:  }
 ---
+{"jsonrpc":"2.0","id":0,"result":{"applied":true}}
+#  CHECK:  "id": 4,
+# CHECK-NEXT:  "jsonrpc": "2.0",
+# CHECK-NEXT:  "result": "Fix applied."
+---
 {"jsonrpc":"2.0","id":4,"method":"shutdown"}
 ---
 {"jsonrpc":"2.0","method":"exit"}
Index: clang-tools-extra/clangd/Protocol.h
===
--- clang-tools-extra/clangd/Protocol.h
+++ clang-tools-extra/clangd/Protocol.h
@@ -873,6 +873,12 @@
 };
 llvm::json::Value toJSON(const ApplyWorkspaceEditParams &);
 
+struct ApplyWorkspaceEditResponse {
+  bool applied = true;
+  llvm::Optional failureReason;
+};
+bool fromJSON(const llvm::json::Value &, ApplyWorkspaceEditResponse &);
+
 struct TextDocumentPositionParams {
   /// The text document.
   TextDocumentIdentifier textDocument;
Index: clang-tools-extra/clangd/Protocol.cpp
===
--- clang-tools-extra/clangd/Protocol.cpp
+++ clang-tools-extra/clangd/Protocol.cpp
@@ -670,6 +670,15 @@
   return llvm::json::Object{{"edit", Params.edit}};
 }
 
+bool fromJSON(const llvm::json::Value &Response,
+  ApplyWorkspaceEditResponse &R) {
+  llvm::json::ObjectMapper O(Response);
+  if (!O || !O.map("applied", R.applied))
+return false;
+  O.map("failureReason", R.failureReason);
+  return true;
+}
+
 bool fromJSON(const llvm::json::Value 

[PATCH] D65387: [clangd] Add a callback mechanism for handling responses from client.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/ClangdLSPServer.cpp:205
+  // Return a call id of the request.
+  int bindReply(Callback Reply) {
+llvm::Optional>> OldestCB;

sammccall wrote:
> nit: I think this function could return json::Value, encapsulating the fact 
> that we use integers inside the MessageHandler class.
> 
> (Or does something outside the class depend on this?)
we just use it for logging, changing it to Value is totally fine.



Comment at: clang-tools-extra/clangd/test/fixits-command.test:206
 ---
+{"jsonrpc":"2.0","id":0,"result":{"applied":true}}
+#  CHECK:  "id": 4,

sammccall wrote:
> this ID is reused
this ID is not reused, it is for server request `applyEdit` (see line `168`).



Comment at: clang-tools-extra/clangd/test/request-reply.test:28
+---
+{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{"command":"clangd.applyTweak","arguments":[{"file":"file:///clangd-test/main.cpp","selection":{"end":{"character":4,"line":0},"start":{"character":0,"line":0}},"tweakID":"ExpandAutoType"}]}}
+#  CHECK:  "id": 1,

sammccall wrote:
> ID reuse here (4 was previously used on line 6)
good catch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65387



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


[PATCH] D65387: [clangd] Add a callback mechanism for handling responses from client.

2019-08-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/test/fixits-command.test:206
 ---
+{"jsonrpc":"2.0","id":0,"result":{"applied":true}}
+#  CHECK:  "id": 4,

hokein wrote:
> sammccall wrote:
> > this ID is reused
> this ID is not reused, it is for server request `applyEdit` (see line `168`).
Doh, sorry :-(


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65387



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


[clang-tools-extra] r367845 - [clangd] Add a callback mechanism for handling responses from client.

2019-08-05 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Aug  5 05:48:09 2019
New Revision: 367845

URL: http://llvm.org/viewvc/llvm-project?rev=367845&view=rev
Log:
[clangd] Add a callback mechanism for handling responses from client.

Summary:
The callback will be invoked in clangd when we receive a reply from the client.

This is a prerequisite of implementing a generic mechanism for chainable
refactorings (e.g. extract variable and rename), this would allow server to
trigger a new request to the LSP client after receiving a reply from the client.

Reviewers: sammccall

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

Tags: #clang

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

Added:
clang-tools-extra/trunk/clangd/test/request-reply.test
Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/clangd/test/fixits-command.test

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=367845&r1=367844&r2=367845&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Mon Aug  5 05:48:09 2019
@@ -146,11 +146,39 @@ public:
   bool onReply(llvm::json::Value ID,
llvm::Expected Result) override {
 WithContext HandlerContext(handlerContext());
-// We ignore replies, just log them.
-if (Result)
+
+Callback ReplyHandler = nullptr;
+if (auto IntID = ID.getAsInteger()) {
+  std::lock_guard Mutex(CallMutex);
+  // Find a corresponding callback for the request ID;
+  for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
+if (ReplyCallbacks[Index].first == *IntID) {
+  ReplyHandler = std::move(ReplyCallbacks[Index].second);
+  ReplyCallbacks.erase(ReplyCallbacks.begin() +
+   Index); // remove the entry
+  break;
+}
+  }
+}
+
+if (!ReplyHandler) {
+  // No callback being found, use a default log callback.
+  ReplyHandler = [&ID](llvm::Expected Result) {
+elog("received a reply with ID {0}, but there was no such call", ID);
+if (!Result)
+  llvm::consumeError(Result.takeError());
+  };
+}
+
+// Log and run the reply handler.
+if (Result) {
   log("<-- reply({0})", ID);
-else
-  log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
+  ReplyHandler(std::move(Result));
+} else {
+  auto Err = Result.takeError();
+  log("<-- reply({0}) error: {1}", ID, Err);
+  ReplyHandler(std::move(Err));
+}
 return true;
   }
 
@@ -171,6 +199,35 @@ public:
 };
   }
 
+  // Bind a reply callback to a request. The callback will be invoked when
+  // clangd receives the reply from the LSP client.
+  // Return a call id of the request.
+  llvm::json::Value bindReply(Callback Reply) {
+llvm::Optional>> OldestCB;
+int ID;
+{
+  std::lock_guard Mutex(CallMutex);
+  ID = NextCallID++;
+  ReplyCallbacks.emplace_back(ID, std::move(Reply));
+
+  // If the queue overflows, we assume that the client didn't reply the
+  // oldest request, and run the corresponding callback which replies an
+  // error to the client.
+  if (ReplyCallbacks.size() > MaxReplayCallbacks) {
+elog("more than {0} outstanding LSP calls, forgetting about {1}",
+ MaxReplayCallbacks, ReplyCallbacks.front().first);
+OldestCB = std::move(ReplyCallbacks.front());
+ReplyCallbacks.pop_front();
+  }
+}
+if (OldestCB)
+  OldestCB->second(llvm::createStringError(
+  llvm::inconvertibleErrorCode(),
+  llvm::formatv("failed to receive a client reply for request ({0})",
+OldestCB->first)));
+return ID;
+  }
+
   // Bind an LSP method name to a notification.
   template 
   void bind(const char *Method,
@@ -220,7 +277,13 @@ private:
 ReplyOnce &operator=(const ReplyOnce &) = delete;
 
 ~ReplyOnce() {
-  if (Server && !Replied) {
+  // There's one legitimate reason to never reply to a request: clangd's
+  // request handler send a call to the client (e.g. applyEdit) and the
+  // client never replied. In this case, the ReplyOnce is owned by
+  // ClangdLSPServer's reply callback table and is destroyed along with the
+  // server. We don't attempt to send a reply in this case, there's little
+  // to be gained from doing so.
+  if (Server && !Server->IsBeingDestroyed && !Replied) {
 elog("No reply to message {0}({1})", Method, ID);
 assert(false && "must reply to all calls!");
 (*this)(llvm::make_error("server 

[PATCH] D65387: [clangd] Add a callback mechanism for handling responses from client.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL367845: [clangd] Add a callback mechanism for handling 
responses from client. (authored by hokein, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65387?vs=213334&id=213337#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65387

Files:
  clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
  clang-tools-extra/trunk/clangd/ClangdLSPServer.h
  clang-tools-extra/trunk/clangd/Protocol.cpp
  clang-tools-extra/trunk/clangd/Protocol.h
  clang-tools-extra/trunk/clangd/test/fixits-command.test
  clang-tools-extra/trunk/clangd/test/request-reply.test

Index: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
@@ -146,11 +146,39 @@
   bool onReply(llvm::json::Value ID,
llvm::Expected Result) override {
 WithContext HandlerContext(handlerContext());
-// We ignore replies, just log them.
-if (Result)
+
+Callback ReplyHandler = nullptr;
+if (auto IntID = ID.getAsInteger()) {
+  std::lock_guard Mutex(CallMutex);
+  // Find a corresponding callback for the request ID;
+  for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
+if (ReplyCallbacks[Index].first == *IntID) {
+  ReplyHandler = std::move(ReplyCallbacks[Index].second);
+  ReplyCallbacks.erase(ReplyCallbacks.begin() +
+   Index); // remove the entry
+  break;
+}
+  }
+}
+
+if (!ReplyHandler) {
+  // No callback being found, use a default log callback.
+  ReplyHandler = [&ID](llvm::Expected Result) {
+elog("received a reply with ID {0}, but there was no such call", ID);
+if (!Result)
+  llvm::consumeError(Result.takeError());
+  };
+}
+
+// Log and run the reply handler.
+if (Result) {
   log("<-- reply({0})", ID);
-else
-  log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
+  ReplyHandler(std::move(Result));
+} else {
+  auto Err = Result.takeError();
+  log("<-- reply({0}) error: {1}", ID, Err);
+  ReplyHandler(std::move(Err));
+}
 return true;
   }
 
@@ -171,6 +199,35 @@
 };
   }
 
+  // Bind a reply callback to a request. The callback will be invoked when
+  // clangd receives the reply from the LSP client.
+  // Return a call id of the request.
+  llvm::json::Value bindReply(Callback Reply) {
+llvm::Optional>> OldestCB;
+int ID;
+{
+  std::lock_guard Mutex(CallMutex);
+  ID = NextCallID++;
+  ReplyCallbacks.emplace_back(ID, std::move(Reply));
+
+  // If the queue overflows, we assume that the client didn't reply the
+  // oldest request, and run the corresponding callback which replies an
+  // error to the client.
+  if (ReplyCallbacks.size() > MaxReplayCallbacks) {
+elog("more than {0} outstanding LSP calls, forgetting about {1}",
+ MaxReplayCallbacks, ReplyCallbacks.front().first);
+OldestCB = std::move(ReplyCallbacks.front());
+ReplyCallbacks.pop_front();
+  }
+}
+if (OldestCB)
+  OldestCB->second(llvm::createStringError(
+  llvm::inconvertibleErrorCode(),
+  llvm::formatv("failed to receive a client reply for request ({0})",
+OldestCB->first)));
+return ID;
+  }
+
   // Bind an LSP method name to a notification.
   template 
   void bind(const char *Method,
@@ -220,7 +277,13 @@
 ReplyOnce &operator=(const ReplyOnce &) = delete;
 
 ~ReplyOnce() {
-  if (Server && !Replied) {
+  // There's one legitimate reason to never reply to a request: clangd's
+  // request handler send a call to the client (e.g. applyEdit) and the
+  // client never replied. In this case, the ReplyOnce is owned by
+  // ClangdLSPServer's reply callback table and is destroyed along with the
+  // server. We don't attempt to send a reply in this case, there's little
+  // to be gained from doing so.
+  if (Server && !Server->IsBeingDestroyed && !Replied) {
 elog("No reply to message {0}({1})", Method, ID);
 assert(false && "must reply to all calls!");
 (*this)(llvm::make_error("server failed to reply",
@@ -255,6 +318,16 @@
 
   llvm::StringMap> Notifications;
   llvm::StringMap> Calls;
+  // The maximum number of callbacks held in clangd.
+  //
+  // We bound the maximum size to the pending map to prevent memory leakage
+  // for cases where LSP clients don't reply for the request.
+  static constexpr int MaxReplayCallbacks = 100;
+  mutable std::mutex CallMutex;
+  int NextCallID = 0; /* GUARDED_BY(CallMutex) */
+  s

[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

2019-08-05 Thread Lingda Li via Phabricator via cfe-commits
lildmh updated this revision to Diff 213339.
lildmh added a comment.

Fix declare mapper codegen test when the function argument has name attached.


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

https://reviews.llvm.org/D59474

Files:
  include/clang/AST/GlobalDecl.h
  lib/AST/ASTContext.cpp
  lib/CodeGen/CGDecl.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/ModuleBuilder.cpp
  test/OpenMP/declare_mapper_codegen.cpp

Index: test/OpenMP/declare_mapper_codegen.cpp
===
--- test/OpenMP/declare_mapper_codegen.cpp
+++ test/OpenMP/declare_mapper_codegen.cpp
@@ -1,92 +1,414 @@
-///==///
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap  %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s
-// RUN: %clang_cc1 -verify -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s
-
-// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap  --check-prefix SIMD-ONLY0 %s
-// RUN: %clang_cc1 -fopenmp-simd -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp-simd -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap  --check-prefix SIMD-ONLY0 %s
-// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap  --check-prefix SIMD-ONLY0 %s
-// RUN: %clang_cc1 -fopenmp-simd -fopenmp-targets=i386-pc-linux-gnu -x c++ -std=c++11 -triple i386-unknown-unknown -emit-pch -o %t %s
-// RUN: %clang_cc1 -fopenmp-simd -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap  --check-prefix SIMD-ONLY0 %s
-
 // SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
 
 // expected-no-diagnostics
 #ifndef HEADER
 #define HEADER
 
+///==///
+// RUN: %clang_cc1 -DCK0 -verify -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm -femit-all-decls -disable-llvm-passes %s -o - | FileCheck --check-prefix CK0 --check-prefix CK0-64 %s
+// RUN: %clang_cc1 -DCK0 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -femit-all-decls -disable-llvm-passes -o %t %s
+// RUN: %clang_cc1 -DCK0 -fopenmp -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -femit-all-decls -disable-llvm-passes -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix CK0 --check-prefix CK0-64 %s
+// RUN: %clang_cc1 -DCK0 -verify -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -emit-llvm -femit-all-decls -disable-llvm-passes %s -o - | FileCheck --check-prefix CK0 --check-prefix CK0-32 %s
+// RUN: %clang_cc1 -DCK0 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -std=c++11 -triple i386-unknown-unknown -emit-pch -femit-all-decls -disable-llvm-passes -o %t %s
+// RUN: %clang_cc1 -DCK0 -fopenmp -fopenmp-targets=i386-pc-linux-gnu -x c++ -triple i386-unknown-unknown -std=c++11 -femit-all-decls -disable-llvm-passes -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix CK0 --check-prefix CK0-32 %s
+
+// RUN: %clang_cc1 -DCK0 -verify -fopenmp-simd -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -triple powerpc64le-unknown-unknown -emit-llvm -femit-all-decls -disable-llvm-passes %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -DCK0 -fopenmp-simd -fopenmp-targets=powerpc64le-ibm-linux-gnu -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -femit-all-decls -disable-llvm-passes -o %t %s
+// RUN: %clang_

[PATCH] D65706: [docs] Better documentation for -Weverything

2019-08-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/docs/UsersManual.rst:999-1000
+diagnostics contradict each other, users of :option:`-Weverything` therefore
+often disable many diagnostics such as :option:`-Wno-c++98-compat`
+:option:`-Wno-c++-compat`.
+

jfb wrote:
> aaron.ballman wrote:
> > Would you care to propose a more exhaustive list of conflicting 
> > diagnostics? (Perhaps in a follow-up patch.)
> I looked a bit and I'm worried that providing a list won't be particularly 
> satisfying for people looking at this. I think it's better to have some 
> warning, and let folks figure out what works for their particular situation. 
> Here I'm assuming that they don't use C++98 and that seems reasonable, but 
> figuring out what side of contradictions they're on doesn't seem like it'll 
> work out.
One of the primary concerns with enabling `-Weverything` is the fact that we 
know this enables conflicting diagnostics. Telling the user "we know there are 
conflicting diagnostics, but we want you to have the joy of figuring out which 
ones conflict for yourself" seems even more unsatisfying, to me. I agree that 
we don't want to tell users which of the conflicting options they should 
disable, but was thinking of something more along the lines of:
```
The following sets of options are known to have some possibly unfortunate 
interactions when enabled together:
  * -Wfoo, -Wbar
  * -Wbaz, -Wquux
  * ...
Note that there may be other conflicting diagnostic flags not listed above.
```
I figure that gives users a bit more of an idea of what they're signing up for 
when they enable -Weverything, which seems useful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65706



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


Re: r367675 - [OpenCL] Allow OpenCL C style vector initialization in C++

2019-08-05 Thread Yvan Roux via cfe-commits
On Mon, 5 Aug 2019 at 13:16, Anastasia Stulova
 wrote:
>
> Hi Yvan,
>
>
> Sorry for this, it should now be fixed  in r367823.

Issue fixed, Thanks Anastasia

>
> Thanks,
>
> Anastasia
>
>
>
> 
> From: Yvan Roux 
> Sent: 02 August 2019 14:09
> To: Anastasia Stulova 
> Cc: cfe-commits 
> Subject: Re: r367675 - [OpenCL] Allow OpenCL C style vector initialization in 
> C++
>
> Hi Anastasia,
>
> This commit broke ARMv8 bots, logs are available here:
>
> http://lab.llvm.org:8011/builders/clang-cmake-armv8-quick/builds/14655/steps/ninja%20check%201/logs/FAIL%3A%20Clang%3A%3Avector_literals_valid.cl
>
> Thanks,
> Yvan
>
> On Fri, 2 Aug 2019 at 13:18, Anastasia Stulova via cfe-commits
>  wrote:
> >
> > Author: stulova
> > Date: Fri Aug  2 04:19:35 2019
> > New Revision: 367675
> >
> > URL: http://llvm.org/viewvc/llvm-project?rev=367675&view=rev
> > Log:
> > [OpenCL] Allow OpenCL C style vector initialization in C++
> >
> > Allow creating vector literals from other vectors.
> >
> >  float4 a = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
> >  float4 v = (float4)(a.s23, a.s01);
> >
> > Differential revision: https://reviews.llvm.org/D65286
> >
> >
> > Removed:
> > cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl
> > cfe/trunk/test/SemaOpenCL/vector_literals_const.cl
> > Modified:
> > cfe/trunk/lib/Sema/SemaInit.cpp
> > cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl
> > cfe/trunk/test/SemaCXX/vector.cpp
> >
> > Modified: cfe/trunk/lib/Sema/SemaInit.cpp
> > URL: 
> > http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=367675&r1=367674&r2=367675&view=diff
> > ==
> > --- cfe/trunk/lib/Sema/SemaInit.cpp (original)
> > +++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  2 04:19:35 2019
> > @@ -1289,7 +1289,16 @@ void InitListChecker::CheckSubElementTyp
> >  // FIXME: Better EqualLoc?
> >  InitializationKind Kind =
> >  InitializationKind::CreateCopy(expr->getBeginLoc(), 
> > SourceLocation());
> > -InitializationSequence Seq(SemaRef, Entity, Kind, expr,
> > +
> > +// Vector elements can be initialized from other vectors in which case
> > +// we need initialization entity with a type of a vector (and not a 
> > vector
> > +// element!) initializing multiple vector elements.
> > +auto TmpEntity =
> > +(ElemType->isExtVectorType() && 
> > !Entity.getType()->isExtVectorType())
> > +? InitializedEntity::InitializeTemporary(ElemType)
> > +: Entity;
> > +
> > +InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
> > /*TopLevelOfInitList*/ true);
> >
> >  // C++14 [dcl.init.aggr]p13:
> > @@ -1300,8 +1309,7 @@ void InitListChecker::CheckSubElementTyp
> >  // assignment-expression.
> >  if (Seq || isa(expr)) {
> >if (!VerifyOnly) {
> > -ExprResult Result =
> > -  Seq.Perform(SemaRef, Entity, Kind, expr);
> > +ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
> >  if (Result.isInvalid())
> >hadError = true;
> >
> >
> > Removed: cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl
> > URL: 
> > http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl?rev=367674&view=auto
> > ==
> > --- cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl (original)
> > +++ cfe/trunk/test/CodeGenOpenCL/vector_literals_nested.cl (removed)
> > @@ -1,23 +0,0 @@
> > -// RUN: %clang_cc1 %s -emit-llvm -O3 -o - | FileCheck %s
> > -
> > -typedef int int2 __attribute((ext_vector_type(2)));
> > -typedef int int4 __attribute((ext_vector_type(4)));
> > -
> > -__constant const int4 itest1 = (int4)(1, 2, ((int2)(3, 4)));
> > -// CHECK: constant <4 x i32> 
> > -__constant const int4 itest2 = (int4)(1, 2, ((int2)(3)));
> > -// CHECK: constant <4 x i32> 
> > -
> > -typedef float float2 __attribute((ext_vector_type(2)));
> > -typedef float float4 __attribute((ext_vector_type(4)));
> > -
> > -void ftest1(float4 *p) {
> > -  *p = (float4)(1.1f, 1.2f, ((float2)(1.3f, 1.4f)));
> > -// CHECK: store <4 x float>  > 0x3FF34000, float 0x3FF4C000, float 0x3FF66000>
> > -}
> > -
> > -float4 ftest2(float4 *p) {
> > -   *p =  (float4)(1.1f, 1.2f, ((float2)(1.3f)));
> > -// CHECK: store <4 x float>  > 0x3FF34000, float 0x3FF4C000, float 0x3FF4C000>
> > -}
> > -
> >
> > Modified: cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl
> > URL: 
> > http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl?rev=367675&r1=367674&r2=367675&view=diff
> > ==
> > --- cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl (original)
> > +++ cfe/trunk/test/CodeGenOpenCL/vector_literals_valid.cl Fri Aug  2 

[PATCH] D65744: [PR42707][OpenCL] Fix addr space deduction for auto

2019-08-05 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia created this revision.
Anastasia added a reviewer: rjmccall.
Herald added subscribers: ebevhan, yaxunl.

A regression was introduced in D64400  because 
auto is using the same logic as templates. However, deduction of addr spaces 
wasn't working correctly even before.

Here are the rules that are implemented in this patch:

- For non-reference and non-pointer types deduction can be done early because 
addr space is not going to be taken from init expr
- For ref or ptr auto types we should prevent deducing addr space before the 
deduction of the whole type (incl its pointee addr spaces) from init expr


https://reviews.llvm.org/D65744

Files:
  include/clang/AST/Type.h
  lib/Sema/SemaType.cpp
  lib/Sema/TreeTransform.h
  test/SemaOpenCLCXX/addrspace-auto.cl

Index: test/SemaOpenCLCXX/addrspace-auto.cl
===
--- /dev/null
+++ test/SemaOpenCLCXX/addrspace-auto.cl
@@ -0,0 +1,31 @@
+//RUN: %clang_cc1 %s -cl-std=clc++ -pedantic -ast-dump -verify | FileCheck %s
+
+kernel void test(){
+  int i;
+//CHECK: VarDecl {{.*}} ai 'int':'int'
+  auto ai = i;
+
+  constexpr int c = 1;
+//CHECK: VarDecl {{.*}} used cai '__constant int':'__constant int'
+  __constant auto cai = c;
+//CHECK: VarDecl {{.*}} aii 'int':'int'
+  auto aii = cai;
+
+//CHECK: VarDecl {{.*}} ref 'int &'
+  auto& ref = i;
+//CHECK: VarDecl {{.*}} ptr 'int *'
+  auto* ptr = &i;
+//CHECK: VarDecl {{.*}} ref_c '__constant int &'
+  auto& ref_c = cai;
+
+//CHECK: VarDecl {{.*}} ptrptr 'int **'
+  auto ** ptrptr = &ptr;
+//CHECK: VarDecl {{.*}} refptr 'int *&'
+  auto *& refptr = ptr;
+
+//CHECK: VarDecl {{.*}} invalid gref '__global auto &'
+  __global auto& gref = i; //expected-error{{variable 'gref' with type '__global auto &' has incompatible initializer of type 'int'}}
+  __local int* ptr_l;
+//CHECK: VarDecl {{.*}} invalid gptr '__global auto *'
+  __global auto* gptr = ptr_l; //expected-error{{variable 'gptr' with type '__global auto *' has incompatible initializer of type '__local int *'}}
+}
Index: lib/Sema/TreeTransform.h
===
--- lib/Sema/TreeTransform.h
+++ lib/Sema/TreeTransform.h
@@ -4538,8 +4538,17 @@
 
 /// Helper to deduce addr space of a pointee type in OpenCL mode.
 /// If the type is updated it will be overwritten in PointeeType param.
-static void deduceOpenCLPointeeAddrSpace(Sema &SemaRef, QualType &PointeeType) {
-  if (PointeeType.getAddressSpace() == LangAS::Default)
+static void deduceOpenCLPointeeAddrSpace(Sema &SemaRef, QualType &PointeeType,
+ QualType TLT) {
+  // Prevent deducing addr space for auto because it will be taken from
+  // the initializing expression.
+  bool IsAuto = false;
+  auto Pointee = TLT->getPointeeType();
+  do {
+IsAuto = Pointee->isAutoType();
+Pointee = Pointee->getPointeeType();
+  }  while (!Pointee.isNull());
+  if (!IsAuto && PointeeType.getAddressSpace() == LangAS::Default)
 PointeeType = SemaRef.Context.getAddrSpaceQualType(PointeeType,
LangAS::opencl_generic);
 }
@@ -4553,7 +4562,7 @@
 return QualType();
 
   if (SemaRef.getLangOpts().OpenCL)
-deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
+deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType, TL.getType());
 
   QualType Result = TL.getType();
   if (PointeeType->getAs()) {
@@ -4594,7 +4603,7 @@
 return QualType();
 
   if (SemaRef.getLangOpts().OpenCL)
-deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
+deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType, TL.getType());
 
   QualType Result = TL.getType();
   if (getDerived().AlwaysRebuild() ||
@@ -4626,7 +4635,7 @@
 return QualType();
 
   if (SemaRef.getLangOpts().OpenCL)
-deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
+deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType, TL.getType());
 
   QualType Result = TL.getType();
   if (getDerived().AlwaysRebuild() ||
Index: lib/Sema/SemaType.cpp
===
--- lib/Sema/SemaType.cpp
+++ lib/Sema/SemaType.cpp
@@ -7398,6 +7398,17 @@
   bool IsFuncType =
   ChunkIndex < D.getNumTypeObjects() &&
   D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
+  bool IsAutoPointee = false;
+  if (State.getSema().getLangOpts().OpenCLCPlusPlus){
+// Detect if pointer or reference are part of auto type.
+if (T->isPointerType() || T->isReferenceType()) {
+  auto Pointee = T->getPointeeType();
+  do {
+IsAutoPointee = Pointee->isAutoType();
+Pointee = Pointee->getPointeeType();
+  } while (!Pointee.isNull());
+}
+  }
   if ( // Do not deduce addr space for function return type and function type,
// otherwise it will fail some sema check.
   IsFuncReturnType || IsFuncType ||
@@ -7425,6 +7436,9 @@
   // Do not deduce addr space 

r367864 - Move LangStandard*, InputKind::Language to Basic

2019-08-05 Thread Rainer Orth via cfe-commits
Author: ro
Date: Mon Aug  5 06:59:26 2019
New Revision: 367864

URL: http://llvm.org/viewvc/llvm-project?rev=367864&view=rev
Log:
Move LangStandard*, InputKind::Language to Basic

This patch is a prerequisite for using LangStandard from Driver in
https://reviews.llvm.org/D64793.

It moves LangStandard* and InputKind::Language to Basic.  It is mostly
mechanical, with only a few changes of note:

- enum Language has been changed into enum class Language : uint8_t to
  avoid a clash between OpenCL in enum Language and OpenCL in enum
  LangFeatures and not to increase the size of class InputKind.

- Now that getLangStandardForName, which is currently unused, also checks
  both canonical and alias names, I've introduced a helper getLangKind
  which factors out a code pattern already used 3 times.

The patch has been tested on x86_64-pc-solaris2.11, sparcv9-sun-solaris2.11,
and x86_64-pc-linux-gnu.

There's a companion patch for lldb which uses LangStandard.h
(https://reviews.llvm.org/D65717).

While polly includes isl which in turn uses InputKind::C, that part of the
code isn't even built inside the llvm tree.  I've posted a patch to allow
for both InputKind::C and Language::C upstream
(https://groups.google.com/forum/#!topic/isl-development/6oEvNWOSQFE).

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

Added:
cfe/trunk/include/clang/Basic/LangStandard.h
  - copied, changed from r367863, 
cfe/trunk/include/clang/Frontend/LangStandard.h
cfe/trunk/include/clang/Basic/LangStandards.def
  - copied, changed from r367863, 
cfe/trunk/include/clang/Frontend/LangStandards.def
cfe/trunk/lib/Basic/LangStandards.cpp
  - copied, changed from r367863, cfe/trunk/lib/Frontend/LangStandards.cpp
Removed:
cfe/trunk/include/clang/Frontend/LangStandard.h
cfe/trunk/include/clang/Frontend/LangStandards.def
cfe/trunk/lib/Frontend/LangStandards.cpp
Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/include/clang/Frontend/CompilerInvocation.h
cfe/trunk/include/clang/Frontend/FrontendOptions.h
cfe/trunk/include/clang/module.modulemap
cfe/trunk/lib/Basic/CMakeLists.txt
cfe/trunk/lib/CodeGen/CodeGenAction.cpp
cfe/trunk/lib/Frontend/ASTUnit.cpp
cfe/trunk/lib/Frontend/CMakeLists.txt
cfe/trunk/lib/Frontend/CompilerInstance.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/lib/Frontend/FrontendAction.cpp
cfe/trunk/lib/Frontend/FrontendActions.cpp
cfe/trunk/lib/Frontend/FrontendOptions.cpp
cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
cfe/trunk/lib/Frontend/Rewrite/FrontendActions.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
cfe/trunk/lib/Tooling/InterpolatingCompilationDatabase.cpp
cfe/trunk/unittests/Frontend/CodeGenActionTest.cpp
cfe/trunk/unittests/Frontend/FrontendActionTest.cpp
cfe/trunk/unittests/Frontend/OutputStreamTest.cpp

Copied: cfe/trunk/include/clang/Basic/LangStandard.h (from r367863, 
cfe/trunk/include/clang/Frontend/LangStandard.h)
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/LangStandard.h?p2=cfe/trunk/include/clang/Basic/LangStandard.h&p1=cfe/trunk/include/clang/Frontend/LangStandard.h&r1=367863&r2=367864&rev=367864&view=diff
==
--- cfe/trunk/include/clang/Frontend/LangStandard.h (original)
+++ cfe/trunk/include/clang/Basic/LangStandard.h Mon Aug  5 06:59:26 2019
@@ -6,16 +6,37 @@
 //
 
//===--===//
 
-#ifndef LLVM_CLANG_FRONTEND_LANGSTANDARD_H
-#define LLVM_CLANG_FRONTEND_LANGSTANDARD_H
+#ifndef LLVM_CLANG_BASIC_LANGSTANDARD_H
+#define LLVM_CLANG_BASIC_LANGSTANDARD_H
 
 #include "clang/Basic/LLVM.h"
-#include "clang/Frontend/FrontendOptions.h"
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
 
-namespace frontend {
+/// The language for the input, used to select and validate the language
+/// standard and possible actions.
+enum class Language : uint8_t {
+  Unknown,
+
+  /// Assembly: we accept this only so that we can preprocess it.
+  Asm,
+
+  /// LLVM IR: we accept this so that we can run the optimizer on it,
+  /// and compile it to assembly or object code.
+  LLVM_IR,
+
+  ///@{ Languages that the frontend can parse and compile.
+  C,
+  CXX,
+  ObjC,
+  ObjCXX,
+  OpenCL,
+  CUDA,
+  RenderScript,
+  HIP,
+  ///@}
+};
 
 enum LangFeatures {
   LineComment = (1 << 0),
@@ -35,22 +56,20 @@ enum LangFeatures {
   OpenCL = (1 << 14)
 };
 
-}
-
 /// LangStandard - Information about the properties of a particular language
 /// standard.
 struct LangStandard {
   enum Kind {
 #define LANGSTANDARD(id, name, lang, desc, features) \
 lang_##id,
-#include "clang/Frontend/LangStandards.def"
+#include "clang/Basic/LangStandards.def"
 lang_unspecified
   };
 
   const char *ShortName;
   const char *Description;
   unsigned Flags;
-  InputKind::Language Language;
+  clang::Language Language;

[PATCH] D65562: Move LangStandard*, InputKind::Language to Basic

2019-08-05 Thread Rainer Orth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL367864: Move LangStandard*, InputKind::Language to Basic 
(authored by ro, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65562?vs=213243&id=213351#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65562

Files:
  cfe/trunk/include/clang/Basic/LangStandard.h
  cfe/trunk/include/clang/Basic/LangStandards.def
  cfe/trunk/include/clang/Driver/Options.td
  cfe/trunk/include/clang/Frontend/CompilerInvocation.h
  cfe/trunk/include/clang/Frontend/FrontendOptions.h
  cfe/trunk/include/clang/Frontend/LangStandard.h
  cfe/trunk/include/clang/Frontend/LangStandards.def
  cfe/trunk/include/clang/module.modulemap
  cfe/trunk/lib/Basic/CMakeLists.txt
  cfe/trunk/lib/Basic/LangStandards.cpp
  cfe/trunk/lib/CodeGen/CodeGenAction.cpp
  cfe/trunk/lib/Frontend/ASTUnit.cpp
  cfe/trunk/lib/Frontend/CMakeLists.txt
  cfe/trunk/lib/Frontend/CompilerInstance.cpp
  cfe/trunk/lib/Frontend/CompilerInvocation.cpp
  cfe/trunk/lib/Frontend/FrontendAction.cpp
  cfe/trunk/lib/Frontend/FrontendActions.cpp
  cfe/trunk/lib/Frontend/FrontendOptions.cpp
  cfe/trunk/lib/Frontend/LangStandards.cpp
  cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
  cfe/trunk/lib/Frontend/Rewrite/FrontendActions.cpp
  cfe/trunk/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
  cfe/trunk/lib/Tooling/InterpolatingCompilationDatabase.cpp
  cfe/trunk/unittests/Frontend/CodeGenActionTest.cpp
  cfe/trunk/unittests/Frontend/FrontendActionTest.cpp
  cfe/trunk/unittests/Frontend/OutputStreamTest.cpp

Index: cfe/trunk/lib/Basic/CMakeLists.txt
===
--- cfe/trunk/lib/Basic/CMakeLists.txt
+++ cfe/trunk/lib/Basic/CMakeLists.txt
@@ -50,6 +50,7 @@
   FixedPoint.cpp
   IdentifierTable.cpp
   LangOptions.cpp
+  LangStandards.cpp
   Module.cpp
   ObjCRuntime.cpp
   OpenMPKinds.cpp
Index: cfe/trunk/lib/Basic/LangStandards.cpp
===
--- cfe/trunk/lib/Basic/LangStandards.cpp
+++ cfe/trunk/lib/Basic/LangStandards.cpp
@@ -0,0 +1,45 @@
+//===--- LangStandards.cpp - Language Standard Definitions ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Basic/LangStandard.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/ErrorHandling.h"
+using namespace clang;
+
+#define LANGSTANDARD(id, name, lang, desc, features)   \
+  static const LangStandard Lang_##id = {name, desc, features, Language::lang};
+#include "clang/Basic/LangStandards.def"
+
+const LangStandard &LangStandard::getLangStandardForKind(Kind K) {
+  switch (K) {
+  case lang_unspecified:
+llvm::report_fatal_error("getLangStandardForKind() on unspecified kind");
+#define LANGSTANDARD(id, name, lang, desc, features) \
+case lang_##id: return Lang_##id;
+#include "clang/Basic/LangStandards.def"
+  }
+  llvm_unreachable("Invalid language kind!");
+}
+
+LangStandard::Kind LangStandard::getLangKind(StringRef Name) {
+  return llvm::StringSwitch(Name)
+#define LANGSTANDARD(id, name, lang, desc, features) .Case(name, lang_##id)
+#define LANGSTANDARD_ALIAS(id, alias) .Case(alias, lang_##id)
+#include "clang/Basic/LangStandards.def"
+  .Default(lang_unspecified);
+}
+
+const LangStandard *LangStandard::getLangStandardForName(StringRef Name) {
+  Kind K = getLangKind(Name);
+  if (K == lang_unspecified)
+return nullptr;
+
+  return &getLangStandardForKind(K);
+}
+
+
Index: cfe/trunk/lib/Frontend/CompilerInvocation.cpp
===
--- cfe/trunk/lib/Frontend/CompilerInvocation.cpp
+++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp
@@ -18,6 +18,7 @@
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Basic/LangStandard.h"
 #include "clang/Basic/ObjCRuntime.h"
 #include "clang/Basic/Sanitizers.h"
 #include "clang/Basic/SourceLocation.h"
@@ -34,7 +35,6 @@
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/FrontendOptions.h"
 #include "clang/Frontend/FrontendPluginRegistry.h"
-#include "clang/Frontend/LangStandard.h"
 #include "clang/Frontend/MigratorOptions.h"
 #include "clang/Frontend/PreprocessorOutputOptions.h"
 #include "clang/Frontend/Utils.h"
@@ -122,7 +122,7 @@
 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
  DiagnosticsEngine &Diags) {
   unsigned DefaultOpt = llvm::CodeGenOpt::None;
-  if (IK.getLanguage() == InputKind::OpenCL && 

Re: r367829 - [CrossTU][NFCI] Refactor loadExternalAST function

2019-08-05 Thread Nico Weber via cfe-commits
The msan bot doesn't like this, it reports an uninitialized read a
t clang/lib/CrossTU/CrossTranslationUnit.cpp :

http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-fast/builds/34087/steps/check-clang%20msan/logs/stdio


Testing: 0
FAIL: Clang :: Analysis/ctu-unknown-parts-in-triples.cpp (492 of 15321)
 TEST 'Clang ::
Analysis/ctu-unknown-parts-in-triples.cpp' FAILED 
Script:
--
: 'RUN: at line 4';   rm -rf
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp
&& mkdir
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp
: 'RUN: at line 5';   mkdir -p
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir
: 'RUN: at line 6';
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/bin/clang -cc1
-internal-isystem
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/lib/clang/10.0.0/include
-nostdsysteminc -triple x86_64-pc-linux-gnu-emit-pch -o
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir/ctu-other.cpp.ast
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/Inputs/ctu-other.cpp
: 'RUN: at line 8';   cp
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir/externalDefMap.txt
: 'RUN: at line 9';
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/bin/clang -cc1
-internal-isystem
/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/lib/clang/10.0.0/include
-nostdsysteminc -analyze -analyzer-constraints=range -triple
x86_64-unknown-linux-gnu-analyzer-checker=core,debug.ExprInspection
 -analyzer-config experimental-enable-naive-ctu-analysis=true
 -analyzer-config
ctu-dir=/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir
   -Werror=ctu-verify
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/ctu-unknown-parts-in-triples.cpp
--
Exit Code: 77

Command Output (stderr):
--
==5072==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0xb05c3c4 in
clang::cross_tu::CrossTranslationUnitContext::loadExternalAST(llvm::StringRef,
llvm::StringRef, llvm::StringRef, bool)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:467:7
#1 0xb053a98 in llvm::Expected
clang::cross_tu::CrossTranslationUnitContext::getCrossTUDefinitionImpl(clang::FunctionDecl
const*, llvm::StringRef, llvm::StringRef, bool)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:241:7
#2 0xb053466 in
clang::cross_tu::CrossTranslationUnitContext::getCrossTUDefinition(clang::FunctionDecl
const*, llvm::StringRef, llvm::StringRef, bool)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:307:10
#3 0xadb69f5 in clang::ento::AnyFunctionCall::getRuntimeDefinition()
const
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CallEvent.cpp:575:14

On Mon, Aug 5, 2019 at 7:05 AM Endre Fulop via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: gamesh411
> Date: Mon Aug  5 04:06:41 2019
> New Revision: 367829
>
> URL: http://llvm.org/viewvc/llvm-project?rev=367829&view=rev
> Log:
> [CrossTU][NFCI] Refactor loadExternalAST function
>
> Summary:
> Refactor loadExternalAST method of CrossTranslationUnitContext in order to
> reduce maintenance burden and so that features are easier to add in the
> future.
>
> Reviewers: martong
>
> Subscribers: rnkovacs, dkrupp, Szelethus, cfe-commits
>
> Tags: #clang
>
> Differential Revision: https://reviews.llvm.org/D64753
>
> Modified:
> cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
> cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp
>
> Modified: cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h?rev=367829&r1=367828&r2=367829&view=diff
>
> ==
> --- cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h (original)
> +++ cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h Mon Aug  5
> 04:06:41 2019
> @@ -192,11 +192,11 @@ private:
>template 
>llvm::Expected importDefinitionImpl(const T *D, ASTUnit
> *Unit);
>
> -  llvm::StringMap> FileASTUnitMap;
> -  llvm::StringMap NameASTUnitMap;
> -  llvm::StringMap NameFileMap;
> -  llvm::DenseMap>
> -  ASTUnitImporterMap;
> +  using ImporterMapTy =
> +  llvm::DenseMap>;
> +
> +  ImporterMapTy ASTUnitImporterMap;
> +
>CompilerInstance &CI;
>ASTContext &C

r367866 - [Driver] Properly use values-X[ca].o, values-xpg[46].o on Solaris

2019-08-05 Thread Rainer Orth via cfe-commits
Author: ro
Date: Mon Aug  5 07:06:16 2019
New Revision: 367866

URL: http://llvm.org/viewvc/llvm-project?rev=367866&view=rev
Log:
[Driver] Properly use values-X[ca].o, values-xpg[46].o on Solaris

Builtins-*-sunos :: compiler_rt_logbf_test.c currently FAILs on Solaris, both 
SPARC and
x86, 32 and 64-bit.

It turned out that this is due to different behaviour of logb depending on the C
standard compiled for, as documented on logb(3M):

  RETURN VALUES
 Upon successful completion, these functions return the exponent of x.
  
 If x is subnormal:
  
 o  For SUSv3-conforming applications compiled with the c99 com-
piler  driver  (see standards(7)), the exponent of x as if x
were normalized is returned.
  
 o  Otherwise, if compiled with the cc compiler  driver,  -1022,
-126,  and  -16382  are  returned  for  logb(), logbf(), and
logbl(), respectively.

Studio c99 and gcc control this by linking with the appropriate version of 
values-xpg[46].o, but clang uses neither of those.

The following patch fixes this by following what gcc does, as corrected some 
time ago in

  Fix use of Solaris values-Xc.o (PR target/40411)
  https://gcc.gnu.org/ml/gcc-patches/2018-01/msg02350.html and
  https://gcc.gnu.org/ml/gcc-patches/2018-01/msg02384.html.

Tested on x86_64-pc-solaris2.11, sparcv9-sun-solaris2.11, and 
x86_64-pc-linux-gnu.

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

Added:
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-Xa.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-Xc.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-xpg4.o
cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-xpg6.o
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/values-Xa.o
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/values-Xc.o
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/values-xpg4.o
cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/values-xpg6.o
cfe/trunk/test/Driver/solaris-ld-values.c
cfe/trunk/test/Driver/solaris-ld-values.cpp
Modified:
cfe/trunk/lib/Driver/ToolChains/Solaris.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/Solaris.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Solaris.cpp?rev=367866&r1=367865&r2=367866&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Solaris.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Solaris.cpp Mon Aug  5 07:06:16 2019
@@ -8,6 +8,7 @@
 
 #include "Solaris.h"
 #include "CommonArgs.h"
+#include "clang/Basic/LangStandard.h"
 #include "clang/Config/config.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
@@ -86,8 +87,28 @@ void solaris::Linker::ConstructJob(Compi
   Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
 
 
CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
+
+const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
+bool HaveAnsi = false;
+const LangStandard *LangStd = nullptr;
+if (Std) {
+  HaveAnsi = Std->getOption().matches(options::OPT_ansi);
+  if (!HaveAnsi)
+LangStd = LangStandard::getLangStandardForName(Std->getValue());
+}
+
+const char *values_X = "values-Xa.o";
+// Use values-Xc.o for -ansi, -std=c*, -std=iso9899:199409.
+if (HaveAnsi || (LangStd && !LangStd->isGNUMode()))
+  values_X = "values-Xc.o";
+
CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(values_X)));
+
+const char *values_xpg = "values-xpg6.o";
+// Use values-xpg4.o for -std=c90, -std=gnu90, -std=iso9899:199409.
+if (LangStd && LangStd->getLanguage() == Language::C && !LangStd->isC99())
+  values_xpg = "values-xpg4.o";
 CmdArgs.push_back(
-Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
+Args.MakeArgString(getToolChain().GetFilePath(values_xpg)));
 CmdArgs.push_back(
 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
   }

Added: cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-Xa.o
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-Xa.o?rev=367866&view=auto
==
(empty)

Added: cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-Xc.o
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-Xc.o?rev=367866&view=auto
==
(empty)

Added: cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-xpg4.o
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-xpg4.o?rev=367866&

[PATCH] D64793: [Driver] Properly use values-X[ca].o, values-xpg[46].o on Solaris

2019-08-05 Thread Rainer Orth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL367866: [Driver] Properly use values-X[ca].o, 
values-xpg[46].o on Solaris (authored by ro, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D64793?vs=212993&id=213355#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D64793

Files:
  cfe/trunk/lib/Driver/ToolChains/Solaris.cpp
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-Xa.o
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-Xc.o
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-xpg4.o
  cfe/trunk/test/Driver/Inputs/solaris_sparc_tree/usr/lib/values-xpg6.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/values-Xa.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/values-Xc.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/values-xpg4.o
  cfe/trunk/test/Driver/Inputs/solaris_x86_tree/usr/lib/values-xpg6.o
  cfe/trunk/test/Driver/solaris-ld-values.c
  cfe/trunk/test/Driver/solaris-ld-values.cpp

Index: cfe/trunk/lib/Driver/ToolChains/Solaris.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Solaris.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Solaris.cpp
@@ -8,6 +8,7 @@
 
 #include "Solaris.h"
 #include "CommonArgs.h"
+#include "clang/Basic/LangStandard.h"
 #include "clang/Config/config.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
@@ -86,8 +87,28 @@
   Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
 
 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
+
+const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
+bool HaveAnsi = false;
+const LangStandard *LangStd = nullptr;
+if (Std) {
+  HaveAnsi = Std->getOption().matches(options::OPT_ansi);
+  if (!HaveAnsi)
+LangStd = LangStandard::getLangStandardForName(Std->getValue());
+}
+
+const char *values_X = "values-Xa.o";
+// Use values-Xc.o for -ansi, -std=c*, -std=iso9899:199409.
+if (HaveAnsi || (LangStd && !LangStd->isGNUMode()))
+  values_X = "values-Xc.o";
+CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(values_X)));
+
+const char *values_xpg = "values-xpg6.o";
+// Use values-xpg4.o for -std=c90, -std=gnu90, -std=iso9899:199409.
+if (LangStd && LangStd->getLanguage() == Language::C && !LangStd->isC99())
+  values_xpg = "values-xpg4.o";
 CmdArgs.push_back(
-Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
+Args.MakeArgString(getToolChain().GetFilePath(values_xpg)));
 CmdArgs.push_back(
 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
   }
Index: cfe/trunk/test/Driver/solaris-ld-values.c
===
--- cfe/trunk/test/Driver/solaris-ld-values.c
+++ cfe/trunk/test/Driver/solaris-ld-values.c
@@ -0,0 +1,77 @@
+// General tests that the correct versions of values-*.o are used on
+// Solaris targets sane. Note that we use sysroot to make these tests
+// independent of the host system.
+
+// Check sparc-sun-solaris2.11, 32bit
+// RUN: %clang -no-canonical-prefixes -ansi %s -### -o %t.o 2>&1 \
+// RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --gcc-toolchain="" \
+// RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-LD-SPARC32-ANSI %s
+// CHECK-LD-SPARC32-ANSI: values-Xc.o
+// CHECK-LD-SPARC32-ANSI: values-xpg6.o
+
+// RUN: %clang -no-canonical-prefixes -std=c89 %s -### -o %t.o 2>&1 \
+// RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --gcc-toolchain="" \
+// RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-LD-SPARC32-C89 %s
+// CHECK-LD-SPARC32-C89: values-Xc.o
+// CHECK-LD-SPARC32-C89: values-xpg4.o
+
+// RUN: %clang -no-canonical-prefixes -std=c90 %s -### -o %t.o 2>&1 \
+// RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --gcc-toolchain="" \
+// RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-LD-SPARC32-C90 %s
+// CHECK-LD-SPARC32-C90: values-Xc.o
+// CHECK-LD-SPARC32-C90: values-xpg4.o
+
+// RUN: %clang -no-canonical-prefixes -std=iso9899:199409 %s -### -o %t.o 2>&1 \
+// RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --gcc-toolchain="" \
+// RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-LD-SPARC32-C94 %s
+// CHECK-LD-SPARC32-C94: values-Xc.o
+// CHECK-LD-SPARC32-C94: values-xpg4.o
+
+// RUN: %clang -no-canonical-prefixes -std=c11 %s -### -o %t.o 2>&1 \
+// RUN: --target=sparc-sun-solaris2.11 \
+// RUN: --gcc-toolchain="" \
+// RUN: --sysroot=%S/Inputs/solaris_sparc_tree \
+// RUN:   | FileCheck --check-prefix=CHECK-L

[PATCH] D65065: [clang-tidy] Possibility of displaying duplicate warnings

2019-08-05 Thread Tibor Brunner via Phabricator via cfe-commits
bruntib updated this revision to Diff 213356.
bruntib edited the summary of this revision.

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D65065

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/test/clang-tidy/duplicate-reports.cpp


Index: clang-tools-extra/test/clang-tidy/duplicate-reports.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/duplicate-reports.cpp
@@ -0,0 +1,19 @@
+// RUN: %check_clang_tidy %s cert-err09-cpp,cert-err61-cpp %t
+
+void alwaysThrows() {
+  int ex = 42;
+  // At this location both cert-err09-cpp and cert-err61-cpp report the
+  // message. The order of the reports is unknown, that's why the checker name
+  // is not included in the expected warning.
+
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous 
temporary values instead
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous 
temporary values instead
+  throw ex;
+}
+
+void doTheJob() {
+  try {
+alwaysThrows();
+  } catch (int&) {
+  }
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -742,8 +742,9 @@
 const tooling::DiagnosticMessage &M1 = LHS.Message;
 const tooling::DiagnosticMessage &M2 = RHS.Message;
 
-return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
-   std::tie(M2.FilePath, M2.FileOffset, M2.Message);
+return
+  std::tie(M1.FilePath, M1.FileOffset, LHS.DiagnosticName, M1.Message) <
+  std::tie(M2.FilePath, M2.FileOffset, RHS.DiagnosticName, M2.Message);
   }
 };
 struct EqualClangTidyError {


Index: clang-tools-extra/test/clang-tidy/duplicate-reports.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/duplicate-reports.cpp
@@ -0,0 +1,19 @@
+// RUN: %check_clang_tidy %s cert-err09-cpp,cert-err61-cpp %t
+
+void alwaysThrows() {
+  int ex = 42;
+  // At this location both cert-err09-cpp and cert-err61-cpp report the
+  // message. The order of the reports is unknown, that's why the checker name
+  // is not included in the expected warning.
+
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead
+  throw ex;
+}
+
+void doTheJob() {
+  try {
+alwaysThrows();
+  } catch (int&) {
+  }
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -742,8 +742,9 @@
 const tooling::DiagnosticMessage &M1 = LHS.Message;
 const tooling::DiagnosticMessage &M2 = RHS.Message;
 
-return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
-   std::tie(M2.FilePath, M2.FileOffset, M2.Message);
+return
+  std::tie(M1.FilePath, M1.FileOffset, LHS.DiagnosticName, M1.Message) <
+  std::tie(M2.FilePath, M2.FileOffset, RHS.DiagnosticName, M2.Message);
   }
 };
 struct EqualClangTidyError {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D65065: [clang-tidy] Possibility of displaying duplicate warnings

2019-08-05 Thread Tibor Brunner via Phabricator via cfe-commits
bruntib added a comment.

Alright, I modified the commit accordingly. Thank you for the suggestions.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D65065



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


[PATCH] D65043: [Format] Add C++20 standard to style options

2019-08-05 Thread Brian Gesiak via Phabricator via cfe-commits
modocache updated this revision to Diff 213360.
modocache added a comment.

Thanks for the reviews, @sammccall, @Quuxplusone, and @MyDeveloperDay. I added 
C++14 and C++17 options. In an earlier comment I mentioned splitting this work 
up into a series of commits, but it ended up being a smaller set of changes 
than I thought, so I'll just update this diff with all of the changes. What do 
you all think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65043

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3794,10 +3794,13 @@
   "if (aa.aa(\n"
   "aa) == 5) {\n"
   "}");
+
+  FormatStyle Cpp2a = getLLVMStyle();
+  Cpp2a.Standard = FormatStyle::LS_Cpp2a;
   verifyFormat(
   "if (a(\n"
   "aa) <=> 5) {\n"
-  "}");
+  "}", Cpp2a);
   // Even explicit parentheses stress the precedence enough to make the
   // additional break unnecessary.
   verifyFormat("if ((a +\n"
@@ -3820,7 +3823,7 @@
   verifyFormat("if (a +\n"
"aa <=>\n"
"5) {\n"
-   "}");
+   "}", Cpp2a);
 
   FormatStyle OnePerLine = getLLVMStyle();
   OnePerLine.BinPackParameters = false;
@@ -11830,8 +11833,14 @@
   Style.Standard = FormatStyle::LS_Auto;
   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Cpp11);
+  CHECK_PARSE("Standard: Cpp14", Standard, FormatStyle::LS_Cpp14);
+  CHECK_PARSE("Standard: Cpp17", Standard, FormatStyle::LS_Cpp17);
+  CHECK_PARSE("Standard: Cpp2a", Standard, FormatStyle::LS_Cpp2a);
   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
+  CHECK_PARSE("Standard: C++14", Standard, FormatStyle::LS_Cpp14);
+  CHECK_PARSE("Standard: C++17", Standard, FormatStyle::LS_Cpp17);
+  CHECK_PARSE("Standard: C++2a", Standard, FormatStyle::LS_Cpp2a);
   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
 
   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
@@ -13761,6 +13770,19 @@
   verifyFormat("auto const &[ a, b ] = f();", Spaces);
 }
 
+TEST_F(FormatTest, Coroutines) {
+  FormatStyle Cpp2a = getLLVMStyle();
+  Cpp2a.Standard = FormatStyle::LS_Cpp2a;
+
+  // 'co_yield' is treated as an identifier in standards below C++2a, and so
+  // the increment is interpreted as a postfix on that identifier.
+  // In C++2a, it is interpreted as a prefix increment on 'i'.
+  verifyFormat("co_yield++ i;");
+  verifyFormat("co_yield ++i;", Cpp2a);
+
+  verifyFormat("co_await []() { co_return; }();", Cpp2a);
+}
+
 TEST_F(FormatTest, FileAndCode) {
   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2860,7 +2860,7 @@
 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
   return !Style.Cpp11BracedListStyle;
 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
-   (Style.Standard < FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
+   (Style.Standard == FormatStyle::LS_Cpp03 || Style.SpacesInAngles);
   }
   if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
   Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
@@ -2879,7 +2879,7 @@
 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
   if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
 return (Left.is(TT_TemplateOpener) &&
-Style.Standard < FormatStyle::LS_Cpp11) ||
+Style.Standard == FormatStyle::LS_Cpp03) ||
!(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
   tok::kw___super, TT_TemplateCloser,
   TT_TemplateOpener)) ||
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -71,6 +71,12 @@
 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);

[PATCH] D65510: [clangd] Fix implicit template instatiations appearing as topLevelDecls.

2019-08-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/ClangdUnit.cpp:68
+  if (const auto *TD = dyn_cast(D))
+return TD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
+  return false;

jvikstrom wrote:
> ilya-biryukov wrote:
> > hokein wrote:
> > > ilya-biryukov wrote:
> > > > We also want to skip `TSK_ExplicitInstantiationDeclaration` and  
> > > > `TSK_ExplicitInstantiationDefinition` here.
> > > > This covers cases like (not sure which one of the two enum values we 
> > > > get, though):
> > > > ```
> > > > template 
> > > > int foo(T) { ... }
> > > > 
> > > > template int foo(int); // we'd rather not traverse these, highlightings 
> > > > will run into the same problems.
> > > > ```
> > > > 
> > > > Semantics I'm describing are roughly similar to 
> > > > `isImplicitInstatiation(D) == !isExplicitInstantion(D)`, where 
> > > > `isExplicitInstantiation` is taken from `CodeComplete.cpp`. (If we 
> > > > ignore `TSK_Undeclared`, which, I believe, should never be encountered 
> > > > in decls passed to HandleTopLevelDecl).
> > > > 
> > > > Please extract the helper from code complete and this one into a 
> > > > separate file (e.g. `clangd/AST.h`) and possibly implement one through 
> > > > the other
> > > > Semantics I'm describing are roughly similar to 
> > > > isImplicitInstatiation(D) == !isExplicitInstantion(D), 
> > > 
> > > I think there is a typo here, I believe you mean 
> > > `isImplicitInstantiation(D) == !isExplicitSpecialization(D) ` (in 
> > > CodeComplete.cpp, it checks whether a Decl is an explicit 
> > > **specialization**).
> > Yes, there's a typo thanks!
> Still want me to move this and the helper from CodeComplete to `AST.h` as it 
> isn't used anywhere else? (esp. when we can't implement them through of each 
> other)
Yes, it's better to share this code between `codeComplete` and `ClangdUnit`. It 
might pop up in more places and it's not trivial.



Comment at: clang-tools-extra/clangd/ClangdUnit.cpp:82
 continue;
+  if (isImplicitTemplateInstantiation(D) ||
+  isImplicitTemplateInstantiation(D) ||

Could we expose the following non-template function instead?
```
bool isImplicitTemplateInstantiation(NamedDecl *);
```

So that the users don't need to specify which `Decl` they are interested in (I 
believe there's no use for it anyway)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65510



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


[PATCH] D65510: [clangd] Fix implicit template instatiations appearing as topLevelDecls.

2019-08-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/ClangdUnit.cpp:68
+  if (const auto *TD = dyn_cast(D))
+return TD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
+  return false;

ilya-biryukov wrote:
> jvikstrom wrote:
> > ilya-biryukov wrote:
> > > hokein wrote:
> > > > ilya-biryukov wrote:
> > > > > We also want to skip `TSK_ExplicitInstantiationDeclaration` and  
> > > > > `TSK_ExplicitInstantiationDefinition` here.
> > > > > This covers cases like (not sure which one of the two enum values we 
> > > > > get, though):
> > > > > ```
> > > > > template 
> > > > > int foo(T) { ... }
> > > > > 
> > > > > template int foo(int); // we'd rather not traverse these, 
> > > > > highlightings will run into the same problems.
> > > > > ```
> > > > > 
> > > > > Semantics I'm describing are roughly similar to 
> > > > > `isImplicitInstatiation(D) == !isExplicitInstantion(D)`, where 
> > > > > `isExplicitInstantiation` is taken from `CodeComplete.cpp`. (If we 
> > > > > ignore `TSK_Undeclared`, which, I believe, should never be 
> > > > > encountered in decls passed to HandleTopLevelDecl).
> > > > > 
> > > > > Please extract the helper from code complete and this one into a 
> > > > > separate file (e.g. `clangd/AST.h`) and possibly implement one 
> > > > > through the other
> > > > > Semantics I'm describing are roughly similar to 
> > > > > isImplicitInstatiation(D) == !isExplicitInstantion(D), 
> > > > 
> > > > I think there is a typo here, I believe you mean 
> > > > `isImplicitInstantiation(D) == !isExplicitSpecialization(D) ` (in 
> > > > CodeComplete.cpp, it checks whether a Decl is an explicit 
> > > > **specialization**).
> > > Yes, there's a typo thanks!
> > Still want me to move this and the helper from CodeComplete to `AST.h` as 
> > it isn't used anywhere else? (esp. when we can't implement them through of 
> > each other)
> Yes, it's better to share this code between `codeComplete` and `ClangdUnit`. 
> It might pop up in more places and it's not trivial.
Sorry, I mean **share functions from the same place** between code complete and 
clangd unit.
They might not be implementable through each other, but they are very similar 
and having them in the same place means that we will have easier time keeping 
them both correct in case we need to change any of them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65510



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


[PATCH] D65738: [clangd] Added a TextMate theme parser that updates when the current theme changes.

2019-08-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Haven't looked at the patch in details.

Looks like the patch is doing different things, and the test just covers a 
small set of the code.

1. find and parse the theme definition files `json` ;
2. define related data structures to save the TM scopes and do the 
transformation;
3. handle changes of the theme;

could we narrow it further? I think we could just implement 1) for this patch.




Comment at: clang-tools-extra/clangd/clients/clangd-vscode/src/TextMate.ts:11
+  // Mapping from a clangd scope index to a color hex string.
+  private colors: string[];
+  // The current best matching scope for every index.

The `color` word here is ambiguous -- we have different colors in 
DecorationRenderOptions, e.g. `color`, `backgroundColor`, `borderColor`, I 
believe you meant `color`, maybe we could just a more descriptive name, like 
`highlightColor`, or `TextColor`? 

I think we may want to use a structure here (`color` is one of the field), so 
that the code is extensible to support more options in  
`DecorationRenderOptions`.



Comment at: clang-tools-extra/clangd/clients/clangd-vscode/src/TextMate.ts:12
+  private colors: string[];
+  // The current best matching scope for every index.
+  private colorScopes: string[];

what does the `index` mean here?



Comment at: clang-tools-extra/clangd/clients/clangd-vscode/src/TextMate.ts:119
+// Gets a TextMate theme by its name and all its included themes.
+async function getFullNamedTheme(themeName: string): Promise {
+  const extension =

I think we may define a type/interface (like `TokenColorRule`) for the entries 
(tokenColors) in the theme file, and have a function that parsing the content 
and returning an array of `TokenColorRule`?





Comment at: clang-tools-extra/clangd/clients/clangd-vscode/src/TextMate.ts:148
+const contents = await readFileText(fullPath);
+const parsed = jsonc.parse(contents);
+if (parsed.include)

note that `json` is one of the theme format files, vscode also supports 
`.tmTheme`. We probably don't support `tmTheme` for now (just add a fixme).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65738



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


[PATCH] D65752: [Sema] Refactor LookupVisibleDecls. NFC

2019-08-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: sammccall.
Herald added subscribers: kadircet, arphaman, jkorous.
Herald added a project: clang.

We accumulated some configuration parameters for LookupVisibleDecls that
are being passed unchanged to recursive calls, e.g. LoadExternal and
IncludeDependentBases.

At the same time, there is a bunch of parameters that can change in the
recursive invocations.

It is hard to tell the difference between those groups, making the code
hard to follow.

This change introduces a helper struct and factors out the non-changing
bits into fields, making recursive calls in the implementation code easier
to read.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D65752

Files:
  clang-tools-extra/clangd/IncludeFixer.cpp
  clang/lib/Sema/SemaLookup.cpp

Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -3609,328 +3609,344 @@
   return nullptr;
 }
 
-static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
-   bool QualifiedNameLookup,
-   bool InBaseClass,
-   VisibleDeclConsumer &Consumer,
-   VisibleDeclsRecord &Visited,
-   bool IncludeDependentBases,
-   bool LoadExternal) {
-  if (!Ctx)
-return;
-
-  // Make sure we don't visit the same context twice.
-  if (Visited.visitedContext(Ctx->getPrimaryContext()))
-return;
-
-  Consumer.EnteredContext(Ctx);
-
-  // Outside C++, lookup results for the TU live on identifiers.
-  if (isa(Ctx) &&
-  !Result.getSema().getLangOpts().CPlusPlus) {
-auto &S = Result.getSema();
-auto &Idents = S.Context.Idents;
-
-// Ensure all external identifiers are in the identifier table.
-if (LoadExternal)
-  if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
-std::unique_ptr Iter(External->getIdentifiers());
-for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
-  Idents.get(Name);
-  }
+struct LookupVisibleHelper {
+  LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
+  bool LoadExternal)
+  : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
+LoadExternal(LoadExternal) {}
+
+  void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
+  bool IncludeGlobalScope) {
+// Determine the set of using directives available during
+// unqualified name lookup.
+Scope *Initial = S;
+UnqualUsingDirectiveSet UDirs(SemaRef);
+if (SemaRef.getLangOpts().CPlusPlus) {
+  // Find the first namespace or translation-unit scope.
+  while (S && !isNamespaceOrTranslationUnitScope(S))
+S = S->getParent();
 
-// Walk all lookup results in the TU for each identifier.
-for (const auto &Ident : Idents) {
-  for (auto I = S.IdResolver.begin(Ident.getValue()),
-E = S.IdResolver.end();
-   I != E; ++I) {
-if (S.IdResolver.isDeclInScope(*I, Ctx)) {
-  if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
-Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
-Visited.add(ND);
-  }
-}
-  }
+  UDirs.visitScopeChain(Initial, S);
 }
+UDirs.done();
 
-return;
+// Look for visible declarations.
+LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
+Result.setAllowHidden(Consumer.includeHiddenDecls());
+if (!IncludeGlobalScope)
+  Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
+ShadowContextRAII Shadow(Visited);
+lookupInScope(Initial, Result, UDirs);
   }
 
-  if (CXXRecordDecl *Class = dyn_cast(Ctx))
-Result.getSema().ForceDeclarationOfImplicitMembers(Class);
-
-  // We sometimes skip loading namespace-level results (they tend to be huge).
-  bool Load = LoadExternal ||
-  !(isa(Ctx) || isa(Ctx));
-  // Enumerate all of the results in this context.
-  for (DeclContextLookupResult R :
-   Load ? Ctx->lookups()
-: Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
-for (auto *D : R) {
-  if (auto *ND = Result.getAcceptableDecl(D)) {
-Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
-Visited.add(ND);
-  }
-}
-  }
+  void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
+  Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
+LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
+Result.setAllowHidden(Consumer.includeHiddenDecls());
+if (!IncludeGlobalScope)
+  Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
 
-  // Traverse us

r367875 - Undo what looks like an unintentional change in r367829

2019-08-05 Thread Nico Weber via cfe-commits
Author: nico
Date: Mon Aug  5 08:23:10 2019
New Revision: 367875

URL: http://llvm.org/viewvc/llvm-project?rev=367875&view=rev
Log:
Undo what looks like an unintentional change in r367829

The MSan bot was (rightfully) complaining that NumASTLoaded was
unitialized, so put the initialization removed in r367829 back in.

While here, remove two needless semicolons added in that change.

Modified:
cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h

Modified: cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h?rev=367875&r1=367874&r2=367875&view=diff
==
--- cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h (original)
+++ cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h Mon Aug  5 08:23:10 
2019
@@ -276,14 +276,14 @@ private:
   /// The number successfully loaded ASTs. Used to indicate, and  - with the
   /// appropriate threshold value - limit the  memory usage of the
   /// CrossTranslationUnitContext.
-  unsigned NumASTLoaded;
+  unsigned NumASTLoaded{0u};
 
   /// RAII counter to signal 'threshold reached' condition, and to increment 
the
   /// NumASTLoaded counter upon a successful load.
   class LoadGuard {
   public:
 LoadGuard(unsigned Limit, unsigned &Counter)
-: Counter(Counter), Enabled(Counter < Limit){};
+: Counter(Counter), Enabled(Counter < Limit) {}
 ~LoadGuard() {
   if (StoreSuccess)
 ++Counter;
@@ -295,7 +295,7 @@ private:
 void storedSuccessfully() { StoreSuccess = true; }
 /// Indicates, whether a new load operation is permitted, it is within the
 /// threshold.
-operator bool() const { return Enabled; };
+operator bool() const { return Enabled; }
 
   private:
 /// The number of ASTs actually imported. LoadGuard does not own the


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


[PATCH] D65752: [Sema] Refactor LookupVisibleDecls. NFC

2019-08-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 213371.
ilya-biryukov added a comment.

- Remove accidental change from revision


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65752

Files:
  clang/lib/Sema/SemaLookup.cpp

Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -3609,328 +3609,344 @@
   return nullptr;
 }
 
-static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
-   bool QualifiedNameLookup,
-   bool InBaseClass,
-   VisibleDeclConsumer &Consumer,
-   VisibleDeclsRecord &Visited,
-   bool IncludeDependentBases,
-   bool LoadExternal) {
-  if (!Ctx)
-return;
-
-  // Make sure we don't visit the same context twice.
-  if (Visited.visitedContext(Ctx->getPrimaryContext()))
-return;
-
-  Consumer.EnteredContext(Ctx);
-
-  // Outside C++, lookup results for the TU live on identifiers.
-  if (isa(Ctx) &&
-  !Result.getSema().getLangOpts().CPlusPlus) {
-auto &S = Result.getSema();
-auto &Idents = S.Context.Idents;
-
-// Ensure all external identifiers are in the identifier table.
-if (LoadExternal)
-  if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
-std::unique_ptr Iter(External->getIdentifiers());
-for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
-  Idents.get(Name);
-  }
+struct LookupVisibleHelper {
+  LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
+  bool LoadExternal)
+  : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
+LoadExternal(LoadExternal) {}
+
+  void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
+  bool IncludeGlobalScope) {
+// Determine the set of using directives available during
+// unqualified name lookup.
+Scope *Initial = S;
+UnqualUsingDirectiveSet UDirs(SemaRef);
+if (SemaRef.getLangOpts().CPlusPlus) {
+  // Find the first namespace or translation-unit scope.
+  while (S && !isNamespaceOrTranslationUnitScope(S))
+S = S->getParent();
 
-// Walk all lookup results in the TU for each identifier.
-for (const auto &Ident : Idents) {
-  for (auto I = S.IdResolver.begin(Ident.getValue()),
-E = S.IdResolver.end();
-   I != E; ++I) {
-if (S.IdResolver.isDeclInScope(*I, Ctx)) {
-  if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
-Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
-Visited.add(ND);
-  }
-}
-  }
+  UDirs.visitScopeChain(Initial, S);
 }
+UDirs.done();
 
-return;
+// Look for visible declarations.
+LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
+Result.setAllowHidden(Consumer.includeHiddenDecls());
+if (!IncludeGlobalScope)
+  Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
+ShadowContextRAII Shadow(Visited);
+lookupInScope(Initial, Result, UDirs);
   }
 
-  if (CXXRecordDecl *Class = dyn_cast(Ctx))
-Result.getSema().ForceDeclarationOfImplicitMembers(Class);
-
-  // We sometimes skip loading namespace-level results (they tend to be huge).
-  bool Load = LoadExternal ||
-  !(isa(Ctx) || isa(Ctx));
-  // Enumerate all of the results in this context.
-  for (DeclContextLookupResult R :
-   Load ? Ctx->lookups()
-: Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
-for (auto *D : R) {
-  if (auto *ND = Result.getAcceptableDecl(D)) {
-Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
-Visited.add(ND);
-  }
-}
-  }
+  void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
+  Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
+LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
+Result.setAllowHidden(Consumer.includeHiddenDecls());
+if (!IncludeGlobalScope)
+  Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
 
-  // Traverse using directives for qualified name lookup.
-  if (QualifiedNameLookup) {
 ShadowContextRAII Shadow(Visited);
-for (auto I : Ctx->using_directives()) {
-  if (!Result.getSema().isVisible(I))
-continue;
-  LookupVisibleDecls(I->getNominatedNamespace(), Result,
- QualifiedNameLookup, InBaseClass, Consumer, Visited,
- IncludeDependentBases, LoadExternal);
-}
+lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
+/*

Re: r367829 - [CrossTU][NFCI] Refactor loadExternalAST function

2019-08-05 Thread Nico Weber via cfe-commits
The problem is probably this part from the diff:

-  unsigned NumASTLoaded{0u};
+
+  /// The number successfully loaded ASTs. Used to indicate, and  - with
the
+  /// appropriate threshold value - limit the  memory usage of the
+  /// CrossTranslationUnitContext.
+  unsigned NumASTLoaded;


i.e. you removed the initialization of NumASTLoaded. Was there a reason for
that? I've put it back for now in r367875, but please verify that the code
now does what you intended it to do – maybe you were planning to initialize
this somewhere else.

On Mon, Aug 5, 2019 at 10:03 AM Nico Weber  wrote:

> The msan bot doesn't like this, it reports an uninitialized read a
> t clang/lib/CrossTU/CrossTranslationUnit.cpp :
>
>
> http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-fast/builds/34087/steps/check-clang%20msan/logs/stdio
>
> 
> Testing: 0
> FAIL: Clang :: Analysis/ctu-unknown-parts-in-triples.cpp (492 of 15321)
>  TEST 'Clang ::
> Analysis/ctu-unknown-parts-in-triples.cpp' FAILED 
> Script:
> --
> : 'RUN: at line 4';   rm -rf
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp
> && mkdir
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp
> : 'RUN: at line 5';   mkdir -p
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir
> : 'RUN: at line 6';
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/bin/clang -cc1
> -internal-isystem
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/lib/clang/10.0.0/include
> -nostdsysteminc -triple x86_64-pc-linux-gnu-emit-pch -o
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir/ctu-other.cpp.ast
> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/Inputs/ctu-other.cpp
> : 'RUN: at line 8';   cp
> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir/externalDefMap.txt
> : 'RUN: at line 9';
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/bin/clang -cc1
> -internal-isystem
> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/lib/clang/10.0.0/include
> -nostdsysteminc -analyze -analyzer-constraints=range -triple
> x86_64-unknown-linux-gnu-analyzer-checker=core,debug.ExprInspection
>  -analyzer-config experimental-enable-naive-ctu-analysis=true
>  -analyzer-config
> ctu-dir=/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir
>-Werror=ctu-verify
> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/ctu-unknown-parts-in-triples.cpp
> --
> Exit Code: 77
>
> Command Output (stderr):
> --
> ==5072==WARNING: MemorySanitizer: use-of-uninitialized-value
> #0 0xb05c3c4 in
> clang::cross_tu::CrossTranslationUnitContext::loadExternalAST(llvm::StringRef,
> llvm::StringRef, llvm::StringRef, bool)
> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:467:7
> #1 0xb053a98 in llvm::Expected
> clang::cross_tu::CrossTranslationUnitContext::getCrossTUDefinitionImpl(clang::FunctionDecl
> const*, llvm::StringRef, llvm::StringRef, bool)
> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:241:7
> #2 0xb053466 in
> clang::cross_tu::CrossTranslationUnitContext::getCrossTUDefinition(clang::FunctionDecl
> const*, llvm::StringRef, llvm::StringRef, bool)
> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:307:10
> #3 0xadb69f5 in clang::ento::AnyFunctionCall::getRuntimeDefinition()
> const
> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CallEvent.cpp:575:14
>
> On Mon, Aug 5, 2019 at 7:05 AM Endre Fulop via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: gamesh411
>> Date: Mon Aug  5 04:06:41 2019
>> New Revision: 367829
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=367829&view=rev
>> Log:
>> [CrossTU][NFCI] Refactor loadExternalAST function
>>
>> Summary:
>> Refactor loadExternalAST method of CrossTranslationUnitContext in order to
>> reduce maintenance burden and so that features are easier to add in the
>> future.
>>
>> Reviewers: martong
>>
>> Subscribers: rnkovacs, dkrupp, Szelethus, cfe-commits
>>
>> Tags: #clang
>>
>> Differential Revision: https://reviews.llvm.org/D64753
>>
>> Modified:
>> cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
>> cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp
>>
>> Modified: cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/

[PATCH] D65752: [Sema] Refactor LookupVisibleDecls. NFC

2019-08-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

This is just a proposal, there are probably other ways to reach better 
readability, e.g. group some of those parameters into a struct.
But let me know what you think, happy to refactor in a slightly different 
manner or simply drop this revision.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65752



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


[PATCH] D65753: Builtins: Add some v2f16 variants

2019-08-05 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm created this revision.
arsenm added reviewers: rjmccall, Anastasia, yaxunl, rsmith.
Herald added a subscriber: wdng.
arsenm added a parent revision: D65597: WIP: Builtins: Start adding half 
versions of math builtins.

This will avoid hacks in the OpenCL builtin library.


https://reviews.llvm.org/D65753

Files:
  include/clang/Basic/Builtins.def
  lib/CodeGen/CGBuiltin.cpp
  test/CodeGenOpenCL/builtins-f16.cl

Index: test/CodeGenOpenCL/builtins-f16.cl
===
--- test/CodeGenOpenCL/builtins-f16.cl
+++ test/CodeGenOpenCL/builtins-f16.cl
@@ -1,7 +1,10 @@
-// RUN: %clang_cc1 -emit-llvm -o - -triple x86_64-darwin-apple %s | FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -o - -triple amdgcn-amd-amdhsa %s | FileCheck %s
 
 #pragma OPENCL EXTENSION cl_khr_fp16 : enable
 
+typedef half __attribute__((ext_vector_type(2))) half2;
+
+
 // CHECK-LABEL: define void @test_half_builtins
 void test_half_builtins(half h0, half h1, half h2) {
   volatile half res;
@@ -69,3 +72,35 @@
   // CHECK: call half @llvm.canonicalize.f16(half %h0)
   res = __builtin_canonicalizef16(h0);
 }
+
+// CHECK-LABEL: @test_v2f16_builtins(
+void test_v2f16_builtins(half2 h0, half2 h1, half2 h2) {
+  volatile half2 res;
+
+  // CHECK: call <2 x half> @llvm.fma.v2f16(<2 x half> %h0, <2 x half> %h1, <2 x half> %h2)
+  res = __builtin_fmav2f16(h0, h1 ,h2);
+
+  // CHECK: call <2 x half> @llvm.maxnum.v2f16(<2 x half> %h0, <2 x half> %h1)
+  res = __builtin_fmaxv2f16(h0, h1);
+
+  // CHECK: call <2 x half> @llvm.minnum.v2f16(<2 x half> %h0, <2 x half> %h1)
+  res = __builtin_fminv2f16(h0, h1);
+
+  // CHECK: call <2 x half> @llvm.copysign.v2f16(<2 x half> %h0, <2 x half> %h1)
+  res = __builtin_copysignv2f16(h0, h1);
+
+  // CHECK: call <2 x half> @llvm.floor.v2f16(<2 x half> %h0)
+  res = __builtin_floorv2f16(h0);
+
+  // CHECK: call <2 x half> @llvm.ceil.v2f16(<2 x half> %h0)
+  res = __builtin_ceilv2f16(h0);
+
+  // CHECK: call <2 x half> @llvm.trunc.v2f16(<2 x half> %h0)
+  res = __builtin_truncv2f16(h0);
+
+  // CHECK: call <2 x half> @llvm.rint.v2f16(<2 x half> %h0)
+  res = __builtin_rintv2f16(h0);
+
+  // CHECK: call <2 x half> @llvm.canonicalize.v2f16(<2 x half> %h0)
+  res = __builtin_canonicalizev2f16(h0);
+}
Index: lib/CodeGen/CGBuiltin.cpp
===
--- lib/CodeGen/CGBuiltin.cpp
+++ lib/CodeGen/CGBuiltin.cpp
@@ -1558,6 +1558,7 @@
 case Builtin::BI__builtin_ceil:
 case Builtin::BI__builtin_ceilf:
 case Builtin::BI__builtin_ceilf16:
+case Builtin::BI__builtin_ceilv2f16:
 case Builtin::BI__builtin_ceill:
   return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::ceil));
 
@@ -1567,6 +1568,7 @@
 case Builtin::BI__builtin_copysign:
 case Builtin::BI__builtin_copysignf:
 case Builtin::BI__builtin_copysignf16:
+case Builtin::BI__builtin_copysignv2f16:
 case Builtin::BI__builtin_copysignl:
 case Builtin::BI__builtin_copysignf128:
   return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::copysign));
@@ -1614,6 +1616,7 @@
 case Builtin::BI__builtin_floor:
 case Builtin::BI__builtin_floorf:
 case Builtin::BI__builtin_floorf16:
+case Builtin::BI__builtin_floorv2f16:
 case Builtin::BI__builtin_floorl:
   return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::floor));
 
@@ -1623,6 +1626,7 @@
 case Builtin::BI__builtin_fma:
 case Builtin::BI__builtin_fmaf:
 case Builtin::BI__builtin_fmaf16:
+case Builtin::BI__builtin_fmav2f16:
 case Builtin::BI__builtin_fmal:
   return RValue::get(emitTernaryBuiltin(*this, E, Intrinsic::fma));
 
@@ -1632,6 +1636,7 @@
 case Builtin::BI__builtin_fmax:
 case Builtin::BI__builtin_fmaxf:
 case Builtin::BI__builtin_fmaxf16:
+case Builtin::BI__builtin_fmaxv2f16:
 case Builtin::BI__builtin_fmaxl:
   return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::maxnum));
 
@@ -1641,6 +1646,7 @@
 case Builtin::BI__builtin_fmin:
 case Builtin::BI__builtin_fminf:
 case Builtin::BI__builtin_fminf16:
+case Builtin::BI__builtin_fminv2f16:
 case Builtin::BI__builtin_fminl:
   return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::minnum));
 
@@ -1708,6 +1714,7 @@
 case Builtin::BI__builtin_rint:
 case Builtin::BI__builtin_rintf:
 case Builtin::BI__builtin_rintf16:
+case Builtin::BI__builtin_rintv2f16:
 case Builtin::BI__builtin_rintl:
   return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::rint));
 
@@ -1744,6 +1751,7 @@
 case Builtin::BI__builtin_trunc:
 case Builtin::BI__builtin_truncf:
 case Builtin::BI__builtin_truncf16:
+case Builtin::BI__builtin_truncv2f16:
 case Builtin::BI__builtin_truncl:
   return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::trunc));
 
@@ -4000,6 +4008,7 @@
   case Builtin::BI__builtin_canonicalize:
   case Builtin::BI__builtin_canonicalizef:
   case Builtin::BI__builtin_canonical

[PATCH] D65754: Fix toHalfOpenFileRange assertion fail

2019-08-05 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah created this revision.
SureYeaah added reviewers: sammccall, kadircet.
Herald added subscribers: cfe-commits, arphaman, jkorous, ilya-biryukov.
Herald added a project: clang.

- Removed assumption that begin and end need to be in same file id.
- Fixes the crash at https://github.com/clangd/clangd/issues/113


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D65754

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/unittests/SourceCodeTests.cpp

Index: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -460,15 +460,22 @@
 #define FOO(X, Y) int Y = ++X
 #define BAR(X) X + 1
 #define ECHO(X) X
+
+#define BUZZ BAZZ(ADD)
+#define BAZZ(m) m(1)
+#define ADD(a) int f = a + 1;
 template
 class P {};
-void f() {
+
+int main() {
   $a[[P a]];
   $b[[int b = 1]];
   $c[[FOO(b, c)]]; 
   $d[[FOO(BAR(BAR(b)), d)]];
   // FIXME: We might want to select everything inside the outer ECHO.
   ECHO(ECHO($e[[int) ECHO(e]]));
+  // Shouldn't crash.
+  $f[[BUZZ]];
 }
   )cpp");
 
@@ -495,6 +502,7 @@
   CheckRange("c");
   CheckRange("d");
   CheckRange("e");
+  CheckRange("f");
 }
 
 } // namespace
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -295,37 +295,63 @@
   return SourceRange(std::min(R1.getBegin(), R2.getBegin()),
  E1 < E2 ? R2.getEnd() : R1.getEnd());
 }
-
-// Returns the tokenFileRange for a given Location as a Token Range
+// If Loc is a macro arg expansion, return the immediate spelling loc.
+// Otherwise 
+// Assumes Loc is in a macro file ID
+static SourceRange getExpansionOrSpellingRange(SourceLocation Loc,
+   const SourceManager &SM,
+   const LangOptions &LangOpts) {
+  if (SM.isMacroArgExpansion(Loc))
+return SM.getImmediateSpellingLoc(Loc);
+  return toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts);
+}
+
+// Returns the tokenFileRange for a given Range as a Token Range
 // This is quite similar to getFileLoc in SourceManager as both use
 // getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
 // However:
 // - We want to maintain the full range information as we move from one file to
 //   the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
-// - We want to split '>>' tokens as the lexer parses the '>>' in template
-//   instantiations as a '>>' instead of a '>'.
+// - We want to split '>>' tokens as the lexer parses the '>>' in nested
+// template instantiations as a '>>' instead of two '>'s.
 // There is also getExpansionRange but it simply calls
 // getImmediateExpansionRange on the begin and ends separately which is wrong.
-static SourceRange getTokenFileRange(SourceLocation Loc,
- const SourceManager &SM,
+static SourceRange getTokenFileRange(SourceRange Rng, const SourceManager &SM,
  const LangOptions &LangOpts) {
-  SourceRange FileRange = Loc;
-  while (!FileRange.getBegin().isFileID()) {
-assert(!FileRange.getEnd().isFileID() &&
-   "Both Begin and End should be MacroIDs.");
-if (SM.isMacroArgExpansion(FileRange.getBegin())) {
-  FileRange.setBegin(SM.getImmediateSpellingLoc(FileRange.getBegin()));
-  FileRange.setEnd(SM.getImmediateSpellingLoc(FileRange.getEnd()));
-} else {
-  SourceRange ExpansionRangeForBegin = toTokenRange(
-  SM.getImmediateExpansionRange(FileRange.getBegin()), SM, LangOpts);
-  SourceRange ExpansionRangeForEnd = toTokenRange(
-  SM.getImmediateExpansionRange(FileRange.getEnd()), SM, LangOpts);
-  FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
-  SM, LangOpts);
-}
+  // Map from FileID hash to SourceRange
+  std::map RngMap;
+  // Adds a Location to the RngMap
+  auto AddLocToMap = [&RngMap, &SM, &LangOpts](SourceLocation Loc) {
+unsigned FileIDHash = SM.getFileID(Loc).getHashValue();
+auto It = RngMap.find(FileIDHash);
+if (It == RngMap.end())
+  RngMap[FileIDHash] = Loc;
+else
+  It->second = unionTokenRange(It->second, Loc, SM, LangOpts);
+  };
+  auto AddRngToMap = [&](SourceRange SR) {
+AddLocToMap(SR.getBegin());
+AddLocToMap(SR.getEnd());
+  };
+  // Initialize RngMap
+  AddRngToMap(Rng);
+  // Iterate until only one range is left which is not a macroID
+  for (auto It = RngMap.rbegin();
+   !RngMap.empty() && It->second.getBegin().isMacroID();
+   It = RngMap.

r367885 - [AST] Fix RecursiveASTVisitorTest multiline string literal. NFC

2019-08-05 Thread David Green via cfe-commits
Author: dmgreen
Date: Mon Aug  5 09:27:36 2019
New Revision: 367885

URL: http://llvm.org/viewvc/llvm-project?rev=367885&view=rev
Log:
[AST] Fix RecursiveASTVisitorTest multiline string literal. NFC

Some compiler, notably older gccs (< 8) can have trouble with multiline raw
string literals inside macros. This just moves the code outsize the macro, to
attempt to appease the bots.

Modified:

cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp

Modified: 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp?rev=367885&r1=367884&r2=367885&view=diff
==
--- 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
 (original)
+++ 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
 Mon Aug  5 09:27:36 2019
@@ -41,7 +41,7 @@ TEST(RecursiveASTVisitor, CXXCtorInitial
   for (bool VisitImplCode : {true, false}) {
 CXXCtorInitializerVisitor Visitor(VisitImplCode);
 Visitor.ExpectMatch("initializer", 7, 17);
-EXPECT_TRUE(Visitor.runOver(R"cpp(
+auto Code = R"cpp(
 class A {};
 class B : public A {
   B() {};
@@ -49,8 +49,8 @@ TEST(RecursiveASTVisitor, CXXCtorInitial
 class C : public A {
   C() : A() {}
 };
-  )cpp",
-CXXCtorInitializerVisitor::Lang_CXX));
+  )cpp";
+EXPECT_TRUE(Visitor.runOver(Code, CXXCtorInitializerVisitor::Lang_CXX));
 EXPECT_EQ(Visitor.VisitedImplicitInitializer, VisitImplCode);
   }
 }


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


[PATCH] D65300: [clang] [CodeGen] clang-misexpect prototype for compiler warnings

2019-08-05 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth updated this revision to Diff 213379.
paulkirth edited the summary of this revision.
paulkirth added a comment.

Update threshold values to match those assigned when lowering __builtin_expect 
intrinsic.

I've modified the branch probability to match the probability assigned in 
LowerExpectIntrinsics.cpp

This is still debatable, but seems like a reasonable default. My next patch 
will make the probability threshold assignable through the command line, and 
extend the probability calculation into switch statements. This way users can 
determine how hot is hot enough, and otherwise get the same behavior that 
builtin expect will use anyway.

I also re applied a fix to a typo that I overwrote in an earlier patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65300

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CMakeLists.txt
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/MisExpect.cpp
  clang/lib/CodeGen/MisExpect.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Profile/Inputs/misexpect-branch-nonconst-expect-arg.proftext
  clang/test/Profile/Inputs/misexpect-branch.proftext
  clang/test/Profile/Inputs/misexpect-switch-default-only.proftext
  clang/test/Profile/Inputs/misexpect-switch.proftext
  clang/test/Profile/misexpect-branch-cold.c
  clang/test/Profile/misexpect-branch-nonconst-expected-val.c
  clang/test/Profile/misexpect-branch.c
  clang/test/Profile/misexpect-no-warning-without-flag.c
  clang/test/Profile/misexpect-switch-default.c
  clang/test/Profile/misexpect-switch-nonconst.c
  clang/test/Profile/misexpect-switch-only-default-case.c
  clang/test/Profile/misexpect-switch.c

Index: clang/test/Profile/misexpect-switch.c
===
--- /dev/null
+++ clang/test/Profile/misexpect-switch.c
@@ -0,0 +1,68 @@
+// Test that misexpect detects mis-annotated switch statements
+
+// RUN: llvm-profdata merge %S/Inputs/misexpect-switch.proftext -o %t.profdata
+// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify -fmisexpect
+
+int sum(int *buff, int size);
+int random_sample(int *buff, int size);
+int rand();
+
+const int inner_loop = 1000;
+const int outer_loop = 20;
+const int arry_size = 25;
+
+int arry[arry_size] = {0};
+
+void init_arry() {
+  int i;
+  for (i = 0; i < arry_size; ++i) {
+arry[i] = rand() % 10;
+  }
+}
+
+int main() {
+  init_arry();
+  int val = 0;
+
+  int j, k;
+  for (j = 0; j < outer_loop; ++j) {
+for (k = 0; k < inner_loop; ++k) {
+  unsigned condition = rand() % 1;
+  switch (__builtin_expect(condition, 0)) { // expected-warning-re {{Potential performance regression from use of __builtin_expect(): Annotation was correct on {{.+}}% of profiled executions.}}
+  case 0:
+val += sum(arry, arry_size);
+break;
+  case 1:
+  case 2:
+  case 3:
+  case 4:
+val += random_sample(arry, arry_size);
+break;
+  default:
+__builtin_unreachable();
+  } // end switch
+}   // end inner_loop
+  } // end outer_loop
+
+  return 0;
+}
+
+int sum(int *buff, int size) {
+  int total = 0;
+  int i = 0;
+  for (i = 0; i < size; ++i) {
+total += buff[i];
+  }
+  return total;
+}
+
+int random_sample(int *buff, int size) {
+  int total = 0;
+  int i;
+  for (i = 0; i < size; ++i) {
+if (rand() % 5 == 0)
+  total += buff[i];
+  }
+
+  return total;
+}
Index: clang/test/Profile/misexpect-switch-only-default-case.c
===
--- /dev/null
+++ clang/test/Profile/misexpect-switch-only-default-case.c
@@ -0,0 +1,62 @@
+// Test that misexpect detects mis-annotated switch statements
+
+// RUN: llvm-profdata merge %S/Inputs/misexpect-switch-default-only.proftext -o %t.profdata
+// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify -fmisexpect
+
+// expected-no-diagnostics
+int sum(int *buff, int size);
+int random_sample(int *buff, int size);
+int rand();
+
+const int inner_loop = 1000;
+const int outer_loop = 20;
+const int arry_size = 25;
+
+int arry[arry_size] = {0};
+
+void init_arry() {
+  int i;
+  for (i = 0; i < arry_size; ++i) {
+arry[i] = rand() % 10;
+  }
+}
+
+int main()
+{
+init_arry();
+int val = 0;
+
+int j, k;
+for (j = 0; j < outer_loop; ++j) {
+for (k = 0; k < inner_loop; ++k) {
+unsigned condition = rand() % 1;
+switch (__builtin_expect(condition, 0)) {
+default:
+val += random_sample(arry, arry_size);
+break;
+}; // end switch
+}  // end inner_loop
+

[PATCH] D65706: [docs] Better documentation for -Weverything

2019-08-05 Thread JF Bastien via Phabricator via cfe-commits
jfb marked an inline comment as done.
jfb added inline comments.



Comment at: clang/docs/UsersManual.rst:999-1000
+diagnostics contradict each other, users of :option:`-Weverything` therefore
+often disable many diagnostics such as :option:`-Wno-c++98-compat`
+:option:`-Wno-c++-compat`.
+

aaron.ballman wrote:
> jfb wrote:
> > aaron.ballman wrote:
> > > Would you care to propose a more exhaustive list of conflicting 
> > > diagnostics? (Perhaps in a follow-up patch.)
> > I looked a bit and I'm worried that providing a list won't be particularly 
> > satisfying for people looking at this. I think it's better to have some 
> > warning, and let folks figure out what works for their particular 
> > situation. Here I'm assuming that they don't use C++98 and that seems 
> > reasonable, but figuring out what side of contradictions they're on doesn't 
> > seem like it'll work out.
> One of the primary concerns with enabling `-Weverything` is the fact that we 
> know this enables conflicting diagnostics. Telling the user "we know there 
> are conflicting diagnostics, but we want you to have the joy of figuring out 
> which ones conflict for yourself" seems even more unsatisfying, to me. I 
> agree that we don't want to tell users which of the conflicting options they 
> should disable, but was thinking of something more along the lines of:
> ```
> The following sets of options are known to have some possibly unfortunate 
> interactions when enabled together:
>   * -Wfoo, -Wbar
>   * -Wbaz, -Wquux
>   * ...
> Note that there may be other conflicting diagnostic flags not listed above.
> ```
> I figure that gives users a bit more of an idea of what they're signing up 
> for when they enable -Weverything, which seems useful.
OK I can do that as a follow-up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65706



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


[PATCH] D62829: [clang-tidy] Check for dynamically initialized statics in headers.

2019-08-05 Thread Charles Zhang via Phabricator via cfe-commits
czhang marked an inline comment as done.
czhang added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp:47
+void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus || getLangOpts().ThreadsafeStatics)
+return;

aaron.ballman wrote:
> Why is this check disabled for C++? I would expect dynamic init of a static 
> in a C++ header file would be flagged by this check.
I'm confused now. If the language is not C++, we do an early return; that is, 
the check is run if we are on C++. Perhaps the early return is too confusing?


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

https://reviews.llvm.org/D62829



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


[PATCH] D62829: [clang-tidy] Check for dynamically initialized statics in headers.

2019-08-05 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp:47
+void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus || getLangOpts().ThreadsafeStatics)
+return;

czhang wrote:
> aaron.ballman wrote:
> > Why is this check disabled for C++? I would expect dynamic init of a static 
> > in a C++ header file would be flagged by this check.
> I'm confused now. If the language is not C++, we do an early return; that is, 
> the check is run if we are on C++. Perhaps the early return is too confusing?
Then the question is opposite, is this meaningless for C?


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

https://reviews.llvm.org/D62829



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


[PATCH] D64696: Adds a warning when an inline Doxygen comment has no argument

2019-08-05 Thread Mark de Wever via Phabricator via cfe-commits
Mordante added a comment.

I think it should warn; according to the documentation [1]  `\c` expects a 
word. Testing with Doxygen indeed gives a warning.

Can you post the real comment where this occurs?

[1] http://www.doxygen.nl/manual/commands.html#cmdc


Repository:
  rL LLVM

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

https://reviews.llvm.org/D64696



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


[PATCH] D65510: [clangd] Fix implicit template instatiations appearing as topLevelDecls.

2019-08-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 213388.
jvikstrom marked an inline comment as done.
jvikstrom added a comment.

Move isImplicitTemplateInstantiation and isExplicitTemplateSpecialization, also 
share implementation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65510

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/ClangdUnit.cpp
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp

Index: clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
@@ -103,6 +103,20 @@
   EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
 }
 
+TEST(ClangdUnitTest, DoesNotGetImplicitTemplateTopDecls) {
+  TestTU TU;
+  TU.Code = R"cpp(
+template
+void f(T) {}
+void s() {
+  f(10UL);
+}
+  )cpp";
+  auto AST = TU.build();
+  EXPECT_THAT(AST.getLocalTopLevelDecls(),
+  ElementsAre(DeclNamed("f"), DeclNamed("s")));
+}
+
 TEST(ClangdUnitTest, TokensAfterPreamble) {
   TestTU TU;
   TU.AdditionalFiles["foo.h"] = R"(
Index: clang-tools-extra/clangd/CodeComplete.cpp
===
--- clang-tools-extra/clangd/CodeComplete.cpp
+++ clang-tools-extra/clangd/CodeComplete.cpp
@@ -1674,13 +1674,6 @@
   }
 };
 
-template  bool isExplicitTemplateSpecialization(const NamedDecl &ND) {
-  if (const auto *TD = dyn_cast(&ND))
-if (TD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
-  return true;
-  return false;
-}
-
 } // namespace
 
 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
@@ -1783,9 +1776,7 @@
   };
   // We only complete symbol's name, which is the same as the name of the
   // *primary* template in case of template specializations.
-  if (isExplicitTemplateSpecialization(ND) ||
-  isExplicitTemplateSpecialization(ND) ||
-  isExplicitTemplateSpecialization(ND))
+  if (isExplicitTemplateSpecialization(&ND))
 return false;
 
   if (InTopLevelScope(ND))
Index: clang-tools-extra/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/clangd/ClangdUnit.cpp
+++ clang-tools-extra/clangd/ClangdUnit.cpp
@@ -9,6 +9,7 @@
 #include "ClangdUnit.h"
 #include "../clang-tidy/ClangTidyDiagnosticConsumer.h"
 #include "../clang-tidy/ClangTidyModuleRegistry.h"
+#include "AST.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
 #include "Headers.h"
@@ -19,8 +20,11 @@
 #include "index/CanonicalIncludes.h"
 #include "index/Index.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
@@ -70,6 +74,9 @@
   auto &SM = D->getASTContext().getSourceManager();
   if (!isInsideMainFile(D->getLocation(), SM))
 continue;
+  if (const NamedDecl *ND = dyn_cast(D))
+if (isImplicitTemplateInstantiation(ND))
+  continue;
 
   // ObjCMethodDecl are not actually top-level decls.
   if (isa(D))
Index: clang-tools-extra/clangd/AST.h
===
--- clang-tools-extra/clangd/AST.h
+++ clang-tools-extra/clangd/AST.h
@@ -80,9 +80,11 @@
 /// take in to account using directives etc
 /// Example: shortenNamespace("ns1::MyClass", "ns1")
 ///--> "MyClass"
-std::string  shortenNamespace(const llvm::StringRef OriginalName,
-  const llvm::StringRef CurrentNamespace);
+std::string shortenNamespace(const llvm::StringRef OriginalName,
+ const llvm::StringRef CurrentNamespace);
 
+bool isImplicitTemplateInstantiation(const NamedDecl *D);
+bool isExplicitTemplateSpecialization(const NamedDecl *D);
 
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/AST.cpp
===
--- clang-tools-extra/clangd/AST.cpp
+++ clang-tools-extra/clangd/AST.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/TemplateBase.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Index/USRGeneration.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/Support/Casting.h"
@@ -40,8 +41,32 @@
   // contain TemplateArgumentLoc information.
   return llvm::None;
 }
+
+template 
+bool isTemplateSpecializationKind(const NamedDecl *D,
+  TemplateSpecializationKind Kind) {
+  if (const auto *TD = dyn_ca

[PATCH] D65706: [docs] Better documentation for -Weverything

2019-08-05 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.

LGTM!




Comment at: clang/docs/UsersManual.rst:999-1000
+diagnostics contradict each other, users of :option:`-Weverything` therefore
+often disable many diagnostics such as :option:`-Wno-c++98-compat`
+:option:`-Wno-c++-compat`.
+

jfb wrote:
> aaron.ballman wrote:
> > jfb wrote:
> > > aaron.ballman wrote:
> > > > Would you care to propose a more exhaustive list of conflicting 
> > > > diagnostics? (Perhaps in a follow-up patch.)
> > > I looked a bit and I'm worried that providing a list won't be 
> > > particularly satisfying for people looking at this. I think it's better 
> > > to have some warning, and let folks figure out what works for their 
> > > particular situation. Here I'm assuming that they don't use C++98 and 
> > > that seems reasonable, but figuring out what side of contradictions 
> > > they're on doesn't seem like it'll work out.
> > One of the primary concerns with enabling `-Weverything` is the fact that 
> > we know this enables conflicting diagnostics. Telling the user "we know 
> > there are conflicting diagnostics, but we want you to have the joy of 
> > figuring out which ones conflict for yourself" seems even more 
> > unsatisfying, to me. I agree that we don't want to tell users which of the 
> > conflicting options they should disable, but was thinking of something more 
> > along the lines of:
> > ```
> > The following sets of options are known to have some possibly unfortunate 
> > interactions when enabled together:
> >   * -Wfoo, -Wbar
> >   * -Wbaz, -Wquux
> >   * ...
> > Note that there may be other conflicting diagnostic flags not listed above.
> > ```
> > I figure that gives users a bit more of an idea of what they're signing up 
> > for when they enable -Weverything, which seems useful.
> OK I can do that as a follow-up.
Awesome, thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65706



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


[PATCH] D65706: [docs] Better documentation for -Weverything

2019-08-05 Thread JF Bastien via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL367889: [docs] document -Weveything more betterer (authored 
by jfb, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65706?vs=213278&id=213390#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65706

Files:
  cfe/trunk/docs/UsersManual.rst


Index: cfe/trunk/docs/UsersManual.rst
===
--- cfe/trunk/docs/UsersManual.rst
+++ cfe/trunk/docs/UsersManual.rst
@@ -992,13 +992,24 @@
 Enabling All Diagnostics
 ^
 
-In addition to the traditional ``-W`` flags, one can enable **all**
-diagnostics by passing :option:`-Weverything`. This works as expected
-with
-:option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
+In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
+by passing :option:`-Weverything`. This works as expected with
+:option:`-Werror`, and also includes the warnings from :option:`-pedantic`. 
Some
+diagnostics contradict each other, therefore, users of :option:`-Weverything`
+often disable many diagnostics such as :option:`-Wno-c++98-compat`
+:option:`-Wno-c++-compat` because they contradict recent C++ standards.
+
+Since :option:`-Weverything` enables every diagnostic, we generally don't
+recommend using it. :option:`-Wall` :option:`-Wextra` are a better choice for
+most projects. Using :option:`-Weverything` means that updating your compiler 
is
+more difficult because you're exposed to experimental diagnostics which might 
be
+of lower quality than the default ones. If you do use :option:`-Weverything`
+then we advise that you address all new compiler diagnostics as they get added
+to Clang, either by fixing everything they find or explicitly disabling that
+diagnostic with its corresponding `Wno-` option.
 
-Note that when combined with :option:`-w` (which disables all warnings), that
-flag wins.
+Note that when combined with :option:`-w` (which disables all warnings),
+disabling all warnings wins.
 
 Controlling Static Analyzer Diagnostics
 ^^^


Index: cfe/trunk/docs/UsersManual.rst
===
--- cfe/trunk/docs/UsersManual.rst
+++ cfe/trunk/docs/UsersManual.rst
@@ -992,13 +992,24 @@
 Enabling All Diagnostics
 ^
 
-In addition to the traditional ``-W`` flags, one can enable **all**
-diagnostics by passing :option:`-Weverything`. This works as expected
-with
-:option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
+In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
+by passing :option:`-Weverything`. This works as expected with
+:option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some
+diagnostics contradict each other, therefore, users of :option:`-Weverything`
+often disable many diagnostics such as :option:`-Wno-c++98-compat`
+:option:`-Wno-c++-compat` because they contradict recent C++ standards.
+
+Since :option:`-Weverything` enables every diagnostic, we generally don't
+recommend using it. :option:`-Wall` :option:`-Wextra` are a better choice for
+most projects. Using :option:`-Weverything` means that updating your compiler is
+more difficult because you're exposed to experimental diagnostics which might be
+of lower quality than the default ones. If you do use :option:`-Weverything`
+then we advise that you address all new compiler diagnostics as they get added
+to Clang, either by fixing everything they find or explicitly disabling that
+diagnostic with its corresponding `Wno-` option.
 
-Note that when combined with :option:`-w` (which disables all warnings), that
-flag wins.
+Note that when combined with :option:`-w` (which disables all warnings),
+disabling all warnings wins.
 
 Controlling Static Analyzer Diagnostics
 ^^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r367889 - [docs] document -Weveything more betterer

2019-08-05 Thread JF Bastien via cfe-commits
Author: jfb
Date: Mon Aug  5 09:53:45 2019
New Revision: 367889

URL: http://llvm.org/viewvc/llvm-project?rev=367889&view=rev
Log:
[docs] document -Weveything more betterer

Reviewers: aaron.ballman

Subscribers: jkorous, dexonsmith, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/docs/UsersManual.rst

Modified: cfe/trunk/docs/UsersManual.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/UsersManual.rst?rev=367889&r1=367888&r2=367889&view=diff
==
--- cfe/trunk/docs/UsersManual.rst (original)
+++ cfe/trunk/docs/UsersManual.rst Mon Aug  5 09:53:45 2019
@@ -992,13 +992,24 @@ is treated as a system header.
 Enabling All Diagnostics
 ^
 
-In addition to the traditional ``-W`` flags, one can enable **all**
-diagnostics by passing :option:`-Weverything`. This works as expected
-with
-:option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
+In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
+by passing :option:`-Weverything`. This works as expected with
+:option:`-Werror`, and also includes the warnings from :option:`-pedantic`. 
Some
+diagnostics contradict each other, therefore, users of :option:`-Weverything`
+often disable many diagnostics such as :option:`-Wno-c++98-compat`
+:option:`-Wno-c++-compat` because they contradict recent C++ standards.
 
-Note that when combined with :option:`-w` (which disables all warnings), that
-flag wins.
+Since :option:`-Weverything` enables every diagnostic, we generally don't
+recommend using it. :option:`-Wall` :option:`-Wextra` are a better choice for
+most projects. Using :option:`-Weverything` means that updating your compiler 
is
+more difficult because you're exposed to experimental diagnostics which might 
be
+of lower quality than the default ones. If you do use :option:`-Weverything`
+then we advise that you address all new compiler diagnostics as they get added
+to Clang, either by fixing everything they find or explicitly disabling that
+diagnostic with its corresponding `Wno-` option.
+
+Note that when combined with :option:`-w` (which disables all warnings),
+disabling all warnings wins.
 
 Controlling Static Analyzer Diagnostics
 ^^^


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


[PATCH] D65706: [docs] Better documentation for -Weverything

2019-08-05 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65706



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


[PATCH] D62829: [clang-tidy] Check for dynamically initialized statics in headers.

2019-08-05 Thread Charles Zhang via Phabricator via cfe-commits
czhang marked an inline comment as done.
czhang added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp:47
+void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus || getLangOpts().ThreadsafeStatics)
+return;

lebedev.ri wrote:
> czhang wrote:
> > aaron.ballman wrote:
> > > Why is this check disabled for C++? I would expect dynamic init of a 
> > > static in a C++ header file would be flagged by this check.
> > I'm confused now. If the language is not C++, we do an early return; that 
> > is, the check is run if we are on C++. Perhaps the early return is too 
> > confusing?
> Then the question is opposite, is this meaningless for C?
C can only initialize statics with constants, right?


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

https://reviews.llvm.org/D62829



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


r367892 - [AST] Fix buildbot failure because of raw string inside macro from 367839.

2019-08-05 Thread Johan Vikstrom via cfe-commits
Author: jvikstrom
Date: Mon Aug  5 10:14:46 2019
New Revision: 367892

URL: http://llvm.org/viewvc/llvm-project?rev=367892&view=rev
Log:
[AST] Fix buildbot failure because of raw string inside macro from 367839.

Modified:

cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp

Modified: 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp?rev=367892&r1=367891&r2=367892&view=diff
==
--- 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
 (original)
+++ 
cfe/trunk/unittests/Tooling/RecursiveASTVisitorTests/ImplicitCtorInitializer.cpp
 Mon Aug  5 10:14:46 2019
@@ -41,7 +41,7 @@ TEST(RecursiveASTVisitor, CXXCtorInitial
   for (bool VisitImplCode : {true, false}) {
 CXXCtorInitializerVisitor Visitor(VisitImplCode);
 Visitor.ExpectMatch("initializer", 7, 17);
-auto Code = R"cpp(
+llvm::StringRef Code = R"cpp(
 class A {};
 class B : public A {
   B() {};


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


[libclc] r367893 - Revert "Rename F_{None, Text, Append} to OF_{None, Text, Append}. NFC"

2019-08-05 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Mon Aug  5 10:23:23 2019
New Revision: 367893

URL: http://llvm.org/viewvc/llvm-project?rev=367893&view=rev
Log:
Revert "Rename F_{None,Text,Append} to OF_{None,Text,Append}. NFC"

This reverts commit 58c814614d2ac69bcf79b09543505fac80ada4e6.
Fixes build breakage using LLVM<7.

Modified:
libclc/trunk/utils/prepare-builtins.cpp

Modified: libclc/trunk/utils/prepare-builtins.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/utils/prepare-builtins.cpp?rev=367893&r1=367892&r2=367893&view=diff
==
--- libclc/trunk/utils/prepare-builtins.cpp (original)
+++ libclc/trunk/utils/prepare-builtins.cpp Mon Aug  5 10:23:23 2019
@@ -95,10 +95,10 @@ int main(int argc, char **argv) {
   std::error_code EC;
 #if HAVE_LLVM >= 0x0600
   std::unique_ptr Out(
-  new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
+  new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
 #else
   std::unique_ptr Out(
-  new tool_output_file(OutputFilename, EC, sys::fs::OF_None));
+  new tool_output_file(OutputFilename, EC, sys::fs::F_None));
 #endif
   if (EC) {
 errs() << EC.message() << '\n';


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


Re: [libclc] r367800 - Rename F_{None, Text, Append} to OF_{None, Text, Append}. NFC

2019-08-05 Thread Jan Vesely via cfe-commits
I've reverted this change.
It breaks libclc build using older LLVM version (which is still supported)
and it was committed without review on phabricator or libclc mailing list.
Please don't do that.

Jan

On Mon, Aug 5, 2019 at 1:43 AM Fangrui Song via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: maskray
> Date: Sun Aug  4 22:43:48 2019
> New Revision: 367800
>
> URL: http://llvm.org/viewvc/llvm-project?rev=367800&view=rev
> Log:
> Rename F_{None,Text,Append} to OF_{None,Text,Append}. NFC
>
> F_{None,Text,Append} are kept for compatibility since r334221.
>
> Modified:
> libclc/trunk/utils/prepare-builtins.cpp
>
> Modified: libclc/trunk/utils/prepare-builtins.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/libclc/trunk/utils/prepare-builtins.cpp?rev=367800&r1=367799&r2=367800&view=diff
>
> ==
> --- libclc/trunk/utils/prepare-builtins.cpp (original)
> +++ libclc/trunk/utils/prepare-builtins.cpp Sun Aug  4 22:43:48 2019
> @@ -95,10 +95,10 @@ int main(int argc, char **argv) {
>std::error_code EC;
>  #if HAVE_LLVM >= 0x0600
>std::unique_ptr Out(
> -  new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
> +  new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
>  #else
>std::unique_ptr Out(
> -  new tool_output_file(OutputFilename, EC, sys::fs::F_None));
> +  new tool_output_file(OutputFilename, EC, sys::fs::OF_None));
>  #endif
>if (EC) {
>  errs() << EC.message() << '\n';
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62829: [clang-tidy] Check for dynamically initialized statics in headers.

2019-08-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp:47
+void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus || getLangOpts().ThreadsafeStatics)
+return;

czhang wrote:
> lebedev.ri wrote:
> > czhang wrote:
> > > aaron.ballman wrote:
> > > > Why is this check disabled for C++? I would expect dynamic init of a 
> > > > static in a C++ header file would be flagged by this check.
> > > I'm confused now. If the language is not C++, we do an early return; that 
> > > is, the check is run if we are on C++. Perhaps the early return is too 
> > > confusing?
> > Then the question is opposite, is this meaningless for C?
> C can only initialize statics with constants, right?
Oye, my eyes saw one thing and my brain saw another. :-P You're right, @czhang, 
this code is correct as-is (C only initializes statics with a constant).


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

https://reviews.llvm.org/D62829



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


Re: r367889 - [docs] document -Weveything more betterer

2019-08-05 Thread Nico Weber via cfe-commits
This breaks the sphinx bot:

http://lab.llvm.org:8011/builders/clang-sphinx-docs/builds/45204/steps/docs-clang-html/logs/stdio

Warning, treated as error:
/home/buildbot/llvm-build-dir/clang-sphinx-docs/llvm/src/tools/clang/docs/UsersManual.rst:995:
WARNING: unknown option: -Wno-c++98-compat

On Mon, Aug 5, 2019 at 12:52 PM JF Bastien via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: jfb
> Date: Mon Aug  5 09:53:45 2019
> New Revision: 367889
>
> URL: http://llvm.org/viewvc/llvm-project?rev=367889&view=rev
> Log:
> [docs] document -Weveything more betterer
>
> Reviewers: aaron.ballman
>
> Subscribers: jkorous, dexonsmith, cfe-commits
>
> Tags: #clang
>
> Differential Revision: https://reviews.llvm.org/D65706
>
> Modified:
> cfe/trunk/docs/UsersManual.rst
>
> Modified: cfe/trunk/docs/UsersManual.rst
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/UsersManual.rst?rev=367889&r1=367888&r2=367889&view=diff
>
> ==
> --- cfe/trunk/docs/UsersManual.rst (original)
> +++ cfe/trunk/docs/UsersManual.rst Mon Aug  5 09:53:45 2019
> @@ -992,13 +992,24 @@ is treated as a system header.
>  Enabling All Diagnostics
>  ^
>
> -In addition to the traditional ``-W`` flags, one can enable **all**
> -diagnostics by passing :option:`-Weverything`. This works as expected
> -with
> -:option:`-Werror`, and also includes the warnings from
> :option:`-pedantic`.
> +In addition to the traditional ``-W`` flags, one can enable **all**
> diagnostics
> +by passing :option:`-Weverything`. This works as expected with
> +:option:`-Werror`, and also includes the warnings from
> :option:`-pedantic`. Some
> +diagnostics contradict each other, therefore, users of
> :option:`-Weverything`
> +often disable many diagnostics such as :option:`-Wno-c++98-compat`
> +:option:`-Wno-c++-compat` because they contradict recent C++ standards.
>
> -Note that when combined with :option:`-w` (which disables all warnings),
> that
> -flag wins.
> +Since :option:`-Weverything` enables every diagnostic, we generally don't
> +recommend using it. :option:`-Wall` :option:`-Wextra` are a better choice
> for
> +most projects. Using :option:`-Weverything` means that updating your
> compiler is
> +more difficult because you're exposed to experimental diagnostics which
> might be
> +of lower quality than the default ones. If you do use
> :option:`-Weverything`
> +then we advise that you address all new compiler diagnostics as they get
> added
> +to Clang, either by fixing everything they find or explicitly disabling
> that
> +diagnostic with its corresponding `Wno-` option.
> +
> +Note that when combined with :option:`-w` (which disables all warnings),
> +disabling all warnings wins.
>
>  Controlling Static Analyzer Diagnostics
>  ^^^
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64838: [Attr] Support _attribute__ ((fallthrough))

2019-08-05 Thread Nathan Huckleberry via Phabricator via cfe-commits
Nathan-Huckleberry updated this revision to Diff 213406.
Nathan-Huckleberry added a comment.

- Allow decl-specifier source location to propagate to decl parsing


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D64838

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/test/Index/blocks.c
  clang/test/Index/load-exprs.c
  clang/test/Sema/fallthrough-attr.c
  clang/test/SemaCXX/switch-implicit-fallthrough.cpp
  clang/test/SemaCXX/warn-unused-label-error.cpp

Index: clang/test/SemaCXX/warn-unused-label-error.cpp
===
--- clang/test/SemaCXX/warn-unused-label-error.cpp
+++ clang/test/SemaCXX/warn-unused-label-error.cpp
@@ -18,9 +18,9 @@
   }
 
   void h() {
-D: // expected-warning {{unused label 'D'}}
-  #pragma weak unused_local_static
-  __attribute__((unused))  // expected-warning {{declaration does not declare anything}}
-  ;
+  D:
+#pragma weak unused_local_static
+__attribute__((unused)) // expected-error {{'unused' attribute cannot be applied to a statement}}
+;
   }
 }
Index: clang/test/SemaCXX/switch-implicit-fallthrough.cpp
===
--- clang/test/SemaCXX/switch-implicit-fallthrough.cpp
+++ clang/test/SemaCXX/switch-implicit-fallthrough.cpp
@@ -329,3 +329,15 @@
   }
   return n;
 }
+
+int fallthrough_attribute_spelling(int n) {
+  switch (n) {
+  case 0:
+n++;
+__attribute__((fallthrough));
+  case 1:
+n++;
+break;
+  }
+  return n;
+}
Index: clang/test/Sema/fallthrough-attr.c
===
--- /dev/null
+++ clang/test/Sema/fallthrough-attr.c
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -fsyntax-only -std=gnu89 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=gnu99 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=c99 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=c11 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=c2x -DC2X -verify -Wimplicit-fallthrough %s
+
+int fallthrough_attribute_spelling(int n) {
+  switch (n) {
+  case 0:
+n++;
+  case 1:
+#if defined(C2X)
+// expected-warning@-2{{unannotated fall-through between switch labels}} expected-note@-2{{insert '[[fallthrough]];' to silence this warning}} expected-note@-2{{insert 'break;' to avoid fall-through}}
+#else
+// expected-warning@-4{{unannotated fall-through between switch labels}} expected-note@-4{{insert '__attribute__((fallthrough));' to silence this warning}} expected-note@-4{{insert 'break;' to avoid fall-through}}
+#endif
+n++;
+__attribute__((fallthrough));
+  case 2:
+n++;
+break;
+  }
+  return n;
+}
Index: clang/test/Index/load-exprs.c
===
--- clang/test/Index/load-exprs.c
+++ clang/test/Index/load-exprs.c
@@ -78,4 +78,3 @@
 // CHECK: load-exprs.c:31:32: MemberRef=array:24:12 Extent=[31:32 - 31:37]
 // CHECK: load-exprs.c:31:38: DeclRefExpr=StartIndex:27:8 Extent=[31:38 - 31:48]
 // CHECK: load-exprs.c:31:50: MemberRef=b:2:19 Extent=[31:50 - 31:51]
-
Index: clang/test/Index/blocks.c
===
--- clang/test/Index/blocks.c
+++ clang/test/Index/blocks.c
@@ -31,4 +31,3 @@
 // CHECK: blocks.c:9:54: DeclRefExpr=i:8:11 Extent=[9:54 - 9:55]
 // CHECK: blocks.c:9:59: UnaryOperator= Extent=[9:59 - 9:64]
 // CHECK: blocks.c:9:60: DeclRefExpr=_foo:7:21 Extent=[9:60 - 9:64]
-
Index: clang/lib/Sema/AnalysisBasedWarnings.cpp
===
--- clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -1215,7 +1215,7 @@
 tok::r_square, tok::r_square
   };
 
-  bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
+  bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17 && !PP.getLangOpts().C2x;
 
   StringRef MacroName;
   if (PreferClangAttr)
@@ -1224,24 +1224,19 @@
 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
   if (MacroName.empty() && !PreferClangAttr)
 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
-  if (MacroName.empty())
-MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
+  if (MacroName.empty()) {
+if (!PreferClangAttr)
+  MacroName = "[[fallthrough]]";
+else if (PP.getLangOpts().CPlusPlus)
+  MacroName = "[[clang::fallthrough]]";
+else
+  MacroName = "__attribute__((fallthrough))";
+  }
   return MacroName;
 }
 
 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
 bool PerFunction) {
-  // Only perform this analys

[PATCH] D64838: [Attr] Support _attribute__ ((fallthrough))

2019-08-05 Thread Nathan Huckleberry via Phabricator via cfe-commits
Nathan-Huckleberry updated this revision to Diff 213407.
Nathan-Huckleberry added a comment.

- Remove changes from accidentally formatted files


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D64838

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/test/Sema/fallthrough-attr.c
  clang/test/SemaCXX/switch-implicit-fallthrough.cpp
  clang/test/SemaCXX/warn-unused-label-error.cpp

Index: clang/test/SemaCXX/warn-unused-label-error.cpp
===
--- clang/test/SemaCXX/warn-unused-label-error.cpp
+++ clang/test/SemaCXX/warn-unused-label-error.cpp
@@ -18,9 +18,9 @@
   }
 
   void h() {
-D: // expected-warning {{unused label 'D'}}
-  #pragma weak unused_local_static
-  __attribute__((unused))  // expected-warning {{declaration does not declare anything}}
-  ;
+  D:
+#pragma weak unused_local_static
+__attribute__((unused)) // expected-error {{'unused' attribute cannot be applied to a statement}}
+;
   }
 }
Index: clang/test/SemaCXX/switch-implicit-fallthrough.cpp
===
--- clang/test/SemaCXX/switch-implicit-fallthrough.cpp
+++ clang/test/SemaCXX/switch-implicit-fallthrough.cpp
@@ -329,3 +329,15 @@
   }
   return n;
 }
+
+int fallthrough_attribute_spelling(int n) {
+  switch (n) {
+  case 0:
+n++;
+__attribute__((fallthrough));
+  case 1:
+n++;
+break;
+  }
+  return n;
+}
Index: clang/test/Sema/fallthrough-attr.c
===
--- /dev/null
+++ clang/test/Sema/fallthrough-attr.c
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -fsyntax-only -std=gnu89 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=gnu99 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=c99 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=c11 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=c2x -DC2X -verify -Wimplicit-fallthrough %s
+
+int fallthrough_attribute_spelling(int n) {
+  switch (n) {
+  case 0:
+n++;
+  case 1:
+#if defined(C2X)
+// expected-warning@-2{{unannotated fall-through between switch labels}} expected-note@-2{{insert '[[fallthrough]];' to silence this warning}} expected-note@-2{{insert 'break;' to avoid fall-through}}
+#else
+// expected-warning@-4{{unannotated fall-through between switch labels}} expected-note@-4{{insert '__attribute__((fallthrough));' to silence this warning}} expected-note@-4{{insert 'break;' to avoid fall-through}}
+#endif
+n++;
+__attribute__((fallthrough));
+  case 2:
+n++;
+break;
+  }
+  return n;
+}
Index: clang/lib/Sema/AnalysisBasedWarnings.cpp
===
--- clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -1215,7 +1215,7 @@
 tok::r_square, tok::r_square
   };
 
-  bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
+  bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17 && !PP.getLangOpts().C2x;
 
   StringRef MacroName;
   if (PreferClangAttr)
@@ -1224,24 +1224,19 @@
 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
   if (MacroName.empty() && !PreferClangAttr)
 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
-  if (MacroName.empty())
-MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
+  if (MacroName.empty()) {
+if (!PreferClangAttr)
+  MacroName = "[[fallthrough]]";
+else if (PP.getLangOpts().CPlusPlus)
+  MacroName = "[[clang::fallthrough]]";
+else
+  MacroName = "__attribute__((fallthrough))";
+  }
   return MacroName;
 }
 
 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
 bool PerFunction) {
-  // Only perform this analysis when using [[]] attributes. There is no good
-  // workflow for this warning when not using C++11. There is no good way to
-  // silence the warning (no attribute is available) unless we are using
-  // [[]] attributes. One could use pragmas to silence the warning, but as a
-  // general solution that is gross and not in the spirit of this warning.
-  //
-  // NOTE: This an intermediate solution. There are on-going discussions on
-  // how to properly support this warning outside of C++11 with an annotation.
-  if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
-return;
-
   FallthroughMapper FM(S);
   FM.TraverseStmt(AC.getBody());
 
@@ -1281,25 +1276,24 @@
   SourceLocation L = Label->getBeginLoc();
   if (L.isMacroID())
 continue;
-  if (S.getLangOpts().CPlusPlus11) {
-const Stmt *Term = B->getTerminatorStmt()

[PATCH] D64838: [Attr] Support _attribute__ ((fallthrough))

2019-08-05 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

+1, looks good


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D64838



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


[PATCH] D65761: Add Windows Control Flow Guard checks (/guard:cf).

2019-08-05 Thread Andrew Paverd via Phabricator via cfe-commits
ajpaverd created this revision.
Herald added subscribers: llvm-commits, cfe-commits, dexonsmith, steven_wu, 
hiraditya, kristof.beyls, javed.absar, mgorny, mehdi_amini.
Herald added projects: clang, LLVM.

A new module pass (Transforms/CFGuard/CFGuard.cpp) inserts CFGuard checks on
indirect function calls, using either the check or dispatch mechanism. These
checks require new calling conventions for the supported targets (currently
x86, ARM, and AArch64). An additional pass (Target/X86/X86FixupCFGuard.cpp) is
used on x86 to prevent stack spills between loading and calling the check, which
could be exploited. Another pass (CodeGen/CFGuardLongjmp.cpp) is used to
identify and emit valid longjmp targets, as required by /guard:cf.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D65761

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/MSVC.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGen/cfguardtable.c
  clang/test/Driver/cl-options.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/CodeGen/MachineBasicBlock.h
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/include/llvm/CodeGen/Passes.h
  llvm/include/llvm/IR/CallingConv.h
  llvm/include/llvm/InitializePasses.h
  llvm/include/llvm/MC/MCObjectFileInfo.h
  llvm/include/llvm/Transforms/CFGuard.h
  llvm/lib/AsmParser/LLLexer.cpp
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/AsmParser/LLToken.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/CodeGen/AsmPrinter/WinCFGuard.cpp
  llvm/lib/CodeGen/AsmPrinter/WinCFGuard.h
  llvm/lib/CodeGen/CFGuardLongjmp.cpp
  llvm/lib/CodeGen/CMakeLists.txt
  llvm/lib/CodeGen/CodeGen.cpp
  llvm/lib/CodeGen/MachineBasicBlock.cpp
  llvm/lib/IR/AsmWriter.cpp
  llvm/lib/MC/MCObjectFileInfo.cpp
  llvm/lib/Target/AArch64/AArch64CallingConvention.h
  llvm/lib/Target/AArch64/AArch64CallingConvention.td
  llvm/lib/Target/AArch64/AArch64FastISel.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp
  llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
  llvm/lib/Target/AArch64/LLVMBuild.txt
  llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp
  llvm/lib/Target/ARM/ARMCallingConv.h
  llvm/lib/Target/ARM/ARMCallingConv.td
  llvm/lib/Target/ARM/ARMFastISel.cpp
  llvm/lib/Target/ARM/ARMISelLowering.cpp
  llvm/lib/Target/ARM/ARMTargetMachine.cpp
  llvm/lib/Target/ARM/LLVMBuild.txt
  llvm/lib/Target/X86/CMakeLists.txt
  llvm/lib/Target/X86/LLVMBuild.txt
  llvm/lib/Target/X86/X86.h
  llvm/lib/Target/X86/X86AsmPrinter.cpp
  llvm/lib/Target/X86/X86CallingConv.td
  llvm/lib/Target/X86/X86FastISel.cpp
  llvm/lib/Target/X86/X86FixupCFGuard.cpp
  llvm/lib/Target/X86/X86RegisterInfo.cpp
  llvm/lib/Target/X86/X86Subtarget.h
  llvm/lib/Target/X86/X86TargetMachine.cpp
  llvm/lib/Transforms/CFGuard/CFGuard.cpp
  llvm/lib/Transforms/CFGuard/CMakeLists.txt
  llvm/lib/Transforms/CFGuard/LLVMBuild.txt
  llvm/lib/Transforms/CMakeLists.txt
  llvm/lib/Transforms/LLVMBuild.txt
  llvm/test/Bitcode/calling-conventions.3.2.ll
  llvm/test/Bitcode/calling-conventions.3.2.ll.bc
  llvm/test/CodeGen/AArch64/cfguard-checks.ll
  llvm/test/CodeGen/AArch64/cfguard-module-flag.ll
  llvm/test/CodeGen/ARM/cfguard-checks.ll
  llvm/test/CodeGen/ARM/cfguard-module-flag.ll
  llvm/test/CodeGen/WinCFGuard/cfguard-setjmp.ll
  llvm/test/CodeGen/WinCFGuard/cfguard.ll
  llvm/test/CodeGen/X86/cfguard-checks.ll
  llvm/test/CodeGen/X86/cfguard-module-flag.ll

Index: llvm/test/CodeGen/X86/cfguard-module-flag.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/cfguard-module-flag.ll
@@ -0,0 +1,28 @@
+
+; RUN: llc < %s -mtriple=i686-pc-windows-msvc | FileCheck %s -check-prefix=X32
+; RUN: llc < %s -mtriple=x86_64-pc-windows-msvc | FileCheck %s -check-prefix=X64
+
+; This test is disabled on Linux
+; UNSUPPORTED: linux
+
+; Test that Control Flow Guard checks are not added in modules with the 
+; cfguard=1 flag (emit tables but no checks).
+
+
+declare void @target_func()
+
+define void @func_in_module_without_cfguard() #0 {
+entry:
+  %func_ptr = alloca void ()*, align 8
+  store void ()* @target_func, void ()** %func_ptr, align 8
+  %0 = load void ()*, void ()** %func_ptr, align 8
+
+  call void %0()
+  ret void
+
+  ; X32-NOT: __guard_check_icall_fptr
+  ; X64-NOT: __guard_dispatch_icall_fptr
+}
+
+!llvm.module.flags = !{!0}
+!0 = !{i32 2, !"cfguard", i32 1}
\ No newline at end of file
Index: llvm/test/CodeGen/X86/cfguard-checks.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/cfguard-checks.ll
@@ -0,0 +1,124 @@
+; RUN: llc < %s -mtriple=i686-pc-windows-msvc | FileCheck %s -check-prefix=X32
+; RUN: llc < %s -mtriple=x86_64-pc-windows-msvc | FileCheck %s -check-prefix=X64
+
+; This test is disabled on Linux

[PATCH] D64838: [Attr] Support _attribute__ ((fallthrough))

2019-08-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Parse/ParseDecl.cpp:1767
 }
 return ParseSimpleDeclaration(Context, DeclEnd, attrs,
   true);

Should this also be passed `DeclSpecStart`?



Comment at: clang/lib/Parse/ParseStmt.cpp:233
+GNUAttributeLoc = Tok.getLocation();
+MaybeParseGNUAttributes(Attrs);
+goto Retry;

xbolva00 wrote:
> Since you know that tok is kw_attr, I think you can use 'ParseGNUAttributes'.
Agreed, you don't need to use the Maybe check here.



Comment at: clang/lib/Parse/ParseStmt.cpp:156
   StmtResult Res;
+  bool SeenGNUAttributes = false;
+  SourceLocation GNUAttributeLoc;

I think you can use `GNUAttributeLoc.isValid()` instead of using the extra 
local variable.



Comment at: clang/test/SemaCXX/warn-unused-label-error.cpp:23
+#pragma weak unused_local_static
+__attribute__((unused)) // expected-error {{'unused' attribute cannot be 
applied to a statement}}
+;

This change in diagnostics makes me very happy!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D64838



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


r367905 - [OpenMP 5.0] Codegen support for user-defined mappers.

2019-08-05 Thread Michael Kruse via cfe-commits
Author: meinersbur
Date: Mon Aug  5 11:43:21 2019
New Revision: 367905

URL: http://llvm.org/viewvc/llvm-project?rev=367905&view=rev
Log:
[OpenMP 5.0] Codegen support for user-defined mappers.

This patch implements the code generation for OpenMP 5.0 declare mapper
(user-defined mapper) constructs. For each declare mapper, a mapper
function is generated. These mapper functions will be called by the
runtime and/or other mapper functions to achieve user defined mapping.

The design slides can be found at
https://github.com/lingda-li/public-sharing/blob/master/mapper_runtime_design.pptx

Re-commit after revert in r367773 because r367755 changed the LLVM-IR
output such that a CHECK line failed.

Patch by Lingda Li 

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

Modified:
cfe/trunk/include/clang/AST/GlobalDecl.h
cfe/trunk/lib/AST/ASTContext.cpp
cfe/trunk/lib/CodeGen/CGDecl.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.h
cfe/trunk/lib/CodeGen/ModuleBuilder.cpp
cfe/trunk/test/OpenMP/declare_mapper_codegen.cpp

Modified: cfe/trunk/include/clang/AST/GlobalDecl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/GlobalDecl.h?rev=367905&r1=367904&r2=367905&view=diff
==
--- cfe/trunk/include/clang/AST/GlobalDecl.h (original)
+++ cfe/trunk/include/clang/AST/GlobalDecl.h Mon Aug  5 11:43:21 2019
@@ -59,6 +59,7 @@ public:
   GlobalDecl(const CapturedDecl *D) { Init(D); }
   GlobalDecl(const ObjCMethodDecl *D) { Init(D); }
   GlobalDecl(const OMPDeclareReductionDecl *D) { Init(D); }
+  GlobalDecl(const OMPDeclareMapperDecl *D) { Init(D); }
   GlobalDecl(const CXXConstructorDecl *D, CXXCtorType Type) : Value(D, Type) {}
   GlobalDecl(const CXXDestructorDecl *D, CXXDtorType Type) : Value(D, Type) {}
   GlobalDecl(const VarDecl *D, DynamicInitKind StubKind)

Modified: cfe/trunk/lib/AST/ASTContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=367905&r1=367904&r2=367905&view=diff
==
--- cfe/trunk/lib/AST/ASTContext.cpp (original)
+++ cfe/trunk/lib/AST/ASTContext.cpp Mon Aug  5 11:43:21 2019
@@ -9860,7 +9860,7 @@ bool ASTContext::DeclMustBeEmitted(const
 return !D->getDeclContext()->isDependentContext();
   else if (isa(D))
 return !D->getDeclContext()->isDependentContext();
-  else if (isa(D))
+  else if (isa(D) || isa(D))
 return !D->getDeclContext()->isDependentContext();
   else if (isa(D))
 return true;

Modified: cfe/trunk/lib/CodeGen/CGDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDecl.cpp?rev=367905&r1=367904&r2=367905&view=diff
==
--- cfe/trunk/lib/CodeGen/CGDecl.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDecl.cpp Mon Aug  5 11:43:21 2019
@@ -2530,10 +2530,11 @@ void CodeGenModule::EmitOMPDeclareReduct
 }
 
 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
-CodeGenFunction *CGF) {
-  if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
+ CodeGenFunction *CGF) {
+  if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
+  (!LangOpts.EmitAllDecls && !D->isUsed()))
 return;
-  // FIXME: need to implement mapper code generation
+  getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
 }
 
 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp?rev=367905&r1=367904&r2=367905&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp Mon Aug  5 11:43:21 2019
@@ -752,6 +752,11 @@ enum OpenMPRTLFunction {
   // arg_num, void** args_base, void **args, int64_t *arg_sizes, int64_t
   // *arg_types);
   OMPRTL__tgt_target_data_update_nowait,
+  // Call to int64_t __tgt_mapper_num_components(void *rt_mapper_handle);
+  OMPRTL__tgt_mapper_num_components,
+  // Call to void __tgt_push_mapper_component(void *rt_mapper_handle, void
+  // *base, void *begin, int64_t size, int64_t type);
+  OMPRTL__tgt_push_mapper_component,
 };
 
 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
@@ -1686,6 +1691,12 @@ void CGOpenMPRuntime::functionFinished(C
   UDRMap.erase(D);
 FunctionUDRMap.erase(CGF.CurFn);
   }
+  auto I = FunctionUDMMap.find(CGF.CurFn);
+  if (I != FunctionUDMMap.end()) {
+for(auto *D : I->second)
+  UDMMap.erase(D);
+FunctionUDMMap.erase(I);
+  }
 }
 
 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
@@ -2459,6 +2470,24 @@ llvm::FunctionCallee CGOpenMPRuntime::cr
 RTLFn = CGM.CreateR

r367906 - [DirectoryWatcher][linux] Fix build for older kernels

2019-08-05 Thread Jan Korous via cfe-commits
Author: jkorous
Date: Mon Aug  5 11:44:07 2019
New Revision: 367906

URL: http://llvm.org/viewvc/llvm-project?rev=367906&view=rev
Log:
[DirectoryWatcher][linux] Fix build for older kernels

Apparently kernel support for IN_EXCL_UNLINK in inotify_add_watch() doesn't 
imply it's defined in sys/inotify.h.

https://bugs.llvm.org/show_bug.cgi?id=42824

Modified:
cfe/trunk/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp

Modified: cfe/trunk/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp?rev=367906&r1=367905&r2=367906&view=diff
==
--- cfe/trunk/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp (original)
+++ cfe/trunk/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp Mon Aug  5 
11:44:07 2019
@@ -24,7 +24,6 @@
 #include 
 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -336,7 +335,7 @@ std::unique_ptr clang:
   InotifyFD, Path.str().c_str(),
   IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY |
   IN_MOVED_FROM | IN_MOVE_SELF | IN_MOVED_TO | IN_ONLYDIR | IN_IGNORED
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36)
+#ifdef IN_EXCL_UNLINK
   | IN_EXCL_UNLINK
 #endif
   );


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


[PATCH] D65597: WIP: Builtins: Start adding half versions of math builtins

2019-08-05 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D65597



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


[PATCH] D65628: [clang-doc] Parallelize reducing phase

2019-08-05 Thread Diego Astiazarán via Phabricator via cfe-commits
DiegoAstiazaran updated this revision to Diff 213425.
DiegoAstiazaran marked 2 inline comments as done.
DiegoAstiazaran added a comment.
Herald added a subscriber: jfb.

Fix atomicity issues.


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

https://reviews.llvm.org/D65628

Files:
  clang-tools-extra/clang-doc/tool/ClangDocMain.cpp

Index: clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
===
--- clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
+++ clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
@@ -38,7 +38,9 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/ThreadPool.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 
 using namespace clang::ast_matchers;
@@ -67,6 +69,12 @@
 llvm::cl::desc("CSS stylesheets to extend the default styles."),
 llvm::cl::cat(ClangDocCategory));
 
+static llvm::cl::opt ThreadCount(
+"thread-count",
+llvm::cl::desc("Threads to use for collecting and reducing infos."),
+llvm::cl::init(llvm::hardware_concurrency()),
+llvm::cl::cat(ClangDocCategory));
+
 enum OutputFormatTy {
   md,
   yaml,
@@ -153,30 +161,6 @@
   return Path;
 }
 
-// Iterate through tool results and build string map of info vectors from the
-// encoded bitstreams.
-bool bitcodeResultsToInfos(
-tooling::ToolResults &Results,
-llvm::StringMap>> &Output) {
-  bool Err = false;
-  Results.forEachResult([&](StringRef Key, StringRef Value) {
-llvm::BitstreamCursor Stream(Value);
-doc::ClangDocBitcodeReader Reader(Stream);
-auto Infos = Reader.readBitcode();
-if (!Infos) {
-  llvm::errs() << toString(Infos.takeError()) << "\n";
-  Err = true;
-  return;
-}
-for (auto &I : Infos.get()) {
-  auto R =
-  Output.try_emplace(Key, std::vector>());
-  R.first->second.emplace_back(std::move(I));
-}
-  });
-  return Err;
-}
-
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   std::error_code OK;
@@ -237,37 +221,68 @@
   // In ToolResults, the Key is the hashed USR and the value is the
   // bitcode-encoded representation of the Info object.
   llvm::outs() << "Collecting infos...\n";
-  llvm::StringMap>> USRToInfos;
-  if (bitcodeResultsToInfos(*Exec->get()->getToolResults(), USRToInfos))
-return 1;
+  llvm::StringMap> USRToBitcode;
+  Exec->get()->getToolResults()->forEachResult(
+  [&](StringRef Key, StringRef Value) {
+auto R = USRToBitcode.try_emplace(Key, std::vector());
+R.first->second.emplace_back(Value);
+  });
 
   // First reducing phase (reduce all decls into one info per decl).
-  llvm::outs() << "Reducing " << USRToInfos.size() << " infos...\n";
-  for (auto &Group : USRToInfos) {
-auto Reduced = doc::mergeInfos(Group.getValue());
-if (!Reduced) {
-  llvm::errs() << llvm::toString(Reduced.takeError());
-  continue;
-}
+  llvm::outs() << "Reducing " << USRToBitcode.size() << " infos...\n";
+  std::atomic Error;
+  Error = false;
+  llvm::ThreadPool Pool(ThreadCount);
+  for (auto &Group : USRToBitcode) {
+Pool.async([&]() {
+  std::vector> Infos;
 
-doc::Info *I = Reduced.get().get();
-auto InfoPath = getInfoOutputFile(OutDirectory, I->Path, I->extractName(),
-  "." + Format);
-if (!InfoPath) {
-  llvm::errs() << toString(InfoPath.takeError()) << "\n";
-  return 1;
-}
-std::error_code FileErr;
-llvm::raw_fd_ostream InfoOS(InfoPath.get(), FileErr, llvm::sys::fs::F_None);
-if (FileErr != OK) {
-  llvm::errs() << "Error opening info file: " << FileErr.message() << "\n";
-  continue;
-}
+  for (auto &Bitcode : Group.getValue()) {
+llvm::BitstreamCursor Stream(Bitcode);
+doc::ClangDocBitcodeReader Reader(Stream);
+auto ReadInfos = Reader.readBitcode();
+if (!ReadInfos) {
+  llvm::errs() << toString(ReadInfos.takeError()) << "\n";
+  Error = true;
+  return;
+}
+std::move(ReadInfos->begin(), ReadInfos->end(),
+  std::back_inserter(Infos));
+  }
+
+  auto Reduced = doc::mergeInfos(Infos);
+  if (!Reduced) {
+llvm::errs() << llvm::toString(Reduced.takeError());
+return;
+  }
+
+  doc::Info *I = Reduced.get().get();
+  auto InfoPath = getInfoOutputFile(OutDirectory, I->Path, I->extractName(),
+"." + Format);
+  if (!InfoPath) {
+llvm::errs() << toString(InfoPath.takeError()) << "\n";
+Error = true;
+return;
+  }
+  std::error_code FileErr;
+  llvm::raw_fd_ostream InfoOS(InfoPath.get(), FileErr,
+  llvm::sys::fs::F_None);
+  if (FileErr != OK) {
+llvm::errs() << "Error opening info file: " << FileErr.message()
+ 

r367912 - Fix another uninit read found by msan after r367829

2019-08-05 Thread Nico Weber via cfe-commits
Author: nico
Date: Mon Aug  5 12:35:59 2019
New Revision: 367912

URL: http://llvm.org/viewvc/llvm-project?rev=367912&view=rev
Log:
Fix another uninit read found by msan after r367829

Modified:
cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h

Modified: cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h?rev=367912&r1=367911&r2=367912&view=diff
==
--- cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h (original)
+++ cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h Mon Aug  5 12:35:59 
2019
@@ -283,7 +283,7 @@ private:
   class LoadGuard {
   public:
 LoadGuard(unsigned Limit, unsigned &Counter)
-: Counter(Counter), Enabled(Counter < Limit) {}
+: Counter(Counter), Enabled(Counter < Limit), StoreSuccess(false) {}
 ~LoadGuard() {
   if (StoreSuccess)
 ++Counter;


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


Re: r367829 - [CrossTU][NFCI] Refactor loadExternalAST function

2019-08-05 Thread Nico Weber via cfe-commits
There was yet another uninit read:


Testing: 0 .. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80..
FAIL: Clang-Unit ::
CrossTU/./CrossTUTests/CrossTranslationUnit.RespectsLoadThreshold (13891 of
15323)
 TEST 'Clang-Unit ::
CrossTU/./CrossTUTests/CrossTranslationUnit.RespectsLoadThreshold' FAILED

Note: Google Test filter = CrossTranslationUnit.RespectsLoadThreshold
[==] Running 1 test from 1 test case.
[--] Global test environment set-up.
[--] 1 test from CrossTranslationUnit
[ RUN  ] CrossTranslationUnit.RespectsLoadThreshold
==8561==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x1010708 in ~LoadGuard
/b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm/tools/clang/include/clang/CrossTU/CrossTranslationUnit.h:288:11
#1 0x1010708 in
clang::cross_tu::CrossTranslationUnitContext::loadExternalAST(llvm::StringRef,
llvm::StringRef, llvm::StringRef, bool)
/b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:499:1
#2 0x100babc in llvm::Expected
clang::cross_tu::CrossTranslationUnitContext::getCrossTUDefinitionImpl(clang::FunctionDecl
const*, llvm::StringRef, llvm::StringRef, bool)
/b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:241:7
#3 0x100b476 in
clang::cross_tu::CrossTranslationUnitContext::getCrossTUDefinition(clang::FunctionDecl
const*, llvm::StringRef, llvm::StringRef, bool)
/b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm/tools/clang/lib/CrossTU/CrossTranslationUnit.cpp:307:10


I tried fixing that one in r367912. Please verify that that's what you
meant as well.

On Mon, Aug 5, 2019 at 11:22 AM Nico Weber  wrote:

> The problem is probably this part from the diff:
>
> -  unsigned NumASTLoaded{0u};
> +
> +  /// The number successfully loaded ASTs. Used to indicate, and  - with
> the
> +  /// appropriate threshold value - limit the  memory usage of the
> +  /// CrossTranslationUnitContext.
> +  unsigned NumASTLoaded;
>
>
> i.e. you removed the initialization of NumASTLoaded. Was there a reason
> for that? I've put it back for now in r367875, but please verify that the
> code now does what you intended it to do – maybe you were planning to
> initialize this somewhere else.
>
> On Mon, Aug 5, 2019 at 10:03 AM Nico Weber  wrote:
>
>> The msan bot doesn't like this, it reports an uninitialized read a
>> t clang/lib/CrossTU/CrossTranslationUnit.cpp :
>>
>>
>> http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-fast/builds/34087/steps/check-clang%20msan/logs/stdio
>>
>> 
>> Testing: 0
>> FAIL: Clang :: Analysis/ctu-unknown-parts-in-triples.cpp (492 of 15321)
>>  TEST 'Clang ::
>> Analysis/ctu-unknown-parts-in-triples.cpp' FAILED 
>> Script:
>> --
>> : 'RUN: at line 4';   rm -rf
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp
>> && mkdir
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp
>> : 'RUN: at line 5';   mkdir -p
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir
>> : 'RUN: at line 6';
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/bin/clang -cc1
>> -internal-isystem
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/lib/clang/10.0.0/include
>> -nostdsysteminc -triple x86_64-pc-linux-gnu-emit-pch -o
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir/ctu-other.cpp.ast
>> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/Inputs/ctu-other.cpp
>> : 'RUN: at line 8';   cp
>> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir/externalDefMap.txt
>> : 'RUN: at line 9';
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/bin/clang -cc1
>> -internal-isystem
>> /b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/lib/clang/10.0.0/include
>> -nostdsysteminc -analyze -analyzer-constraints=range -triple
>> x86_64-unknown-linux-gnu-analyzer-checker=core,debug.ExprInspection
>>  -analyzer-config experimental-enable-naive-ctu-analysis=true
>>  -analyzer-config
>> ctu-dir=/b/sanitizer-x86_64-linux-fast/build/llvm_build_msan/tools/clang/test/Analysis/Output/ctu-unknown-parts-in-triples.cpp.tmp/ctudir
>>-Werror=ctu-verify
>> /b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/Analysis/ctu-unknown-parts-in-triples.cpp
>> --
>> Exit Code: 77
>>
>> Command Output (stderr):
>> --
>> ==5072==WARNING: MemorySanitizer: use-of-uninitialized-value
>> #0 0xb05c3c4 in
>> clang::cross_tu::CrossTranslationUni

  1   2   >