[PATCH] D46050: [Frontend] Avoid running plugins during code completion parse

2018-05-16 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik updated this revision to Diff 146999.
nik added a comment.

Addressed inline nit.


Repository:
  rC Clang

https://reviews.llvm.org/D46050

Files:
  lib/Frontend/FrontendAction.cpp
  test/Index/complete-and-plugins.c


Index: test/Index/complete-and-plugins.c
===
--- /dev/null
+++ test/Index/complete-and-plugins.c
@@ -0,0 +1,7 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load 
%llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck 
%s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
+
Index: lib/Frontend/FrontendAction.cpp
===
--- lib/Frontend/FrontendAction.cpp
+++ lib/Frontend/FrontendAction.cpp
@@ -153,6 +153,10 @@
   if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
 return Consumer;
 
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
   // Collect the list of plugins that go before the main action (in Consumers)
   // or after it (in AfterConsumers)
   std::vector> Consumers;


Index: test/Index/complete-and-plugins.c
===
--- /dev/null
+++ test/Index/complete-and-plugins.c
@@ -0,0 +1,7 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load %llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck %s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
+
Index: lib/Frontend/FrontendAction.cpp
===
--- lib/Frontend/FrontendAction.cpp
+++ lib/Frontend/FrontendAction.cpp
@@ -153,6 +153,10 @@
   if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
 return Consumer;
 
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
   // Collect the list of plugins that go before the main action (in Consumers)
   // or after it (in AfterConsumers)
   std::vector> Consumers;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46050: [Frontend] Avoid running plugins during code completion parse

2018-05-16 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik added a comment.

If this is fine now, please submit as I don't have the permissions to do so.


Repository:
  rC Clang

https://reviews.llvm.org/D46050



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


[PATCH] D43290: clang-format: tweak formatting of variable initialization blocks

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 147002.
Typz marked 6 inline comments as done.
Typz added a comment.

Address review comment & rebase


Repository:
  rC Clang

https://reviews.llvm.org/D43290

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


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -6708,6 +6708,15 @@
"};");
   verifyFormat("#define A {a, a},");
 
+  // Avoid breaking between equal sign and opening brace
+  FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
+  AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable =\n"
+   "{{\"a\", 0},\n"
+   " {\"b\", 1},\n"
+   " {\"c\", 2}};",
+   AvoidBreakingFirstArgument);
+
   // Binpacking only if there is no trailing comma
   verifyFormat("const Aa a = {aa, bb,\n"
"  cc, dd};",
@@ -6864,6 +6873,21 @@
   verifyFormat("vector foo = { ::SomeGlobalFunction() };", ExtraSpaces);
   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
+
+  // Avoid breaking between initializer/equal sign and opening brace
+  ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable = {\n"
+   "  { \"a\", 0 },\n"
+   "  { \"b\", 1 },\n"
+   "  { \"c\", 2 }\n"
+   "};",
+   ExtraSpaces);
+  verifyFormat("const std::unordered_map MyHashTable{\n"
+   "  { \"a\", 0 },\n"
+   "  { \"b\", 1 },\n"
+   "  { \"c\", 2 }\n"
+   "};",
+   ExtraSpaces);
 }
 
 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2311,6 +2311,8 @@
   if (Left.opensScope()) {
 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
   return 0;
+if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
+  return 19;
 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
: 19;
   }
@@ -3048,6 +3050,9 @@
   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
   Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
 return false;
+  if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
+  !Style.Cpp11BracedListStyle)
+return false;
   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
 return false;
   if (Left.is(tok::l_paren) && Left.Previous &&


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -6708,6 +6708,15 @@
"};");
   verifyFormat("#define A {a, a},");
 
+  // Avoid breaking between equal sign and opening brace
+  FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
+  AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable =\n"
+   "{{\"a\", 0},\n"
+   " {\"b\", 1},\n"
+   " {\"c\", 2}};",
+   AvoidBreakingFirstArgument);
+
   // Binpacking only if there is no trailing comma
   verifyFormat("const Aa a = {aa, bb,\n"
"  cc, dd};",
@@ -6864,6 +6873,21 @@
   verifyFormat("vector foo = { ::SomeGlobalFunction() };", ExtraSpaces);
   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
+
+  // Avoid breaking between initializer/equal sign and opening brace
+  ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable = {\n"
+   "  { \"a\", 0 },\n"
+   "  { \"b\", 1 },\n"
+   "  { \"c\", 2 }\n"
+   "};",
+   ExtraSpaces);
+  verifyFormat("const std::unordered_map MyHashTable{\n"
+   "  { \"a\", 0 },\n"
+   "  { \"b\", 1 },\n"
+   "  { \"c\", 2 }\n"
+   "};",
+   ExtraSpaces);
 }
 
 TEST_F(Format

Re: r332314 - [AST] Fix printing tag decl groups in decl contexts

2018-05-16 Thread Hans Wennborg via cfe-commits
On Tue, May 15, 2018 at 7:30 PM, Joel E. Denny  wrote:
> Hi Hans,
>
> On Tue, May 15, 2018 at 6:23 AM, Hans Wennborg  wrote:
>>
>> This broke the ast-print-record-decl.c test on Windows, see for
>> example
>> http://lab.llvm.org:8011/builders/clang-with-thin-lto-windows/builds/9066
>>
>> One way to reproduce the failure on Linux is to pass a Windows triple
>> to this ast-print command:
>>
>> --- a/test/Misc/ast-print-record-decl.c
>> +++ b/test/Misc/ast-print-record-decl.c
>> @@ -54,7 +54,7 @@
>>  //   RUN:-DKW=struct -DBASES=' : B' -o - -xc++ %s \
>>  //   RUN: | FileCheck --check-prefixes=CHECK,LLVM %s
>>  //
>> -//   RUN: %clang_cc1 -verify -ast-print -DKW=struct -DBASES=' : B' -xc++
>> %s \
>> +//   RUN: %clang_cc1 -verify -triple i686-pc-win32 -ast-print
>> -DKW=struct -DBASES=' : B' -xc++ %s \
>>  //   RUN: > %t.cpp
>>  //   RUN: FileCheck --check-prefixes=CHECK,PRINT,PRINT-CXX -DKW=struct \
>>  //   RUN:   -DBASES=' : B' %s --input-file %t.cpp
>>
>> What's happening is that on Windows, "__single_inheritance(1)" is
>> printed before T1. But if I change the test to allow that in the
>> output, it still doesn't pass as Clang doesn't seem able to parse it.
>
>
> The underlying bug is present at least as far back as 4.0.1.  The bug is
> revealed by an earlier patch, r332281, simply because it introduces this
> test.
>
> There are two parts to this bug.  First, implicit attributes shouldn't print
> as that's not faithful to the original source.  I'm addressing that at
>
> https://reviews.llvm.org/D46894
>
> Second, when this attribute is explicit, the "(1)" shouldn't print as it's
> not part of the accepted syntax.  I'll address that in another patch.

Great! Thanks for digging into this and fixing.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332434 - clang-format: tweak formatting of variable initialization blocks

2018-05-16 Thread Francois Ferrand via cfe-commits
Author: typz
Date: Wed May 16 01:03:52 2018
New Revision: 332434

URL: http://llvm.org/viewvc/llvm-project?rev=332434&view=rev
Log:
clang-format: tweak formatting of variable initialization blocks

Summary:
This patch changes the behavior of PenaltyBreakBeforeFirstCallParameter
so that is does not apply after a brace, when Cpp11BracedListStyle is
false.

This way, variable initialization is wrapped more like an initializer
than like a function call, which is more consistent with user
expectations for this braced list style.

With PenaltyBreakBeforeFirstCallParameter=200, this gives the following
code: (with Cpp11BracedListStyle=false)

Before :

  const std::unordered_map Something::MyHashTable =
  { { "a", 0 },
{ "b", 1 },
{ "c", 2 } };

After :

  const std::unordered_set Something::MyUnorderedSet = {
{ "a", 0 },
{ "b", 1 },
{ "c", 2 }
  };

Reviewers: krasimir, djasper, klimek

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=332434&r1=332433&r2=332434&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Wed May 16 01:03:52 2018
@@ -2311,6 +2311,8 @@ unsigned TokenAnnotator::splitPenalty(co
   if (Left.opensScope()) {
 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
   return 0;
+if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
+  return 19;
 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
: 19;
   }
@@ -3048,6 +3050,9 @@ bool TokenAnnotator::canBreakBefore(cons
   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
   Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
 return false;
+  if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
+  !Style.Cpp11BracedListStyle)
+return false;
   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
 return false;
   if (Left.is(tok::l_paren) && Left.Previous &&

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=332434&r1=332433&r2=332434&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed May 16 01:03:52 2018
@@ -6708,6 +6708,15 @@ TEST_F(FormatTest, LayoutCxx11BraceIniti
"};");
   verifyFormat("#define A {a, a},");
 
+  // Avoid breaking between equal sign and opening brace
+  FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
+  AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable =\n"
+   "{{\"a\", 0},\n"
+   " {\"b\", 1},\n"
+   " {\"c\", 2}};",
+   AvoidBreakingFirstArgument);
+
   // Binpacking only if there is no trailing comma
   verifyFormat("const Aa a = {aa, bb,\n"
"  cc, dd};",
@@ -6864,6 +6873,21 @@ TEST_F(FormatTest, LayoutCxx11BraceIniti
   verifyFormat("vector foo = { ::SomeGlobalFunction() };", ExtraSpaces);
   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
+
+  // Avoid breaking between initializer/equal sign and opening brace
+  ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable = {\n"
+   "  { \"a\", 0 },\n"
+   "  { \"b\", 1 },\n"
+   "  { \"c\", 2 }\n"
+   "};",
+   ExtraSpaces);
+  verifyFormat("const std::unordered_map MyHashTable{\n"
+   "  { \"a\", 0 },\n"
+   "  { \"b\", 1 },\n"
+   "  { \"c\", 2 }\n"
+   "};",
+   ExtraSpaces);
 }
 
 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {


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


[PATCH] D43290: clang-format: tweak formatting of variable initialization blocks

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC332434: clang-format: tweak formatting of variable 
initialization blocks (authored by Typz, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D43290?vs=147002&id=147003#toc

Repository:
  rC Clang

https://reviews.llvm.org/D43290

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


Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2311,6 +2311,8 @@
   if (Left.opensScope()) {
 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
   return 0;
+if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
+  return 19;
 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
: 19;
   }
@@ -3048,6 +3050,9 @@
   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
   Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
 return false;
+  if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
+  !Style.Cpp11BracedListStyle)
+return false;
   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
 return false;
   if (Left.is(tok::l_paren) && Left.Previous &&
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -6708,6 +6708,15 @@
"};");
   verifyFormat("#define A {a, a},");
 
+  // Avoid breaking between equal sign and opening brace
+  FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
+  AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable =\n"
+   "{{\"a\", 0},\n"
+   " {\"b\", 1},\n"
+   " {\"c\", 2}};",
+   AvoidBreakingFirstArgument);
+
   // Binpacking only if there is no trailing comma
   verifyFormat("const Aa a = {aa, bb,\n"
"  cc, dd};",
@@ -6864,6 +6873,21 @@
   verifyFormat("vector foo = { ::SomeGlobalFunction() };", ExtraSpaces);
   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
+
+  // Avoid breaking between initializer/equal sign and opening brace
+  ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable = {\n"
+   "  { \"a\", 0 },\n"
+   "  { \"b\", 1 },\n"
+   "  { \"c\", 2 }\n"
+   "};",
+   ExtraSpaces);
+  verifyFormat("const std::unordered_map MyHashTable{\n"
+   "  { \"a\", 0 },\n"
+   "  { \"b\", 1 },\n"
+   "  { \"c\", 2 }\n"
+   "};",
+   ExtraSpaces);
 }
 
 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {


Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2311,6 +2311,8 @@
   if (Left.opensScope()) {
 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
   return 0;
+if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
+  return 19;
 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
: 19;
   }
@@ -3048,6 +3050,9 @@
   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
   Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
 return false;
+  if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
+  !Style.Cpp11BracedListStyle)
+return false;
   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
 return false;
   if (Left.is(tok::l_paren) && Left.Previous &&
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -6708,6 +6708,15 @@
"};");
   verifyFormat("#define A {a, a},");
 
+  // Avoid breaking between equal sign and opening brace
+  FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
+  AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
+  verifyFormat("const std::unordered_map MyHashTable =\n"
+   "{{\"a\", 0},\n"
+   " {\"b\", 1},\n"
+   " {\"c\", 2}};",
+   AvoidBreakingFirstArgument);
+
   // Binpacking only if there is no t

[PATCH] D42684: clang-format: Allow optimizer to break template declaration.

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 147005.
Typz marked 3 inline comments as done.
Typz added a comment.

Rebase on latest master & address review comments


Repository:
  rC Clang

https://reviews.llvm.org/D42684

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -5475,7 +5475,7 @@
"const typename  aaa);");
 
   FormatStyle AlwaysBreak = getLLVMStyle();
-  AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
+  AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
   verifyFormat("template \nclass C {};", AlwaysBreak);
   verifyFormat("template \nvoid f();", AlwaysBreak);
   verifyFormat("template \nvoid f() {}", AlwaysBreak);
@@ -5493,6 +5493,32 @@
"public:\n"
"  E *f();\n"
"};");
+
+  FormatStyle NeverBreak = getLLVMStyle();
+  NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
+  verifyFormat("template  class C {};", NeverBreak);
+  verifyFormat("template  void f();", NeverBreak);
+  verifyFormat("template  void f() {}", NeverBreak);
+  verifyFormat("template \nvoid foo(aa ) {}",
+   NeverBreak);
+  verifyFormat("void aaa(\n"
+   "ccc);",
+   NeverBreak);
+  verifyFormat("template  class Fooo,\n"
+   "  template  class Baaar>\n"
+   "struct C {};",
+   NeverBreak);
+  verifyFormat("template  // T can be A, B or C.\n"
+   "struct C {};",
+   NeverBreak);
+  verifyFormat("template  class A {\n"
+   "public:\n"
+   "  E *f();\n"
+   "};", NeverBreak);
+  NeverBreak.PenaltyBreakTemplateDeclaration = 100;
+  verifyFormat("template  void\nfoo(aa ) {}",
+   NeverBreak);
 }
 
 TEST_F(FormatTest, WrapsTemplateParameters) {
@@ -10440,7 +10466,6 @@
   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
   CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
-  CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
   CHECK_PARSE_BOOL(BinPackArguments);
   CHECK_PARSE_BOOL(BinPackParameters);
   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
@@ -10506,6 +10531,8 @@
   PenaltyBreakAssignment, 1234u);
   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
   PenaltyBreakBeforeFirstCallParameter, 1234u);
+  CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
+  PenaltyBreakTemplateDeclaration, 1234u);
   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
   PenaltyReturnTypeOnItsOwnLine, 1234u);
@@ -10660,6 +10687,18 @@
   AlwaysBreakAfterReturnType,
   FormatStyle::RTBS_TopLevelDefinitions);
 
+  Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_No);
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_MultiLine);
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_Yes);
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_MultiLine);
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_Yes);
+
   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
   AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2338,6 +2338,8 @@
   return 2;
 return 1;
   }
+  if (Left.ClosesTemplateDeclaration)
+return Style.PenaltyBreakTemplateDeclaration;
   if (Left.is(TT_ConditionalExpr))
 return prec::Conditional;
   prec::Level Level = Left.getPrecedence();
@@ -2869,7 +2871,7 @@
   if (Right.Previous->ClosesTemplateDeclaration &&
   Right.Previous->MatchingParen &&
   Right.Previous->MatchingParen->NestingLevel == 0 &&
-  Style.AlwaysBreakTemplateDeclarations)
+  Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
 return true;
   if (Righ

r332436 - clang-format: Allow optimizer to break template declaration.

2018-05-16 Thread Francois Ferrand via cfe-commits
Author: typz
Date: Wed May 16 01:25:03 2018
New Revision: 332436

URL: http://llvm.org/viewvc/llvm-project?rev=332436&view=rev
Log:
clang-format: Allow optimizer to break template declaration.

Summary:
Introduce `PenaltyBreakTemplateDeclaration` to control the penalty,
and change `AlwaysBreakTemplateDeclarations` to an enum with 3 modes:
* `No` for regular, penalty based, wrapping of template declaration
* `MultiLine` for always wrapping before multi-line declarations (e.g.
  same as legacy behavior when `AlwaysBreakTemplateDeclarations=false`)
* `Yes` for always wrapping (e.g. same as legacy behavior when
  `AlwaysBreakTemplateDeclarations=true`)

Reviewers: krasimir, djasper, klimek

Subscribers: cfe-commits

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

Modified:
cfe/trunk/docs/ClangFormatStyleOptions.rst
cfe/trunk/include/clang/Format/Format.h
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=332436&r1=332435&r2=332436&view=diff
==
--- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
+++ cfe/trunk/docs/ClangFormatStyleOptions.rst Wed May 16 01:25:03 2018
@@ -490,15 +490,50 @@ the configuration (without a prefix: ``A
  """";
  "";
 
-**AlwaysBreakTemplateDeclarations** (``bool``)
-  If ``true``, always break after the ``template<...>`` of a template
-  declaration.
+**AlwaysBreakTemplateDeclarations** (``BreakTemplateDeclarationsStyle``)
+  The template declaration breaking style to use.
+
+  Possible values:
+
+  * ``BTDS_No`` (in configuration: ``No``)
+Do not force break before declaration.
+``PenaltyBreakTemplateDeclaration`` is taken into account.
+
+.. code-block:: c++
+
+   template  T foo() {
+   }
+   template  T foo(int a,
+   int b) {
+   }
+
+  * ``BTDS_MultiLine`` (in configuration: ``MultiLine``)
+Force break after template declaration only when the following
+declaration spans multiple lines.
+
+.. code-block:: c++
+
+   template  T foo() {
+   }
+   template 
+   T foo(int a,
+ int b) {
+   }
+
+  * ``BTDS_Yes`` (in configuration: ``Yes``)
+Always break after template declaration.
+
+.. code-block:: c++
+
+   template 
+   T foo() {
+   }
+   template 
+   T foo(int a,
+ int b) {
+   }
 
-  .. code-block:: c++
 
- true:  false:
- template   vs. template  class C {};
- class C {};
 
 **BinPackArguments** (``bool``)
   If ``false``, a function call's arguments will either be all on the
@@ -1590,6 +1625,9 @@ the configuration (without a prefix: ``A
 **PenaltyBreakString** (``unsigned``)
   The penalty for each line break introduced inside a string literal.
 
+**PenaltyBreakTemplateDeclaration** (``unsigned``)
+  The penalty for breaking after template declaration.
+
 **PenaltyExcessCharacter** (``unsigned``)
   The penalty for each character outside of the column limit.
 

Modified: cfe/trunk/include/clang/Format/Format.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=332436&r1=332435&r2=332436&view=diff
==
--- cfe/trunk/include/clang/Format/Format.h (original)
+++ cfe/trunk/include/clang/Format/Format.h Wed May 16 01:25:03 2018
@@ -351,14 +351,44 @@ struct FormatStyle {
   /// \endcode
   bool AlwaysBreakBeforeMultilineStrings;
 
-  /// If ``true``, always break after the ``template<...>`` of a template
-  /// declaration.
-  /// \code
-  ///true:  false:
-  ///template   vs. template  class C 
{};
-  ///class C {};
-  /// \endcode
-  bool AlwaysBreakTemplateDeclarations;
+  /// Different ways to break after the template declaration.
+  enum BreakTemplateDeclarationsStyle {
+  /// Do not force break before declaration.
+  /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
+  /// \code
+  ///template  T foo() {
+  ///}
+  ///template  T foo(int a,
+  ///int b) {
+  ///}
+  /// \endcode
+  BTDS_No,
+  /// Force break after template declaration only when the following
+  /// declaration spans multiple lines.
+  /// \code
+  ///template  T foo() {
+  ///}
+  ///template 
+  ///T foo(int 

[PATCH] D42684: clang-format: Allow optimizer to break template declaration.

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332436: clang-format: Allow optimizer to break template 
declaration. (authored by Typz, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42684?vs=147005&id=147006#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42684

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

Index: cfe/trunk/include/clang/Format/Format.h
===
--- cfe/trunk/include/clang/Format/Format.h
+++ cfe/trunk/include/clang/Format/Format.h
@@ -351,14 +351,44 @@
   /// \endcode
   bool AlwaysBreakBeforeMultilineStrings;
 
-  /// If ``true``, always break after the ``template<...>`` of a template
-  /// declaration.
-  /// \code
-  ///true:  false:
-  ///template   vs. template  class C {};
-  ///class C {};
-  /// \endcode
-  bool AlwaysBreakTemplateDeclarations;
+  /// Different ways to break after the template declaration.
+  enum BreakTemplateDeclarationsStyle {
+  /// Do not force break before declaration.
+  /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
+  /// \code
+  ///template  T foo() {
+  ///}
+  ///template  T foo(int a,
+  ///int b) {
+  ///}
+  /// \endcode
+  BTDS_No,
+  /// Force break after template declaration only when the following
+  /// declaration spans multiple lines.
+  /// \code
+  ///template  T foo() {
+  ///}
+  ///template 
+  ///T foo(int a,
+  ///  int b) {
+  ///}
+  /// \endcode
+  BTDS_MultiLine,
+  /// Always break after template declaration.
+  /// \code
+  ///template 
+  ///T foo() {
+  ///}
+  ///template 
+  ///T foo(int a,
+  ///  int b) {
+  ///}
+  /// \endcode
+  BTDS_Yes
+  };
+
+  /// The template declaration breaking style to use.
+  BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
 
   /// If ``false``, a function call's arguments will either be all on the
   /// same line or will have one line each.
@@ -1295,6 +1325,9 @@
   /// The penalty for each line break introduced inside a string literal.
   unsigned PenaltyBreakString;
 
+  /// The penalty for breaking after template declaration.
+  unsigned PenaltyBreakTemplateDeclaration;
+
   /// The penalty for each character outside of the column limit.
   unsigned PenaltyExcessCharacter;
 
@@ -1679,6 +1712,8 @@
PenaltyBreakString == R.PenaltyBreakString &&
PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
+   PenaltyBreakTemplateDeclaration ==
+   R.PenaltyBreakTemplateDeclaration &&
PointerAlignment == R.PointerAlignment &&
RawStringFormats == R.RawStringFormats &&
SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2338,6 +2338,8 @@
   return 2;
 return 1;
   }
+  if (Left.ClosesTemplateDeclaration)
+return Style.PenaltyBreakTemplateDeclaration;
   if (Left.is(TT_ConditionalExpr))
 return prec::Conditional;
   prec::Level Level = Left.getPrecedence();
@@ -2869,7 +2871,7 @@
   if (Right.Previous->ClosesTemplateDeclaration &&
   Right.Previous->MatchingParen &&
   Right.Previous->MatchingParen->NestingLevel == 0 &&
-  Style.AlwaysBreakTemplateDeclarations)
+  Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
 return true;
   if (Right.is(TT_CtorInitializerComma) &&
   Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
Index: cfe/trunk/lib/Format/ContinuationIndenter.cpp
===
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp
@@ -402,6 +402,12 @@
 Style.Language == FormatStyle::LK_JavaScript))
 return true;
 
+  // If the template declaration spans multiple lines, force wrap before the
+  // function/class declaration
+  if (Previous.ClosesTemplateDeclaration &&
+  State.Stack.back().BreakBeforeParameter)
+return true;
+
   if (State.Column <= NewLineColumn)
 return false;
 
@@ -453,7 +459,7 @@
 // for cases whe

[PATCH] D46906: [clangd] Fix a link failure in unittests

2018-05-16 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46906



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


[PATCH] D43015: clang-format: Introduce BreakInheritanceList option

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 147011.
Typz added a comment.

Rebase on latest master


Repository:
  rC Clang

https://reviews.llvm.org/D43015

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1316,15 +1316,40 @@
   verifyFormat("class ::A::B {};");
 }
 
-TEST_F(FormatTest, BreakBeforeInheritanceComma) {
-  FormatStyle StyleWithInheritanceBreak = getLLVMStyle();
-  StyleWithInheritanceBreak.BreakBeforeInheritanceComma = true;
-
-  verifyFormat("class MyClass : public X {};", StyleWithInheritanceBreak);
+TEST_F(FormatTest, BreakInheritanceStyle) {
+  FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
+  StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
+  FormatStyle::BILS_BeforeComma;
+  verifyFormat("class MyClass : public X {};",
+   StyleWithInheritanceBreakBeforeComma);
   verifyFormat("class MyClass\n"
": public X\n"
", public Y {};",
-   StyleWithInheritanceBreak);
+   StyleWithInheritanceBreakBeforeComma);
+  verifyFormat("class AA\n"
+   ": public BB\n"
+   ", public CC {};",
+   StyleWithInheritanceBreakBeforeComma);
+  verifyFormat("struct a\n"
+   ": public aaa< // break\n"
+   "  > {};",
+   StyleWithInheritanceBreakBeforeComma);
+
+  FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
+  StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
+  FormatStyle::BILS_AfterColon;
+  verifyFormat("class MyClass : public X {};",
+   StyleWithInheritanceBreakAfterColon);
+  verifyFormat("class MyClass : public X, public Y {};",
+   StyleWithInheritanceBreakAfterColon);
+  verifyFormat("class AA :\n"
+   "public BB,\n"
+   "public CC {};",
+   StyleWithInheritanceBreakAfterColon);
+  verifyFormat("struct a :\n"
+   "public aaa< // break\n"
+   "> {};",
+   StyleWithInheritanceBreakAfterColon);
 }
 
 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
@@ -3726,6 +3751,23 @@
"  aa,\n"
"  bb {}",
Style);
+
+  // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as well
+  Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
+  verifyFormat("class SomeClass\n"
+   "  : public aa,\n"
+   "public bb {};",
+   Style);
+  Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
+  verifyFormat("class SomeClass\n"
+   "  : public aa\n"
+   "  , public bb {};",
+   Style);
+  Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
+  verifyFormat("class SomeClass :\n"
+   "  public aa,\n"
+   "  public bb {};",
+   Style);
 }
 
 #ifndef EXPENSIVE_CHECKS
@@ -9101,7 +9143,7 @@
"  (2) {}",
CtorInitializerStyle);
 
-  FormatStyle InheritanceStyle = getLLVMStyle();
+  FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
   InheritanceStyle.SpaceBeforeInheritanceColon = false;
   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
@@ -9117,6 +9159,29 @@
"default:\n"
"}",
InheritanceStyle);
+  InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
+  verifyFormat("class Foo:\n"
+   "public aa,\n"
+   "public bb {\n"
+   "}",
+   InheritanceStyle);
+  InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
+  verifyFormat("class Foo\n"
+   ": public aa\n"
+   ", public bb {\n"
+   "}",
+   Inher

[PATCH] D43015: clang-format: Introduce BreakInheritanceList option

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

ping?


Repository:
  rC Clang

https://reviews.llvm.org/D43015



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


[PATCH] D46906: [clangd] Fix a link failure in unittests

2018-05-16 Thread Heejin Ahn via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332438: [clangd] Fix a link failure in unittests (authored 
by aheejin, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D46906

Files:
  clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt


Index: clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
===
--- clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
+++ clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
@@ -38,6 +38,7 @@
 
 target_link_libraries(ClangdTests
   PRIVATE
+  clangAST
   clangBasic
   clangDaemon
   clangFormat


Index: clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
===
--- clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
+++ clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
@@ -38,6 +38,7 @@
 
 target_link_libraries(ClangdTests
   PRIVATE
+  clangAST
   clangBasic
   clangDaemon
   clangFormat
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r332438 - [clangd] Fix a link failure in unittests

2018-05-16 Thread Heejin Ahn via cfe-commits
Author: aheejin
Date: Wed May 16 01:53:57 2018
New Revision: 332438

URL: http://llvm.org/viewvc/llvm-project?rev=332438&view=rev
Log:
[clangd] Fix a link failure in unittests

Summary: D46524 (rL332378) introduced a link failure when built with
`-DSHARED_LIB=ON`, which this patch fixes.

Reviewers: ioeric

Subscribers: klimek, mgorny, ilya-biryukov, ioeric, MaskRay, jkorous, 
cfe-commits

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

Modified:
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt

Modified: clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt?rev=332438&r1=332437&r2=332438&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt Wed May 16 01:53:57 
2018
@@ -38,6 +38,7 @@ add_extra_unittest(ClangdTests
 
 target_link_libraries(ClangdTests
   PRIVATE
+  clangAST
   clangBasic
   clangDaemon
   clangFormat


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


[PATCH] D45927: [clang-tidy] [modernize-use-auto] Correct way to calculate a type name length for multi-token types

2018-05-16 Thread Zinovy Nis via Phabricator via cfe-commits
zinovy.nis marked an inline comment as done.
zinovy.nis added inline comments.



Comment at: modernize/UseAutoCheck.cpp:40
+? Alpha
+: (std::isspace(C) || (!RemoveStars && C == '*')) ? Space
+  : Punctuation;

rsmith wrote:
> `isspace` here is wrong: it's a locale-sensitive check. Clang assumes UTF-8 
> throughout; you can use `isWhitespace` from clang/Basic/CharInfo.h to test if 
> the character should be treated as whitespace.
Thanks!


https://reviews.llvm.org/D45927



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


[PATCH] D33440: clang-format: better handle statement macros

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 147024.
Typz added a comment.
Herald added a subscriber: mgrang.

Rebase on latest master


Repository:
  rC Clang

https://reviews.llvm.org/D33440

Files:
  include/clang/Format/Format.h
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/FormatTokenLexer.cpp
  lib/Format/FormatTokenLexer.h
  lib/Format/UnwrappedLineParser.cpp
  lib/Format/UnwrappedLineParser.h
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -2472,6 +2472,45 @@
getLLVMStyleWithColumns(40)));
 
   verifyFormat("MACRO(>)");
+
+  // Some macros contain an implicit semicolon
+  FormatStyle Style = getLLVMStyle();
+  Style.StatementMacros.push_back("FOO");
+  verifyFormat("FOO(a) int b = 0;");
+  verifyFormat("FOO(a)\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("FOO(a);\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("FOO()\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("FOO\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("void f() {\n"
+   "  FOO(a)\n"
+   "  return a;\n"
+   "}",
+   Style);
+  verifyFormat("FOO(a)\n"
+   "FOO(b)",
+   Style);
+  verifyFormat("int a = 0;\n"
+   "FOO(b)\n"
+   "int c = 0;",
+   Style);
+  verifyFormat("int a = 0;\n"
+   "int x = FOO(a)\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("void foo(int a) { FOO(a) }\n"
+   "uint32_t bar() {}",
+   Style);
 }
 
 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
@@ -10728,6 +10767,12 @@
   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
   BoostAndQForeach);
 
+  Style.StatementMacros.clear();
+  CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
+  std::vector{"QUNUSED"});
+  CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
+  std::vector({"QUNUSED", "QT_REQUIRE_VERSION"}));
+
   Style.IncludeStyle.IncludeCategories.clear();
   std::vector ExpectedCategories = {
   {"abc/.*", 2}, {".*", 1}};
Index: lib/Format/UnwrappedLineParser.h
===
--- lib/Format/UnwrappedLineParser.h
+++ lib/Format/UnwrappedLineParser.h
@@ -125,6 +125,7 @@
   void parseObjCInterfaceOrImplementation();
   bool parseObjCProtocol();
   void parseJavaScriptEs6ImportExport();
+  void parseStatementMacro();
   bool tryToParseLambda();
   bool tryToParseLambdaIntroducer();
   void tryToParseJSFunction();
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -473,6 +473,10 @@
   }
   LBraceStack.pop_back();
   break;
+case tok::identifier:
+  if (!Tok->is(TT_StatementMacro))
+  break;
+  LLVM_FALLTHROUGH;
 case tok::at:
 case tok::semi:
 case tok::kw_if:
@@ -1098,6 +1102,10 @@
 return;
   }
 }
+if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
+  parseStatementMacro();
+  return;
+}
 // In all other cases, parse the declaration.
 break;
   default:
@@ -1297,6 +1305,11 @@
 return;
   }
 
+  if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
+parseStatementMacro();
+return;
+  }
+
   // See if the following token should start a new unwrapped line.
   StringRef Text = FormatTok->TokenText;
   nextToken();
@@ -2295,6 +2308,16 @@
   }
 }
 
+void UnwrappedLineParser::parseStatementMacro()
+{
+  nextToken();
+  if (FormatTok->is(tok::l_paren))
+parseParens();
+  if (FormatTok->is(tok::semi))
+nextToken();
+  addUnwrappedLine();
+}
+
 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
  StringRef Prefix = "") {
   llvm::dbgs() << Prefix << "Line(" << Line.Level
Index: lib/Format/FormatTokenLexer.h
===
--- lib/Format/FormatTokenLexer.h
+++ lib/Format/FormatTokenLexer.h
@@ -22,6 +22,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Format/Format.h"
 #include "llvm/Support/Regex.h"
+#include "llvm/ADT/MapVector.h"
 
 #include 
 
@@ -99,7 +100,8 @@
   // Index (in 'Tokens') of the last token that starts a new line.
   unsigned FirstInLineIndex;
   SmallVector Tokens;
-  SmallVector ForEachMacros;
+
+  llvm::SmallMapVector Macros;
 
   bool FormattingDisabled;
 
Index: lib/Format/FormatTokenLexer.cpp
=

[PATCH] D46932: [AArch64] Correct inline assembly test case for S modifier [NFC]

2018-05-16 Thread Peter Smith via Phabricator via cfe-commits
peter.smith created this revision.
peter.smith added reviewers: t.p.northover, manojgupta.
Herald added subscribers: kristof.beyls, eraman, rengolin.
Herald added a reviewer: javed.absar.

The existing test for the AArch64 constraint S uses the A and L modifiers. 
These modifiers were implemented in the original AArch64 backend but were not 
carried forward to the merged backend. The A is associated with ADRP and does 
nothing, the L is associated with :lo12: . Given that A and L are not supported 
by GCC and not supported by the new implementation of constraint S in LLVM (see 
https://reviews.llvm.org/D46745) I've altered the test to put :lo12: directly 
in the string so that A and L are not needed. A recent use of S in the linux 
kernel can be found at 
https://github.com/torvalds/linux/commit/44a497abd621a71c645f06d3d545ae2f46448830


https://reviews.llvm.org/D46932

Files:
  test/CodeGen/aarch64-inline-asm.c


Index: test/CodeGen/aarch64-inline-asm.c
===
--- test/CodeGen/aarch64-inline-asm.c
+++ test/CodeGen/aarch64-inline-asm.c
@@ -44,9 +44,9 @@
 
 void test_constraint_S(void) {
 int *addr;
-asm("adrp %0, %A1\n\t"
-"add %0, %0, %L1" : "=r"(addr) : "S"(&var));
-// CHECK: call i32* asm "adrp $0, ${1:A}\0A\09add $0, $0, ${1:L}", "=r,S"(i64* 
@var)
+asm("adrp %0, %1\n\t"
+"add %0, %0, :lo12:%1" : "=r"(addr) : "S"(&var));
+// CHECK: call i32* asm "adrp $0, $1\0A\09add $0, $0, :lo12:$1", "=r,S"(i64* 
@var)
 }
 
 void test_constraint_Q(void) {


Index: test/CodeGen/aarch64-inline-asm.c
===
--- test/CodeGen/aarch64-inline-asm.c
+++ test/CodeGen/aarch64-inline-asm.c
@@ -44,9 +44,9 @@
 
 void test_constraint_S(void) {
 int *addr;
-asm("adrp %0, %A1\n\t"
-"add %0, %0, %L1" : "=r"(addr) : "S"(&var));
-// CHECK: call i32* asm "adrp $0, ${1:A}\0A\09add $0, $0, ${1:L}", "=r,S"(i64* @var)
+asm("adrp %0, %1\n\t"
+"add %0, %0, :lo12:%1" : "=r"(addr) : "S"(&var));
+// CHECK: call i32* asm "adrp $0, $1\0A\09add $0, $0, :lo12:$1", "=r,S"(i64* @var)
 }
 
 void test_constraint_Q(void) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37813: clang-format: better handle namespace macros

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

In https://reviews.llvm.org/D37813#958222, @klimek wrote:

> Some initial design work has been done, and Krasimir said that he's 
> interested. No timeline though :(


@klimek , @krasimir : any progress on this new preprocessor-like way to 
configure macros ?


Repository:
  rC Clang

https://reviews.llvm.org/D37813



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


[PATCH] D37813: clang-format: better handle namespace macros

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 147027.
Typz added a comment.

Rebase


Repository:
  rC Clang

https://reviews.llvm.org/D37813

Files:
  include/clang/Format/Format.h
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/FormatTokenLexer.cpp
  lib/Format/NamespaceEndCommentsFixer.cpp
  lib/Format/TokenAnnotator.cpp
  lib/Format/UnwrappedLineFormatter.cpp
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/NamespaceEndCommentsFixerTest.cpp

Index: unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -53,6 +53,7 @@
 "  int i;\n"
 "  int j;\n"
 "}"));
+
   EXPECT_EQ("namespace {\n"
 "  int i;\n"
 "  int j;\n"
@@ -249,6 +250,85 @@
 "// unrelated"));
 }
 
+TEST_F(NamespaceEndCommentsFixerTest, AddsMacroEndComment) {
+  FormatStyle Style = getLLVMStyle();
+  Style.NamespaceMacros.push_back("TESTSUITE");
+
+  EXPECT_EQ("TESTSUITE() {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE()",
+fixNamespaceEndComments("TESTSUITE() {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+
+  EXPECT_EQ("TESTSUITE(A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(A)",
+fixNamespaceEndComments("TESTSUITE(A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("inline TESTSUITE(A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(A)",
+fixNamespaceEndComments("inline TESTSUITE(A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(::A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(::A)",
+fixNamespaceEndComments("TESTSUITE(::A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(::A::B) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(::A::B)",
+fixNamespaceEndComments("TESTSUITE(::A::B) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(/**/::/**/A/**/::/**/B/**/) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(::A::B)",
+fixNamespaceEndComments("TESTSUITE(/**/::/**/A/**/::/**/B/**/) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(A, B) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(A)",
+fixNamespaceEndComments("TESTSUITE(A, B) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(\"Test1\") {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(\"Test1\")",
+fixNamespaceEndComments("TESTSUITE(\"Test1\") {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+}
+
 TEST_F(NamespaceEndCommentsFixerTest, AddsNewlineIfNeeded) {
   EXPECT_EQ("namespace A {\n"
 "  int i;\n"
@@ -381,6 +461,54 @@
 "}; /* unnamed namespace */"));
 }
 
+TEST_F(NamespaceEndCommentsFixerTest, KeepsValidMacroEndComment) {
+  FormatStyle Style = getLLVMStyle();
+  Style.NamespaceMacros.push_back("TESTSUITE");
+
+  EXPECT_EQ("TESTSUITE() {\n"
+"  int i;\n"
+"} // end anonymous TESTSUITE()",
+fixNamespaceEndComments("TESTSUITE() {\n"
+"  int i;\n"
+"} // end anonymous TESTSUITE()",
+Style));
+  EXPECT_EQ("TESTSUITE(A) {\n"
+"  int i;\n"
+"} /* en

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

2018-05-16 Thread Sergey Avseyev via Phabricator via cfe-commits
avsej added a comment.
Herald added a subscriber: chrib.

A modified version of this patch (v8-6.7.17-fix-gcc-unwind-header.patch 
)
 has been integrated in Fedora Linux and will be accessible in v8-6.7.17-4.fc28 



https://reviews.llvm.org/D42242



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


[PATCH] D32478: [clang-format] Fix AlignOperands when BreakBeforeBinaryOperators is set

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 147031.
Typz added a comment.

Rebase


Repository:
  rC Clang

https://reviews.llvm.org/D32478

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

Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -267,7 +267,7 @@
   verifyFormat("var x = a() in\n"
".aa.aa;");
   FormatStyle Style = getGoogleJSStyleWithColumns(80);
-  Style.AlignOperands = true;
+  Style.AlignOperands = FormatStyle::OAS_Align;
   verifyFormat("var x = a() in\n"
".aa.aa;",
Style);
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -3319,6 +3319,9 @@
"  > c) {\n"
"}",
Style);
+  verifyFormat("return a\n"
+   "   && bbb;",
+   Style);
   verifyFormat("return (a)\n"
"   // comment\n"
"   + b;",
@@ -3347,11 +3350,103 @@
 
   Style.ColumnLimit = 60;
   verifyFormat("zz\n"
-   "= b\n"
+   "= \n"
"  >> (aa);",
Style);
 }
 
+TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+  Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
+
+  verifyFormat("bool value = a\n"
+   "   + a\n"
+   "   + a\n"
+   "  == a\n"
+   " * b\n"
+   " + b\n"
+   "  && a\n"
+   " * a\n"
+   " > c;",
+   Style);
+  verifyFormat("if (a\n"
+   "* \n"
+   "+ aa\n"
+   "== bbb) {\n}",
+   Style);
+  verifyFormat("if (a\n"
+   "+ \n"
+   "  * aa\n"
+   "== bbb) {\n}",
+   Style);
+  verifyFormat("if (a\n"
+   "== \n"
+   "   * aa\n"
+   "   + bbb) {\n}",
+   Style);
+  verifyFormat("if () {\n"
+   "} else if (a\n"
+   "   && b // break\n"
+   "  > c) {\n"
+   "}",
+   Style);
+  verifyFormat("return a\n"
+   "&& bbb;",
+   Style);
+  verifyFormat("return (a)\n"
+   " // comment\n"
+   " + b;",
+   Style);
+  verifyFormat(
+  "int aa = aa\n"
+  "   * bbb\n"
+  "   + cc;",
+  Style);
+
+  verifyFormat("a\n"
+   "=  + ;",
+   Style);
+
+  verifyFormat("return boost::fusion::at_c<0>().second\n"
+   "== boost::fusion::at_c<1>().second;",
+   Style);
+
+  Style.ColumnLimit = 60;
+  verifyFormat("z\n"
+   "= \n"
+   "   >> (aaa

[PATCH] D46751: [clangd] Filter out private proto symbols in SymbolCollector.

2018-05-16 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:101
+// we check whether it starts with PROTO_HEADER_COMMENT.
+bool isPrivateProtoSymbol(const NamedDecl &ND) {
+  const auto &SM = ND.getASTContext().getSourceManager();

sammccall wrote:
> We're going to end up calling this code on every decl/def we see.
> Am I being paranoid by thinking we should check whether the file is a proto 
> once, rather than doing a bunch of string matching every time?
`s/Symbol/Decl/`

We could store a cache in the symbol collector (just need to add another state 
in the class, remember to invalidate for a new ASTContext, make this a member 
etc), but I think the matching is cheap enough?



Comment at: clangd/index/SymbolCollector.cpp:112
+
+  auto Name = ND.getName();
+  if (!Name.contains('_'))

sammccall wrote:
> this asserts if the name is not a simple identifier (Maybe operators or 
> something will trigger this?).
Good catch!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46751



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


[PATCH] D46751: [clangd] Filter out private proto symbols in SymbolCollector.

2018-05-16 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 147032.
ioeric marked an inline comment as done.
ioeric added a comment.

- Address review comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46751

Files:
  clangd/ClangdLSPServer.cpp
  clangd/SourceCode.cpp
  clangd/SourceCode.h
  clangd/index/SymbolCollector.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -697,6 +697,40 @@
AllOf(QName("pörk"), DeclRange(Header.range();
 }
 
+TEST_F(SymbolCollectorTest, FilterPrivateProtoSymbols) {
+  TestHeaderName = testPath("x.proto.h");
+  const std::string Header =
+  R"(// Generated by the protocol buffer compiler.  DO NOT EDIT!
+ namespace nx {
+   class Top_Level {};
+   class TopLevel {};
+   enum Kind {
+ KIND_OK,
+ Kind_Not_Ok,
+   };
+   bool operator<(int x, int y);
+ })";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("nx"), QName("nx::TopLevel"),
+QName("nx::Kind"),
+QName("nx::KIND_OK")));
+}
+
+TEST_F(SymbolCollectorTest, DoubleCheckProtoHeaderComment) {
+  TestHeaderName = testPath("x.proto.h");
+  const std::string Header = R"(
+  namespace nx {
+class Top_Level {};
+enum Kind {
+  Kind_Fine
+};
+  }
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("nx"), QName("nx::Top_Level"),
+   QName("nx::Kind"), QName("nx::Kind_Fine")));
+}
 
 } // namespace
 } // namespace clangd
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -90,6 +90,44 @@
   return llvm::None;
 }
 
+// All proto generated headers should start with this line.
+static const char *PROTO_HEADER_COMMENT =
+"// Generated by the protocol buffer compiler.  DO NOT EDIT!";
+
+// Checks whether the decl is a private symbol in a header generated by
+// protobuf compiler.
+// To identify whether a proto header is actually generated by proto compiler,
+// we check whether it starts with PROTO_HEADER_COMMENT.
+// FIXME: make filtering extensible when there are more use cases for symbol
+// filters.
+bool isPrivateProtoDecl(const NamedDecl &ND) {
+  const auto &SM = ND.getASTContext().getSourceManager();
+  auto Loc = findNameLoc(&ND);
+  auto FileName = SM.getFilename(Loc);
+  if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h"))
+return false;
+  auto FID = SM.getFileID(Loc);
+  // Double check that this is an actual protobuf header.
+  if (!SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT))
+return false;
+
+  // If ND does not have an identifier/name, it must be private.
+  if (ND.getIdentifier() == nullptr)
+return true;
+  auto Name = ND.getIdentifier()->getName();
+  if (!Name.contains('_'))
+return false;
+  // Nested proto entities (e.g. Message::Nested) have top-level decls
+  // that shouldn't be used (Message_Nested). Ignore them completely.
+  // The nested entities are dangling type aliases, we may want to reconsider
+  // including them in the future.
+  // For enum constants, SOME_ENUM_CONSTANT is not private and should be
+  // indexed. Outer_INNER is private. This heuristic relies on naming style, it
+  // will include OUTER_INNER and exclude some_enum_constant.
+  return (ND.getKind() != Decl::EnumConstant) ||
+ std::any_of(Name.begin(), Name.end(), islower);
+}
+
 bool shouldFilterDecl(const NamedDecl *ND, ASTContext *ASTCtx,
   const SymbolCollector::Options &Opts) {
   using namespace clang::ast_matchers;
@@ -130,6 +168,9 @@
   .empty())
 return true;
 
+  // Avoid indexing internal symbols in protobuf generated headers.
+  if (isPrivateProtoDecl(*ND))
+return true;
   return false;
 }
 
Index: clangd/SourceCode.h
===
--- clangd/SourceCode.h
+++ clangd/SourceCode.h
@@ -15,6 +15,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_SOURCECODE_H
 #include "Protocol.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Tooling/Core/Replacement.h"
 
 namespace clang {
 class SourceManager;
@@ -55,6 +56,11 @@
 std::pair
 splitQualifiedName(llvm::StringRef QName);
 
+TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R);
+
+std::vector replacementsToEdits(StringRef Code,
+  const tooling::Replacements &Repls);
+
 } // namespace clangd
 } // namespace clang
 #endif
Index: clangd/SourceCode.cpp
===

[PATCH] D46751: [clangd] Filter out private proto symbols in SymbolCollector.

2018-05-16 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

> ...I hadn't noticed the latest version. I think it's safe enough in the new 
> version that we don't need to discuss this much further until it becomes a 
> bigger problem (more libraries, etc).

Sounds good, thanks!

@ilya-biryukov Could you take another look at the patch?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46751



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


[PATCH] D46891: [StaticAnalyzer] Added a getLValue method to ProgramState for bases

2018-05-16 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 147033.
Szelethus edited the summary of this revision.
Szelethus added a comment.

Added a `CXXRecordDecl` version.


https://reviews.llvm.org/D46891

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h


Index: include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -294,6 +294,13 @@
   ProgramStateRef enterStackFrame(const CallEvent &Call,
   const StackFrameContext *CalleeCtx) const;
 
+  /// Get the lvalue for a base class object reference.
+  Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) 
const;
+
+  /// Get the lvalue for a base class object reference.
+  Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
+bool isVirtual) const;
+
   /// Get the lvalue for a variable reference.
   Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
 
@@ -724,6 +731,22 @@
   return this;
 }
 
+inline Loc ProgramState::getLValue(const CXXBaseSpecifier &BaseSpec,
+   const SubRegion *Super) const {
+  const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
+  return loc::MemRegionVal(
+  getStateManager().getRegionManager().getCXXBaseObjectRegion(
+Base, Super, 
BaseSpec.isVirtual()));
+}
+
+inline Loc ProgramState::getLValue(const CXXRecordDecl *BaseClass,
+   const SubRegion *Super,
+   bool isVirtual) const {
+  return loc::MemRegionVal(
+   getStateManager().getRegionManager().getCXXBaseObjectRegion(
+  BaseClass, Super, 
isVirtual));
+}
+
 inline Loc ProgramState::getLValue(const VarDecl *VD,
const LocationContext *LC) const {
   return getStateManager().StoreMgr->getLValueVar(VD, LC);


Index: include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -294,6 +294,13 @@
   ProgramStateRef enterStackFrame(const CallEvent &Call,
   const StackFrameContext *CalleeCtx) const;
 
+  /// Get the lvalue for a base class object reference.
+  Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
+
+  /// Get the lvalue for a base class object reference.
+  Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
+bool isVirtual) const;
+
   /// Get the lvalue for a variable reference.
   Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
 
@@ -724,6 +731,22 @@
   return this;
 }
 
+inline Loc ProgramState::getLValue(const CXXBaseSpecifier &BaseSpec,
+   const SubRegion *Super) const {
+  const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
+  return loc::MemRegionVal(
+  getStateManager().getRegionManager().getCXXBaseObjectRegion(
+Base, Super, BaseSpec.isVirtual()));
+}
+
+inline Loc ProgramState::getLValue(const CXXRecordDecl *BaseClass,
+   const SubRegion *Super,
+   bool isVirtual) const {
+  return loc::MemRegionVal(
+   getStateManager().getRegionManager().getCXXBaseObjectRegion(
+  BaseClass, Super, isVirtual));
+}
+
 inline Loc ProgramState::getLValue(const VarDecl *VD,
const LocationContext *LC) const {
   return getStateManager().StoreMgr->getLValueVar(VD, LC);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332448 - [diagtool] Add diagtool to install target.

2018-05-16 Thread Jonas Devlieghere via cfe-commits
Author: jdevlieghere
Date: Wed May 16 03:23:25 2018
New Revision: 332448

URL: http://llvm.org/viewvc/llvm-project?rev=332448&view=rev
Log:
[diagtool] Add diagtool to install target.

Although not very well known, diagtool is an incredibly convenient
utility for dealing with diagnostics.
Particularly useful are the "tree" and "show-enabled" commands:

 - The former prints the hierarchy of diagnostic (warning) flags and
   which of them are enabled by default.
 - The latter can be used to replace an invocation to clang and will
   print which diagnostics are disabled, warnings or errors.
   For instance: `diagtool show-enabled -Wall -Werror /tmp/test.c` will
   print that -Wunused-variable (warn_unused_variable) will be treated as
   an error.

This patch adds them to the install target so it gets shipped with the
LLVM release. It also adds a very basic man page and mentions this
change in the release notes.

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

Added:
cfe/trunk/docs/CommandGuide/diagtool.rst
Modified:
cfe/trunk/docs/CommandGuide/index.rst
cfe/trunk/docs/ReleaseNotes.rst
cfe/trunk/tools/diagtool/CMakeLists.txt

Added: cfe/trunk/docs/CommandGuide/diagtool.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/CommandGuide/diagtool.rst?rev=332448&view=auto
==
--- cfe/trunk/docs/CommandGuide/diagtool.rst (added)
+++ cfe/trunk/docs/CommandGuide/diagtool.rst Wed May 16 03:23:25 2018
@@ -0,0 +1,52 @@
+diagtool - clang diagnostics tool
+=
+
+SYNOPSIS
+
+
+:program:`diagtool` *command* [*args*]
+
+DESCRIPTION
+---
+
+:program:`diagtool` is a combination of four tool for dealing with diagnostics 
in :program:`clang`.
+
+SUBCOMMANDS
+---
+
+:program:`diagtool` is separated into several subcommands each tailored to a
+different purpose. A brief summary of each command follows, with more detail in
+the sections that follow.
+
+  * :ref:`find_diagnostic_id` - Print the id of the given diagnostic.
+  * :ref:`list_warnings` - List warnings and their corresponding flags.
+  * :ref:`show_enabled` - Show which warnings are enabled for a given command 
line.
+  * :ref:`tree` - Show warning flags in a tree view.
+
+.. _find_diagnostic_id:
+
+find-diagnostic-id
+~~
+
+:program:`diagtool` find-diagnostic-id *diagnostic-name*
+
+.. _list_warnings:
+
+list-warnings
+~
+
+:program:`diagtool` list-warnings
+
+.. _show_enabled:
+
+show-enabled
+
+
+:program:`diagtool` show-enabled [*options*] *filename ...*
+
+.. _tree:
+
+tree
+
+
+:program:`diagtool` tree [*diagnostic-group*]

Modified: cfe/trunk/docs/CommandGuide/index.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/CommandGuide/index.rst?rev=332448&r1=332447&r2=332448&view=diff
==
--- cfe/trunk/docs/CommandGuide/index.rst (original)
+++ cfe/trunk/docs/CommandGuide/index.rst Wed May 16 03:23:25 2018
@@ -15,3 +15,4 @@ Basic Commands
:maxdepth: 1
 
clang
+   diagtool

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=332448&r1=332447&r2=332448&view=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Wed May 16 03:23:25 2018
@@ -93,6 +93,11 @@ Non-comprehensive list of changes in thi
   behavior can be restored by setting ``-fclang-abi-compat`` to ``6`` or
   lower.
 
+- An existing tool named ``diagtool`` has been added to the release. As the
+  name suggests, it helps with dealing with diagnostics in ``clang``, such as
+  finding out the warning hierarchy, and which of them are enabled by default
+  or for a particular compiler invocation.
+
 - ...
 
 New Compiler Flags

Modified: cfe/trunk/tools/diagtool/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/diagtool/CMakeLists.txt?rev=332448&r1=332447&r2=332448&view=diff
==
--- cfe/trunk/tools/diagtool/CMakeLists.txt (original)
+++ cfe/trunk/tools/diagtool/CMakeLists.txt Wed May 16 03:23:25 2018
@@ -17,3 +17,15 @@ target_link_libraries(diagtool
   clangBasic
   clangFrontend
   )
+
+if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
+  install(TARGETS diagtool
+COMPONENT diagtool
+RUNTIME DESTINATION bin)
+
+  if (NOT CMAKE_CONFIGURATION_TYPES)
+add_llvm_install_targets(install-diagtool
+  DEPENDS diagtool
+  COMPONENT diagtool)
+  endif()
+endif()


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


[PATCH] D46694: [diagtool] Install diagtool

2018-05-16 Thread Jonas Devlieghere via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332448: [diagtool] Add diagtool to install target. (authored 
by JDevlieghere, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D46694?vs=146129&id=147036#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D46694

Files:
  cfe/trunk/docs/CommandGuide/diagtool.rst
  cfe/trunk/docs/CommandGuide/index.rst
  cfe/trunk/docs/ReleaseNotes.rst
  cfe/trunk/tools/diagtool/CMakeLists.txt

Index: cfe/trunk/tools/diagtool/CMakeLists.txt
===
--- cfe/trunk/tools/diagtool/CMakeLists.txt
+++ cfe/trunk/tools/diagtool/CMakeLists.txt
@@ -17,3 +17,15 @@
   clangBasic
   clangFrontend
   )
+
+if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
+  install(TARGETS diagtool
+COMPONENT diagtool
+RUNTIME DESTINATION bin)
+
+  if (NOT CMAKE_CONFIGURATION_TYPES)
+add_llvm_install_targets(install-diagtool
+  DEPENDS diagtool
+  COMPONENT diagtool)
+  endif()
+endif()
Index: cfe/trunk/docs/CommandGuide/index.rst
===
--- cfe/trunk/docs/CommandGuide/index.rst
+++ cfe/trunk/docs/CommandGuide/index.rst
@@ -15,3 +15,4 @@
:maxdepth: 1
 
clang
+   diagtool
Index: cfe/trunk/docs/CommandGuide/diagtool.rst
===
--- cfe/trunk/docs/CommandGuide/diagtool.rst
+++ cfe/trunk/docs/CommandGuide/diagtool.rst
@@ -0,0 +1,52 @@
+diagtool - clang diagnostics tool
+=
+
+SYNOPSIS
+
+
+:program:`diagtool` *command* [*args*]
+
+DESCRIPTION
+---
+
+:program:`diagtool` is a combination of four tool for dealing with diagnostics in :program:`clang`.
+
+SUBCOMMANDS
+---
+
+:program:`diagtool` is separated into several subcommands each tailored to a
+different purpose. A brief summary of each command follows, with more detail in
+the sections that follow.
+
+  * :ref:`find_diagnostic_id` - Print the id of the given diagnostic.
+  * :ref:`list_warnings` - List warnings and their corresponding flags.
+  * :ref:`show_enabled` - Show which warnings are enabled for a given command line.
+  * :ref:`tree` - Show warning flags in a tree view.
+
+.. _find_diagnostic_id:
+
+find-diagnostic-id
+~~
+
+:program:`diagtool` find-diagnostic-id *diagnostic-name*
+
+.. _list_warnings:
+
+list-warnings
+~
+
+:program:`diagtool` list-warnings
+
+.. _show_enabled:
+
+show-enabled
+
+
+:program:`diagtool` show-enabled [*options*] *filename ...*
+
+.. _tree:
+
+tree
+
+
+:program:`diagtool` tree [*diagnostic-group*]
Index: cfe/trunk/docs/ReleaseNotes.rst
===
--- cfe/trunk/docs/ReleaseNotes.rst
+++ cfe/trunk/docs/ReleaseNotes.rst
@@ -93,6 +93,11 @@
   behavior can be restored by setting ``-fclang-abi-compat`` to ``6`` or
   lower.
 
+- An existing tool named ``diagtool`` has been added to the release. As the
+  name suggests, it helps with dealing with diagnostics in ``clang``, such as
+  finding out the warning hierarchy, and which of them are enabled by default
+  or for a particular compiler invocation.
+
 - ...
 
 New Compiler Flags
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D40864: [Darwin] Add a new -mstack-probe option and enable by default

2018-05-16 Thread Amara Emerson via Phabricator via cfe-commits
aemerson abandoned this revision.
aemerson added a comment.

In https://reviews.llvm.org/D40864#1100492, @dexonsmith wrote:

> Did this eventually go in?


No, this approach was superseded. I will upstream a new implementation in the 
near future.


Repository:
  rC Clang

https://reviews.llvm.org/D40864



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


[PATCH] D46927: Augmented Assignment for Fixed Point Types

2018-05-16 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Hi @leonardchan.
Could you please prepend some appropriate tag to the subjects of all your 
differentials, so it is less hard to read through cfe-commits mails, please?


Repository:
  rC Clang

https://reviews.llvm.org/D46927



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


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

2018-05-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 147039.
yvvan marked 4 inline comments as done.
yvvan added a comment.

Append PrintingCodeCompleteConsumer and CompilerInvocation options, add 
CodeCompletion tests.


https://reviews.llvm.org/D41537

Files:
  include/clang/Driver/CC1Options.td
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  include/clang/Sema/Sema.h
  lib/Frontend/ASTUnit.cpp
  lib/Frontend/CompilerInvocation.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/CodeCompleteConsumer.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/member-access.cpp

Index: test/CodeCompletion/member-access.cpp
===
--- test/CodeCompletion/member-access.cpp
+++ test/CodeCompletion/member-access.cpp
@@ -166,3 +166,47 @@
   typename Template::Nested m;
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:166:25 %s -o - | FileCheck -check-prefix=CHECK-CC7 %s
 }
+
+class Proxy2 {
+public:
+  Derived *operator->() const;
+  int member5;
+};
+
+void test2(const Proxy2 &p) {
+  p->
+}
+
+void test3(const Proxy2 &p) {
+  p.
+}
+
+// RUN: %clang_cc1 -fsyntax-only -code-completion-include-fixits -code-completion-at=%s:177:6 %s -o - | FileCheck -check-prefix=CHECK-CC8 --implicit-check-not="Derived : Derived(" %s
+// CHECK-CC8: Base1 : Base1::
+// CHECK-CC8: member1 : [#int#][#Base1::#]member1
+// CHECK-CC8: member1 : [#int#][#Base2::#]member1
+// CHECK-CC8: member2 : [#float#][#Base1::#]member2
+// CHECK-CC8: member3 : [#double#][#Base2::#]member3
+// CHECK-CC8: member4 : [#int#]member4
+// CHECK-CC8: member5 : [#int#]member5 (requires fix: "->" to ".")
+// CHECK-CC8: memfun1 : [#void#][#Base3::#]memfun1(<#float#>)
+// CHECK-CC8: memfun1 : [#void#][#Base3::#]memfun1(<#double#>)[# const#]
+// CHECK-CC8: memfun1 (Hidden) : [#void#]Base2::memfun1(<#int#>)
+// CHECK-CC8: memfun2 : [#void#][#Base3::#]memfun2(<#int#>)
+// CHECK-CC8: memfun3 : [#int#]memfun3(<#int#>)
+// CHECK-CC8: operator-> : [#Derived *#]operator->()[# const#] (requires fix: "->" to ".")
+
+// RUN: %clang_cc1 -fsyntax-only -code-completion-include-fixits -code-completion-at=%s:181:6 %s -o - | FileCheck -check-prefix=CHECK-CC9 --implicit-check-not="Derived : Derived(" %s
+// CHECK-CC9: Base1 : Base1::
+// CHECK-CC9: member1 : [#int#][#Base1::#]member1 (requires fix: "." to "->")
+// CHECK-CC9: member1 : [#int#][#Base2::#]member1 (requires fix: "." to "->")
+// CHECK-CC9: member2 : [#float#][#Base1::#]member2 (requires fix: "." to "->")
+// CHECK-CC9: member3 : [#double#][#Base2::#]member3 (requires fix: "." to "->")
+// CHECK-CC9: member4 : [#int#]member4 (requires fix: "." to "->")
+// CHECK-CC9: member5 : [#int#]member5
+// CHECK-CC9: memfun1 : [#void#][#Base3::#]memfun1(<#float#>) (requires fix: "." to "->")
+// CHECK-CC9: memfun1 : [#void#][#Base3::#]memfun1(<#double#>)[# const#] (requires fix: "." to "->")
+// CHECK-CC9: memfun1 (Hidden) : [#void#]Base2::memfun1(<#int#>) (requires fix: "." to "->")
+// CHECK-CC9: memfun2 : [#void#][#Base3::#]memfun2(<#int#>) (requires fix: "." to "->")
+// CHECK-CC9: memfun3 : [#int#]memfun3(<#int#>) (requires fix: "." to "->")
+// CHECK-CC9: operator-> : [#Derived *#]operator->()[# const#]
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1291,19 +1291,22 @@
   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
 ResultBuilder &Results;
 DeclContext *CurContext;
+std::vector FixIts;
 
   public:
-CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
-  : Results(Results), CurContext(CurContext) { }
+CodeCompletionDeclConsumer(
+ResultBuilder &Results, DeclContext *CurContext,
+std::vector FixIts = std::vector())
+: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) {}
 
 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override {
   bool Accessible = true;
   if (Ctx)
 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
 
   ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
-   false, Accessible);
+   false, Accessible, FixIts);
   Results.AddResult(Result, CurContext, Hiding, InBaseClass);
 }
 
@@ -3947,14 +3950,18 @@
 static void AddRecordMembersCompletionResults(Sema &SemaRef,
   ResultBuilder &Results, Scope *S,
   QualType BaseType,
-  RecordDecl *RD) {
+  RecordDecl *RD,
+  Optional AccessOpFixIt) {
   // Indicate that we are performing a member access, and the cv-qualifiers
   // for the base object type.

[PATCH] D46862: Optionally add code completion results for arrow instead of dot (libclang)

2018-05-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 147042.
yvvan added a comment.

The base revision has changed - some minor changes were also required here.


https://reviews.llvm.org/D46862

Files:
  include/clang-c/Index.h
  test/Index/complete-arrow-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -171,6 +171,8 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionNumFixIts
+clang_getCompletionFixIt
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -16,6 +16,7 @@
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
 #include "CXCursor.h"
+#include "CXSourceLocation.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
 #include "clang/AST/Decl.h"
@@ -302,10 +303,53 @@
   /// \brief A string containing the Objective-C selector entered thus far for a
   /// message send.
   std::string Selector;
+
+  /// \brief Vector of fix-its for each completion result that *must* be applied
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };
 
 } // end anonymous namespace
 
+unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
+  unsigned completion_index) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
+return 0;
+
+  return static_cast(allocated_results->FixItsVector[completion_index].size());
+}
+
+CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
+  unsigned completion_index,
+  unsigned fixit_index,
+  CXSourceRange *replacement_range) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  ArrayRef FixIts = allocated_results->FixItsVector[completion_index];
+  if (FixIts.size() <= fixit_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  const FixItHint &FixIt = FixIts[fixit_index];
+  if (replacement_range) {
+*replacement_range = cxloc::translateSourceRange(
+*allocated_results->SourceMgr, allocated_results->LangOpts,
+FixIt.RemoveRange);
+  }
+
+  return cxstring::createRef(FixIt.CodeToInsert.c_str());
+}
+
 /// \brief Tracks the number of code-completion result objects that are 
 /// currently active.
 ///
@@ -531,18 +575,22 @@
 CodeCompletionResult *Results,
 unsigned NumResults) override {
   StoredResults.reserve(StoredResults.size() + NumResults);
+  if (includeFixIts())
+AllocatedResults.FixItsVector.reserve(NumResults);
   for (unsigned I = 0; I != NumResults; ++I) {
-CodeCompletionString *StoredCompletion
+CodeCompletionString *StoredCompletion
   = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
   getCodeCompletionTUInfo(),
   includeBriefComments());
 
 CXCompletionResult R;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
+if (includeFixIts())
+  AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
   }
-  
+
   enum CodeCompletionContext::Kind contextKind = Context.getKind();
   
   AllocatedResults.ContextKind = contextKind;
@@ -644,13 +692,13 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeFixIts = options & CXCodeComplete_IncludeFixIts;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
 #endif
 #endif
-
   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
 
   if (cxtu::isNotUsableTU(TU)) {
@@ -691,6 +739,7 @@
   CodeCompleteOptions Opts;
   Opts.IncludeBriefComments = 

Re: r332436 - clang-format: Allow optimizer to break template declaration.

2018-05-16 Thread David Zarzycki via cfe-commits
This change broke `test/Index/overriding-ftemplate-comments.cpp` on Red Hat 
Fedora 28. Was this expected?

> On May 16, 2018, at 4:25 AM, Francois Ferrand via cfe-commits 
>  wrote:
> 
> Author: typz
> Date: Wed May 16 01:25:03 2018
> New Revision: 332436
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=332436&view=rev
> Log:
> clang-format: Allow optimizer to break template declaration.
> 
> Summary:
> Introduce `PenaltyBreakTemplateDeclaration` to control the penalty,
> and change `AlwaysBreakTemplateDeclarations` to an enum with 3 modes:
> * `No` for regular, penalty based, wrapping of template declaration
> * `MultiLine` for always wrapping before multi-line declarations (e.g.
>  same as legacy behavior when `AlwaysBreakTemplateDeclarations=false`)
> * `Yes` for always wrapping (e.g. same as legacy behavior when
>  `AlwaysBreakTemplateDeclarations=true`)
> 
> Reviewers: krasimir, djasper, klimek
> 
> Subscribers: cfe-commits
> 
> Differential Revision: https://reviews.llvm.org/D42684
> 
> Modified:
>cfe/trunk/docs/ClangFormatStyleOptions.rst
>cfe/trunk/include/clang/Format/Format.h
>cfe/trunk/lib/Format/ContinuationIndenter.cpp
>cfe/trunk/lib/Format/Format.cpp
>cfe/trunk/lib/Format/TokenAnnotator.cpp
>cfe/trunk/unittests/Format/FormatTest.cpp
> 
> Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=332436&r1=332435&r2=332436&view=diff
> ==
> --- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
> +++ cfe/trunk/docs/ClangFormatStyleOptions.rst Wed May 16 01:25:03 2018
> @@ -490,15 +490,50 @@ the configuration (without a prefix: ``A
>  """";
>  "";
> 
> -**AlwaysBreakTemplateDeclarations** (``bool``)
> -  If ``true``, always break after the ``template<...>`` of a template
> -  declaration.
> +**AlwaysBreakTemplateDeclarations** (``BreakTemplateDeclarationsStyle``)
> +  The template declaration breaking style to use.
> +
> +  Possible values:
> +
> +  * ``BTDS_No`` (in configuration: ``No``)
> +Do not force break before declaration.
> +``PenaltyBreakTemplateDeclaration`` is taken into account.
> +
> +.. code-block:: c++
> +
> +   template  T foo() {
> +   }
> +   template  T foo(int a,
> +   int b) {
> +   }
> +
> +  * ``BTDS_MultiLine`` (in configuration: ``MultiLine``)
> +Force break after template declaration only when the following
> +declaration spans multiple lines.
> +
> +.. code-block:: c++
> +
> +   template  T foo() {
> +   }
> +   template 
> +   T foo(int a,
> + int b) {
> +   }
> +
> +  * ``BTDS_Yes`` (in configuration: ``Yes``)
> +Always break after template declaration.
> +
> +.. code-block:: c++
> +
> +   template 
> +   T foo() {
> +   }
> +   template 
> +   T foo(int a,
> + int b) {
> +   }
> 
> -  .. code-block:: c++
> 
> - true:  false:
> - template   vs. template  class C {};
> - class C {};
> 
> **BinPackArguments** (``bool``)
>   If ``false``, a function call's arguments will either be all on the
> @@ -1590,6 +1625,9 @@ the configuration (without a prefix: ``A
> **PenaltyBreakString** (``unsigned``)
>   The penalty for each line break introduced inside a string literal.
> 
> +**PenaltyBreakTemplateDeclaration** (``unsigned``)
> +  The penalty for breaking after template declaration.
> +
> **PenaltyExcessCharacter** (``unsigned``)
>   The penalty for each character outside of the column limit.
> 
> 
> Modified: cfe/trunk/include/clang/Format/Format.h
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=332436&r1=332435&r2=332436&view=diff
> ==
> --- cfe/trunk/include/clang/Format/Format.h (original)
> +++ cfe/trunk/include/clang/Format/Format.h Wed May 16 01:25:03 2018
> @@ -351,14 +351,44 @@ struct FormatStyle {
>   /// \endcode
>   bool AlwaysBreakBeforeMultilineStrings;
> 
> -  /// If ``true``, always break after the ``template<...>`` of a template
> -  /// declaration.
> -  /// \code
> -  ///true:  false:
> -  ///template   vs. template  class 
> C {};
> -  ///class C {};
> -  /// \endcode
> -  bool AlwaysBreakTemplateDeclarations;
> +  /// Different ways to break after the template declaration.
> +  enum BreakTemplateDeclarationsStyle {
> +  /// Do not force break before declaration.
> +  /// ``PenaltyBreakTemplateDeclaration`` is taken into account.
> +  /// \code
> +  ///template  T foo() {
> +  ///}
> +  

[PATCH] D46891: [StaticAnalyzer] Added a getLValue method to ProgramState for bases

2018-05-16 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 147045.
Szelethus added a comment.

Fixed a typo.


https://reviews.llvm.org/D46891

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h


Index: include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -294,6 +294,13 @@
   ProgramStateRef enterStackFrame(const CallEvent &Call,
   const StackFrameContext *CalleeCtx) const;
 
+  /// Get the lvalue for a base class object reference.
+  Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) 
const;
+
+  /// Get the lvalue for a base class object reference.
+  Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
+bool IsVirtual) const;
+
   /// Get the lvalue for a variable reference.
   Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
 
@@ -724,6 +731,22 @@
   return this;
 }
 
+inline Loc ProgramState::getLValue(const CXXBaseSpecifier &BaseSpec,
+   const SubRegion *Super) const {
+  const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
+  return loc::MemRegionVal(
+   getStateManager().getRegionManager().getCXXBaseObjectRegion(
+Base, Super, 
BaseSpec.isVirtual()));
+}
+
+inline Loc ProgramState::getLValue(const CXXRecordDecl *BaseClass,
+   const SubRegion *Super,
+   bool IsVirtual) const {
+  return loc::MemRegionVal(
+   getStateManager().getRegionManager().getCXXBaseObjectRegion(
+  BaseClass, Super, 
IsVirtual));
+}
+
 inline Loc ProgramState::getLValue(const VarDecl *VD,
const LocationContext *LC) const {
   return getStateManager().StoreMgr->getLValueVar(VD, LC);


Index: include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -294,6 +294,13 @@
   ProgramStateRef enterStackFrame(const CallEvent &Call,
   const StackFrameContext *CalleeCtx) const;
 
+  /// Get the lvalue for a base class object reference.
+  Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const;
+
+  /// Get the lvalue for a base class object reference.
+  Loc getLValue(const CXXRecordDecl *BaseClass, const SubRegion *Super,
+bool IsVirtual) const;
+
   /// Get the lvalue for a variable reference.
   Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
 
@@ -724,6 +731,22 @@
   return this;
 }
 
+inline Loc ProgramState::getLValue(const CXXBaseSpecifier &BaseSpec,
+   const SubRegion *Super) const {
+  const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
+  return loc::MemRegionVal(
+   getStateManager().getRegionManager().getCXXBaseObjectRegion(
+Base, Super, BaseSpec.isVirtual()));
+}
+
+inline Loc ProgramState::getLValue(const CXXRecordDecl *BaseClass,
+   const SubRegion *Super,
+   bool IsVirtual) const {
+  return loc::MemRegionVal(
+   getStateManager().getRegionManager().getCXXBaseObjectRegion(
+  BaseClass, Super, IsVirtual));
+}
+
 inline Loc ProgramState::getLValue(const VarDecl *VD,
const LocationContext *LC) const {
   return getStateManager().StoreMgr->getLValueVar(VD, LC);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46747: [Sema] Use dotted form of macOS version for unguarded availability FixIts

2018-05-16 Thread Jan Korous via Phabricator via cfe-commits
jkorous added a comment.

Eric, thanks for the context. I am now clarifying internally and if possible 
would like to simplify the whole format business by using just one delimiter 
everywhere. Would that make sense to you or do you think we should respect 
delimiter used in sources?


https://reviews.llvm.org/D46747



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


[PATCH] D46820: Fix __uuidof handling on non-type template parameter in C++17

2018-05-16 Thread Nico Weber via Phabricator via cfe-commits
thakis accepted this revision.
thakis added a comment.
This revision is now accepted and ready to land.

lgtm, but:




Comment at: test/SemaCXX/PR24986.cpp:12
+  f<&__uuidof(0)>();
+}

Maybe this test could be in test/SemaCXX/ms-uuid.cpp instead?


Repository:
  rC Clang

https://reviews.llvm.org/D46820



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


[PATCH] D46190: For a referenced declaration, mark any associated usings as referenced.

2018-05-16 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
CarlosAlbertoEnciso updated this revision to Diff 147050.
CarlosAlbertoEnciso edited the summary of this revision.
CarlosAlbertoEnciso added a comment.

Address the issues raised by the reviewer (rsmith).


https://reviews.llvm.org/D46190

Files:
  include/clang/Sema/Sema.h
  lib/Sema/Sema.cpp
  lib/Sema/SemaCXXScopeSpec.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaDeclCXX.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaExprCXX.cpp
  lib/Sema/SemaTemplate.cpp
  test/PCH/cxx-templates.cpp
  test/SemaCXX/referenced_alias_declaration_1.cpp
  test/SemaCXX/referenced_alias_declaration_2.cpp
  test/SemaCXX/referenced_using_all.cpp
  test/SemaCXX/referenced_using_declaration_1.cpp
  test/SemaCXX/referenced_using_declaration_2.cpp
  test/SemaCXX/referenced_using_directive.cpp

Index: test/SemaCXX/referenced_using_directive.cpp
===
--- test/SemaCXX/referenced_using_directive.cpp
+++ test/SemaCXX/referenced_using_directive.cpp
@@ -0,0 +1,55 @@
+// RUN: %clang_cc1 -std=c++11 -ast-dump %s | FileCheck %s --strict-whitespace
+
+namespace N {
+  typedef int Integer;
+  int var;
+}
+
+void Fa() {
+  using namespace N;  // Referenced
+  var = 1;
+}
+
+void Fb() {
+  using namespace N;
+  N::var = 1;
+}
+
+void Fc() {
+  using namespace N;  // Referenced
+  Integer var = 1;
+}
+
+void Fd() {
+  using namespace N;
+  N::Integer var = 1;
+}
+
+//CHECK:  |-FunctionDecl {{.*}} Fa 'void ()'
+//CHECK-NEXT: | `-CompoundStmt {{.*}}
+//CHECK-NEXT: |   |-DeclStmt {{.*}}
+//CHECK-NEXT: |   | `-UsingDirectiveDecl {{.*}} referenced Namespace {{.*}} 'N'
+//CHECK-NEXT: |   `-BinaryOperator {{.*}} 'int' lvalue '='
+//CHECK-NEXT: | |-DeclRefExpr {{.*}} 'int' lvalue Var {{.*}} 'var' 'int'
+//CHECK-NEXT: | `-IntegerLiteral {{.*}} 'int' 1
+//CHECK-NEXT: |-FunctionDecl {{.*}} Fb 'void ()'
+//CHECK-NEXT: | `-CompoundStmt {{.*}}
+//CHECK-NEXT: |   |-DeclStmt {{.*}}
+//CHECK-NEXT: |   | `-UsingDirectiveDecl {{.*}} Namespace {{.*}} 'N'
+//CHECK-NEXT: |   `-BinaryOperator {{.*}} 'int' lvalue '='
+//CHECK-NEXT: | |-DeclRefExpr {{.*}} 'int' lvalue Var {{.*}} 'var' 'int'
+//CHECK-NEXT: | `-IntegerLiteral {{.*}} 'int' 1
+//CHECK-NEXT: |-FunctionDecl {{.*}} Fc 'void ()'
+//CHECK-NEXT: | `-CompoundStmt {{.*}}
+//CHECK-NEXT: |   |-DeclStmt {{.*}}
+//CHECK-NEXT: |   | `-UsingDirectiveDecl {{.*}} referenced Namespace {{.*}} 'N'
+//CHECK-NEXT: |   `-DeclStmt {{.*}}
+//CHECK-NEXT: | `-VarDecl {{.*}} var 'N::Integer':'int' cinit
+//CHECK-NEXT: |   `-IntegerLiteral {{.*}} 'int' 1
+//CHECK-NEXT: `-FunctionDecl {{.*}} Fd 'void ()'
+//CHECK-NEXT:   `-CompoundStmt {{.*}}
+//CHECK-NEXT: |-DeclStmt {{.*}}
+//CHECK-NEXT: | `-UsingDirectiveDecl {{.*}} Namespace {{.*}} 'N'
+//CHECK-NEXT: `-DeclStmt {{.*}}
+//CHECK-NEXT:   `-VarDecl {{.*}} var 'N::Integer':'int' cinit
+//CHECK-NEXT: `-IntegerLiteral {{.*}} 'int' 1
Index: test/SemaCXX/referenced_using_declaration_2.cpp
===
--- test/SemaCXX/referenced_using_declaration_2.cpp
+++ test/SemaCXX/referenced_using_declaration_2.cpp
@@ -0,0 +1,52 @@
+// RUN: %clang_cc1 -std=c++11 -ast-dump %s | FileCheck %s --strict-whitespace
+
+namespace N {
+  typedef int Integer;
+  typedef char Char;
+}
+
+using N::Integer;
+using N::Char;  // Referenced
+
+void Foo(int p1, N::Integer p2, Char p3) {
+  N::Integer var;
+  var = 0;
+}
+
+using N::Integer;   // Referenced
+Integer Bar() {
+  using N::Char;
+  return 0;
+}
+
+//CHECK:  |-UsingDecl {{.*}} N::Integer
+//CHECK-NEXT: |-UsingShadowDecl {{.*}} implicit Typedef {{.*}} 'Integer'
+//CHECK-NEXT: | `-TypedefType {{.*}} 'N::Integer' sugar
+//CHECK-NEXT: |   |-Typedef {{.*}} 'Integer'
+//CHECK-NEXT: |   `-BuiltinType {{.*}} 'int'
+//CHECK-NEXT: |-UsingDecl {{.*}} referenced N::Char
+//CHECK-NEXT: |-UsingShadowDecl {{.*}} implicit referenced Typedef {{.*}} 'Char'
+//CHECK-NEXT: | `-TypedefType {{.*}} 'N::Char' sugar
+//CHECK-NEXT: |   |-Typedef {{.*}} 'Char'
+//CHECK-NEXT: |   `-BuiltinType {{.*}} 'char'
+//CHECK-NEXT: |-FunctionDecl {{.*}} Foo 'void (int, N::Integer, N::Char)'
+//CHECK-NEXT: | |-ParmVarDecl {{.*}} p1 'int'
+//CHECK-NEXT: | |-ParmVarDecl {{.*}} p2 'N::Integer':'int'
+//CHECK-NEXT: | |-ParmVarDecl {{.*}} p3 'N::Char':'char'
+//CHECK-NEXT: | `-CompoundStmt {{.*}}
+//CHECK-NEXT: |   |-DeclStmt {{.*}}
+//CHECK-NEXT: |   | `-VarDecl {{.*}} used var 'N::Integer':'int'
+//CHECK-NEXT: |   `-BinaryOperator {{.*}} 'N::Integer':'int' lvalue '='
+//CHECK-NEXT: | |-DeclRefExpr {{.*}} 'N::Integer':'int' lvalue Var {{.*}} 'var' 'N::Integer':'int'
+//CHECK-NEXT: | `-IntegerLiteral {{.*}} 'int' 0
+//CHECK-NEXT: |-UsingDecl {{.*}} referenced N::Integer
+//CHECK-NEXT: |-UsingShadowDecl {{.*}} implicit referenced Typedef {{.*}} 'Integer'
+//CHECK-NEXT: | `-TypedefType {{.*}} 'N::Integer' sugar
+//CHECK-NEXT: |   |-Typedef {{.*}} 'Integer'
+//CHECK-NEXT: |   `-BuiltinType {{.*}} 'int'
+//CHECK-NEXT: `-FunctionDe

[PATCH] D46937: [Timers] TimerGroup::printJSONValue(): print doubles with no precision loss

2018-05-16 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added reviewers: george.karpenkov, NoQ, alexfh, sbenza.
Herald added a subscriber: llvm-commits.
lebedev.ri added a dependent revision: D46938: [Timers] TimerGroup: make 
printJSONValues() method public.
lebedev.ri added a dependency: D46936: [Timers] TimerGroup::printJSONValues(): 
print mem timer with .mem suffix.

Although this is not stricly required, i would very much prefer
not to have known random precision losses along the way.


Repository:
  rL LLVM

https://reviews.llvm.org/D46937

Files:
  lib/Support/Timer.cpp


Index: lib/Support/Timer.cpp
===
--- lib/Support/Timer.cpp
+++ lib/Support/Timer.cpp
@@ -22,6 +22,8 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/YAMLTraits.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
+
 using namespace llvm;
 
 // This ugly hack is brought to you courtesy of constructor/destructor ordering
@@ -367,10 +369,12 @@
 void TimerGroup::printJSONValue(raw_ostream &OS, const PrintRecord &R,
 const char *suffix, double Value) {
   assert(yaml::needsQuotes(Name) == yaml::QuotingType::None &&
- "TimerGroup name needs no quotes");
+ "TimerGroup name should not need quotes");
   assert(yaml::needsQuotes(R.Name) == yaml::QuotingType::None &&
- "Timer name needs no quotes");
-  OS << "\t\"time." << Name << '.' << R.Name << suffix << "\": " << Value;
+ "Timer name should not need quotes");
+  constexpr auto max_digits10 = std::numeric_limits::max_digits10;
+  OS << "\t\"time." << Name << '.' << R.Name << suffix
+ << "\": " << format("%.*e", max_digits10 - 1, Value);
 }
 
 const char *TimerGroup::printJSONValues(raw_ostream &OS, const char *delim) {


Index: lib/Support/Timer.cpp
===
--- lib/Support/Timer.cpp
+++ lib/Support/Timer.cpp
@@ -22,6 +22,8 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/YAMLTraits.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
+
 using namespace llvm;
 
 // This ugly hack is brought to you courtesy of constructor/destructor ordering
@@ -367,10 +369,12 @@
 void TimerGroup::printJSONValue(raw_ostream &OS, const PrintRecord &R,
 const char *suffix, double Value) {
   assert(yaml::needsQuotes(Name) == yaml::QuotingType::None &&
- "TimerGroup name needs no quotes");
+ "TimerGroup name should not need quotes");
   assert(yaml::needsQuotes(R.Name) == yaml::QuotingType::None &&
- "Timer name needs no quotes");
-  OS << "\t\"time." << Name << '.' << R.Name << suffix << "\": " << Value;
+ "Timer name should not need quotes");
+  constexpr auto max_digits10 = std::numeric_limits::max_digits10;
+  OS << "\t\"time." << Name << '.' << R.Name << suffix
+ << "\": " << format("%.*e", max_digits10 - 1, Value);
 }
 
 const char *TimerGroup::printJSONValues(raw_ostream &OS, const char *delim) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46936: [Timers] TimerGroup::printJSONValues(): print mem timer with .mem suffix

2018-05-16 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added reviewers: george.karpenkov, NoQ, alexfh, sbenza.
Herald added a subscriber: llvm-commits.
lebedev.ri added a dependent revision: D46937: [Timers] 
TimerGroup::printJSONValue(): print doubles with no precision loss.

We have just used `.sys` suffix for the previous timer, this is clearly a typo


Repository:
  rL LLVM

https://reviews.llvm.org/D46936

Files:
  lib/Support/Timer.cpp


Index: lib/Support/Timer.cpp
===
--- lib/Support/Timer.cpp
+++ lib/Support/Timer.cpp
@@ -387,7 +387,7 @@
 printJSONValue(OS, R, ".sys", T.getSystemTime());
 if (T.getMemUsed()) {
   OS << delim;
-  printJSONValue(OS, R, ".sys", T.getMemUsed());
+  printJSONValue(OS, R, ".mem", T.getMemUsed());
 }
   }
   TimersToPrint.clear();


Index: lib/Support/Timer.cpp
===
--- lib/Support/Timer.cpp
+++ lib/Support/Timer.cpp
@@ -387,7 +387,7 @@
 printJSONValue(OS, R, ".sys", T.getSystemTime());
 if (T.getMemUsed()) {
   OS << delim;
-  printJSONValue(OS, R, ".sys", T.getMemUsed());
+  printJSONValue(OS, R, ".mem", T.getMemUsed());
 }
   }
   TimersToPrint.clear();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46939: [Timers] TimerGroup: add constructor from StringMap

2018-05-16 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added reviewers: george.karpenkov, NoQ, alexfh, sbenza.
Herald added a subscriber: llvm-commits.
lebedev.ri added a dependency: D46938: [Timers] TimerGroup: make 
printJSONValues() method public.
lebedev.ri added a dependent revision: D46602: [clang-tidy] Store checks 
profiling info as YAML files.

This is needed for the continuation of https://reviews.llvm.org/D46504,
to be able to store the timings.


Repository:
  rL LLVM

https://reviews.llvm.org/D46939

Files:
  include/llvm/Support/Timer.h
  lib/Support/Timer.cpp


Index: lib/Support/Timer.cpp
===
--- lib/Support/Timer.cpp
+++ lib/Support/Timer.cpp
@@ -236,6 +236,15 @@
   TimerGroupList = this;
 }
 
+TimerGroup::TimerGroup(StringRef Name, StringRef Description,
+   const StringMap &Records)
+: TimerGroup(Name, Description) {
+  TimersToPrint.reserve(Records.size());
+  for (const auto &P : Records)
+TimersToPrint.emplace_back(P.getValue(), P.getKey(), P.getKey());
+  assert(TimersToPrint.size() == Records.size() && "Size mismatch");
+}
+
 TimerGroup::~TimerGroup() {
   // If the timer group is destroyed before the timers it owns, accumulate and
   // print the timing data.
Index: include/llvm/Support/Timer.h
===
--- include/llvm/Support/Timer.h
+++ include/llvm/Support/Timer.h
@@ -10,6 +10,7 @@
 #ifndef LLVM_SUPPORT_TIMER_H
 #define LLVM_SUPPORT_TIMER_H
 
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/DataTypes.h"
 #include 
@@ -194,6 +195,10 @@
 
 public:
   explicit TimerGroup(StringRef Name, StringRef Description);
+
+  explicit TimerGroup(StringRef Name, StringRef Description,
+  const StringMap &Records);
+
   ~TimerGroup();
 
   void setName(StringRef NewName, StringRef NewDescription) {


Index: lib/Support/Timer.cpp
===
--- lib/Support/Timer.cpp
+++ lib/Support/Timer.cpp
@@ -236,6 +236,15 @@
   TimerGroupList = this;
 }
 
+TimerGroup::TimerGroup(StringRef Name, StringRef Description,
+   const StringMap &Records)
+: TimerGroup(Name, Description) {
+  TimersToPrint.reserve(Records.size());
+  for (const auto &P : Records)
+TimersToPrint.emplace_back(P.getValue(), P.getKey(), P.getKey());
+  assert(TimersToPrint.size() == Records.size() && "Size mismatch");
+}
+
 TimerGroup::~TimerGroup() {
   // If the timer group is destroyed before the timers it owns, accumulate and
   // print the timing data.
Index: include/llvm/Support/Timer.h
===
--- include/llvm/Support/Timer.h
+++ include/llvm/Support/Timer.h
@@ -10,6 +10,7 @@
 #ifndef LLVM_SUPPORT_TIMER_H
 #define LLVM_SUPPORT_TIMER_H
 
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/DataTypes.h"
 #include 
@@ -194,6 +195,10 @@
 
 public:
   explicit TimerGroup(StringRef Name, StringRef Description);
+
+  explicit TimerGroup(StringRef Name, StringRef Description,
+  const StringMap &Records);
+
   ~TimerGroup();
 
   void setName(StringRef NewName, StringRef NewDescription) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46938: [Timers] TimerGroup: make printJSONValues() method public

2018-05-16 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added reviewers: george.karpenkov, NoQ, alexfh, sbenza.
Herald added a subscriber: llvm-commits.
lebedev.ri added a dependent revision: D46939: [Timers] TimerGroup: add 
constructor from StringMap.
lebedev.ri added a dependency: D46937: [Timers] TimerGroup::printJSONValue(): 
print doubles with no precision loss.

This is needed for the continuation of https://reviews.llvm.org/D46504,
to be able to store the timings.


Repository:
  rL LLVM

https://reviews.llvm.org/D46938

Files:
  include/llvm/Support/Timer.h
  lib/Support/Timer.cpp


Index: lib/Support/Timer.cpp
===
--- lib/Support/Timer.cpp
+++ lib/Support/Timer.cpp
@@ -378,6 +378,8 @@
 }
 
 const char *TimerGroup::printJSONValues(raw_ostream &OS, const char *delim) {
+  sys::SmartScopedLock L(*TimerLock);
+
   prepareToPrintList();
   for (const PrintRecord &R : TimersToPrint) {
 OS << delim;
Index: include/llvm/Support/Timer.h
===
--- include/llvm/Support/Timer.h
+++ include/llvm/Support/Timer.h
@@ -207,6 +207,8 @@
   /// This static method prints all timers and clears them all out.
   static void printAll(raw_ostream &OS);
 
+  const char *printJSONValues(raw_ostream &OS, const char *delim);
+
   /// Prints all timers as JSON key/value pairs, and clears them all out.
   static const char *printAllJSONValues(raw_ostream &OS, const char *delim);
 
@@ -223,7 +225,6 @@
   void PrintQueuedTimers(raw_ostream &OS);
   void printJSONValue(raw_ostream &OS, const PrintRecord &R,
   const char *suffix, double Value);
-  const char *printJSONValues(raw_ostream &OS, const char *delim);
 };
 
 } // end namespace llvm


Index: lib/Support/Timer.cpp
===
--- lib/Support/Timer.cpp
+++ lib/Support/Timer.cpp
@@ -378,6 +378,8 @@
 }
 
 const char *TimerGroup::printJSONValues(raw_ostream &OS, const char *delim) {
+  sys::SmartScopedLock L(*TimerLock);
+
   prepareToPrintList();
   for (const PrintRecord &R : TimersToPrint) {
 OS << delim;
Index: include/llvm/Support/Timer.h
===
--- include/llvm/Support/Timer.h
+++ include/llvm/Support/Timer.h
@@ -207,6 +207,8 @@
   /// This static method prints all timers and clears them all out.
   static void printAll(raw_ostream &OS);
 
+  const char *printJSONValues(raw_ostream &OS, const char *delim);
+
   /// Prints all timers as JSON key/value pairs, and clears them all out.
   static const char *printAllJSONValues(raw_ostream &OS, const char *delim);
 
@@ -223,7 +225,6 @@
   void PrintQueuedTimers(raw_ostream &OS);
   void printJSONValue(raw_ostream &OS, const PrintRecord &R,
   const char *suffix, double Value);
-  const char *printJSONValues(raw_ostream &OS, const char *delim);
 };
 
 } // end namespace llvm
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46603: [Support] TimerGroup changes

2018-05-16 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri abandoned this revision.
lebedev.ri added a comment.

In https://reviews.llvm.org/D46603#1100455, @george.karpenkov wrote:

> I see four separate changes: s/.sys/mem one (can be committed without 
> review), exposing printJSONValues and consequent adding of a lock, adding a 
> constructor accepting a map, and fixing formatting in `printJSONValue`. All 
> four look good to me, but probably should be reviewed separately.


Thank you for taking a look!
Posted as https://reviews.llvm.org/D46936, https://reviews.llvm.org/D46937, 
https://reviews.llvm.org/D46938, https://reviews.llvm.org/D46939


Repository:
  rL LLVM

https://reviews.llvm.org/D46603



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


[PATCH] D46751: [clangd] Filter out private proto symbols in SymbolCollector.

2018-05-16 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/ClangdLSPServer.cpp:274
 WorkspaceEdit WE;
 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
 reply(WE);

NIT: not related to this change, but maybe use `std::move(Edits)` to avoid 
extra copies.



Comment at: clangd/index/SymbolCollector.cpp:127
+  // will include OUTER_INNER and exclude some_enum_constant.
+  return (ND.getKind() != Decl::EnumConstant) ||
+ std::any_of(Name.begin(), Name.end(), islower);

The heuristrics that rely on naming style seem too fragile.
More thorough heuristics should do better, but are more complicated.
Maybe we could leave a fixme saying that these can be improved in case we'll 
run into problems. WDYT?



Comment at: unittests/clangd/SymbolCollectorTests.cpp:711
+   };
+   bool operator<(int x, int y);
+ })";

Could you give an intuition on why is this considered private?
We don't filter out those operators from other headers, right? Why are proto 
headers special?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46751



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


[PATCH] D46751: [clangd] Filter out private proto symbols in SymbolCollector.

2018-05-16 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 147058.
ioeric marked 3 inline comments as done.
ioeric added a comment.

- Merge remote-tracking branch 'origin/master' into proto
- Addressed review comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46751

Files:
  clangd/index/SymbolCollector.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -697,6 +697,41 @@
AllOf(QName("pörk"), DeclRange(Header.range();
 }
 
+TEST_F(SymbolCollectorTest, FilterPrivateProtoSymbols) {
+  TestHeaderName = testPath("x.proto.h");
+  const std::string Header =
+  R"(// Generated by the protocol buffer compiler.  DO NOT EDIT!
+ namespace nx {
+   class Top_Level {};
+   class TopLevel {};
+   enum Kind {
+ KIND_OK,
+ Kind_Not_Ok,
+   };
+   bool operator<(const TopLevel &, const TopLevel &);
+ })";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("nx"), QName("nx::TopLevel"),
+   QName("nx::Kind"), QName("nx::KIND_OK"),
+   QName("nx::operator<")));
+}
+
+TEST_F(SymbolCollectorTest, DoubleCheckProtoHeaderComment) {
+  TestHeaderName = testPath("x.proto.h");
+  const std::string Header = R"(
+  namespace nx {
+class Top_Level {};
+enum Kind {
+  Kind_Fine
+};
+  }
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("nx"), QName("nx::Top_Level"),
+   QName("nx::Kind"), QName("nx::Kind_Fine")));
+}
 
 } // namespace
 } // namespace clangd
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -89,6 +89,46 @@
   return llvm::None;
 }
 
+// All proto generated headers should start with this line.
+static const char *PROTO_HEADER_COMMENT =
+"// Generated by the protocol buffer compiler.  DO NOT EDIT!";
+
+// Checks whether the decl is a private symbol in a header generated by
+// protobuf compiler.
+// To identify whether a proto header is actually generated by proto compiler,
+// we check whether it starts with PROTO_HEADER_COMMENT.
+// FIXME: make filtering extensible when there are more use cases for symbol
+// filters.
+bool isPrivateProtoDecl(const NamedDecl &ND) {
+  const auto &SM = ND.getASTContext().getSourceManager();
+  auto Loc = findNameLoc(&ND);
+  auto FileName = SM.getFilename(Loc);
+  if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h"))
+return false;
+  auto FID = SM.getFileID(Loc);
+  // Double check that this is an actual protobuf header.
+  if (!SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT))
+return false;
+
+  // ND without identifier can be operators.
+  if (ND.getIdentifier() == nullptr)
+return false;
+  auto Name = ND.getIdentifier()->getName();
+  if (!Name.contains('_'))
+return false;
+  // Nested proto entities (e.g. Message::Nested) have top-level decls
+  // that shouldn't be used (Message_Nested). Ignore them completely.
+  // The nested entities are dangling type aliases, we may want to reconsider
+  // including them in the future.
+  // For enum constants, SOME_ENUM_CONSTANT is not private and should be
+  // indexed. Outer_INNER is private. This heuristic relies on naming style, it
+  // will include OUTER_INNER and exclude some_enum_constant.
+  // FIXME: the heuristic relies on naming style (i.e. no underscore in
+  // user-defined names) and can be improved.
+  return (ND.getKind() != Decl::EnumConstant) ||
+ std::any_of(Name.begin(), Name.end(), islower);
+}
+
 bool shouldFilterDecl(const NamedDecl *ND, ASTContext *ASTCtx,
   const SymbolCollector::Options &Opts) {
   using namespace clang::ast_matchers;
@@ -129,6 +169,9 @@
   .empty())
 return true;
 
+  // Avoid indexing internal symbols in protobuf generated headers.
+  if (isPrivateProtoDecl(*ND))
+return true;
   return false;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46751: [clangd] Filter out private proto symbols in SymbolCollector.

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

LGTM


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46751



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


[clang-tools-extra] r332456 - [clangd] Filter out private proto symbols in SymbolCollector.

2018-05-16 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Wed May 16 05:12:30 2018
New Revision: 332456

URL: http://llvm.org/viewvc/llvm-project?rev=332456&view=rev
Log:
[clangd] Filter out private proto symbols in SymbolCollector.

Summary:
This uses heuristics to identify private proto symbols. For example,
top-level symbols whose name contains "_" are considered private. These symbols
are not expected to be used by users.

Reviewers: ilya-biryukov, malaperle

Reviewed By: ilya-biryukov

Subscribers: sammccall, klimek, MaskRay, jkorous, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=332456&r1=332455&r2=332456&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Wed May 16 
05:12:30 2018
@@ -89,6 +89,46 @@ llvm::Optional toURI(const
   return llvm::None;
 }
 
+// All proto generated headers should start with this line.
+static const char *PROTO_HEADER_COMMENT =
+"// Generated by the protocol buffer compiler.  DO NOT EDIT!";
+
+// Checks whether the decl is a private symbol in a header generated by
+// protobuf compiler.
+// To identify whether a proto header is actually generated by proto compiler,
+// we check whether it starts with PROTO_HEADER_COMMENT.
+// FIXME: make filtering extensible when there are more use cases for symbol
+// filters.
+bool isPrivateProtoDecl(const NamedDecl &ND) {
+  const auto &SM = ND.getASTContext().getSourceManager();
+  auto Loc = findNameLoc(&ND);
+  auto FileName = SM.getFilename(Loc);
+  if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h"))
+return false;
+  auto FID = SM.getFileID(Loc);
+  // Double check that this is an actual protobuf header.
+  if (!SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT))
+return false;
+
+  // ND without identifier can be operators.
+  if (ND.getIdentifier() == nullptr)
+return false;
+  auto Name = ND.getIdentifier()->getName();
+  if (!Name.contains('_'))
+return false;
+  // Nested proto entities (e.g. Message::Nested) have top-level decls
+  // that shouldn't be used (Message_Nested). Ignore them completely.
+  // The nested entities are dangling type aliases, we may want to reconsider
+  // including them in the future.
+  // For enum constants, SOME_ENUM_CONSTANT is not private and should be
+  // indexed. Outer_INNER is private. This heuristic relies on naming style, it
+  // will include OUTER_INNER and exclude some_enum_constant.
+  // FIXME: the heuristic relies on naming style (i.e. no underscore in
+  // user-defined names) and can be improved.
+  return (ND.getKind() != Decl::EnumConstant) ||
+ std::any_of(Name.begin(), Name.end(), islower);
+}
+
 bool shouldFilterDecl(const NamedDecl *ND, ASTContext *ASTCtx,
   const SymbolCollector::Options &Opts) {
   using namespace clang::ast_matchers;
@@ -129,6 +169,9 @@ bool shouldFilterDecl(const NamedDecl *N
   .empty())
 return true;
 
+  // Avoid indexing internal symbols in protobuf generated headers.
+  if (isPrivateProtoDecl(*ND))
+return true;
   return false;
 }
 

Modified: clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp?rev=332456&r1=332455&r2=332456&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp Wed May 
16 05:12:30 2018
@@ -697,6 +697,41 @@ TEST_F(SymbolCollectorTest, UTF16Charact
AllOf(QName("pörk"), DeclRange(Header.range();
 }
 
+TEST_F(SymbolCollectorTest, FilterPrivateProtoSymbols) {
+  TestHeaderName = testPath("x.proto.h");
+  const std::string Header =
+  R"(// Generated by the protocol buffer compiler.  DO NOT EDIT!
+ namespace nx {
+   class Top_Level {};
+   class TopLevel {};
+   enum Kind {
+ KIND_OK,
+ Kind_Not_Ok,
+   };
+   bool operator<(const TopLevel &, const TopLevel &);
+ })";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("nx"), QName("nx::TopLevel"),
+   QName("nx::Kind"), QName("nx::KIND_OK"),
+   QName("nx::operator<")));
+}
+
+TEST_F(SymbolCollectorTest, DoubleCheckProtoHeaderComment) {
+  TestHeaderName = testPath("x.proto.h");
+  const std::string Header

[PATCH] D46751: [clangd] Filter out private proto symbols in SymbolCollector.

2018-05-16 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332456: [clangd] Filter out private proto symbols in 
SymbolCollector. (authored by ioeric, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D46751

Files:
  clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
  clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
@@ -697,6 +697,41 @@
AllOf(QName("pörk"), DeclRange(Header.range();
 }
 
+TEST_F(SymbolCollectorTest, FilterPrivateProtoSymbols) {
+  TestHeaderName = testPath("x.proto.h");
+  const std::string Header =
+  R"(// Generated by the protocol buffer compiler.  DO NOT EDIT!
+ namespace nx {
+   class Top_Level {};
+   class TopLevel {};
+   enum Kind {
+ KIND_OK,
+ Kind_Not_Ok,
+   };
+   bool operator<(const TopLevel &, const TopLevel &);
+ })";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("nx"), QName("nx::TopLevel"),
+   QName("nx::Kind"), QName("nx::KIND_OK"),
+   QName("nx::operator<")));
+}
+
+TEST_F(SymbolCollectorTest, DoubleCheckProtoHeaderComment) {
+  TestHeaderName = testPath("x.proto.h");
+  const std::string Header = R"(
+  namespace nx {
+class Top_Level {};
+enum Kind {
+  Kind_Fine
+};
+  }
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("nx"), QName("nx::Top_Level"),
+   QName("nx::Kind"), QName("nx::Kind_Fine")));
+}
 
 } // namespace
 } // namespace clangd
Index: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
@@ -89,6 +89,46 @@
   return llvm::None;
 }
 
+// All proto generated headers should start with this line.
+static const char *PROTO_HEADER_COMMENT =
+"// Generated by the protocol buffer compiler.  DO NOT EDIT!";
+
+// Checks whether the decl is a private symbol in a header generated by
+// protobuf compiler.
+// To identify whether a proto header is actually generated by proto compiler,
+// we check whether it starts with PROTO_HEADER_COMMENT.
+// FIXME: make filtering extensible when there are more use cases for symbol
+// filters.
+bool isPrivateProtoDecl(const NamedDecl &ND) {
+  const auto &SM = ND.getASTContext().getSourceManager();
+  auto Loc = findNameLoc(&ND);
+  auto FileName = SM.getFilename(Loc);
+  if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h"))
+return false;
+  auto FID = SM.getFileID(Loc);
+  // Double check that this is an actual protobuf header.
+  if (!SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT))
+return false;
+
+  // ND without identifier can be operators.
+  if (ND.getIdentifier() == nullptr)
+return false;
+  auto Name = ND.getIdentifier()->getName();
+  if (!Name.contains('_'))
+return false;
+  // Nested proto entities (e.g. Message::Nested) have top-level decls
+  // that shouldn't be used (Message_Nested). Ignore them completely.
+  // The nested entities are dangling type aliases, we may want to reconsider
+  // including them in the future.
+  // For enum constants, SOME_ENUM_CONSTANT is not private and should be
+  // indexed. Outer_INNER is private. This heuristic relies on naming style, it
+  // will include OUTER_INNER and exclude some_enum_constant.
+  // FIXME: the heuristic relies on naming style (i.e. no underscore in
+  // user-defined names) and can be improved.
+  return (ND.getKind() != Decl::EnumConstant) ||
+ std::any_of(Name.begin(), Name.end(), islower);
+}
+
 bool shouldFilterDecl(const NamedDecl *ND, ASTContext *ASTCtx,
   const SymbolCollector::Options &Opts) {
   using namespace clang::ast_matchers;
@@ -129,6 +169,9 @@
   .empty())
 return true;
 
+  // Avoid indexing internal symbols in protobuf generated headers.
+  if (isPrivateProtoDecl(*ND))
+return true;
   return false;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D45999: [clangd] Retrieve minimally formatted comment text in completion.

2018-05-16 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 147060.
ilya-biryukov added a comment.

Rebase onto head, fix merge conflicts


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45999

Files:
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/CodeCompletionStrings.cpp
  clangd/CodeCompletionStrings.h
  clangd/index/SymbolCollector.cpp
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/CodeCompletionStringsTests.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -490,11 +490,11 @@
 }
   )";
   runSymbolCollector(Header, /*Main=*/"");
-  EXPECT_THAT(Symbols,
-  UnorderedElementsAre(QName("nx"),
-   AllOf(QName("nx::ff"),
- Labeled("ff(int x, double y)"),
- Detail("int"), Doc("Foo comment.";
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  QName("nx"), AllOf(QName("nx::ff"), Labeled("ff(int x, double y)"),
+ Detail("int"), Doc("Foo comment.";
 }
 
 TEST_F(SymbolCollectorTest, PlainAndSnippet) {
Index: unittests/clangd/CodeCompletionStringsTests.cpp
===
--- unittests/clangd/CodeCompletionStringsTests.cpp
+++ unittests/clangd/CodeCompletionStringsTests.cpp
@@ -51,23 +51,24 @@
 }
 
 TEST_F(CompletionStringTest, Documentation) {
-  Builder.addBriefComment("Is this brief?");
-  EXPECT_EQ(getDocumentation(*Builder.TakeString()), "Is this brief?");
+  Builder.addBriefComment("This is ignored");
+  EXPECT_EQ(formatDocumentation(*Builder.TakeString(), "Is this brief?"),
+"Is this brief?");
 }
 
 TEST_F(CompletionStringTest, DocumentationWithAnnotation) {
-  Builder.addBriefComment("Is this brief?");
+  Builder.addBriefComment("This is ignored");
   Builder.AddAnnotation("Ano");
-  EXPECT_EQ(getDocumentation(*Builder.TakeString()),
+  EXPECT_EQ(formatDocumentation(*Builder.TakeString(), "Is this brief?"),
 "Annotation: Ano\n\nIs this brief?");
 }
 
 TEST_F(CompletionStringTest, MultipleAnnotations) {
   Builder.AddAnnotation("Ano1");
   Builder.AddAnnotation("Ano2");
   Builder.AddAnnotation("Ano3");
 
-  EXPECT_EQ(getDocumentation(*Builder.TakeString()),
+  EXPECT_EQ(formatDocumentation(*Builder.TakeString(), ""),
 "Annotations: Ano1 Ano2 Ano3\n");
 }
 
@@ -97,7 +98,7 @@
 
 TEST_F(CompletionStringTest, FunctionSnippet) {
   Builder.AddResultTypeChunk("result no no");
-  Builder.addBriefComment("Foo's comment");
+  Builder.addBriefComment("This comment is ignored");
   Builder.AddTypedTextChunk("Foo");
   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
   Builder.AddPlaceholderChunk("p1");
@@ -113,7 +114,7 @@
   labelAndInsertText(*CCS, /*EnableSnippets=*/true);
   EXPECT_EQ(Label, "Foo(p1, p2)");
   EXPECT_EQ(InsertText, "Foo(${1:p1}, ${2:p2})");
-  EXPECT_EQ(getDocumentation(*CCS), "Foo's comment");
+  EXPECT_EQ(formatDocumentation(*CCS, "Foo's comment"), "Foo's comment");
   EXPECT_EQ(getFilterText(*CCS), "Foo");
 }
 
Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -261,8 +261,7 @@
   // completion. At least there aren't any we're aware of.
   EXPECT_THAT(Results.items, Not(Contains(Kind(CompletionItemKind::Snippet;
   // Check documentation.
-  EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
- Contains(IsDocumented()));
+  EXPECT_IFF(Opts.IncludeComments, Results.items, Contains(IsDocumented()));
 }
 
 void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
@@ -307,8 +306,7 @@
   AllOf(Has("local_var"), Has("LocalClass"),
 Contains(Kind(CompletionItemKind::Snippet;
   // Check documentation.
-  EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
- Contains(IsDocumented()));
+  EXPECT_IFF(Opts.IncludeComments, Results.items, Contains(IsDocumented()));
 }
 
 TEST(CompletionTest, CompletionOptions) {
@@ -319,7 +317,7 @@
   // We used to test every combination of options, but that got too slow (2^N).
   auto Flags = {
   &clangd::CodeCompleteOptions::IncludeMacros,
-  &clangd::CodeCompleteOptions::IncludeBriefComments,
+  &clangd::CodeCompleteOptions::IncludeComments,
   &clangd::CodeCompleteOptions::EnableSnippets,
   &clangd::CodeCompleteOptions::IncludeCodePatterns,
   &clangd::CodeCompleteOptions::IncludeIneligibleResults,
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -295,7 +295,8 @@
 
 const Symbol *Sy

Re: r332436 - clang-format: Allow optimizer to break template declaration.

2018-05-16 Thread Eric Liu via cfe-commits
I can also reproduce on my local machine (Debian).

On Wed, May 16, 2018 at 1:01 PM David Zarzycki via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> This change broke `test/Index/overriding-ftemplate-comments.cpp` on Red
> Hat Fedora 28. Was this expected?
>
> > On May 16, 2018, at 4:25 AM, Francois Ferrand via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
> >
> > Author: typz
> > Date: Wed May 16 01:25:03 2018
> > New Revision: 332436
> >
> > URL: http://llvm.org/viewvc/llvm-project?rev=332436&view=rev
> > Log:
> > clang-format: Allow optimizer to break template declaration.
> >
> > Summary:
> > Introduce `PenaltyBreakTemplateDeclaration` to control the penalty,
> > and change `AlwaysBreakTemplateDeclarations` to an enum with 3 modes:
> > * `No` for regular, penalty based, wrapping of template declaration
> > * `MultiLine` for always wrapping before multi-line declarations (e.g.
> >  same as legacy behavior when `AlwaysBreakTemplateDeclarations=false`)
> > * `Yes` for always wrapping (e.g. same as legacy behavior when
> >  `AlwaysBreakTemplateDeclarations=true`)
> >
> > Reviewers: krasimir, djasper, klimek
> >
> > Subscribers: cfe-commits
> >
> > Differential Revision: https://reviews.llvm.org/D42684
> >
> > Modified:
> >cfe/trunk/docs/ClangFormatStyleOptions.rst
> >cfe/trunk/include/clang/Format/Format.h
> >cfe/trunk/lib/Format/ContinuationIndenter.cpp
> >cfe/trunk/lib/Format/Format.cpp
> >cfe/trunk/lib/Format/TokenAnnotator.cpp
> >cfe/trunk/unittests/Format/FormatTest.cpp
> >
> > Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
> > URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=332436&r1=332435&r2=332436&view=diff
> >
> ==
> > --- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
> > +++ cfe/trunk/docs/ClangFormatStyleOptions.rst Wed May 16 01:25:03 2018
> > @@ -490,15 +490,50 @@ the configuration (without a prefix: ``A
> >  """";
> >  "";
> >
> > -**AlwaysBreakTemplateDeclarations** (``bool``)
> > -  If ``true``, always break after the ``template<...>`` of a template
> > -  declaration.
> > +**AlwaysBreakTemplateDeclarations** (``BreakTemplateDeclarationsStyle``)
> > +  The template declaration breaking style to use.
> > +
> > +  Possible values:
> > +
> > +  * ``BTDS_No`` (in configuration: ``No``)
> > +Do not force break before declaration.
> > +``PenaltyBreakTemplateDeclaration`` is taken into account.
> > +
> > +.. code-block:: c++
> > +
> > +   template  T foo() {
> > +   }
> > +   template  T foo(int a,
> > +   int b) {
> > +   }
> > +
> > +  * ``BTDS_MultiLine`` (in configuration: ``MultiLine``)
> > +Force break after template declaration only when the following
> > +declaration spans multiple lines.
> > +
> > +.. code-block:: c++
> > +
> > +   template  T foo() {
> > +   }
> > +   template 
> > +   T foo(int a,
> > + int b) {
> > +   }
> > +
> > +  * ``BTDS_Yes`` (in configuration: ``Yes``)
> > +Always break after template declaration.
> > +
> > +.. code-block:: c++
> > +
> > +   template 
> > +   T foo() {
> > +   }
> > +   template 
> > +   T foo(int a,
> > + int b) {
> > +   }
> >
> > -  .. code-block:: c++
> >
> > - true:  false:
> > - template   vs. template  class
> C {};
> > - class C {};
> >
> > **BinPackArguments** (``bool``)
> >   If ``false``, a function call's arguments will either be all on the
> > @@ -1590,6 +1625,9 @@ the configuration (without a prefix: ``A
> > **PenaltyBreakString** (``unsigned``)
> >   The penalty for each line break introduced inside a string literal.
> >
> > +**PenaltyBreakTemplateDeclaration** (``unsigned``)
> > +  The penalty for breaking after template declaration.
> > +
> > **PenaltyExcessCharacter** (``unsigned``)
> >   The penalty for each character outside of the column limit.
> >
> >
> > Modified: cfe/trunk/include/clang/Format/Format.h
> > URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=332436&r1=332435&r2=332436&view=diff
> >
> ==
> > --- cfe/trunk/include/clang/Format/Format.h (original)
> > +++ cfe/trunk/include/clang/Format/Format.h Wed May 16 01:25:03 2018
> > @@ -351,14 +351,44 @@ struct FormatStyle {
> >   /// \endcode
> >   bool AlwaysBreakBeforeMultilineStrings;
> >
> > -  /// If ``true``, always break after the ``template<...>`` of a
> template
> > -  /// declaration.
> > -  /// \code
> > -  ///true:  false:
> > -  ///template   vs. tem

r332457 - [CodeComplete] Expose helpers to get RawComment of completion result.

2018-05-16 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed May 16 05:30:01 2018
New Revision: 332457

URL: http://llvm.org/viewvc/llvm-project?rev=332457&view=rev
Log:
[CodeComplete] Expose helpers to get RawComment of completion result.

Summary: Used in clangd, see D45999.

Reviewers: sammccall, hokein, ioeric, arphaman

Reviewed By: sammccall

Subscribers: arphaman, cfe-commits

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

Modified:
cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
cfe/trunk/lib/Sema/SemaCodeComplete.cpp

Modified: cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h?rev=332457&r1=332456&r2=332457&view=diff
==
--- cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h (original)
+++ cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h Wed May 16 05:30:01 2018
@@ -46,6 +46,7 @@ class NamedDecl;
 class NestedNameSpecifier;
 class Preprocessor;
 class Sema;
+class RawComment;
 
 /// Default priority values for code-completion results based
 /// on their kind.
@@ -1073,6 +1074,23 @@ public:
   virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
 };
 
+/// Get the documentation comment used to produce
+/// CodeCompletionString::BriefComment for RK_Declaration.
+const RawComment *getCompletionComment(const ASTContext &Ctx,
+   const NamedDecl *Decl);
+
+/// Get the documentation comment used to produce
+/// CodeCompletionString::BriefComment for RK_Pattern.
+const RawComment *getPatternCompletionComment(const ASTContext &Ctx,
+  const NamedDecl *Decl);
+
+/// Get the documentation comment used to produce
+/// CodeCompletionString::BriefComment for OverloadCandidate.
+const RawComment *
+getParameterComment(const ASTContext &Ctx,
+const CodeCompleteConsumer::OverloadCandidate &Result,
+unsigned ArgIndex);
+
 /// A simple code-completion consumer that prints the results it
 /// receives in a simple format.
 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {

Modified: cfe/trunk/lib/Sema/SemaCodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCodeComplete.cpp?rev=332457&r1=332456&r2=332457&view=diff
==
--- cfe/trunk/lib/Sema/SemaCodeComplete.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCodeComplete.cpp Wed May 16 05:30:01 2018
@@ -2765,27 +2765,11 @@ CodeCompletionResult::CreateCodeCompleti
 if (Declaration) {
   Result.addParentContext(Declaration->getDeclContext());
   Pattern->ParentName = Result.getParentName();
-  // Provide code completion comment for self.GetterName where
-  // GetterName is the getter method for a property with name
-  // different from the property name (declared via a property
-  // getter attribute.
-  const NamedDecl *ND = Declaration;
-  if (const ObjCMethodDecl *M = dyn_cast(ND))
-if (M->isPropertyAccessor())
-  if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
-if (PDecl->getGetterName() == M->getSelector() &&
-PDecl->getIdentifier() != M->getIdentifier()) {
-  if (const RawComment *RC = 
-Ctx.getRawCommentForAnyRedecl(M)) {
-Result.addBriefComment(RC->getBriefText(Ctx));
-Pattern->BriefComment = Result.getBriefComment();
-  }
-  else if (const RawComment *RC = 
- Ctx.getRawCommentForAnyRedecl(PDecl)) {
-Result.addBriefComment(RC->getBriefText(Ctx));
-Pattern->BriefComment = Result.getBriefComment();
-  }
-}
+  if (const RawComment *RC =
+  getPatternCompletionComment(Ctx, Declaration)) {
+Result.addBriefComment(RC->getBriefText(Ctx));
+Pattern->BriefComment = Result.getBriefComment();
+  }
 }
 
 return Pattern;
@@ -2845,14 +2829,9 @@ CodeCompletionResult::CreateCodeCompleti
 
   if (IncludeBriefComments) {
 // Add documentation comment, if it exists.
-if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
+if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
   Result.addBriefComment(RC->getBriefText(Ctx));
 } 
-else if (const ObjCMethodDecl *OMD = dyn_cast(ND))
-  if (OMD->isPropertyAccessor())
-if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
-  if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
-Result.addBriefComment(RC->getBriefText(Ctx));
   }
 
   if (StartsNestedNameSpecifier) {
@@ -3042,6 +3021,59 @@ CodeCompletionResult::CreateCodeCompleti
   return Result.TakeString();
 }
 
+const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
+ 

r332458 - [AST] Added a helper to extract a user-friendly text of a comment.

2018-05-16 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed May 16 05:30:09 2018
New Revision: 332458

URL: http://llvm.org/viewvc/llvm-project?rev=332458&view=rev
Log:
[AST] Added a helper to extract a user-friendly text of a comment.

Summary:
The helper is used in clangd for documentation shown in code completion
and storing the docs in the symbols. See D45999.

This patch reuses the code of the Doxygen comment lexer, disabling the
bits that do command and html tag parsing.
The new helper works on all comments, including non-doxygen comments.
However, it does not understand or transform any doxygen directives,
i.e. cannot extract brief text, etc.

Reviewers: sammccall, hokein, ioeric

Reviewed By: ioeric

Subscribers: mgorny, cfe-commits

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

Added:
cfe/trunk/unittests/AST/CommentTextTest.cpp
Modified:
cfe/trunk/include/clang/AST/CommentLexer.h
cfe/trunk/include/clang/AST/RawCommentList.h
cfe/trunk/lib/AST/CommentLexer.cpp
cfe/trunk/lib/AST/RawCommentList.cpp
cfe/trunk/unittests/AST/CMakeLists.txt

Modified: cfe/trunk/include/clang/AST/CommentLexer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/CommentLexer.h?rev=332458&r1=332457&r2=332458&view=diff
==
--- cfe/trunk/include/clang/AST/CommentLexer.h (original)
+++ cfe/trunk/include/clang/AST/CommentLexer.h Wed May 16 05:30:09 2018
@@ -281,6 +281,11 @@ private:
   /// command, including command marker.
   SmallString<16> VerbatimBlockEndCommandName;
 
+  /// If true, the commands, html tags, etc will be parsed and reported as
+  /// separate tokens inside the comment body. If false, the comment text will
+  /// be parsed into text and newline tokens.
+  bool ParseCommands;
+
   /// Given a character reference name (e.g., "lt"), return the character that
   /// it stands for (e.g., "<").
   StringRef resolveHTMLNamedCharacterReference(StringRef Name) const;
@@ -315,12 +320,11 @@ private:
   /// Eat string matching regexp \code \s*\* \endcode.
   void skipLineStartingDecorations();
 
-  /// Lex stuff inside comments.  CommentEnd should be set correctly.
+  /// Lex comment text, including commands if ParseCommands is set to true.
   void lexCommentText(Token &T);
 
-  void setupAndLexVerbatimBlock(Token &T,
-const char *TextBegin,
-char Marker, const CommandInfo *Info);
+  void setupAndLexVerbatimBlock(Token &T, const char *TextBegin, char Marker,
+const CommandInfo *Info);
 
   void lexVerbatimBlockFirstLine(Token &T);
 
@@ -343,14 +347,13 @@ private:
 
 public:
   Lexer(llvm::BumpPtrAllocator &Allocator, DiagnosticsEngine &Diags,
-const CommandTraits &Traits,
-SourceLocation FileLoc,
-const char *BufferStart, const char *BufferEnd);
+const CommandTraits &Traits, SourceLocation FileLoc,
+const char *BufferStart, const char *BufferEnd,
+bool ParseCommands = true);
 
   void lex(Token &T);
 
-  StringRef getSpelling(const Token &Tok,
-const SourceManager &SourceMgr,
+  StringRef getSpelling(const Token &Tok, const SourceManager &SourceMgr,
 bool *Invalid = nullptr) const;
 };
 

Modified: cfe/trunk/include/clang/AST/RawCommentList.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/RawCommentList.h?rev=332458&r1=332457&r2=332458&view=diff
==
--- cfe/trunk/include/clang/AST/RawCommentList.h (original)
+++ cfe/trunk/include/clang/AST/RawCommentList.h Wed May 16 05:30:09 2018
@@ -111,6 +111,30 @@ public:
 return extractBriefText(Context);
   }
 
+  /// Returns sanitized comment text, suitable for presentation in editor UIs.
+  /// E.g. will transform:
+  /// // This is a long multiline comment.
+  /// //   Parts of it  might be indented.
+  /// /* The comments styles might be mixed. */
+  ///  into
+  /// "This is a long multiline comment.\n"
+  /// "  Parts of it  might be indented.\n"
+  /// "The comments styles might be mixed."
+  /// Also removes leading indentation and sanitizes some common cases:
+  /// /* This is a first line.
+  ///  *   This is a second line. It is indented.
+  ///  * This is a third line. */
+  /// and
+  /// /* This is a first line.
+  ///  This is a second line. It is indented.
+  /// This is a third line. */
+  /// will both turn into:
+  /// "This is a first line.\n"
+  /// "  This is a second line. It is indented.\n"
+  /// "This is a third line."
+  std::string getFormattedText(const SourceManager &SourceMgr,
+   DiagnosticsEngine &Diags) const;
+
   /// Parse the comment, assuming it is attached to decl \c D.
   comments::FullComment *parse(const ASTContext &Context,
const Prepr

[PATCH] D46001: [CodeComplete] Expose helpers to get RawComment of completion result.

2018-05-16 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC332457: [CodeComplete] Expose helpers to get RawComment of 
completion result. (authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D46001?vs=146812&id=147061#toc

Repository:
  rC Clang

https://reviews.llvm.org/D46001

Files:
  include/clang/Sema/CodeCompleteConsumer.h
  lib/Sema/SemaCodeComplete.cpp

Index: include/clang/Sema/CodeCompleteConsumer.h
===
--- include/clang/Sema/CodeCompleteConsumer.h
+++ include/clang/Sema/CodeCompleteConsumer.h
@@ -46,6 +46,7 @@
 class NestedNameSpecifier;
 class Preprocessor;
 class Sema;
+class RawComment;
 
 /// Default priority values for code-completion results based
 /// on their kind.
@@ -1073,6 +1074,23 @@
   virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
 };
 
+/// Get the documentation comment used to produce
+/// CodeCompletionString::BriefComment for RK_Declaration.
+const RawComment *getCompletionComment(const ASTContext &Ctx,
+   const NamedDecl *Decl);
+
+/// Get the documentation comment used to produce
+/// CodeCompletionString::BriefComment for RK_Pattern.
+const RawComment *getPatternCompletionComment(const ASTContext &Ctx,
+  const NamedDecl *Decl);
+
+/// Get the documentation comment used to produce
+/// CodeCompletionString::BriefComment for OverloadCandidate.
+const RawComment *
+getParameterComment(const ASTContext &Ctx,
+const CodeCompleteConsumer::OverloadCandidate &Result,
+unsigned ArgIndex);
+
 /// A simple code-completion consumer that prints the results it
 /// receives in a simple format.
 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2765,27 +2765,11 @@
 if (Declaration) {
   Result.addParentContext(Declaration->getDeclContext());
   Pattern->ParentName = Result.getParentName();
-  // Provide code completion comment for self.GetterName where
-  // GetterName is the getter method for a property with name
-  // different from the property name (declared via a property
-  // getter attribute.
-  const NamedDecl *ND = Declaration;
-  if (const ObjCMethodDecl *M = dyn_cast(ND))
-if (M->isPropertyAccessor())
-  if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
-if (PDecl->getGetterName() == M->getSelector() &&
-PDecl->getIdentifier() != M->getIdentifier()) {
-  if (const RawComment *RC = 
-Ctx.getRawCommentForAnyRedecl(M)) {
-Result.addBriefComment(RC->getBriefText(Ctx));
-Pattern->BriefComment = Result.getBriefComment();
-  }
-  else if (const RawComment *RC = 
- Ctx.getRawCommentForAnyRedecl(PDecl)) {
-Result.addBriefComment(RC->getBriefText(Ctx));
-Pattern->BriefComment = Result.getBriefComment();
-  }
-}
+  if (const RawComment *RC =
+  getPatternCompletionComment(Ctx, Declaration)) {
+Result.addBriefComment(RC->getBriefText(Ctx));
+Pattern->BriefComment = Result.getBriefComment();
+  }
 }
 
 return Pattern;
@@ -2845,14 +2829,9 @@
 
   if (IncludeBriefComments) {
 // Add documentation comment, if it exists.
-if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
+if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
   Result.addBriefComment(RC->getBriefText(Ctx));
 } 
-else if (const ObjCMethodDecl *OMD = dyn_cast(ND))
-  if (OMD->isPropertyAccessor())
-if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
-  if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
-Result.addBriefComment(RC->getBriefText(Ctx));
   }
 
   if (StartsNestedNameSpecifier) {
@@ -3042,6 +3021,59 @@
   return Result.TakeString();
 }
 
+const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
+  const NamedDecl *ND) {
+  if (!ND)
+return nullptr;
+  if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
+return RC;
+
+  // Try to find comment from a property for ObjC methods.
+  const ObjCMethodDecl *M = dyn_cast(ND);
+  if (!M)
+return nullptr;
+  const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
+  if (!PDecl)
+return nullptr;
+
+  return Ctx.getRawCommentForAnyRedecl(PDecl);
+}
+
+const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx,
+ const NamedDecl *ND) {
+  const ObjCMethodDecl *M = dyn_cast_or_null(ND

[PATCH] D46000: [AST] Added a helper to extract a user-friendly text of a comment.

2018-05-16 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332458: [AST] Added a helper to extract a user-friendly text 
of a comment. (authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D46000

Files:
  cfe/trunk/include/clang/AST/CommentLexer.h
  cfe/trunk/include/clang/AST/RawCommentList.h
  cfe/trunk/lib/AST/CommentLexer.cpp
  cfe/trunk/lib/AST/RawCommentList.cpp
  cfe/trunk/unittests/AST/CMakeLists.txt
  cfe/trunk/unittests/AST/CommentTextTest.cpp

Index: cfe/trunk/include/clang/AST/CommentLexer.h
===
--- cfe/trunk/include/clang/AST/CommentLexer.h
+++ cfe/trunk/include/clang/AST/CommentLexer.h
@@ -281,6 +281,11 @@
   /// command, including command marker.
   SmallString<16> VerbatimBlockEndCommandName;
 
+  /// If true, the commands, html tags, etc will be parsed and reported as
+  /// separate tokens inside the comment body. If false, the comment text will
+  /// be parsed into text and newline tokens.
+  bool ParseCommands;
+
   /// Given a character reference name (e.g., "lt"), return the character that
   /// it stands for (e.g., "<").
   StringRef resolveHTMLNamedCharacterReference(StringRef Name) const;
@@ -315,12 +320,11 @@
   /// Eat string matching regexp \code \s*\* \endcode.
   void skipLineStartingDecorations();
 
-  /// Lex stuff inside comments.  CommentEnd should be set correctly.
+  /// Lex comment text, including commands if ParseCommands is set to true.
   void lexCommentText(Token &T);
 
-  void setupAndLexVerbatimBlock(Token &T,
-const char *TextBegin,
-char Marker, const CommandInfo *Info);
+  void setupAndLexVerbatimBlock(Token &T, const char *TextBegin, char Marker,
+const CommandInfo *Info);
 
   void lexVerbatimBlockFirstLine(Token &T);
 
@@ -343,14 +347,13 @@
 
 public:
   Lexer(llvm::BumpPtrAllocator &Allocator, DiagnosticsEngine &Diags,
-const CommandTraits &Traits,
-SourceLocation FileLoc,
-const char *BufferStart, const char *BufferEnd);
+const CommandTraits &Traits, SourceLocation FileLoc,
+const char *BufferStart, const char *BufferEnd,
+bool ParseCommands = true);
 
   void lex(Token &T);
 
-  StringRef getSpelling(const Token &Tok,
-const SourceManager &SourceMgr,
+  StringRef getSpelling(const Token &Tok, const SourceManager &SourceMgr,
 bool *Invalid = nullptr) const;
 };
 
Index: cfe/trunk/include/clang/AST/RawCommentList.h
===
--- cfe/trunk/include/clang/AST/RawCommentList.h
+++ cfe/trunk/include/clang/AST/RawCommentList.h
@@ -111,6 +111,30 @@
 return extractBriefText(Context);
   }
 
+  /// Returns sanitized comment text, suitable for presentation in editor UIs.
+  /// E.g. will transform:
+  /// // This is a long multiline comment.
+  /// //   Parts of it  might be indented.
+  /// /* The comments styles might be mixed. */
+  ///  into
+  /// "This is a long multiline comment.\n"
+  /// "  Parts of it  might be indented.\n"
+  /// "The comments styles might be mixed."
+  /// Also removes leading indentation and sanitizes some common cases:
+  /// /* This is a first line.
+  ///  *   This is a second line. It is indented.
+  ///  * This is a third line. */
+  /// and
+  /// /* This is a first line.
+  ///  This is a second line. It is indented.
+  /// This is a third line. */
+  /// will both turn into:
+  /// "This is a first line.\n"
+  /// "  This is a second line. It is indented.\n"
+  /// "This is a third line."
+  std::string getFormattedText(const SourceManager &SourceMgr,
+   DiagnosticsEngine &Diags) const;
+
   /// Parse the comment, assuming it is attached to decl \c D.
   comments::FullComment *parse(const ASTContext &Context,
const Preprocessor *PP, const Decl *D) const;
Index: cfe/trunk/lib/AST/CommentLexer.cpp
===
--- cfe/trunk/lib/AST/CommentLexer.cpp
+++ cfe/trunk/lib/AST/CommentLexer.cpp
@@ -294,6 +294,39 @@
   assert(CommentState == LCS_InsideBCPLComment ||
  CommentState == LCS_InsideCComment);
 
+  // Handles lexing non-command text, i.e. text and newline.
+  auto HandleNonCommandToken = [&]() -> void {
+assert(State == LS_Normal);
+
+const char *TokenPtr = BufferPtr;
+assert(TokenPtr < CommentEnd);
+switch (*TokenPtr) {
+  case '\n':
+  case '\r':
+  TokenPtr = skipNewline(TokenPtr, CommentEnd);
+  formTokenWithChars(T, TokenPtr, tok::newline);
+
+  if (CommentState == LCS_InsideCComment)
+skipLineStartingDecorations();
+  return;
+
+  default: {
+   

[clang-tools-extra] r332460 - [clangd] Parse all comments in Sema and completion.

2018-05-16 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed May 16 05:32:49 2018
New Revision: 332460

URL: http://llvm.org/viewvc/llvm-project?rev=332460&view=rev
Log:
[clangd] Parse all comments in Sema and completion.

Summary:
And add tests for the comment extraction code.

clangd will now show non-doxygen comments in completion for results
coming from Sema and Dynamic index.
Static index does not include the comments yet, I will enable it in
a separate commit after investigating which implications it has for
the size of the index.

Reviewers: sammccall, hokein, ioeric

Reviewed By: sammccall

Subscribers: klimek, MaskRay, jkorous, cfe-commits

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

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

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=332460&r1=332459&r2=332460&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Wed May 16 05:32:49 2018
@@ -25,6 +25,7 @@
 #include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Tooling/CompilationDatabase.h"
+#include "clang/Basic/LangOptions.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
@@ -316,6 +317,7 @@ llvm::Optional> CppFil
 }
 // createInvocationFromCommandLine sets DisableFree.
 CI->getFrontendOpts().DisableFree = false;
+CI->getLangOpts()->CommentOpts.ParseAllComments = true;
   }
 
   std::unique_ptr ContentsBuffer =

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=332460&r1=332459&r2=332460&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Wed May 16 05:32:49 2018
@@ -25,6 +25,7 @@
 #include "Trace.h"
 #include "URI.h"
 #include "index/Index.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Format/Format.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendActions.h"
@@ -648,6 +649,7 @@ bool semaCodeComplete(std::unique_ptrgetFrontendOpts().DisableFree = false;
+  CI->getLangOpts()->CommentOpts.ParseAllComments = true;
 
   std::unique_ptr ContentsBuffer =
   llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);

Modified: clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp?rev=332460&r1=332459&r2=332460&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp Wed May 16 
05:32:49 2018
@@ -628,6 +628,30 @@ TEST(CompletionTest, DynamicIndexMultiFi
 Doc("Doooc"), Detail("void";
 }
 
+TEST(CompletionTest, Documentation) {
+  auto Results = completions(
+  R"cpp(
+  // Non-doxygen comment.
+  int foo();
+  /// Doxygen comment.
+  /// \param int a
+  int bar(int a);
+  /* Multi-line
+ block comment
+  */
+  int baz();
+
+  int x = ^
+ )cpp");
+  EXPECT_THAT(Results.items,
+  Contains(AllOf(Named("foo"), Doc("Non-doxygen comment.";
+  EXPECT_THAT(
+  Results.items,
+  Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a";
+  EXPECT_THAT(Results.items,
+  Contains(AllOf(Named("baz"), Doc("Multi-line\nblock comment";
+}
+
 TEST(CodeCompleteTest, DisableTypoCorrection) {
   auto Results = completions(R"cpp(
  namespace clang { int v; }


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


[clang-tools-extra] r332459 - [clangd] Retrieve minimally formatted comment text in completion.

2018-05-16 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed May 16 05:32:44 2018
New Revision: 332459

URL: http://llvm.org/viewvc/llvm-project?rev=332459&view=rev
Log:
[clangd] Retrieve minimally formatted comment text in completion.

Summary:
Previous implementation used to extract brief text from doxygen comments.
Brief text parsing slows down completion and is not suited for
non-doxygen comments.

This commit switches to providing comments that mimic the ones
originally written in the source code, doing minimal reindenting and
removing the comments markers to make the output more user-friendly.

It means we lose support for doxygen-specific features, e.g. extracting
brief text, but provide useful results for non-doxygen comments.
Switching the doxygen support back is an option, but I suggest to see
whether the current approach gives more useful results.

Reviewers: sammccall, hokein, ioeric

Reviewed By: sammccall

Subscribers: klimek, MaskRay, jkorous, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/CodeComplete.h
clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp
clang-tools-extra/trunk/clangd/CodeCompletionStrings.h
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
clang-tools-extra/trunk/unittests/clangd/CodeCompletionStringsTests.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=332459&r1=332458&r2=332459&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Wed May 16 05:32:44 2018
@@ -230,7 +230,8 @@ struct CompletionCandidate {
   CompletionItem build(StringRef FileName, const CompletionItemScores &Scores,
const CodeCompleteOptions &Opts,
CodeCompletionString *SemaCCS,
-   const IncludeInserter *Includes) const {
+   const IncludeInserter *Includes,
+   llvm::StringRef SemaDocComment) const {
 assert(bool(SemaResult) == bool(SemaCCS));
 CompletionItem I;
 if (SemaResult) {
@@ -238,7 +239,7 @@ struct CompletionCandidate {
   getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
 Opts.EnableSnippets);
   I.filterText = getFilterText(*SemaCCS);
-  I.documentation = getDocumentation(*SemaCCS);
+  I.documentation = formatDocumentation(*SemaCCS, SemaDocComment);
   I.detail = getDetail(*SemaCCS);
 }
 if (IndexResult) {
@@ -481,17 +482,17 @@ struct CompletionRecorder : public CodeC
 case CodeCompletionResult::RK_Pattern:
   return Result.Pattern->getTypedText();
 }
-auto *CCS = codeCompletionString(Result, /*IncludeBriefComments=*/false);
+auto *CCS = codeCompletionString(Result);
 return CCS->getTypedText();
   }
 
   // Build a CodeCompletion string for R, which must be from Results.
   // The CCS will be owned by this recorder.
-  CodeCompletionString *codeCompletionString(const CodeCompletionResult &R,
- bool IncludeBriefComments) {
+  CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
 // CodeCompletionResult doesn't seem to be const-correct. We own it, 
anyway.
 return const_cast(R).CreateCodeCompletionString(
-*CCSema, CCContext, *CCAllocator, CCTUInfo, IncludeBriefComments);
+*CCSema, CCContext, *CCAllocator, CCTUInfo,
+/*IncludeBriefComments=*/false);
   }
 
 private:
@@ -535,7 +536,9 @@ public:
   const auto *CCS = Candidate.CreateSignatureString(
   CurrentArg, S, *Allocator, CCTUInfo, true);
   assert(CCS && "Expected the CodeCompletionString to be non-null");
-  SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
+  SigHelp.signatures.push_back(ProcessOverloadCandidate(
+  Candidate, *CCS,
+  getParameterDocComment(S.getASTContext(), Candidate, CurrentArg)));
 }
   }
 
@@ -548,11 +551,12 @@ private:
   // CompletionString.h.
   SignatureInformation
   ProcessOverloadCandidate(const OverloadCandidate &Candidate,
-   const CodeCompletionString &CCS) const {
+   const CodeCompletionString &CCS,
+   llvm::StringRef DocComment) const {
 SignatureInformation Result;
 const char *ReturnType = nullptr;
 
-Result.documentation = getDocumentation(CCS);
+Result.documentation = formatDocumentation(CCS, DocComment);
 
 for (const auto &Chunk : CCS) {
   switch (Chunk.Kind) {
@@ -802,7 +806,11 @@ clang::CodeCompleteOptions CodeCompleteO
   Result.

[PATCH] D46002: [clangd] Parse all comments in Sema and completion.

2018-05-16 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE332460: [clangd] Parse all comments in Sema and 
completion. (authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D46002?vs=146831&id=147064#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46002

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


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -628,6 +628,30 @@
 Doc("Doooc"), Detail("void";
 }
 
+TEST(CompletionTest, Documentation) {
+  auto Results = completions(
+  R"cpp(
+  // Non-doxygen comment.
+  int foo();
+  /// Doxygen comment.
+  /// \param int a
+  int bar(int a);
+  /* Multi-line
+ block comment
+  */
+  int baz();
+
+  int x = ^
+ )cpp");
+  EXPECT_THAT(Results.items,
+  Contains(AllOf(Named("foo"), Doc("Non-doxygen comment.";
+  EXPECT_THAT(
+  Results.items,
+  Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a";
+  EXPECT_THAT(Results.items,
+  Contains(AllOf(Named("baz"), Doc("Multi-line\nblock comment";
+}
+
 TEST(CodeCompleteTest, DisableTypoCorrection) {
   auto Results = completions(R"cpp(
  namespace clang { int v; }
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -25,6 +25,7 @@
 #include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Tooling/CompilationDatabase.h"
+#include "clang/Basic/LangOptions.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
@@ -316,6 +317,7 @@
 }
 // createInvocationFromCommandLine sets DisableFree.
 CI->getFrontendOpts().DisableFree = false;
+CI->getLangOpts()->CommentOpts.ParseAllComments = true;
   }
 
   std::unique_ptr ContentsBuffer =
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -25,6 +25,7 @@
 #include "Trace.h"
 #include "URI.h"
 #include "index/Index.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Format/Format.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendActions.h"
@@ -648,6 +649,7 @@
 return false;
   }
   CI->getFrontendOpts().DisableFree = false;
+  CI->getLangOpts()->CommentOpts.ParseAllComments = true;
 
   std::unique_ptr ContentsBuffer =
   llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -628,6 +628,30 @@
 Doc("Doooc"), Detail("void";
 }
 
+TEST(CompletionTest, Documentation) {
+  auto Results = completions(
+  R"cpp(
+  // Non-doxygen comment.
+  int foo();
+  /// Doxygen comment.
+  /// \param int a
+  int bar(int a);
+  /* Multi-line
+ block comment
+  */
+  int baz();
+
+  int x = ^
+ )cpp");
+  EXPECT_THAT(Results.items,
+  Contains(AllOf(Named("foo"), Doc("Non-doxygen comment.";
+  EXPECT_THAT(
+  Results.items,
+  Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a";
+  EXPECT_THAT(Results.items,
+  Contains(AllOf(Named("baz"), Doc("Multi-line\nblock comment";
+}
+
 TEST(CodeCompleteTest, DisableTypoCorrection) {
   auto Results = completions(R"cpp(
  namespace clang { int v; }
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -25,6 +25,7 @@
 #include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Tooling/CompilationDatabase.h"
+#include "clang/Basic/LangOptions.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
@@ -316,6 +317,7 @@
 }
 // createInvocationFromCommandLine sets DisableFree.
 CI->getFrontendOpts().DisableFree = false;
+CI->getLangOpts()->CommentOpts.ParseAllComments = true;
   }
 
   std::unique_ptr ContentsBuffer =
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -25,6 +25,7 @@
 #include "Trace.h"
 #include "URI.h"
 #include "index/Index.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Format/Format.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang

[PATCH] D45999: [clangd] Retrieve minimally formatted comment text in completion.

2018-05-16 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE332459: [clangd] Retrieve minimally formatted comment text 
in completion. (authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D45999?vs=147060&id=147063#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45999

Files:
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/CodeCompletionStrings.cpp
  clangd/CodeCompletionStrings.h
  clangd/index/SymbolCollector.cpp
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/CodeCompletionStringsTests.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/CodeCompletionStringsTests.cpp
===
--- unittests/clangd/CodeCompletionStringsTests.cpp
+++ unittests/clangd/CodeCompletionStringsTests.cpp
@@ -51,23 +51,24 @@
 }
 
 TEST_F(CompletionStringTest, Documentation) {
-  Builder.addBriefComment("Is this brief?");
-  EXPECT_EQ(getDocumentation(*Builder.TakeString()), "Is this brief?");
+  Builder.addBriefComment("This is ignored");
+  EXPECT_EQ(formatDocumentation(*Builder.TakeString(), "Is this brief?"),
+"Is this brief?");
 }
 
 TEST_F(CompletionStringTest, DocumentationWithAnnotation) {
-  Builder.addBriefComment("Is this brief?");
+  Builder.addBriefComment("This is ignored");
   Builder.AddAnnotation("Ano");
-  EXPECT_EQ(getDocumentation(*Builder.TakeString()),
+  EXPECT_EQ(formatDocumentation(*Builder.TakeString(), "Is this brief?"),
 "Annotation: Ano\n\nIs this brief?");
 }
 
 TEST_F(CompletionStringTest, MultipleAnnotations) {
   Builder.AddAnnotation("Ano1");
   Builder.AddAnnotation("Ano2");
   Builder.AddAnnotation("Ano3");
 
-  EXPECT_EQ(getDocumentation(*Builder.TakeString()),
+  EXPECT_EQ(formatDocumentation(*Builder.TakeString(), ""),
 "Annotations: Ano1 Ano2 Ano3\n");
 }
 
@@ -97,7 +98,7 @@
 
 TEST_F(CompletionStringTest, FunctionSnippet) {
   Builder.AddResultTypeChunk("result no no");
-  Builder.addBriefComment("Foo's comment");
+  Builder.addBriefComment("This comment is ignored");
   Builder.AddTypedTextChunk("Foo");
   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
   Builder.AddPlaceholderChunk("p1");
@@ -113,7 +114,7 @@
   labelAndInsertText(*CCS, /*EnableSnippets=*/true);
   EXPECT_EQ(Label, "Foo(p1, p2)");
   EXPECT_EQ(InsertText, "Foo(${1:p1}, ${2:p2})");
-  EXPECT_EQ(getDocumentation(*CCS), "Foo's comment");
+  EXPECT_EQ(formatDocumentation(*CCS, "Foo's comment"), "Foo's comment");
   EXPECT_EQ(getFilterText(*CCS), "Foo");
 }
 
Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -490,11 +490,11 @@
 }
   )";
   runSymbolCollector(Header, /*Main=*/"");
-  EXPECT_THAT(Symbols,
-  UnorderedElementsAre(QName("nx"),
-   AllOf(QName("nx::ff"),
- Labeled("ff(int x, double y)"),
- Detail("int"), Doc("Foo comment.";
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  QName("nx"), AllOf(QName("nx::ff"), Labeled("ff(int x, double y)"),
+ Detail("int"), Doc("Foo comment.";
 }
 
 TEST_F(SymbolCollectorTest, PlainAndSnippet) {
Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -261,8 +261,7 @@
   // completion. At least there aren't any we're aware of.
   EXPECT_THAT(Results.items, Not(Contains(Kind(CompletionItemKind::Snippet;
   // Check documentation.
-  EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
- Contains(IsDocumented()));
+  EXPECT_IFF(Opts.IncludeComments, Results.items, Contains(IsDocumented()));
 }
 
 void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
@@ -307,8 +306,7 @@
   AllOf(Has("local_var"), Has("LocalClass"),
 Contains(Kind(CompletionItemKind::Snippet;
   // Check documentation.
-  EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
- Contains(IsDocumented()));
+  EXPECT_IFF(Opts.IncludeComments, Results.items, Contains(IsDocumented()));
 }
 
 TEST(CompletionTest, CompletionOptions) {
@@ -319,7 +317,7 @@
   // We used to test every combination of options, but that got too slow (2^N).
   auto Flags = {
   &clangd::CodeCompleteOptions::IncludeMacros,
-  &clangd::CodeCompleteOptions::IncludeBriefComments,
+  &clangd::CodeCompleteOptions::IncludeComments,
   &clangd::CodeCompleteOptions::EnableSnippets,
   &clangd::CodeCompleteOptions::IncludeCodePatterns,
   &clangd::CodeCompleteOptions::IncludeIneligibleResults,
Index: clangd/index/SymbolCollector.cpp
==

r332463 - [analyzer] Improve the modeling of memset().

2018-05-16 Thread Henry Wong via cfe-commits
Author: henrywong
Date: Wed May 16 05:37:53 2018
New Revision: 332463

URL: http://llvm.org/viewvc/llvm-project?rev=332463&view=rev
Log:
[analyzer] Improve the modeling of memset().

Since there is no perfect way bind the non-zero value with the default binding, 
this patch only considers the case where buffer's offset is zero and the char 
value is 0. And according to the value for overwriting, decide how to update 
the string length.

Reviewers: dcoughlin, NoQ, xazax.hun, a.sidorin, george.karpenkov

Reviewed By: NoQ

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
cfe/trunk/test/Analysis/bstring.cpp
cfe/trunk/test/Analysis/null-deref-ps-region.c
cfe/trunk/test/Analysis/string.c

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp?rev=332463&r1=332462&r2=332463&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp Wed May 16 
05:37:53 2018
@@ -158,6 +158,10 @@ public:
   static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
   const MemRegion *MR);
 
+  static bool memsetAux(const Expr *DstBuffer, const Expr *CharE,
+const Expr *Size, CheckerContext &C,
+ProgramStateRef &State);
+
   // Re-usable checks
   ProgramStateRef checkNonNull(CheckerContext &C,
ProgramStateRef state,
@@ -999,6 +1003,95 @@ bool CStringChecker::SummarizeRegion(raw
   }
 }
 
+bool CStringChecker::memsetAux(const Expr *DstBuffer, const Expr *CharE,
+   const Expr *Size, CheckerContext &C,
+   ProgramStateRef &State) {
+  SVal MemVal = C.getSVal(DstBuffer);
+  SVal CharVal = C.getSVal(CharE);
+  SVal SizeVal = C.getSVal(Size);
+  const MemRegion *MR = MemVal.getAsRegion();
+  if (!MR)
+return false;
+
+  // We're about to model memset by producing a "default binding" in the Store.
+  // Our current implementation - RegionStore - doesn't support default 
bindings
+  // that don't cover the whole base region. So we should first get the offset
+  // and the base region to figure out whether the offset of buffer is 0.
+  RegionOffset Offset = MR->getAsOffset();
+  const MemRegion *BR = Offset.getRegion();
+
+  Optional SizeNL = SizeVal.getAs();
+  if (!SizeNL)
+return false;
+
+  SValBuilder &svalBuilder = C.getSValBuilder();
+  ASTContext &Ctx = C.getASTContext();
+
+  // void *memset(void *dest, int ch, size_t count);
+  // For now we can only handle the case of offset is 0 and concrete char 
value.
+  if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
+  Offset.getOffset() == 0) {
+// Get the base region's extent.
+auto *SubReg = cast(BR);
+DefinedOrUnknownSVal Extent = SubReg->getExtent(svalBuilder);
+
+ProgramStateRef StateWholeReg, StateNotWholeReg;
+std::tie(StateWholeReg, StateNotWholeReg) =
+State->assume(svalBuilder.evalEQ(State, Extent, *SizeNL));
+
+// With the semantic of 'memset()', we should convert the CharVal to 
+// unsigned char.
+CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
+
+ProgramStateRef StateNullChar, StateNonNullChar;
+std::tie(StateNullChar, StateNonNullChar) =
+assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
+
+if (StateWholeReg && !StateNotWholeReg && StateNullChar &&
+!StateNonNullChar) {
+  // If the 'memset()' acts on the whole region of destination buffer and
+  // the value of the second argument of 'memset()' is zero, bind the 
second
+  // argument's value to the destination buffer with 'default binding'.
+  // FIXME: Since there is no perfect way to bind the non-zero character, 
we
+  // can only deal with zero value here. In the future, we need to deal 
with
+  // the binding of non-zero value in the case of whole region.
+  State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
+ C.getLocationContext());
+} else {
+  // If the destination buffer's extent is not equal to the value of
+  // third argument, just invalidate buffer.
+  State = InvalidateBuffer(C, State, DstBuffer, MemVal,
+   /*IsSourceBuffer*/ false, Size);
+}
+
+if (StateNullChar && !StateNonNullChar) {
+  // If the value of the second argument of 'memset()' is zero, set the
+  // string length of destination buffer to 0 directly.
+  State = setCStringLength(State, MR,
+   svalBuilder.makeZeroVal(Ctx.getSizeType()));
+} else if (!StateNullChar && StateNonNullChar) {
+  SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
+  

[PATCH] D44934: [analyzer] Improve the modeling of `memset()`.

2018-05-16 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332463: [analyzer] Improve the modeling of memset(). 
(authored by henrywong, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D44934?vs=146816&id=147066#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D44934

Files:
  cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  cfe/trunk/test/Analysis/bstring.cpp
  cfe/trunk/test/Analysis/null-deref-ps-region.c
  cfe/trunk/test/Analysis/string.c

Index: cfe/trunk/test/Analysis/bstring.cpp
===
--- cfe/trunk/test/Analysis/bstring.cpp
+++ cfe/trunk/test/Analysis/bstring.cpp
@@ -1,7 +1,8 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.cstring,alpha.unix.cstring,debug.ExprInspection -analyzer-store=region -verify %s
-// RUN: %clang_analyze_cc1 -DUSE_BUILTINS -analyzer-checker=core,unix.cstring,alpha.unix.cstring,debug.ExprInspection -analyzer-store=region -verify %s
-// RUN: %clang_analyze_cc1 -DVARIANT -analyzer-checker=core,unix.cstring,alpha.unix.cstring,debug.ExprInspection -analyzer-store=region -verify %s
-// RUN: %clang_analyze_cc1 -DUSE_BUILTINS -DVARIANT -analyzer-checker=core,unix.cstring,alpha.unix.cstring,debug.ExprInspection -analyzer-store=region -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.cstring,unix.Malloc,alpha.unix.cstring,debug.ExprInspection -analyzer-store=region -verify %s
+// RUN: %clang_analyze_cc1 -DUSE_BUILTINS -analyzer-checker=core,unix.cstring,unix.Malloc,alpha.unix.cstring,debug.ExprInspection -analyzer-store=region -verify %s
+// RUN: %clang_analyze_cc1 -DVARIANT -analyzer-checker=core,unix.cstring,alpha.unix.cstring,unix.Malloc,debug.ExprInspection -analyzer-store=region -verify %s
+// RUN: %clang_analyze_cc1 -DUSE_BUILTINS -DVARIANT -analyzer-checker=core,unix.cstring,alpha.unix.cstring,unix.Malloc,debug.ExprInspection -analyzer-store=region -verify %s
+// RUN: %clang_analyze_cc1 -DSUPPRESS_OUT_OF_BOUND -analyzer-checker=core,unix.cstring,unix.Malloc,alpha.unix.cstring.BufferOverlap,alpha.unix.cstring.NotNullTerminated,debug.ExprInspection -analyzer-store=region -verify %s
 
 #include "Inputs/system-header-simulator-cxx.h"
 #include "Inputs/system-header-simulator-for-malloc.h"
@@ -77,3 +78,118 @@
   unsigned *f;
 };
 }
+
+void *memset(void *dest, int ch, std::size_t count);
+namespace memset_non_pod {
+class Base {
+public:
+  int b_mem;
+  Base() : b_mem(1) {}
+};
+
+class Derived : public Base {
+public:
+  int d_mem;
+  Derived() : d_mem(2) {}
+};
+
+void memset1_inheritance() {
+  Derived d;
+  memset(&d, 0, sizeof(Derived));
+  clang_analyzer_eval(d.b_mem == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(d.d_mem == 0); // expected-warning{{TRUE}}
+}
+
+#ifdef SUPPRESS_OUT_OF_BOUND
+void memset2_inheritance_field() {
+  Derived d;
+  memset(&d.d_mem, 0, sizeof(Derived));
+  clang_analyzer_eval(d.b_mem == 0); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(d.d_mem == 0); // expected-warning{{UNKNOWN}}
+}
+
+void memset3_inheritance_field() {
+  Derived d;
+  memset(&d.b_mem, 0, sizeof(Derived));
+  clang_analyzer_eval(d.b_mem == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(d.d_mem == 0); // expected-warning{{TRUE}}
+}
+#endif
+
+void memset4_array_nonpod_object() {
+  Derived array[10];
+  clang_analyzer_eval(array[1].b_mem == 1); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(array[1].d_mem == 2); // expected-warning{{UNKNOWN}}
+  memset(&array[1], 0, sizeof(Derived));
+  clang_analyzer_eval(array[1].b_mem == 0); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(array[1].d_mem == 0); // expected-warning{{UNKNOWN}}
+}
+
+void memset5_array_nonpod_object() {
+  Derived array[10];
+  clang_analyzer_eval(array[1].b_mem == 1); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(array[1].d_mem == 2); // expected-warning{{UNKNOWN}}
+  memset(array, 0, sizeof(array));
+  clang_analyzer_eval(array[1].b_mem == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(array[1].d_mem == 0); // expected-warning{{TRUE}}
+}
+
+void memset6_new_array_nonpod_object() {
+  Derived *array = new Derived[10];
+  clang_analyzer_eval(array[2].b_mem == 1); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(array[2].d_mem == 2); // expected-warning{{UNKNOWN}}
+  memset(array, 0, 10 * sizeof(Derived));
+  clang_analyzer_eval(array[2].b_mem == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(array[2].d_mem == 0); // expected-warning{{TRUE}}
+  delete[] array;
+}
+
+void memset7_placement_new() {
+  Derived *d = new Derived();
+  clang_analyzer_eval(d->b_mem == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(d->d_mem == 2); // expected-warning{{TRUE}}
+
+  memset(d, 0, sizeof(Derived));
+  clang_analyzer_eval(d->b_mem == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(d->d_mem == 0); // expected-warning{{TRUE}}
+
+  Derived *d1 = new (d) Deriv

Re: r332436 - clang-format: Allow optimizer to break template declaration.

2018-05-16 Thread Eric Liu via cfe-commits
OK, I'll send a fix for the index test. Please make sure you run all clang
tests (`ninja check-clang` and `ninja check-clang-tools`) before landing a
patch! Thanks!

On Wed, May 16, 2018 at 2:32 PM Eric Liu  wrote:

> I can also reproduce on my local machine (Debian).
>
> On Wed, May 16, 2018 at 1:01 PM David Zarzycki via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> This change broke `test/Index/overriding-ftemplate-comments.cpp` on Red
>> Hat Fedora 28. Was this expected?
>>
>> > On May 16, 2018, at 4:25 AM, Francois Ferrand via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>> >
>> > Author: typz
>> > Date: Wed May 16 01:25:03 2018
>> > New Revision: 332436
>> >
>> > URL: http://llvm.org/viewvc/llvm-project?rev=332436&view=rev
>> > Log:
>> > clang-format: Allow optimizer to break template declaration.
>> >
>> > Summary:
>> > Introduce `PenaltyBreakTemplateDeclaration` to control the penalty,
>> > and change `AlwaysBreakTemplateDeclarations` to an enum with 3 modes:
>> > * `No` for regular, penalty based, wrapping of template declaration
>> > * `MultiLine` for always wrapping before multi-line declarations (e.g.
>> >  same as legacy behavior when `AlwaysBreakTemplateDeclarations=false`)
>> > * `Yes` for always wrapping (e.g. same as legacy behavior when
>> >  `AlwaysBreakTemplateDeclarations=true`)
>> >
>> > Reviewers: krasimir, djasper, klimek
>> >
>> > Subscribers: cfe-commits
>> >
>> > Differential Revision: https://reviews.llvm.org/D42684
>> >
>> > Modified:
>> >cfe/trunk/docs/ClangFormatStyleOptions.rst
>> >cfe/trunk/include/clang/Format/Format.h
>> >cfe/trunk/lib/Format/ContinuationIndenter.cpp
>> >cfe/trunk/lib/Format/Format.cpp
>> >cfe/trunk/lib/Format/TokenAnnotator.cpp
>> >cfe/trunk/unittests/Format/FormatTest.cpp
>> >
>> > Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
>> > URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=332436&r1=332435&r2=332436&view=diff
>> >
>> ==
>> > --- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
>> > +++ cfe/trunk/docs/ClangFormatStyleOptions.rst Wed May 16 01:25:03 2018
>> > @@ -490,15 +490,50 @@ the configuration (without a prefix: ``A
>> >  """";
>> >  "";
>> >
>> > -**AlwaysBreakTemplateDeclarations** (``bool``)
>> > -  If ``true``, always break after the ``template<...>`` of a template
>> > -  declaration.
>> > +**AlwaysBreakTemplateDeclarations**
>> (``BreakTemplateDeclarationsStyle``)
>> > +  The template declaration breaking style to use.
>> > +
>> > +  Possible values:
>> > +
>> > +  * ``BTDS_No`` (in configuration: ``No``)
>> > +Do not force break before declaration.
>> > +``PenaltyBreakTemplateDeclaration`` is taken into account.
>> > +
>> > +.. code-block:: c++
>> > +
>> > +   template  T foo() {
>> > +   }
>> > +   template  T foo(int a,
>> > +   int b) {
>> > +   }
>> > +
>> > +  * ``BTDS_MultiLine`` (in configuration: ``MultiLine``)
>> > +Force break after template declaration only when the following
>> > +declaration spans multiple lines.
>> > +
>> > +.. code-block:: c++
>> > +
>> > +   template  T foo() {
>> > +   }
>> > +   template 
>> > +   T foo(int a,
>> > + int b) {
>> > +   }
>> > +
>> > +  * ``BTDS_Yes`` (in configuration: ``Yes``)
>> > +Always break after template declaration.
>> > +
>> > +.. code-block:: c++
>> > +
>> > +   template 
>> > +   T foo() {
>> > +   }
>> > +   template 
>> > +   T foo(int a,
>> > + int b) {
>> > +   }
>> >
>> > -  .. code-block:: c++
>> >
>> > - true:  false:
>> > - template   vs. template 
>> class C {};
>> > - class C {};
>> >
>> > **BinPackArguments** (``bool``)
>> >   If ``false``, a function call's arguments will either be all on the
>> > @@ -1590,6 +1625,9 @@ the configuration (without a prefix: ``A
>> > **PenaltyBreakString** (``unsigned``)
>> >   The penalty for each line break introduced inside a string literal.
>> >
>> > +**PenaltyBreakTemplateDeclaration** (``unsigned``)
>> > +  The penalty for breaking after template declaration.
>> > +
>> > **PenaltyExcessCharacter** (``unsigned``)
>> >   The penalty for each character outside of the column limit.
>> >
>> >
>> > Modified: cfe/trunk/include/clang/Format/Format.h
>> > URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=332436&r1=332435&r2=332436&view=diff
>> >
>> ==
>> > --- cfe/trunk/include/clang/Format/Format.h (original)
>> > +++ cfe/trunk/include/clang/Format/Format.h Wed May 16 01:25:03

r332454 - Test commit access: remove superflous spaces

2018-05-16 Thread Gabor Marton via cfe-commits
Author: martong
Date: Wed May 16 04:48:11 2018
New Revision: 332454

URL: http://llvm.org/viewvc/llvm-project?rev=332454&view=rev
Log:
Test commit access: remove superflous spaces

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

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=332454&r1=332453&r2=332454&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Wed May 16 04:48:11 2018
@@ -78,7 +78,7 @@ namespace clang {
 
   public:
 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
-
+
 using TypeVisitor::Visit;
 using DeclVisitor::Visit;
 using StmtVisitor::Visit;


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


[PATCH] D46905: [Attr] Don't print fake MSInheritance argument

2018-05-16 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!


https://reviews.llvm.org/D46905



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


r332465 - Fix an Index test caused by a clang-format change (r332436).

2018-05-16 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Wed May 16 05:58:13 2018
New Revision: 332465

URL: http://llvm.org/viewvc/llvm-project?rev=332465&view=rev
Log:
Fix an Index test caused by a clang-format change (r332436).

Modified:
cfe/trunk/test/Index/overriding-ftemplate-comments.cpp

Modified: cfe/trunk/test/Index/overriding-ftemplate-comments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/overriding-ftemplate-comments.cpp?rev=332465&r1=332464&r2=332465&view=diff
==
--- cfe/trunk/test/Index/overriding-ftemplate-comments.cpp (original)
+++ cfe/trunk/test/Index/overriding-ftemplate-comments.cpp Wed May 16 05:58:13 
2018
@@ -77,10 +77,10 @@ void comment_to_html_conversion_21();
 template  class 
BBB > class AAA>
 void comment_to_html_conversion_22();
 
-// CHECK: FullCommentAsXML=[comment_to_html_conversion_22c:@FT@>2#T#t>2#T#t>2#T#Tcomment_to_html_conversion_22#v#template
  class 
BBB>\n  class AAA>\nvoid 
comment_to_html_conversion_22()C10
 Ccc 1 
AAA1
 Zzz 
C2 
Ccc 2 
C3 
Ccc 3 
C4 
Ccc 4 
BBB 
Bbb]
+// CHECK: FullCommentAsXML=[comment_to_html_conversion_22c:@FT@>2#T#t>2#T#t>2#T#Tcomment_to_html_conversion_22#v#template
  class 
BBB>\nclass AAA>\nvoid 
comment_to_html_conversion_22()C10
 Ccc 1 
AAA1
 Zzz 
C2 
Ccc 2 
C3 
Ccc 3 
C4 
Ccc 4 
BBB 
Bbb]
 
 template 
class QQQ> class PPP>
 void comment_to_html_conversion_22();
 
-// CHECK: FullCommentAsXML=[comment_to_html_conversion_22c:@FT@>2#T#t>2#T#t>2#T#Tcomment_to_html_conversion_22#v#template
 \n class QQQ> class PPP>\nvoid 
comment_to_html_conversion_22()CCC10
 Ccc 1 
PPP1
 Zzz 
CCC2 
Ccc 2 
CCC3 
Ccc 3 
CCC4 
Ccc 4 
QQQ 
Bbb]
+// CHECK: FullCommentAsXML=[comment_to_html_conversion_22c:@FT@>2#T#t>2#T#t>2#T#Tcomment_to_html_conversion_22#v#template
  class QQQ>\n  class PPP>\nvoid 
comment_to_html_conversion_22()CCC10
 Ccc 1 
PPP1
 Zzz 
CCC2 
Ccc 2 
CCC3 
Ccc 3 
CCC4 
Ccc 4 
QQQ 
Bbb]
 


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


Re: r332436 - clang-format: Allow optimizer to break template declaration.

2018-05-16 Thread Eric Liu via cfe-commits
This should be fixed by r332465

On Wed, May 16, 2018 at 2:50 PM Eric Liu  wrote:

> OK, I'll send a fix for the index test. Please make sure you run all clang
> tests (`ninja check-clang` and `ninja check-clang-tools`) before landing a
> patch! Thanks!
>
> On Wed, May 16, 2018 at 2:32 PM Eric Liu  wrote:
>
>> I can also reproduce on my local machine (Debian).
>>
>> On Wed, May 16, 2018 at 1:01 PM David Zarzycki via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>>
>>> This change broke `test/Index/overriding-ftemplate-comments.cpp` on Red
>>> Hat Fedora 28. Was this expected?
>>>
>>> > On May 16, 2018, at 4:25 AM, Francois Ferrand via cfe-commits <
>>> cfe-commits@lists.llvm.org> wrote:
>>> >
>>> > Author: typz
>>> > Date: Wed May 16 01:25:03 2018
>>> > New Revision: 332436
>>> >
>>> > URL: http://llvm.org/viewvc/llvm-project?rev=332436&view=rev
>>> > Log:
>>> > clang-format: Allow optimizer to break template declaration.
>>> >
>>> > Summary:
>>> > Introduce `PenaltyBreakTemplateDeclaration` to control the penalty,
>>> > and change `AlwaysBreakTemplateDeclarations` to an enum with 3 modes:
>>> > * `No` for regular, penalty based, wrapping of template declaration
>>> > * `MultiLine` for always wrapping before multi-line declarations (e.g.
>>> >  same as legacy behavior when `AlwaysBreakTemplateDeclarations=false`)
>>> > * `Yes` for always wrapping (e.g. same as legacy behavior when
>>> >  `AlwaysBreakTemplateDeclarations=true`)
>>> >
>>> > Reviewers: krasimir, djasper, klimek
>>> >
>>> > Subscribers: cfe-commits
>>> >
>>> > Differential Revision: https://reviews.llvm.org/D42684
>>> >
>>> > Modified:
>>> >cfe/trunk/docs/ClangFormatStyleOptions.rst
>>> >cfe/trunk/include/clang/Format/Format.h
>>> >cfe/trunk/lib/Format/ContinuationIndenter.cpp
>>> >cfe/trunk/lib/Format/Format.cpp
>>> >cfe/trunk/lib/Format/TokenAnnotator.cpp
>>> >cfe/trunk/unittests/Format/FormatTest.cpp
>>> >
>>> > Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
>>> > URL:
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=332436&r1=332435&r2=332436&view=diff
>>> >
>>> ==
>>> > --- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
>>> > +++ cfe/trunk/docs/ClangFormatStyleOptions.rst Wed May 16 01:25:03 2018
>>> > @@ -490,15 +490,50 @@ the configuration (without a prefix: ``A
>>> >  """";
>>> >  "";
>>> >
>>> > -**AlwaysBreakTemplateDeclarations** (``bool``)
>>> > -  If ``true``, always break after the ``template<...>`` of a template
>>> > -  declaration.
>>> > +**AlwaysBreakTemplateDeclarations**
>>> (``BreakTemplateDeclarationsStyle``)
>>> > +  The template declaration breaking style to use.
>>> > +
>>> > +  Possible values:
>>> > +
>>> > +  * ``BTDS_No`` (in configuration: ``No``)
>>> > +Do not force break before declaration.
>>> > +``PenaltyBreakTemplateDeclaration`` is taken into account.
>>> > +
>>> > +.. code-block:: c++
>>> > +
>>> > +   template  T foo() {
>>> > +   }
>>> > +   template  T foo(int a,
>>> > +   int b) {
>>> > +   }
>>> > +
>>> > +  * ``BTDS_MultiLine`` (in configuration: ``MultiLine``)
>>> > +Force break after template declaration only when the following
>>> > +declaration spans multiple lines.
>>> > +
>>> > +.. code-block:: c++
>>> > +
>>> > +   template  T foo() {
>>> > +   }
>>> > +   template 
>>> > +   T foo(int a,
>>> > + int b) {
>>> > +   }
>>> > +
>>> > +  * ``BTDS_Yes`` (in configuration: ``Yes``)
>>> > +Always break after template declaration.
>>> > +
>>> > +.. code-block:: c++
>>> > +
>>> > +   template 
>>> > +   T foo() {
>>> > +   }
>>> > +   template 
>>> > +   T foo(int a,
>>> > + int b) {
>>> > +   }
>>> >
>>> > -  .. code-block:: c++
>>> >
>>> > - true:  false:
>>> > - template   vs. template 
>>> class C {};
>>> > - class C {};
>>> >
>>> > **BinPackArguments** (``bool``)
>>> >   If ``false``, a function call's arguments will either be all on the
>>> > @@ -1590,6 +1625,9 @@ the configuration (without a prefix: ``A
>>> > **PenaltyBreakString** (``unsigned``)
>>> >   The penalty for each line break introduced inside a string literal.
>>> >
>>> > +**PenaltyBreakTemplateDeclaration** (``unsigned``)
>>> > +  The penalty for breaking after template declaration.
>>> > +
>>> > **PenaltyExcessCharacter** (``unsigned``)
>>> >   The penalty for each character outside of the column limit.
>>> >
>>> >
>>> > Modified: cfe/trunk/include/clang/Format/Format.h
>>> > URL:
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=332436&r1=332435&r2=332436&view=diff

[PATCH] D46940: [ASTImporter] make sure that ACtx::getParents still works

2018-05-16 Thread Rafael Stahl via Phabricator via cfe-commits
r.stahl created this revision.
r.stahl added reviewers: a.sidorin, klimek.
Herald added subscribers: cfe-commits, martong.

If an AST node is imported after a call to getParents in the ToCtx, it was no 
longer possible to retrieve its parents since the old results were cached.

Valid types for getParents:

- Decl, Stmt, NestedNameSpecifier: handled explicitly
- Type: not supported by ast importer
- TypeLoc: not imported
- NestedNameSpecifierLoc: calls import for NNS


Repository:
  rC Clang

https://reviews.llvm.org/D46940

Files:
  include/clang/AST/ASTContext.h
  lib/AST/ASTImporter.cpp
  unittests/AST/ASTImporterTest.cpp

Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -1431,6 +1431,36 @@
   MatchVerifier{}.match(To->getTranslationUnitDecl(), Pattern));
 }
 
+TEST_P(ASTImporterTestBase, ValidParents) {
+  // Create parent cache in To context.
+  Decl *PreTU = getTuDecl("struct S {};", Lang_CXX, "pre.cc");
+  RecordDecl *FromRD = FirstDeclMatcher().match(PreTU, recordDecl());
+  auto ToRD = cast(Import(FromRD, Lang_CXX));
+  auto &ToACtx = ToAST->getASTContext();
+  ToACtx.getParents(*ToRD);
+
+  Decl *FromTU = getTuDecl("void f() {}", Lang_CXX);
+  CompoundStmt *FromCS = FirstDeclMatcher().match(FromTU,
+compoundStmt());
+  FunctionDecl *FromFD = FirstDeclMatcher().match(FromTU,
+functionDecl());
+
+  auto FromPs = FromFD->getASTContext().getParents(*FromCS);
+  ASSERT_TRUE(!FromPs.empty());
+  auto FromP = FromPs[0].get();
+  EXPECT_EQ(FromP, FromFD);
+
+  auto ToFD = cast(Import(FromFD, Lang_CXX));
+
+  Decl *ToTU = ToACtx.getTranslationUnitDecl();
+  auto ToCS = FirstDeclMatcher().match(ToTU, compoundStmt());
+
+  auto ToPs = ToACtx.getParents(*ToCS);
+  ASSERT_TRUE(!ToPs.empty());
+  auto ToP = ToPs[0].get();
+  EXPECT_EQ(ToP, ToFD);
+}
+
 INSTANTIATE_TEST_CASE_P(
 ParameterizedTests, ASTImporterTestBase,
 ::testing::Values(ArgVector(), ArgVector{"-fdelayed-template-parsing"}),);
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -6751,7 +6751,11 @@
   if (!FromE)
 return nullptr;
 
-  return cast_or_null(Import(cast(FromE)));
+  auto ToE = cast_or_null(Import(cast(FromE)));
+  if (ToE)
+ToContext.invalidateParents();
+
+  return ToE;
 }
 
 Stmt *ASTImporter::Import(Stmt *FromS) {
@@ -6762,13 +6766,15 @@
   llvm::DenseMap::iterator Pos = ImportedStmts.find(FromS);
   if (Pos != ImportedStmts.end())
 return Pos->second;
-  
+
   // Import the type
   ASTNodeImporter Importer(*this);
   Stmt *ToS = Importer.Visit(FromS);
   if (!ToS)
 return nullptr;
 
+  ToContext.invalidateParents();
+
   // Record the imported declaration.
   ImportedStmts[FromS] = ToS;
   return ToS;
@@ -6779,52 +6785,60 @@
 return nullptr;
 
   NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
+  NestedNameSpecifier *ToNNS = nullptr;
 
   switch (FromNNS->getKind()) {
   case NestedNameSpecifier::Identifier:
 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
-  return NestedNameSpecifier::Create(ToContext, prefix, II);
+  ToNNS = NestedNameSpecifier::Create(ToContext, prefix, II);
 }
-return nullptr;
+break;
 
   case NestedNameSpecifier::Namespace:
 if (auto *NS = 
 cast_or_null(Import(FromNNS->getAsNamespace( {
-  return NestedNameSpecifier::Create(ToContext, prefix, NS);
+  ToNNS = NestedNameSpecifier::Create(ToContext, prefix, NS);
 }
-return nullptr;
+break;
 
   case NestedNameSpecifier::NamespaceAlias:
 if (auto *NSAD = 
   cast_or_null(Import(FromNNS->getAsNamespaceAlias( {
-  return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
+  ToNNS = NestedNameSpecifier::Create(ToContext, prefix, NSAD);
 }
-return nullptr;
+break;
 
   case NestedNameSpecifier::Global:
-return NestedNameSpecifier::GlobalSpecifier(ToContext);
+ToNNS = NestedNameSpecifier::GlobalSpecifier(ToContext);
+break;
 
   case NestedNameSpecifier::Super:
 if (auto *RD =
 cast_or_null(Import(FromNNS->getAsRecordDecl( {
-  return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
+  ToNNS = NestedNameSpecifier::SuperSpecifier(ToContext, RD);
 }
-return nullptr;
+break;
 
   case NestedNameSpecifier::TypeSpec:
   case NestedNameSpecifier::TypeSpecWithTemplate: {
   QualType T = Import(QualType(FromNNS->getAsType(), 0u));
   if (!T.isNull()) {
 bool bTemplate = FromNNS->getKind() == 
  NestedNameSpecifier::TypeSpecWithTemplate;
-return NestedNameSpecifier::Create(ToContext, prefix, 
+ToNNS = NestedNameSpecifier::Create(ToContext,

[PATCH] D46835: [ASTImporter] Do not try to remove invisible Decls from DeclContext

2018-05-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Can you roll back the changes in MatchVerifier.h? Phab is telling me that the 
only changes are to whitespace.




Comment at: lib/AST/DeclBase.cpp:1353
 
+static bool shouldBeHidden(NamedDecl *D);
+

Rather than make a hanging forward declaration, can you just move the 
definition of this function here?



Comment at: lib/AST/DeclBase.cpp:1387
+// lookup.  E.g. template specializations are skipped.
+if (shouldBeHidden(ND)) return;
+

The `return` should be on its own line per our usual conventions.


Repository:
  rC Clang

https://reviews.llvm.org/D46835



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


[PATCH] D46439: [Sema] Fix incorrect packed aligned structure layout

2018-05-16 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!


https://reviews.llvm.org/D46439



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


[PATCH] D45702: [clang-tidy] Add a new check, readability-simplify-subscript-expr, that simplifies subscript expressions.

2018-05-16 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D45702#1097294, @shuaiwang wrote:

> Addressed review comments.


This patch was approved; do you need someone to commit this for you?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45702



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


[PATCH] D46602: [clang-tidy] Store checks profiling info as YAML files

2018-05-16 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 147071.
lebedev.ri edited the summary of this revision.
lebedev.ri added a comment.

- Rebased
- Slightly refactor how the profile storage params are computed, move that into 
`ClangTidyProfiling::StorageParams` helper struct.
- Store timestamp in the json too, since it's already in the filename. May be 
useful for garbage collection and alike.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46602

Files:
  clang-tidy/ClangTidy.cpp
  clang-tidy/ClangTidy.h
  clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tidy/ClangTidyProfiling.cpp
  clang-tidy/ClangTidyProfiling.h
  clang-tidy/tool/ClangTidyMain.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/index.rst
  test/clang-tidy/clang-tidy-enable-check-profile-one-tu.cpp
  test/clang-tidy/clang-tidy-enable-check-profile-two-tu.cpp
  test/clang-tidy/clang-tidy-store-check-profile-one-tu.cpp

Index: test/clang-tidy/clang-tidy-store-check-profile-one-tu.cpp
===
--- /dev/null
+++ test/clang-tidy/clang-tidy-store-check-profile-one-tu.cpp
@@ -0,0 +1,37 @@
+// RUN: rm -rf %T/out
+// RUN: clang-tidy -enable-check-profile -checks='-*,readability-function-size' -store-check-profile=%T/out %s 2>&1 | FileCheck --match-full-lines -implicit-check-not='{{warning:|error:}}' -check-prefix=CHECK-CONSOLE %s
+// RUN: cat %T/out/*-clang-tidy-store-check-profile-one-tu.cpp.yaml | FileCheck --match-full-lines -implicit-check-not='{{warning:|error:}}' -check-prefix=CHECK-FILE %s
+// RUN: rm -rf %T/out
+// RUN: clang-tidy -enable-check-profile -checks='-*,readability-function-size' -store-check-profile=%T/out %s 2>&1 | FileCheck --match-full-lines -implicit-check-not='{{warning:|error:}}' -check-prefix=CHECK-CONSOLE %s
+// RUN: cat %T/out/*-clang-tidy-store-check-profile-one-tu.cpp.yaml | FileCheck --match-full-lines -implicit-check-not='{{warning:|error:}}' -check-prefix=CHECK-FILE %s
+
+// CHECK-CONSOLE-NOT: ===-===
+// CHECK-CONSOLE-NOT: {{.*}}  --- Name ---
+// CHECK-CONSOLE-NOT: {{.*}}  readability-function-size
+// CHECK-CONSOLE-NOT: {{.*}}  Total
+// CHECK-CONSOLE-NOT: ===-===
+
+// CHECK-FILE: {
+// CHECK-FILE-NEXT:"file": "{{.*}}clang-tidy-store-check-profile-one-tu.cpp",
+// CHECK-FILE-NEXT:"timestamp": "{{[0-9]+}}-{{[0-9]+}}-{{[0-9]+}} {{[0-9]+}}:{{[0-9]+}}:{{[0-9]+}}.{{[0-9]+}}",
+// CHECK-FILE-NEXT:"profile": {
+// CHECK-FILE-NEXT:	"time.clang-tidy.readability-function-size.wall": {{.*}}{{[0-9]}}.{{[0-9]+}}e{{[-+]}}{{[0-9]}}{{[0-9]}},
+// CHECK-FILE-NEXT:	"time.clang-tidy.readability-function-size.user": {{.*}}{{[0-9]}}.{{[0-9]+}}e{{[-+]}}{{[0-9]}}{{[0-9]}},
+// CHECK-FILE-NEXT:	"time.clang-tidy.readability-function-size.sys": {{.*}}{{[0-9]}}.{{[0-9]+}}e{{[-+]}}{{[0-9]}}{{[0-9]}}
+// CHECK-FILE-NEXT: }
+// CHECK-FILE-NEXT: }
+
+// CHECK-FILE-NOT: {
+// CHECK-FILE-NOT: "file": {{.*}}clang-tidy-store-check-profile-one-tu.cpp{{.*}},
+// CHECK-FILE-NOT: "timestamp": "{{[0-9]+}}-{{[0-9]+}}-{{[0-9]+}} {{[0-9]+}}:{{[0-9]+}}:{{[0-9]+}}.{{[0-9]+}}",
+// CHECK-FILE-NOT: "profile": {
+// CHECK-FILE-NOT:	"time.clang-tidy.readability-function-size.wall": {{.*}}{{[0-9]}}.{{[0-9]+}}e{{[-+]}}{{[0-9]}}{{[0-9]}},
+// CHECK-FILE-NOT:	"time.clang-tidy.readability-function-size.user": {{.*}}{{[0-9]}}.{{[0-9]+}}e{{[-+]}}{{[0-9]}}{{[0-9]}},
+// CHECK-FILE-NOT:	"time.clang-tidy.readability-function-size.sys": {{.*}}{{[0-9]}}.{{[0-9]+}}e{{[-+]}}{{[0-9]}}{{[0-9]}}
+// CHECK-FILE-NOT: }
+// CHECK-FILE-NOT: }
+
+class A {
+  A() {}
+  ~A() {}
+};
Index: test/clang-tidy/clang-tidy-enable-check-profile-two-tu.cpp
===
--- test/clang-tidy/clang-tidy-enable-check-profile-two-tu.cpp
+++ test/clang-tidy/clang-tidy-enable-check-profile-two-tu.cpp
@@ -1,22 +1,31 @@
 // RUN: clang-tidy -enable-check-profile -checks='-*,readability-function-size' %s %s 2>&1 | FileCheck --match-full-lines -implicit-check-not='{{warning:|error:}}' %s
 
 // CHECK: ===-===
-// CHECK-NEXT: {{.*}}  --- Name ---
+// CHECK-NEXT:  clang-tidy checks profiling
+// CHECK-NEXT: ===-===
+// CHECK-NEXT: Total Execution Time: {{.*}} seconds ({{.*}} wall clock)
+
+// CHECK: {{.*}}  --- Name ---
 // CHECK-NEXT: {{.*}}  readability-function-size
 // CHECK-NEXT: {{.*}}  Total
-// CHECK-NEXT: ===-===
 
 // CHECK: ===-===
-// CHECK-NEXT: {{.*}}  --- Name ---
+// CHECK-NEXT:  clang-tidy checks profiling
+// CHECK-NEXT: ===-

r332467 - [OPENMP, NVPTX] Add check for SPMD mode in orphaned parallel directives.

2018-05-16 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Wed May 16 06:36:30 2018
New Revision: 332467

URL: http://llvm.org/viewvc/llvm-project?rev=332467&view=rev
Log:
[OPENMP, NVPTX] Add check for SPMD mode in orphaned parallel directives.

If the orphaned directive is executed in SPMD mode, we need to emit the
check for the SPMD mode and run the orphaned parallel directive in
sequential mode.

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/test/OpenMP/nvptx_target_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp?rev=332467&r1=332466&r2=332467&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp Wed May 16 06:36:30 2018
@@ -96,6 +96,8 @@ enum OpenMPRTLFunctionNVPTX {
   /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
   /// global_tid);
   OMPRTL_NVPTX__kmpc_parallel_level,
+  /// Call to int8_t __kmpc_is_spmd_exec_mode();
+  OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
 };
 
 /// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
@@ -220,8 +222,7 @@ class CheckVarsEscapingDeclContext final
"Parameter captured by value with variably modified type");
 EscapedParameters.insert(VD);
   }
-} else if (VD->getType()->isAnyPointerType() ||
-   VD->getType()->isReferenceType())
+} else if (VD->getType()->isReferenceType())
   // Do not globalize variables with reference or pointer type.
   return;
 if (VD->getType()->isVariablyModifiedType())
@@ -317,8 +318,18 @@ public:
   return;
 if (D->hasAssociatedStmt()) {
   if (const auto *S =
-  dyn_cast_or_null(D->getAssociatedStmt()))
+  dyn_cast_or_null(D->getAssociatedStmt())) {
+// Do not analyze directives that do not actually require capturing,
+// like `omp for` or `omp simd` directives.
+llvm::SmallVector CaptureRegions;
+getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
+if (CaptureRegions.size() == 1 &&
+CaptureRegions.back() == OMPD_unknown) {
+  VisitStmt(S->getCapturedStmt());
+  return;
+}
 VisitOpenMPCapturedStmt(S);
+  }
 }
   }
   void VisitCapturedStmt(const CapturedStmt *S) {
@@ -1411,6 +1422,12 @@ CGOpenMPRuntimeNVPTX::createNVPTXRuntime
 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
 break;
   }
+  case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
+// Build int8_t __kmpc_is_spmd_exec_mode();
+auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
+RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
+break;
+  }
   }
   return RTLFn;
 }
@@ -1828,7 +1845,9 @@ void CGOpenMPRuntimeNVPTX::emitNonSPMDPa
   RCG(CGF);
 } else {
   // Check for master and then parallelism:
-  // if (is_master) {
+  // if (__kmpc_is_spmd_exec_mode()) {
+  //  Serialized execution.
+  // } else if (is_master) {
   //   Worker call.
   // } else if (__kmpc_parallel_level(loc, gtid)) {
   //   Serialized execution.
@@ -1837,13 +1856,22 @@ void CGOpenMPRuntimeNVPTX::emitNonSPMDPa
   // }
   CGBuilderTy &Bld = CGF.Builder;
   llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
+  llvm::BasicBlock *SPMDCheckBB = CGF.createBasicBlock(".spmdcheck");
   llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
   llvm::BasicBlock *ParallelCheckBB =
   CGF.createBasicBlock(".parallelcheck");
+  llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
+  createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
+  Bld.CreateCondBr(IsSPMD, SPMDCheckBB, MasterCheckBB);
+  CGF.EmitBlock(SPMDCheckBB);
+  SeqGen(CGF, Action);
+  CGF.EmitBranch(ExitBB);
+  CGF.EmitBlock(MasterCheckBB);
+  llvm::BasicBlock *MasterThenBB = CGF.createBasicBlock("master.then");
   llvm::Value *IsMaster =
   Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
-  Bld.CreateCondBr(IsMaster, MasterCheckBB, ParallelCheckBB);
-  CGF.EmitBlock(MasterCheckBB);
+  Bld.CreateCondBr(IsMaster, MasterThenBB, ParallelCheckBB);
+  CGF.EmitBlock(MasterThenBB);
   L0ParallelGen(CGF, Action);
   CGF.EmitBranch(ExitBB);
   // There is no need to emit line number for unconditional branch.

Modified: cfe/trunk/test/OpenMP/nvptx_target_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/nvptx_target_codegen.cpp?rev=332467&r1=332466&r2=332467&view=diff
==
--- cfe/trunk/test/OpenMP/nvptx_target_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/nvptx_target_codegen.cpp Wed May 16 06:36:30 2

[PATCH] D46867: [ASTImporter] Add unit tests for structural equivalence

2018-05-16 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Hello Gabor!

Thank you for this patch! Do you plan to enable this functionality for AST 
import checking?
Some comments are inline.




Comment at: unittests/AST/Language.h:1
+//===- unittest/AST/Language.h - AST unit test support ---===//
+//

Header line is too short.



Comment at: unittests/AST/Language.h:8
+//
+//===--===//
+

Could you please add a brief file description?



Comment at: unittests/AST/Language.h:13
+
+#include 
+#include 

System includes should follow LLVM includes.



Comment at: unittests/AST/Language.h:37
+
+inline ArgVector getBasicRunOptionsForLanguage(Language Lang) {
+  ArgVector BasicArgs;

I think this function is too big for a header. Same below. Could you create a 
source file?



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:2
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTImporter.h"
+#include "clang/ASTMatchers/ASTMatchers.h"

Do we need ASTImporter.h?



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:39
+auto getDecl = [](ASTContext &Ctx, const std::string &Name) -> NamedDecl * 
{
+  IdentifierInfo *ImportedII = &Ctx.Idents.get(Name);
+  assert(ImportedII && "Declaration with the identifier "

s/Import/Search?



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:47
+
+  // We should find one Decl but one only
+  assert(FoundDecls.size() > 0);

Nit: comments should end with dot. Could you please check?



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:48
+  // We should find one Decl but one only
+  assert(FoundDecls.size() > 0);
+  assert(FoundDecls.size() < 2);

Can we `assert(FoundDecls.size() == 1)`?



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:54
+
+NamedDecl *d0 = getDecl(Ctx0, Identifier);
+NamedDecl *d1 = getDecl(Ctx1, Identifier);

`D0`, `D1` (capital). Same below.



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:73
+  auto t = makeNamedDecls("int foo;", "int foo;", Lang_CXX);
+  EXPECT_TRUE(testStructuralMatch(get<0>(t), get<1>(t)));
+}

Could we just overload testStructuralMatch to accept tuple or pair?



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:119
+  *cast(get<1>(t))->spec_begin();
+  ASSERT_TRUE(Spec0 != nullptr);
+  ASSERT_TRUE(Spec1 != nullptr);

Should we assert for `spec_begin() != spec_end()` instead or within these 
assertions?



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:163
+TEST_F(StructuralEquivalenceTest, DISABLED_WrongOrderInNamespace) {
+  auto Code0 =
+  R"(

There is no Code1, so I think we can call it just "Code". Same below.



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:174
+  )";
+  auto t = makeNamedDecls( Code0, Code0, Lang_CXX);
+

1. It's better to use more meaningful names than `t`. DeclTuple?
2. The space after `(` is redundant.



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:193
+  auto Code0 = "class X { int a; int b; };";
+  auto t = makeNamedDecls( Code0, Code0, Lang_CXX, "X");
+

Redundant space. Could you clang-format?



Comment at: unittests/AST/StructuralEquivalenceTest.cpp:195
+
+  ASSERT_TRUE(get<0>(t) != nullptr);
+  ASSERT_TRUE(get<1>(t) != nullptr);

These assertions are always true because there is a strong C assertion in the 
callee.


Repository:
  rC Clang

https://reviews.llvm.org/D46867



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


[PATCH] D46942: Make sure getCanonicalName returns absolute paths even on VFS.

2018-05-16 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added a reviewer: bkramer.
Herald added a subscriber: cfe-commits.

Generally, canonical paths are expected to be absolute. This is the
behavior for Windows build. But for unix, it might return relative paths when
failing to resolve real path (e.g. unsupported symlink on VFS).


Repository:
  rC Clang

https://reviews.llvm.org/D46942

Files:
  lib/Basic/FileManager.cpp
  unittests/Basic/FileManagerTest.cpp


Index: unittests/Basic/FileManagerTest.cpp
===
--- unittests/Basic/FileManagerTest.cpp
+++ unittests/Basic/FileManagerTest.cpp
@@ -322,4 +322,35 @@
   EXPECT_EQ(Path, ExpectedResult);
 }
 
+TEST_F(FileManagerTest, GetCanonicalNameReturnsAbsolutePathOnVFS) {
+  SmallString<64> CustomWorkingDir;
+#ifdef _WIN32
+  CustomWorkingDir = "C:\\test";
+#else
+  CustomWorkingDir = "/test";
+#endif
+  llvm::sys::path::append(CustomWorkingDir, "some", "weird", "path");
+
+  auto FS =
+  IntrusiveRefCntPtr(new vfs::InMemoryFileSystem);
+  // setCurrentworkingdirectory must finish without error.
+  ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
+  SmallString<64> FooPath("weird/foo/foo.cpp");
+  FS->addFile(FooPath.str(), 0, llvm::MemoryBuffer::getMemBuffer(""));
+
+  FileSystemOptions Opts;
+  FileManager Manager(Opts, FS);
+
+  // Use relative path to open the directory.
+  const DirectoryEntry *Dir =
+  Manager.getDirectory(llvm::sys::path::parent_path(FooPath.str()));
+  EXPECT_TRUE(Dir != nullptr);
+  EXPECT_FALSE(llvm::sys::path::is_absolute(Dir->getName()));
+
+  SmallString<64> AbsFooPath(CustomWorkingDir);
+  llvm::sys::path::append(AbsFooPath, FooPath);
+  EXPECT_EQ(Manager.getCanonicalName(Dir),
+llvm::sys::path::parent_path(AbsFooPath.str()));
+}
+
 } // anonymous namespace
Index: lib/Basic/FileManager.cpp
===
--- lib/Basic/FileManager.cpp
+++ lib/Basic/FileManager.cpp
@@ -532,15 +532,17 @@
   if (Known != CanonicalDirNames.end())
 return Known->second;
 
-  StringRef CanonicalName(Dir->getName());
+  // Canonical name should still be an absolute path even if realpath fails.
+  llvm::SmallString<128> AbsDirPath(Dir->getName());
+  makeAbsolutePath(AbsDirPath);
+  StringRef CanonicalName = AbsDirPath.str().copy(CanonicalNameStorage);
 
 #ifdef LLVM_ON_UNIX
   char CanonicalNameBuf[PATH_MAX];
-  if (realpath(Dir->getName().str().c_str(), CanonicalNameBuf))
+  if (realpath(AbsDirPath.c_str(), CanonicalNameBuf))
 CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
 #else
   SmallString<256> CanonicalNameBuf(CanonicalName);
-  llvm::sys::fs::make_absolute(CanonicalNameBuf);
   llvm::sys::path::native(CanonicalNameBuf);
   // We've run into needing to remove '..' here in the wild though, so
   // remove it.


Index: unittests/Basic/FileManagerTest.cpp
===
--- unittests/Basic/FileManagerTest.cpp
+++ unittests/Basic/FileManagerTest.cpp
@@ -322,4 +322,35 @@
   EXPECT_EQ(Path, ExpectedResult);
 }
 
+TEST_F(FileManagerTest, GetCanonicalNameReturnsAbsolutePathOnVFS) {
+  SmallString<64> CustomWorkingDir;
+#ifdef _WIN32
+  CustomWorkingDir = "C:\\test";
+#else
+  CustomWorkingDir = "/test";
+#endif
+  llvm::sys::path::append(CustomWorkingDir, "some", "weird", "path");
+
+  auto FS =
+  IntrusiveRefCntPtr(new vfs::InMemoryFileSystem);
+  // setCurrentworkingdirectory must finish without error.
+  ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
+  SmallString<64> FooPath("weird/foo/foo.cpp");
+  FS->addFile(FooPath.str(), 0, llvm::MemoryBuffer::getMemBuffer(""));
+
+  FileSystemOptions Opts;
+  FileManager Manager(Opts, FS);
+
+  // Use relative path to open the directory.
+  const DirectoryEntry *Dir =
+  Manager.getDirectory(llvm::sys::path::parent_path(FooPath.str()));
+  EXPECT_TRUE(Dir != nullptr);
+  EXPECT_FALSE(llvm::sys::path::is_absolute(Dir->getName()));
+
+  SmallString<64> AbsFooPath(CustomWorkingDir);
+  llvm::sys::path::append(AbsFooPath, FooPath);
+  EXPECT_EQ(Manager.getCanonicalName(Dir),
+llvm::sys::path::parent_path(AbsFooPath.str()));
+}
+
 } // anonymous namespace
Index: lib/Basic/FileManager.cpp
===
--- lib/Basic/FileManager.cpp
+++ lib/Basic/FileManager.cpp
@@ -532,15 +532,17 @@
   if (Known != CanonicalDirNames.end())
 return Known->second;
 
-  StringRef CanonicalName(Dir->getName());
+  // Canonical name should still be an absolute path even if realpath fails.
+  llvm::SmallString<128> AbsDirPath(Dir->getName());
+  makeAbsolutePath(AbsDirPath);
+  StringRef CanonicalName = AbsDirPath.str().copy(CanonicalNameStorage);
 
 #ifdef LLVM_ON_UNIX
   char CanonicalNameBuf[PATH_MAX];
-  if (realpath(Dir->getName().str().c_str(), CanonicalNameBuf))
+  if (realpath(AbsDirPath.c_str(), CanonicalNameBuf))
 Cano

[PATCH] D46050: [Frontend] Avoid running plugins during code completion parse

2018-05-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332469: [Frontend] Avoid running plugins during code 
completion parse (authored by yvvan, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D46050?vs=146999&id=147078#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D46050

Files:
  cfe/trunk/lib/Frontend/FrontendAction.cpp
  cfe/trunk/test/Index/complete-and-plugins.c


Index: cfe/trunk/test/Index/complete-and-plugins.c
===
--- cfe/trunk/test/Index/complete-and-plugins.c
+++ cfe/trunk/test/Index/complete-and-plugins.c
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load 
%llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck 
%s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
Index: cfe/trunk/lib/Frontend/FrontendAction.cpp
===
--- cfe/trunk/lib/Frontend/FrontendAction.cpp
+++ cfe/trunk/lib/Frontend/FrontendAction.cpp
@@ -150,12 +150,16 @@
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();


Index: cfe/trunk/test/Index/complete-and-plugins.c
===
--- cfe/trunk/test/Index/complete-and-plugins.c
+++ cfe/trunk/test/Index/complete-and-plugins.c
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load %llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck %s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
Index: cfe/trunk/lib/Frontend/FrontendAction.cpp
===
--- cfe/trunk/lib/Frontend/FrontendAction.cpp
+++ cfe/trunk/lib/Frontend/FrontendAction.cpp
@@ -150,12 +150,16 @@
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332469 - [Frontend] Avoid running plugins during code completion parse

2018-05-16 Thread Ivan Donchevskii via cfe-commits
Author: yvvan
Date: Wed May 16 06:50:05 2018
New Revision: 332469

URL: http://llvm.org/viewvc/llvm-project?rev=332469&view=rev
Log:
[Frontend] Avoid running plugins during code completion parse

The parsing that is done for code completion is a special case that will
discard any generated diagnostics, so avoid running plugins for this
case in the first place to avoid performance penalties due to the
plugins.

A scenario for this is for example libclang with extra plugins like tidy.

Patch by Nikolai Kosjar

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

Added:
cfe/trunk/test/Index/complete-and-plugins.c
Modified:
cfe/trunk/lib/Frontend/FrontendAction.cpp

Modified: cfe/trunk/lib/Frontend/FrontendAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/FrontendAction.cpp?rev=332469&r1=332468&r2=332469&view=diff
==
--- cfe/trunk/lib/Frontend/FrontendAction.cpp (original)
+++ cfe/trunk/lib/Frontend/FrontendAction.cpp Wed May 16 06:50:05 2018
@@ -150,12 +150,16 @@ FrontendAction::CreateWrappedASTConsumer
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();

Added: cfe/trunk/test/Index/complete-and-plugins.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/complete-and-plugins.c?rev=332469&view=auto
==
--- cfe/trunk/test/Index/complete-and-plugins.c (added)
+++ cfe/trunk/test/Index/complete-and-plugins.c Wed May 16 06:50:05 2018
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load 
%llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck 
%s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();


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


[PATCH] D46050: [Frontend] Avoid running plugins during code completion parse

2018-05-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC332469: [Frontend] Avoid running plugins during code 
completion parse (authored by yvvan, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D46050?vs=146999&id=147077#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D46050

Files:
  lib/Frontend/FrontendAction.cpp
  test/Index/complete-and-plugins.c


Index: test/Index/complete-and-plugins.c
===
--- test/Index/complete-and-plugins.c
+++ test/Index/complete-and-plugins.c
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load 
%llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck 
%s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
Index: lib/Frontend/FrontendAction.cpp
===
--- lib/Frontend/FrontendAction.cpp
+++ lib/Frontend/FrontendAction.cpp
@@ -150,12 +150,16 @@
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();


Index: test/Index/complete-and-plugins.c
===
--- test/Index/complete-and-plugins.c
+++ test/Index/complete-and-plugins.c
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load %llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck %s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
Index: lib/Frontend/FrontendAction.cpp
===
--- lib/Frontend/FrontendAction.cpp
+++ lib/Frontend/FrontendAction.cpp
@@ -150,12 +150,16 @@
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D43183: clang-format: introduce `CaseBlockIndent` to control indent in switch

2018-05-16 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 147079.
Typz added a comment.

rebase


Repository:
  rC Clang

https://reviews.llvm.org/D43183

Files:
  include/clang/Format/Format.h
  lib/Format/Format.cpp
  lib/Format/UnwrappedLineParser.cpp
  lib/Format/UnwrappedLineParser.h
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1010,6 +1010,96 @@
"  return;\n"
"}",
getLLVMStyleWithColumns(34));
+
+  FormatStyle indentClosingBrace = getLLVMStyle();
+  indentClosingBrace.CaseBlockIndent = FormatStyle::CBIS_ClosingBrace;
+  verifyFormat("switch (x) {\n"
+   "case 1:\n"
+   "  f();\n"
+   "  break;\n"
+   "}",
+   indentClosingBrace);
+  verifyFormat("switch (x) {\n"
+   "case 1: {\n"
+   "  f();\n"
+   "  break;\n"
+   "  }\n"
+   "case 2: {\n"
+   "  break;\n"
+   "  }\n"
+   "}",
+   indentClosingBrace);
+  verifyFormat("switch (x) {\n"
+   "case 1: {\n"
+   "  f();\n"
+   "  } break;\n"
+   "case 2: {\n"
+   "  } break;\n"
+   "}",
+   indentClosingBrace);
+  verifyFormat("switch (x) {\n"
+   "case 1: {\n"
+   "  f();\n"
+   "  }\n"
+   "  g();\n"
+   "  break;\n"
+   "}",
+   indentClosingBrace);
+  verifyFormat("switch (x) {\n"
+   "case 1:\n"
+   "  f();\n"
+   "  {\n"
+   "g();\n"
+   "h();\n"
+   "  }\n"
+   "  break;\n"
+   "}",
+   indentClosingBrace);
+
+  FormatStyle indentBlock = getLLVMStyle();
+  indentBlock.CaseBlockIndent = FormatStyle::CBIS_Block;
+  verifyFormat("switch (x) {\n"
+   "case 1:\n"
+   "  f();\n"
+   "  break;\n"
+   "}",
+   indentBlock);
+  verifyFormat("switch (x) {\n"
+   "case 1: {\n"
+   "f();\n"
+   "break;\n"
+   "  }\n"
+   "case 2: {\n"
+   "break;\n"
+   "  }\n"
+   "}",
+   indentBlock);
+  verifyFormat("switch (x) {\n"
+   "case 1: {\n"
+   "f();\n"
+   "  } break;\n"
+   "case 2: {\n"
+   "  } break;\n"
+   "}",
+   indentBlock);
+  verifyFormat("switch (x) {\n"
+   "case 1: {\n"
+   "f();\n"
+   "  }\n"
+   "  g();\n"
+   "  break;\n"
+   "}",
+   indentBlock);
+  verifyFormat("switch (x) {\n"
+   "case 1:\n"
+   "  f();\n"
+   "  {\n"
+   "g();\n"
+   "h();\n"
+   "  }\n"
+   "  break;\n"
+   "}",
+   indentBlock);
 }
 
 TEST_F(FormatTest, CaseRanges) {
@@ -10639,6 +10729,13 @@
   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
   AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
 
+  Style.CaseBlockIndent = FormatStyle::CBIS_Block;
+  CHECK_PARSE("CaseBlockIndent: None", CaseBlockIndent, FormatStyle::CBIS_None);
+  CHECK_PARSE("CaseBlockIndent: ClosingBrace", CaseBlockIndent,
+  FormatStyle::CBIS_ClosingBrace);
+  CHECK_PARSE("CaseBlockIndent: Block", CaseBlockIndent,
+  FormatStyle::CBIS_Block);
+
   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
   FormatStyle::SBPO_Never);
Index: lib/Format/UnwrappedLineParser.h
===
--- lib/Format/UnwrappedLineParser.h
+++ lib/Format/UnwrappedLineParser.h
@@ -88,6 +88,10 @@
   void parseFile();
   void parseLevel(bool HasOpeningBrace);
   void parseBlock(bool MustBeDeclaration, bool AddLevel = true,
+  bool MunchSemi = true) {
+parseBlock(MustBeDeclaration, AddLevel ? 1 : 0, MunchSemi);
+  }
+  void parseBlock(bool MustBeDeclaration, int AddLevel,
   bool MunchSemi = true);
   void parseChildBlock();
   void parsePPDirective();
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -515,7 +515,7 @@
   return h;
 }
 
-void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
+void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, int AddLevel,
  bool MunchSemi) {
   assert(FormatTok->isOneOf(tok::l_brace,

r332470 - Add support for __declspec(code_seg("segname"))

2018-05-16 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Wed May 16 06:57:17 2018
New Revision: 332470

URL: http://llvm.org/viewvc/llvm-project?rev=332470&view=rev
Log:
Add support for __declspec(code_seg("segname"))

Add support for __declspec(code_seg("segname"))

This patch is built on the existing support for #pragma code_seg. The code_seg
declspec is allowed on functions and classes. The attribute enables the
placement of code into separate named segments, including compiler-generated
members and template instantiations.

For more information, please see the following:
https://msdn.microsoft.com/en-us/library/dn636922.aspx

A new CodeSeg attribute is used instead of adding a new spelling to the existing
Section attribute since they don’t apply to the same Subjects. Section
attributes are also added for the code_seg declspec since they are used for
#pragma code_seg. No CodeSeg attributes are added to the AST.

The patch is written to match with the Microsoft compiler’s behavior even where
that behavior is a little complicated (see https://reviews.llvm.org/D22931, the
Microsoft feedback page is no longer available since MS has removed the page).
That code is in getImplicitSectionAttrFromClass routine.

Diagnostics messages are added to match with the Microsoft compiler for code-seg
attribute mismatches on base and derived classes and virtual overrides.


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

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/lib/Sema/SemaLambda.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=332470&r1=332469&r2=332470&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed May 16 06:57:17 2018
@@ -1769,6 +1769,13 @@ def Section : InheritableAttr {
   let Documentation = [SectionDocs];
 }
 
+def CodeSeg : InheritableAttr {
+  let Spellings = [Declspec<"code_seg">];
+  let Args = [StringArgument<"Name">];
+  let Subjects = SubjectList<[Function, CXXRecord], ErrorDiag>;
+  let Documentation = [CodeSegDocs];
+}
+
 def PragmaClangBSSSection : InheritableAttr {
   // This attribute has no spellings as it is only ever created implicitly.
   let Spellings = [];

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=332470&r1=332469&r2=332470&view=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Wed May 16 06:57:17 2018
@@ -306,6 +306,18 @@ An example of how to use ``alloc_size``
   }];
 }
 
+def CodeSegDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+The ``__declspec(code_seg)`` attribute enables the placement of code into 
separate
+named segments that can be paged or locked in memory individually. This 
attribute
+is used to control the placement of instantiated templates and 
compiler-generated
+code. See the documentation for `__declspec(code_seg)`_ on MSDN.
+
+.. _`__declspec(code_seg)`: 
http://msdn.microsoft.com/en-us/library/dn636922.aspx
+  }];
+}
+
 def AllocAlignDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=332470&r1=332469&r2=332470&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Wed May 16 06:57:17 
2018
@@ -2668,6 +2668,14 @@ def warn_mismatched_section : Warning<
 def warn_attribute_section_on_redeclaration : Warning<
   "section attribute is specified on redeclared variable">, InGroup;
 
+def err_mismatched_code_seg_base : Error<
+  "derived class must specify the same code segment as its base classes">;
+def err_mismatched_code_seg_override : Error<
+  "overriding virtual function must specify the same code segment as its 
overridden function">;
+def err_conflicting_codeseg_attribute : Error<
+  "conflicting code segment specifiers">;
+def warn_duplicate_codeseg_attribute : Warning<
+  "duplicate code segment specifiers">, InGroup;
 def err_anonymous_property: Error<
   "anonymous property is not supported">;
 def err_property_is_variably_modified : Error<

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=332470&r1=332469&r2=33

[PATCH] D43352: Add support for __declspec(code_seg("segname"))

2018-05-16 Thread Erich Keane via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC332470: Add support for 
__declspec(code_seg("segname")) (authored by erichkeane, committed by 
).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D43352?vs=147075&id=147081#toc

Repository:
  rC Clang

https://reviews.llvm.org/D43352

Files:
  include/clang/Basic/Attr.td
  include/clang/Basic/AttrDocs.td
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/Sema.h
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaDeclAttr.cpp
  lib/Sema/SemaDeclCXX.cpp
  lib/Sema/SemaLambda.cpp

Index: lib/Sema/SemaDeclCXX.cpp
===
--- lib/Sema/SemaDeclCXX.cpp
+++ lib/Sema/SemaDeclCXX.cpp
@@ -2231,6 +2231,20 @@
   CXXRecordDecl *CXXBaseDecl = cast(BaseDecl);
   assert(CXXBaseDecl && "Base type is not a C++ type");
 
+  // Microsoft docs say:
+  // "If a base-class has a code_seg attribute, derived classes must have the
+  // same attribute."
+   const auto *BaseSA = CXXBaseDecl->getAttr();
+   const auto *DerivedSA = Class->getAttr();
+   if (BaseSA || DerivedSA) {
+ if (!BaseSA || !DerivedSA || BaseSA->getName() != DerivedSA->getName()) {
+   Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
+   Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
+ << CXXBaseDecl;
+   return nullptr;
+ }
+   }
+
   // A class which contains a flexible array member is not suitable for use as a
   // base class:
   //   - If the layout determines that a base comes before another base,
@@ -5576,6 +5590,16 @@
   }
 }
 
+void Sema::checkClassLevelSectionAttribute(CXXRecordDecl *Class) {
+  // Mark any compiler-generated routines with the implicit Section attribute.
+  for (auto *Method : Class->methods()) {
+if (Method->isUserProvided())
+  continue;
+if (Attr *A = getImplicitSectionAttrForFunction(Method))
+  Method->addAttr(A);
+  }
+}
+
 /// Check class-level dllimport/dllexport attribute.
 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
   Attr *ClassAttr = getDLLAttr(Class);
@@ -6079,6 +6103,7 @@
   }
 
   checkClassLevelDLLAttribute(Record);
+  checkClassLevelSectionAttribute(Record);
 
   bool ClangABICompat4 =
   Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
@@ -14531,6 +14556,16 @@
  diag::note_overridden_marked_noescape);
   }
   }
+  // Virtual overrides must have the same code_seg.
+  const auto *OldSA = Old->getAttr();
+  const auto *NewSA = New->getAttr();
+  if (OldSA || NewSA) {
+if (!OldSA || !NewSA || NewSA->getName() != OldSA->getName()) {
+  Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
+  Diag(Old->getLocation(), diag::note_previous_declaration);
+  return true;
+}
+  }
 
   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
 
Index: lib/Sema/SemaLambda.cpp
===
--- lib/Sema/SemaLambda.cpp
+++ lib/Sema/SemaLambda.cpp
@@ -910,6 +910,10 @@
   AddRangeBasedOptnone(Method);
   
   // Attributes on the lambda apply to the method.  
+  if (Attr *A = getImplicitSectionAttrForFunction(Method))
+Method->addAttr(A);
+  
+  // Attributes on the lambda apply to the method.
   ProcessDeclAttributes(CurScope, Method, ParamInfo);
 
   // CUDA lambdas get implicit attributes based on the scope in which they're
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -2667,9 +2667,14 @@
 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
 Diag(Old->getLocation(), diag::note_previous_declaration);
   }
+} else if (isa(New)) {
+  const auto *NewSA = New->getAttr();
+  if (!NewSA->isImplicit()) {
+Diag(New->getLocation(), diag::warn_mismatched_section);
+Diag(Old->getLocation(), diag::note_previous_declaration);
+  }
 }
   }
-
   if (!Old->hasAttrs())
 return;
 
@@ -8716,18 +8721,18 @@
  PragmaClangTextSection.PragmaLocation));
   }
 
-  // Apply an implicit SectionAttr if #pragma code_seg is active.
-  if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
-  !NewFD->hasAttr()) {
-NewFD->addAttr(
-SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
-CodeSegStack.CurrentValue->getString(),
-CodeSegStack.CurrentPragmaLocation));
-if (UnifySection(CodeSegStack.CurrentValue->getString(),
- ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
- ASTContext::PSF_Read,
- NewFD))
-  NewFD->dropAttr();
+  // Apply an implicit SectionAttr from class declspec or from
+  // #pragma code_seg i

[PATCH] D46943: [clangd] Boost scores for decls from current file in completion

2018-05-16 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added reviewers: ioeric, sammccall.
Herald added subscribers: mgrang, jkorous, MaskRay, klimek.

This should, arguably, give better ranking.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46943

Files:
  clangd/AST.cpp
  clangd/AST.h
  clangd/Quality.cpp
  clangd/Quality.h
  unittests/clangd/CodeCompleteTests.cpp

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -962,6 +962,48 @@
   }
 }
 
+TEST(CompletionTest, BoostCurrentFileDecls) {
+  MockFSProvider FS;
+  FS.Files[testPath("foo.h")] = R"cpp(
+int test_func_in_header();
+int test_func_in_header_and_cpp();
+)cpp";
+
+  MockCompilationDatabase CDB;
+  IgnoreDiagnostics DiagConsumer;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+  llvm::StringLiteral Text = R"cpp(
+#include "foo.h"
+int ::test_func_in_header_and_cpp() {
+}
+int test_func_in_cpp();
+
+int test() {
+  test_func_^
+}
+  )cpp";
+
+  auto Results =
+  completions(Server, Text, {}, clangd::CodeCompleteOptions()).items;
+  std::sort(Results.begin(), Results.end(),
+[](const CompletionItem &L, const CompletionItem &R) {
+  return L.sortText < R.sortText;
+});
+  ASSERT_THAT(Results,
+  UnorderedElementsAre(Named("test_func_in_cpp"),
+   Named("test_func_in_header"),
+   Named("test_func_in_header_and_cpp")));
+
+  auto &FuncInCpp = Results[0];
+  auto &FuncInHeader = Results[1];
+  auto &FuncInHeaderAndCpp = Results[2];
+
+  EXPECT_LE(FuncInHeader.scoreInfo->finalScore,
+FuncInCpp.scoreInfo->finalScore);
+  EXPECT_FLOAT_EQ(FuncInHeader.scoreInfo->finalScore,
+  FuncInHeaderAndCpp.scoreInfo->finalScore);
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -47,6 +47,7 @@
   unsigned SemaCCPriority = 0; // 1-80, 1 is best. 0 means absent.
// FIXME: this is actually a mix of symbol
//quality and relevance. Untangle this.
+  bool AllDeclsInMainFile = false;
   bool Deprecated = false;
   unsigned References = 0;
 
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -7,6 +7,7 @@
 //
 //===-===//
 #include "Quality.h"
+#include "AST.h"
 #include "index/Index.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -19,7 +20,8 @@
 
 void SymbolQualitySignals::merge(const CodeCompletionResult &SemaCCResult) {
   SemaCCPriority = SemaCCResult.Priority;
-
+  if (SemaCCResult.Declaration)
+AllDeclsInMainFile = allDeclsInMainFile(SemaCCResult.Declaration);
   if (SemaCCResult.Availability == CXAvailability_Deprecated)
 Deprecated = true;
 }
@@ -41,6 +43,10 @@
 // Priority 80 is a really bad score.
 Score *= 2 - std::min(80, SemaCCPriority) / 40;
 
+  // Things declared in the main file get a large boost.
+  if (AllDeclsInMainFile)
+Score *= 2;
+
   if (Deprecated)
 Score *= 0.1;
 
Index: clangd/AST.h
===
--- clangd/AST.h
+++ clangd/AST.h
@@ -26,7 +26,10 @@
 ///
 /// The returned location is usually the spelling location where the name of the
 /// decl occurs in the code.
-SourceLocation findNameLoc(const clang::Decl* D);
+SourceLocation findNameLoc(const Decl *D);
+
+/// Returns true iff all redecls of \p D are in the main file.
+bool allDeclsInMainFile(const Decl *D);
 
 } // namespace clangd
 } // namespace clang
Index: clangd/AST.cpp
===
--- clangd/AST.cpp
+++ clangd/AST.cpp
@@ -17,8 +17,8 @@
 namespace clangd {
 using namespace llvm;
 
-SourceLocation findNameLoc(const clang::Decl* D) {
-  const auto& SM = D->getASTContext().getSourceManager();
+SourceLocation findNameLoc(const Decl *D) {
+  const auto &SM = D->getASTContext().getSourceManager();
   // FIXME: Revisit the strategy, the heuristic is limitted when handling
   // macros, we should use the location where the whole definition occurs.
   SourceLocation SpellingLoc = SM.getSpellingLoc(D->getLocation());
@@ -38,5 +38,15 @@
   return SpellingLoc;
 }
 
+bool allDeclsInMainFile(const Decl *D) {
+  const SourceManager &SM = D->getASTContext().getSourceManager();
+  for (auto *Redecl : D->redecls()) {
+auto Loc = Redecl->getLocation();
+if (!SM.isWrittenInMainFile(Loc))
+  return false;
+  }
+  return true;
+}
+
 } // namespace clangd
 } // namespace

[PATCH] D44100: [ASTImporter] Reorder fields after structure import is finished

2018-05-16 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Ping.


Repository:
  rC Clang

https://reviews.llvm.org/D44100



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


[PATCH] D46944: [analyzer] Use sufficiently large types for index/size calculation.

2018-05-16 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan created this revision.
ebevhan added reviewers: dergachev.a, dcoughlin.
Herald added subscribers: cfe-commits, a.sidorin, szepet, xazax.hun.
Herald added a reviewer: george.karpenkov.

RegionStoreManager::getSizeInElements used 'int' for size
calculations, and ProgramState::assumeInBound fell back
to 'int' as well for its index calculations. This causes
truncation for sufficiently large sizes/indexes.

Use a signed size_t and ArrayIndexTy respectively to
prevent these problems.


Repository:
  rC Clang

https://reviews.llvm.org/D46944

Files:
  lib/StaticAnalyzer/Core/ProgramState.cpp
  lib/StaticAnalyzer/Core/RegionStore.cpp
  test/Analysis/array-index.c


Index: test/Analysis/array-index.c
===
--- /dev/null
+++ test/Analysis/array-index.c
@@ -0,0 +1,21 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.security.ArrayBound,alpha.unix.cstring.OutOfBounds 
-verify -Wno-implicit-function-declaration %s
+
+// expected-no-diagnostics
+
+#define SIZE 4294967296
+
+static unsigned size;
+static void * addr;
+static unsigned buf[SIZE];
+
+void fie() {
+  buf[SIZE-1] = 1;
+}
+
+void foo() {
+  memcpy(buf, addr, size);
+}
+
+void bar() {
+  memcpy(addr, buf, size);
+}
Index: lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- lib/StaticAnalyzer/Core/RegionStore.cpp
+++ lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1341,7 +1341,7 @@
   // If a variable is reinterpreted as a type that doesn't fit into a larger
   // type evenly, round it down.
   // This is a signed value, since it's used in arithmetic with signed indices.
-  return svalBuilder.makeIntVal(RegionSize / EleSize, false);
+  return svalBuilder.makeIntVal(RegionSize / EleSize, Ctx.getSignedSizeType());
 }
 
 
//===--===//
Index: lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- lib/StaticAnalyzer/Core/ProgramState.cpp
+++ lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -336,9 +336,8 @@
 
   // Get the offset: the minimum value of the array index type.
   BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
-  // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
   if (indexTy.isNull())
-indexTy = Ctx.IntTy;
+indexTy = svalBuilder.getArrayIndexType();
   nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
 
   // Adjust the index.


Index: test/Analysis/array-index.c
===
--- /dev/null
+++ test/Analysis/array-index.c
@@ -0,0 +1,21 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.security.ArrayBound,alpha.unix.cstring.OutOfBounds -verify -Wno-implicit-function-declaration %s
+
+// expected-no-diagnostics
+
+#define SIZE 4294967296
+
+static unsigned size;
+static void * addr;
+static unsigned buf[SIZE];
+
+void fie() {
+  buf[SIZE-1] = 1;
+}
+
+void foo() {
+  memcpy(buf, addr, size);
+}
+
+void bar() {
+  memcpy(addr, buf, size);
+}
Index: lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- lib/StaticAnalyzer/Core/RegionStore.cpp
+++ lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1341,7 +1341,7 @@
   // If a variable is reinterpreted as a type that doesn't fit into a larger
   // type evenly, round it down.
   // This is a signed value, since it's used in arithmetic with signed indices.
-  return svalBuilder.makeIntVal(RegionSize / EleSize, false);
+  return svalBuilder.makeIntVal(RegionSize / EleSize, Ctx.getSignedSizeType());
 }
 
 //===--===//
Index: lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- lib/StaticAnalyzer/Core/ProgramState.cpp
+++ lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -336,9 +336,8 @@
 
   // Get the offset: the minimum value of the array index type.
   BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
-  // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
   if (indexTy.isNull())
-indexTy = Ctx.IntTy;
+indexTy = svalBuilder.getArrayIndexType();
   nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
 
   // Adjust the index.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46943: [clangd] Boost scores for decls from current file in completion

2018-05-16 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/Quality.cpp:24
+  if (SemaCCResult.Declaration)
+AllDeclsInMainFile = allDeclsInMainFile(SemaCCResult.Declaration);
   if (SemaCCResult.Availability == CXAvailability_Deprecated)

Could you explain why `AllDeclsInMainFile` is necessary? I think it might still 
be fine to boost score for symbols with a declaration in the main file even if 
it has redecls in other files (e.g. function fwd in headers).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46943



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


[PATCH] D46940: [ASTImporter] make sure that ACtx::getParents still works

2018-05-16 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Hello Rafael,

The patch is awesome. The only thing I'm uncomfortable with is that we call 
invalidation on every stmt import - not only during the top-level one. Fixing 
this requires separating entry point from internal imports and is out of scope 
of this patch, but adding some FIXMEs is very appreciated.




Comment at: lib/AST/ASTImporter.cpp:6755
+  auto ToE = cast_or_null(Import(cast(FromE)));
+  if (ToE)
+ToContext.invalidateParents();

We already do the invalidation in Import(Stmt), so it looks redundant here.


Repository:
  rC Clang

https://reviews.llvm.org/D46940



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


r332473 - [OpenCL] make test independent of optimizer

2018-05-16 Thread Sanjay Patel via cfe-commits
Author: spatel
Date: Wed May 16 07:38:07 2018
New Revision: 332473

URL: http://llvm.org/viewvc/llvm-project?rev=332473&view=rev
Log:
[OpenCL] make test independent of optimizer

There shouldn't be any tests that run the entire optimizer here,
but the last test in this file is definitely going to break with 
a change in LLVM IR canonicalization. Change that part to check
the unoptimized IR because that's the real intent of this file.

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

Modified: cfe/trunk/test/CodeGenOpenCL/shifts.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenOpenCL/shifts.cl?rev=332473&r1=332472&r2=332473&view=diff
==
--- cfe/trunk/test/CodeGenOpenCL/shifts.cl (original)
+++ cfe/trunk/test/CodeGenOpenCL/shifts.cl Wed May 16 07:38:07 2018
@@ -58,16 +58,17 @@ int4 vectorVectorTest(int4 a,int4 b) {
   return f;
 }
 
-//OPT: @vectorScalarTest
+//NOOPT-LABEL: @vectorScalarTest
 int4 vectorScalarTest(int4 a,int b) {
-  //OPT: [[SP0:%.+]] = insertelement <4 x i32> undef, i32 %b, i32 0
-  //OPT: [[SP1:%.+]] = shufflevector <4 x i32> [[SP0]], <4 x i32> undef, <4 x 
i32> zeroinitializer
-  //OPT: [[VSM:%.+]] = and <4 x i32> [[SP1]], 
-  //OPT-NEXT: [[VSC:%.+]] = shl <4 x i32> %a, [[VSM]]
+  //NOOPT: [[SP0:%.+]] = insertelement <4 x i32> undef
+  //NOOPT: [[SP1:%.+]] = shufflevector <4 x i32> [[SP0]], <4 x i32> undef, <4 
x i32> zeroinitializer
+  //NOOPT: [[VSM:%.+]] = and <4 x i32> [[SP1]], 
+  //NOOPT: [[VSC:%.+]] = shl <4 x i32> [[VSS:%.+]], [[VSM]]
   int4 c = a << b;
-  //OPT-NEXT: [[VSF:%.+]] = add <4 x i32> [[VSC]], 
+  //NOOPT: [[VSF:%.+]] = shl <4 x i32> [[VSC1:%.+]], 
+  //NOOPT: [[VSA:%.+]] = add <4 x i32> [[VSC2:%.+]], [[VSF]]
   int4 d = {1, 1, 1, 1};
   int4 f = c + (d << 34);
-  //OPT-NEXT: ret <4 x i32> [[VSF]]
+  //NOOPT: ret <4 x i32>
   return f;
 }


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


[PATCH] D46919: [libclang] Deprecate CXPrintingPolicy_IncludeTagDefinition

2018-05-16 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

In https://reviews.llvm.org/D46919#1100493, @rsmith wrote:

> The deprecated enumerator is also referenced by 
> `tools/c-index-test/c-index-test.c`


This test prompted me to keep the IncludeTagDefinition member in PrintingPolicy 
so that clang_PrintingPolicy_getProperty would return the previous value set by 
clang_PrintingPolicy_setProperty.  Otherwise, the value doesn't have any 
effect.  Is that self-consistency not worth worrying about?  If so, I'll remove 
both.

> This looks fine to me, but let's leave this review thread open for a week or 
> so, to give people a bit more time to object in case they're using the flag 
> for something.

Sure.




Comment at: include/clang/AST/PrettyPrinter.h:100-108
+  /// When true, print any tag declaration owned by an elaborated type.
   ///
-  /// This is used to place the definition of a struct
-  /// in the middle of another declaration as with:
+  /// This is used to faithfully print the exact tag declaration that appears
+  /// within another declaration.  For example:
   ///
   /// \code
+  /// typedef struct T { int x, y; } Point;

rsmith wrote:
> Please explicitly mark this as being transient state that's internal to the 
> printing algorithm and not part of its external configuration, so that people 
> don't try to expose it again in the future. The same is true for a bunch of 
> the other flags around here -- if we're going to do this, we should 
> systematically examine these flags to see which ones are external 
> configuration and which ones are internal state that we're (hackily) passing 
> between printing steps via the `PrintingPolicy`. It would also make sense to 
> move the internal state flags to a separate struct from the policy.
> Please explicitly mark this as being transient state that's internal to the 
> printing algorithm and not part of its external configuration, so that people 
> don't try to expose it again in the future.

Will do.

> The same is true for a bunch of the other flags around here -- if we're going 
> to do this, we should systematically examine these flags to see which ones 
> are external configuration and which ones are internal state that we're 
> (hackily) passing between printing steps via the PrintingPolicy.

Doing that now sounds like a lot of analysis and difficult judgment calls 
without much immediate gain -- at least for me as I'm not so familiar with all 
the flags and their potential uses from libclang.  My inclination is to write a 
fixme and refactor gradually.

> It would also make sense to move the internal state flags to a separate 
> struct from the policy.

Are you ok with making the new struct a member of the existing policy to 
simplify the refactoring effort?


https://reviews.llvm.org/D46919



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


r332474 - [Attr] Don't print fake MSInheritance argument

2018-05-16 Thread Joel E. Denny via cfe-commits
Author: jdenny
Date: Wed May 16 07:51:18 2018
New Revision: 332474

URL: http://llvm.org/viewvc/llvm-project?rev=332474&view=rev
Log:
[Attr] Don't print fake MSInheritance argument

This was discovered at:

http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20180514/228390.html

Reviewed by: aaron.ballman

https://reviews.llvm.org/D46905

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/test/SemaCXX/attr-print.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=332474&r1=332473&r2=332474&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed May 16 07:51:18 2018
@@ -184,7 +184,8 @@ class VersionArgument : Argument;
 
 // A bool argument with a default value
-class DefaultBoolArgument : BoolArgument {
+class DefaultBoolArgument
+: BoolArgument {
   bit Default = default;
 }
 
@@ -2624,7 +2625,7 @@ def UPtr : TypeAttr {
 
 def MSInheritance : InheritableAttr {
   let LangOpts = [MicrosoftExt];
-  let Args = [DefaultBoolArgument<"BestCase", 1>];
+  let Args = [DefaultBoolArgument<"BestCase", /*default*/1, /*fake*/1>];
   let Spellings = [Keyword<"__single_inheritance">,
Keyword<"__multiple_inheritance">,
Keyword<"__virtual_inheritance">,

Modified: cfe/trunk/test/SemaCXX/attr-print.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/attr-print.cpp?rev=332474&r1=332473&r2=332474&view=diff
==
--- cfe/trunk/test/SemaCXX/attr-print.cpp (original)
+++ cfe/trunk/test/SemaCXX/attr-print.cpp Wed May 16 07:51:18 2018
@@ -34,3 +34,12 @@ class __attribute__((consumable(unknown)
   // CHECK: void callableWhen() __attribute__((callable_when("unconsumed", 
"consumed")));
   void callableWhen()  __attribute__((callable_when("unconsumed", 
"consumed")));
 };
+
+// CHECK: class __single_inheritance SingleInheritance;
+class __single_inheritance SingleInheritance;
+
+// CHECK: class __multiple_inheritance MultipleInheritance;
+class __multiple_inheritance MultipleInheritance;
+
+// CHECK: class __virtual_inheritance VirtualInheritance;
+class __virtual_inheritance VirtualInheritance;


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


[PATCH] D40988: Clang-format: add finer-grained options for putting all arguments on one line

2018-05-16 Thread Russell McClellan via Phabricator via cfe-commits
russellmcc added a comment.

Bump!  Thanks for your consideration


https://reviews.llvm.org/D40988



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


[PATCH] D46940: [ASTImporter] make sure that ACtx::getParents still works

2018-05-16 Thread Rafael Stahl via Phabricator via cfe-commits
r.stahl added inline comments.



Comment at: lib/AST/ASTImporter.cpp:6755
+  auto ToE = cast_or_null(Import(cast(FromE)));
+  if (ToE)
+ToContext.invalidateParents();

a.sidorin wrote:
> We already do the invalidation in Import(Stmt), so it looks redundant here.
Yes, sorry this should actually be in Import(Decl) as I wrote in the 
description!


Repository:
  rC Clang

https://reviews.llvm.org/D46940



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


[PATCH] D46944: [analyzer] Use sufficiently large types for index/size calculation.

2018-05-16 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

This is a nice extension of https://reviews.llvm.org/D16063.




Comment at: lib/StaticAnalyzer/Core/RegionStore.cpp:1344
   // This is a signed value, since it's used in arithmetic with signed indices.
-  return svalBuilder.makeIntVal(RegionSize / EleSize, false);
+  return svalBuilder.makeIntVal(RegionSize / EleSize, Ctx.getSignedSizeType());
 }

I think we should initialize SValBuilder::ArrayIndexTy with getSignedSizeType() 
instead of LongLongTy and use `svalBuilder.getArrayIndexType()` here instead.



Comment at: test/Analysis/array-index.c:1
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.security.ArrayBound,alpha.unix.cstring.OutOfBounds 
-verify -Wno-implicit-function-declaration %s
+

Can we place these tests into Analysis/index-type.c?


Repository:
  rC Clang

https://reviews.llvm.org/D46944



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


[PATCH] D46944: [analyzer] Use sufficiently large types for index/size calculation.

2018-05-16 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added inline comments.



Comment at: test/Analysis/array-index.c:11
+
+void fie() {
+  buf[SIZE-1] = 1;

Could you please give meaningful names to the tests?


Repository:
  rC Clang

https://reviews.llvm.org/D46944



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


r332477 - [OPENMP] DO not crash on combined constructs in declare target

2018-05-16 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Wed May 16 08:08:32 2018
New Revision: 332477

URL: http://llvm.org/viewvc/llvm-project?rev=332477&view=rev
Log:
[OPENMP] DO not crash on combined constructs in declare target
functions.

If the combined construct is specified in the declare target function
and the device code is emitted, the compiler crashes because of the
incorrectly chosen captured stmt. We should choose the innermost
captured statement, not the outermost.

Modified:
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
cfe/trunk/test/OpenMP/declare_target_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp?rev=332477&r1=332476&r2=332477&view=diff
==
--- cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp Wed May 16 08:08:32 2018
@@ -3935,7 +3935,7 @@ static void emitCommonOMPTargetDirective
 OMPLexicalScope Scope(CGF, S, OMPD_target);
 CGM.getOpenMPRuntime().emitInlinedDirective(
 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
-  CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
+  CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
 });
 return;
   }

Modified: cfe/trunk/test/OpenMP/declare_target_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/declare_target_codegen.cpp?rev=332477&r1=332476&r2=332477&view=diff
==
--- cfe/trunk/test/OpenMP/declare_target_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/declare_target_codegen.cpp Wed May 16 08:08:32 2018
@@ -82,7 +82,7 @@ int maini1() {
 int baz3() { return 2 + baz2(); }
 int baz2() {
 // CHECK-DAG: define weak void 
@__omp_offloading_{{.*}}baz2{{.*}}_l[[@LINE+1]](i64 {{.*}})
-#pragma omp target
+#pragma omp target parallel
   ++c;
   return 2 + baz3();
 }


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


r332481 - [Attr] Don't print fake MSInheritance argument

2018-05-16 Thread Joel E. Denny via cfe-commits
Author: jdenny
Date: Wed May 16 08:18:30 2018
New Revision: 332481

URL: http://llvm.org/viewvc/llvm-project?rev=332481&view=rev
Log:
[Attr] Don't print fake MSInheritance argument

This was discovered at:

http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20180514/228390.html

Reviewed by: aaron.ballman

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

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/test/SemaCXX/attr-print.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=332481&r1=332480&r2=332481&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed May 16 08:18:30 2018
@@ -184,7 +184,8 @@ class VersionArgument : Argument;
 
 // A bool argument with a default value
-class DefaultBoolArgument : BoolArgument {
+class DefaultBoolArgument
+: BoolArgument {
   bit Default = default;
 }
 
@@ -2624,7 +2625,7 @@ def UPtr : TypeAttr {
 
 def MSInheritance : InheritableAttr {
   let LangOpts = [MicrosoftExt];
-  let Args = [DefaultBoolArgument<"BestCase", 1>];
+  let Args = [DefaultBoolArgument<"BestCase", /*default*/1, /*fake*/1>];
   let Spellings = [Keyword<"__single_inheritance">,
Keyword<"__multiple_inheritance">,
Keyword<"__virtual_inheritance">,

Modified: cfe/trunk/test/SemaCXX/attr-print.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/attr-print.cpp?rev=332481&r1=332480&r2=332481&view=diff
==
--- cfe/trunk/test/SemaCXX/attr-print.cpp (original)
+++ cfe/trunk/test/SemaCXX/attr-print.cpp Wed May 16 08:18:30 2018
@@ -34,3 +34,12 @@ class __attribute__((consumable(unknown)
   // CHECK: void callableWhen() __attribute__((callable_when("unconsumed", 
"consumed")));
   void callableWhen()  __attribute__((callable_when("unconsumed", 
"consumed")));
 };
+
+// CHECK: class __single_inheritance SingleInheritance;
+class __single_inheritance SingleInheritance;
+
+// CHECK: class __multiple_inheritance MultipleInheritance;
+class __multiple_inheritance MultipleInheritance;
+
+// CHECK: class __virtual_inheritance VirtualInheritance;
+class __virtual_inheritance VirtualInheritance;


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


r332480 - Revert r332474: [Attr] Don't print fake MSInheritance argument

2018-05-16 Thread Joel E. Denny via cfe-commits
Author: jdenny
Date: Wed May 16 08:18:27 2018
New Revision: 332480

URL: http://llvm.org/viewvc/llvm-project?rev=332480&view=rev
Log:
Revert r332474: [Attr] Don't print fake MSInheritance argument

I botched the commit log attributes.

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/test/SemaCXX/attr-print.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=332480&r1=332479&r2=332480&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed May 16 08:18:27 2018
@@ -184,8 +184,7 @@ class VersionArgument : Argument;
 
 // A bool argument with a default value
-class DefaultBoolArgument
-: BoolArgument {
+class DefaultBoolArgument : BoolArgument {
   bit Default = default;
 }
 
@@ -2625,7 +2624,7 @@ def UPtr : TypeAttr {
 
 def MSInheritance : InheritableAttr {
   let LangOpts = [MicrosoftExt];
-  let Args = [DefaultBoolArgument<"BestCase", /*default*/1, /*fake*/1>];
+  let Args = [DefaultBoolArgument<"BestCase", 1>];
   let Spellings = [Keyword<"__single_inheritance">,
Keyword<"__multiple_inheritance">,
Keyword<"__virtual_inheritance">,

Modified: cfe/trunk/test/SemaCXX/attr-print.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/attr-print.cpp?rev=332480&r1=332479&r2=332480&view=diff
==
--- cfe/trunk/test/SemaCXX/attr-print.cpp (original)
+++ cfe/trunk/test/SemaCXX/attr-print.cpp Wed May 16 08:18:27 2018
@@ -34,12 +34,3 @@ class __attribute__((consumable(unknown)
   // CHECK: void callableWhen() __attribute__((callable_when("unconsumed", 
"consumed")));
   void callableWhen()  __attribute__((callable_when("unconsumed", 
"consumed")));
 };
-
-// CHECK: class __single_inheritance SingleInheritance;
-class __single_inheritance SingleInheritance;
-
-// CHECK: class __multiple_inheritance MultipleInheritance;
-class __multiple_inheritance MultipleInheritance;
-
-// CHECK: class __virtual_inheritance VirtualInheritance;
-class __virtual_inheritance VirtualInheritance;


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


[PATCH] D46905: [Attr] Don't print fake MSInheritance argument

2018-05-16 Thread Joel E. Denny via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332481: [Attr] Don't print fake MSInheritance argument 
(authored by jdenny, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D46905?vs=146923&id=147096#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D46905

Files:
  cfe/trunk/include/clang/Basic/Attr.td
  cfe/trunk/test/SemaCXX/attr-print.cpp


Index: cfe/trunk/include/clang/Basic/Attr.td
===
--- cfe/trunk/include/clang/Basic/Attr.td
+++ cfe/trunk/include/clang/Basic/Attr.td
@@ -184,7 +184,8 @@
 class AlignedArgument : Argument;
 
 // A bool argument with a default value
-class DefaultBoolArgument : BoolArgument {
+class DefaultBoolArgument
+: BoolArgument {
   bit Default = default;
 }
 
@@ -2624,7 +2625,7 @@
 
 def MSInheritance : InheritableAttr {
   let LangOpts = [MicrosoftExt];
-  let Args = [DefaultBoolArgument<"BestCase", 1>];
+  let Args = [DefaultBoolArgument<"BestCase", /*default*/1, /*fake*/1>];
   let Spellings = [Keyword<"__single_inheritance">,
Keyword<"__multiple_inheritance">,
Keyword<"__virtual_inheritance">,
Index: cfe/trunk/test/SemaCXX/attr-print.cpp
===
--- cfe/trunk/test/SemaCXX/attr-print.cpp
+++ cfe/trunk/test/SemaCXX/attr-print.cpp
@@ -34,3 +34,12 @@
   // CHECK: void callableWhen() __attribute__((callable_when("unconsumed", 
"consumed")));
   void callableWhen()  __attribute__((callable_when("unconsumed", 
"consumed")));
 };
+
+// CHECK: class __single_inheritance SingleInheritance;
+class __single_inheritance SingleInheritance;
+
+// CHECK: class __multiple_inheritance MultipleInheritance;
+class __multiple_inheritance MultipleInheritance;
+
+// CHECK: class __virtual_inheritance VirtualInheritance;
+class __virtual_inheritance VirtualInheritance;


Index: cfe/trunk/include/clang/Basic/Attr.td
===
--- cfe/trunk/include/clang/Basic/Attr.td
+++ cfe/trunk/include/clang/Basic/Attr.td
@@ -184,7 +184,8 @@
 class AlignedArgument : Argument;
 
 // A bool argument with a default value
-class DefaultBoolArgument : BoolArgument {
+class DefaultBoolArgument
+: BoolArgument {
   bit Default = default;
 }
 
@@ -2624,7 +2625,7 @@
 
 def MSInheritance : InheritableAttr {
   let LangOpts = [MicrosoftExt];
-  let Args = [DefaultBoolArgument<"BestCase", 1>];
+  let Args = [DefaultBoolArgument<"BestCase", /*default*/1, /*fake*/1>];
   let Spellings = [Keyword<"__single_inheritance">,
Keyword<"__multiple_inheritance">,
Keyword<"__virtual_inheritance">,
Index: cfe/trunk/test/SemaCXX/attr-print.cpp
===
--- cfe/trunk/test/SemaCXX/attr-print.cpp
+++ cfe/trunk/test/SemaCXX/attr-print.cpp
@@ -34,3 +34,12 @@
   // CHECK: void callableWhen() __attribute__((callable_when("unconsumed", "consumed")));
   void callableWhen()  __attribute__((callable_when("unconsumed", "consumed")));
 };
+
+// CHECK: class __single_inheritance SingleInheritance;
+class __single_inheritance SingleInheritance;
+
+// CHECK: class __multiple_inheritance MultipleInheritance;
+class __multiple_inheritance MultipleInheritance;
+
+// CHECK: class __virtual_inheritance VirtualInheritance;
+class __virtual_inheritance VirtualInheritance;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46950: Fix duplicate class template definitions problem

2018-05-16 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: a.sidorin, xazax.hun, szepet.
Herald added subscribers: cfe-commits, dkrupp, rnkovacs.

We fail to import a `ClassTemplateDecl` if the "To" context already contains a 
definition and then a forward decl.
This is because `localUncachedLookup` does not find the definition.
This is not a lookup error, the parser behaves differently than assumed in the 
importer code.
A `DeclContext` contains one DenseMap (`LookupPtr`) which maps names to lists.
The list is a special list `StoredDeclsList` which is optimized to have one 
element.
During building the initial AST, the parser first adds the definition to the 
`DeclContext`.
Then during parsing the second declaration (the forward decl) the parser again 
calls `DeclContext::addDecl` but that will not add a new element to the 
`StoredDeclsList` rarther it simply overwrites the old element with the most 
recent one.
This patch fixes the error by finding the definition in the redecl chain.
Added tests for the same issue with `CXXRecordDecl` and with 
`ClassTemplateSpecializationDecl`.
These tests pass and they pass because in `VisitRecordDecl` and in 
`VisitClassTemplateSpecializationDecl` we already use `D->getDefinition()` 
after the lookup.


Repository:
  rC Clang

https://reviews.llvm.org/D46950

Files:
  lib/AST/ASTImporter.cpp
  unittests/AST/ASTImporterTest.cpp
  unittests/AST/DeclMatcher.h

Index: unittests/AST/DeclMatcher.h
===
--- unittests/AST/DeclMatcher.h
+++ unittests/AST/DeclMatcher.h
@@ -44,24 +44,35 @@
 using FirstDeclMatcher = DeclMatcher;
 
 template 
-class DeclCounter : public MatchFinder::MatchCallback {
-  unsigned Count = 0;
+class DeclCounterWithPredicate : public MatchFinder::MatchCallback {
+  using UnaryPredicate = std::function;
+  UnaryPredicate predicate;
+  unsigned count = 0;
   void run(const MatchFinder::MatchResult &Result) override {
-  if(Result.Nodes.getNodeAs("")) {
-++Count;
-  }
+if (auto N = Result.Nodes.getNodeAs("")) {
+  if (predicate(N))
+++count;
+}
   }
+
 public:
-  // Returns the number of matched nodes under the tree rooted in `D`.
+  DeclCounterWithPredicate()
+  : predicate([](const NodeType *) { return true; }) {}
+  DeclCounterWithPredicate(UnaryPredicate p) : predicate(p) {}
+  // Returns the number of matched nodes which satisfy the predicate under the
+  // tree rooted in `D`.
   template 
   unsigned match(const Decl *D, const MatcherType &AMatcher) {
 MatchFinder Finder;
 Finder.addMatcher(AMatcher.bind(""), this);
 Finder.matchAST(D->getASTContext());
-return Count;
+return count;
   }
 };
 
+template 
+using DeclCounter = DeclCounterWithPredicate;
+
 } // end namespace ast_matchers
 } // end namespace clang
 
Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -281,8 +281,9 @@
 return std::make_tuple(*FoundDecls.begin(), Imported);
   }
 
-  // Creates a TU decl for the given source code.
-  // May be called several times in a given test.
+  // Creates a TU decl for the given source code which can be used as a From
+  // context.  May be called several times in a given test (with different file
+  // name).
   TranslationUnitDecl *getTuDecl(StringRef SrcCode, Language Lang,
  StringRef FileName = "input.cc") {
 assert(
@@ -297,6 +298,16 @@
 return Tu.TUDecl;
   }
 
+  // Creates the To context with the given source code and returns the TU decl.
+  TranslationUnitDecl *getToTuDecl(StringRef ToSrcCode, Language ToLang) {
+ArgVector ToArgs = getArgVectorForLanguage(ToLang);
+ToCode = ToSrcCode;
+assert(!ToAST);
+ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName);
+
+return ToAST->getASTContext().getTranslationUnitDecl();
+  }
+
   // Import the given Decl into the ToCtx.
   // May be called several times in a given test.
   // The different instances of the param From may have different ASTContext.
@@ -1464,6 +1475,120 @@
   }
 }
 
+TEST_P(ASTImporterTestBase,
+   ImportDefinitionOfClassTemplateIfThereIsAnExistingFwdDeclAndDefinition) {
+  Decl *ToTU = getToTuDecl(
+  R"(
+  template 
+  struct B {
+void f();
+  };
+
+  template 
+  struct B;
+  )",
+  Lang_CXX);
+  ASSERT_EQ(1u, DeclCounterWithPredicate(
+[](const ClassTemplateDecl *T) {
+  return T->isThisDeclarationADefinition();
+})
+.match(ToTU, classTemplateDecl()));
+
+  Decl *FromTU = getTuDecl(
+  R"(
+  template 
+  struct B {
+void f();
+  };
+  )",
+  Lang_CXX, "input1.cc");
+  ClassTemplateDecl *FromD = FirstDeclMatcher().match(
+  FromTU, classTemplateDecl(hasName("B")));
+
+  Import(FromD, L

[PATCH] D46951: [clang-tidy] misc-unused-parameters - retain old behavior under StrictMode

2018-05-16 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh created this revision.
alexfh added reviewers: klimek, ilya-biryukov.
Herald added a subscriber: xazax.hun.

This addresses https://bugs.llvm.org/show_bug.cgi?id=37467.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46951

Files:
  clang-tidy/misc/UnusedParametersCheck.cpp
  clang-tidy/misc/UnusedParametersCheck.h
  docs/clang-tidy/checks/misc-unused-parameters.rst
  test/clang-tidy/misc-unused-parameters-strict.cpp
  test/clang-tidy/misc-unused-parameters.cpp

Index: test/clang-tidy/misc-unused-parameters.cpp
===
--- test/clang-tidy/misc-unused-parameters.cpp
+++ test/clang-tidy/misc-unused-parameters.cpp
@@ -222,5 +222,34 @@
   return Function();
 }
 
+namespace strict_mode_off {
 // Do not warn on empty function bodies.
 void f(int foo) {}
+class E {
+  int i;
+
+public:
+  E(int j) {}
+};
+class F {
+  int i;
+
+public:
+  // Constructor initializer counts as a non-empty body.
+  F(int j) : i() {}
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'j' is unused
+// CHECK-FIXES: {{^}}  F(int  /*j*/) : i() {}{{$}}
+};
+
+class A {
+public:
+  A();
+  A(int);
+};
+class B : public A {
+public:
+  B(int i) : A() {}
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'i' is unused
+// CHECK-FIXES: {{^}}  B(int  /*i*/) : A() {}{{$}}
+};
+} // namespace strict_mode_off
Index: test/clang-tidy/misc-unused-parameters-strict.cpp
===
--- /dev/null
+++ test/clang-tidy/misc-unused-parameters-strict.cpp
@@ -0,0 +1,25 @@
+// RUN: %check_clang_tidy %s misc-unused-parameters %t -- \
+// RUN:   -config="{CheckOptions: [{key: StrictMode, value: 1}]}" --
+
+// Warn on empty function bodies in StrictMode.
+namespace strict_mode {
+void f(int foo) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: parameter 'foo' is unused [misc-unused-parameters]
+// CHECK-FIXES: {{^}}void f(int  /*foo*/) {}{{$}}
+class E {
+  int i;
+
+public:
+  E(int j) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'j' is unused
+// CHECK-FIXES: {{^}}  E(int  /*j*/) {}{{$}}
+};
+class F {
+  int i;
+
+public:
+  F(int j) : i() {}
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: parameter 'j' is unused
+// CHECK-FIXES: {{^}}  F(int  /*j*/) : i() {}{{$}}
+};
+}
Index: docs/clang-tidy/checks/misc-unused-parameters.rst
===
--- docs/clang-tidy/checks/misc-unused-parameters.rst
+++ docs/clang-tidy/checks/misc-unused-parameters.rst
@@ -3,24 +3,40 @@
 misc-unused-parameters
 ==
 
-Finds unused parameters and fixes them, so that `-Wunused-parameter` can be
-turned on.
+Finds unused function parameters. Unused parameters may signal about a bug in
+the code (e.g. when a different parameter is used instead). The suggested fixes
+either comment parameter name out or remove the parameter completely, if all
+callers of the function are in the same translation unit and can be updated.
+
+The check is similar to the `-Wunused-parameter` compiler diagnostic and can be
+used to prepare a codebase to enabling of that diagnostic. By default the check
+is more permissive (see :option:`StrictMode`).
 
 .. code-block:: c++
 
-  void a(int i) {}
+  void a(int i) { /*some code that doesn't use `i`*/ }
 
   // becomes
 
-  void a(int  /*i*/) {}
-
+  void a(int  /*i*/) { /*some code that doesn't use `i`*/ }
 
 .. code-block:: c++
 
   static void staticFunctionA(int i);
-  static void staticFunctionA(int i) {}
+  static void staticFunctionA(int i) { /*some code that doesn't use `i`*/ }
 
   // becomes
 
   static void staticFunctionA()
-  static void staticFunctionA() {}
+  static void staticFunctionA() { /*some code that doesn't use `i`*/ }
+
+Options
+---
+
+.. option:: StrictMode
+
+   When zero (default value), the check will ignore trivially unused parameters,
+   i.e. when the corresponding function has an empty body (and in case of
+   constructors - no constructor initializers). When the function body is empty,
+   an unused parameter is unlikely to be unnoticed by a human reader, and
+   there's basically no place for a bug to hide in.
Index: clang-tidy/misc/UnusedParametersCheck.h
===
--- clang-tidy/misc/UnusedParametersCheck.h
+++ clang-tidy/misc/UnusedParametersCheck.h
@@ -24,8 +24,10 @@
   ~UnusedParametersCheck();
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
 
 private:
+  const bool StrictMode;
   class IndexerVisitor;
   std::unique_ptr Indexer;
 
Index: clang-tidy/misc/UnusedParametersCheck.cpp
===
--- clang-tidy/misc/UnusedParametersCheck.cpp
+++ clang-tidy/misc/UnusedParametersCheck.cpp
@@ -29,11 +29,10 @@
 } // namespace

[PATCH] D46659: [clang-tidy/google-readability-casting] Allow C-style casts to/from Objective-C object types

2018-05-16 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 147102.
benhamilton added a comment.

- Change to simply disable check for Objective-C++


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46659

Files:
  clang-tidy/google/AvoidCStyleCastsCheck.cpp
  test/clang-tidy/google-readability-casting.mm

Index: test/clang-tidy/google-readability-casting.mm
===
--- /dev/null
+++ test/clang-tidy/google-readability-casting.mm
@@ -0,0 +1,179 @@
+// RUN: clang-tidy %s -checks=-*,google-readability-casting -- \
+// RUN:   -xobjective-c++ -fobjc-abi-version=2 -fobjc-arc | count 0
+
+// Note: this test expects no diagnostics, but FileCheck cannot handle that,
+// hence the use of | count 0.
+
+bool g() { return false; }
+
+enum Enum { Enum1 };
+struct X {};
+struct Y : public X {};
+
+void f(int a, double b, const char *cpc, const void *cpv, X *pX) {
+
+  typedef const char *Typedef1;
+  typedef const char *Typedef2;
+  Typedef1 t1;
+  (Typedef2)t1;
+  (const char*)t1;
+  (Typedef1)cpc;
+
+  typedef char Char;
+  char *pc;
+  Char *pChar = (Char*)pc;
+
+  (Char)*cpc;
+
+  (char)*pChar;
+
+  (const char*)cpv;
+
+  char *pc2 = (char*)(cpc + 33);
+
+  const char &crc = *cpc;
+  char &rc = (char&)crc;
+
+  char &rc2 = (char&)*cpc;
+
+  char ** const* const* ppcpcpc;
+  char c = (char)ppcpcpc;
+
+  char ***pppc = (char***)*(ppcpcpc);
+
+  char ***pppc2 = (char***)(*ppcpcpc);
+
+  char *pc5 = (char*)(const char*)(cpv);
+
+  int b1 = (int)b;
+  b1 = (const int&)b;
+
+  b1 = (int) b;
+
+  b1 = (int) b;
+
+  b1 = (int) (b);
+
+  b1 = (int) (b);
+
+  Y *pB = (Y*)pX;
+  Y &rB = (Y&)*pX;
+
+  const char *pc3 = (const char*)cpv;
+
+  char *pc4 = (char*)cpv;
+
+  b1 = (int)Enum1;
+
+  Enum e = (Enum)b1;
+
+  int b2 = int(b);
+  int b3 = static_cast(b);
+  int b4 = b;
+  double aa = a;
+  (void)b2;
+  return (void)g();
+}
+
+template 
+void template_function(T t, int n) {
+  int i = (int)t;
+}
+
+template 
+struct TemplateStruct {
+  void f(T t, int n) {
+int k = (int)t;
+  }
+};
+
+void test_templates() {
+  template_function(1, 42);
+  template_function(1.0, 42);
+  TemplateStruct().f(1, 42);
+  TemplateStruct().f(1.0, 42);
+}
+
+extern "C" {
+void extern_c_code(const char *cpc) {
+  char *pc = (char*)cpc;
+}
+}
+
+#define CAST(type, value) (type)(value)
+void macros(double d) {
+  int i = CAST(int, d);
+}
+
+enum E { E1 = 1 };
+template 
+struct A {
+  // Usage of template argument e = E1 is represented as (E)1 in the AST for
+  // some reason. We have a special treatment of this case to avoid warnings
+  // here.
+  static const E ee = e;
+};
+struct B : public A {};
+
+
+void overloaded_function();
+void overloaded_function(int);
+
+template
+void g(Fn fn) {
+  fn();
+}
+
+void function_casts() {
+  typedef void (*FnPtrVoid)();
+  typedef void (&FnRefVoid)();
+  typedef void (&FnRefInt)(int);
+
+  g((void (*)())overloaded_function);
+  g((void (*)())&overloaded_function);
+  g((void (&)())overloaded_function);
+
+  g((FnPtrVoid)overloaded_function);
+  g((FnPtrVoid)&overloaded_function);
+  g((FnRefVoid)overloaded_function);
+
+  FnPtrVoid fn0 = (void (*)())&overloaded_function;
+  FnPtrVoid fn1 = (void (*)())overloaded_function;
+  FnPtrVoid fn1a = (FnPtrVoid)overloaded_function;
+  FnRefInt fn2 = (void (&)(int))overloaded_function;
+  auto fn3 = (void (*)())&overloaded_function;
+  auto fn4 = (void (*)())overloaded_function;
+  auto fn5 = (void (&)(int))overloaded_function;
+
+  void (*fn6)() = (void (*)())&overloaded_function;
+  void (*fn7)() = (void (*)())overloaded_function;
+  void (*fn8)() = (FnPtrVoid)overloaded_function;
+  void (&fn9)(int) = (void (&)(int))overloaded_function;
+
+  void (*correct1)() = static_cast(overloaded_function);
+  FnPtrVoid correct2 = static_cast(&overloaded_function);
+  FnRefInt correct3 = static_cast(overloaded_function);
+}
+
+struct S {
+S(const char *);
+};
+struct ConvertibleToS {
+  operator S() const;
+};
+struct ConvertibleToSRef {
+  operator const S&() const;
+};
+
+void conversions() {
+  //auto s1 = (const S&)"";
+  auto s2 = (S)"";
+  auto s2a = (struct S)"";
+  auto s2b = (const S)"";
+  ConvertibleToS c;
+  auto s3 = (const S&)c;
+  auto s4 = (S)c;
+  ConvertibleToSRef cr;
+  auto s5 = (const S&)cr;
+  auto s6 = (S)cr;
+}
Index: clang-tidy/google/AvoidCStyleCastsCheck.cpp
===
--- clang-tidy/google/AvoidCStyleCastsCheck.cpp
+++ clang-tidy/google/AvoidCStyleCastsCheck.cpp
@@ -100,7 +100,8 @@
   }
 
   // The rest of this check is only relevant to C++.
-  if (!getLangOpts().CPlusPlus)
+  // We also disable it for Objective-C++.
+  if (!getLangOpts().CPlusPlus || getLangOpts().ObjC1 || getLangOpts().ObjC2)
 return;
   // Ignore code inside extern "C" {} blocks.
   if (!match(expr(hasAncestor(linkageSpecDecl())), *CastExpr, *Result.Context)
___
cfe-commits mailing list

[PATCH] D46659: [clang-tidy/google-readability-casting] Disable check for Objective-C++

2018-05-16 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added a comment.

After discussion, I changed this diff to simply disable the check altogether 
for Objective-C++.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46659



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


[PATCH] D46944: [analyzer] Use sufficiently large types for index/size calculation.

2018-05-16 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan added inline comments.



Comment at: lib/StaticAnalyzer/Core/RegionStore.cpp:1344
   // This is a signed value, since it's used in arithmetic with signed indices.
-  return svalBuilder.makeIntVal(RegionSize / EleSize, false);
+  return svalBuilder.makeIntVal(RegionSize / EleSize, Ctx.getSignedSizeType());
 }

a.sidorin wrote:
> I think we should initialize SValBuilder::ArrayIndexTy with 
> getSignedSizeType() instead of LongLongTy and use 
> `svalBuilder.getArrayIndexType()` here instead.
I made the change, but it caused a spurious out of bounds warning in 
index-type.c for the 32-bit case. Making the type signed means that anything 
above MAX/2 will break, and the test uses arrays of that size.


Repository:
  rC Clang

https://reviews.llvm.org/D46944



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


[PATCH] D46958: [ASTImporter] Fix missing implict CXXRecordDecl

2018-05-16 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: xazax.hun, a.sidorin, szepet.
Herald added subscribers: cfe-commits, dkrupp, rnkovacs.

Implicit CXXRecordDecl is not added to its DeclContext during import, but in
the original AST it is. This patch fixes this.


Repository:
  rC Clang

https://reviews.llvm.org/D46958

Files:
  lib/AST/ASTImporter.cpp
  unittests/AST/ASTImporterTest.cpp


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -1348,7 +1348,7 @@
   Verifier.match(To, cxxRecordDecl(hasFieldOrder({"a", "b", "c"};
 }
 
-TEST_P(ASTImporterTestBase, DISABLED_ShouldImportImplicitCXXRecordDecl) {
+TEST_P(ASTImporterTestBase, ShouldImportImplicitCXXRecordDecl) {
   Decl *From, *To;
   std::tie(From, To) = getImportedDecl(
   R"(
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -2110,7 +2110,7 @@
   D2 = D2CXX;
   D2->setAccess(D->getAccess());
   D2->setLexicalDeclContext(LexicalDC);
-  if (!DCXX->getDescribedClassTemplate())
+  if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
 LexicalDC->addDeclInternal(D2);
 
   Importer.Imported(D, D2);


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -1348,7 +1348,7 @@
   Verifier.match(To, cxxRecordDecl(hasFieldOrder({"a", "b", "c"};
 }
 
-TEST_P(ASTImporterTestBase, DISABLED_ShouldImportImplicitCXXRecordDecl) {
+TEST_P(ASTImporterTestBase, ShouldImportImplicitCXXRecordDecl) {
   Decl *From, *To;
   std::tie(From, To) = getImportedDecl(
   R"(
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -2110,7 +2110,7 @@
   D2 = D2CXX;
   D2->setAccess(D->getAccess());
   D2->setLexicalDeclContext(LexicalDC);
-  if (!DCXX->getDescribedClassTemplate())
+  if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
 LexicalDC->addDeclInternal(D2);
 
   Importer.Imported(D, D2);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46944: [analyzer] Use sufficiently large types for index/size calculation.

2018-05-16 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added inline comments.



Comment at: lib/StaticAnalyzer/Core/RegionStore.cpp:1344
   // This is a signed value, since it's used in arithmetic with signed indices.
-  return svalBuilder.makeIntVal(RegionSize / EleSize, false);
+  return svalBuilder.makeIntVal(RegionSize / EleSize, Ctx.getSignedSizeType());
 }

ebevhan wrote:
> a.sidorin wrote:
> > I think we should initialize SValBuilder::ArrayIndexTy with 
> > getSignedSizeType() instead of LongLongTy and use 
> > `svalBuilder.getArrayIndexType()` here instead.
> I made the change, but it caused a spurious out of bounds warning in 
> index-type.c for the 32-bit case. Making the type signed means that anything 
> above MAX/2 will break, and the test uses arrays of that size.
Hm, yes. ssize_t is 32-bit on 32-bit targets but our indices can exceed it. 
Even if so, `svalBuilder.getArrayIndexType()` should be fine.


Repository:
  rC Clang

https://reviews.llvm.org/D46944



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


  1   2   3   >