[PATCH] D40671: [clang-tidy] Support specific categories for NOLINT directive

2017-12-01 Thread Anton via Phabricator via cfe-commits
xgsa added a comment.

In https://reviews.llvm.org/D40671#941676, @JonasToth wrote:

> Could you please explain what category means? Could i disable all of 
> `cppcoreguidelines` with something like `// NOLINT (cppcoreguidelines-*)`?


No, only individual checks can be disabled. You are right, by "categories" I 
meant just "checks". Sorry for confusion. I'll update the description.




Comment at: test/clang-tidy/nolintnextline.cpp:14
+
+// NOLINTNEXTLINE(not-closed-bracket-is-treated-as-skip-all
+class C2 { C2(int i); };

JonasToth wrote:
> missing `)`
No, it's intentionally: it's a test for case when `)` is missing


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D40671



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


[PATCH] D15075: No error for conflict between inputs\outputs and clobber list

2017-12-01 Thread Marina Yatsina via Phabricator via cfe-commits
myatsina added a comment.

In https://reviews.llvm.org/D15075#940711, @dolson wrote:

> Hello,
>
> In the process of upgrading from clang 3.6.1 to a newer version, I ran into 
> this new error and thus imported the new intrinsics from intrin.h for rep 
> movsb and friends.  I see several discussions in this thread about how having 
> the registers solely in the inputs list is not sufficient for something like 
> "rep movsb" because the modified registers will not be clobbered, however 
> none of these suggested changes made it into the eventual intrin.h.
>
> I found that using the versions of `__movsb` and `__stosb` that are at the 
> head revision intrin.h produced bad code generation vs the versions with the 
> clobbers.  Note this is on PS4 under the older clang 3.6.1, but I don't see 
> anything in this CL that would update the clobber behavior for newer versions 
> of clang.
>
> Shouldn't the intrinsics be updated to use input/output registers or some 
> other method of clobbering?


Reid created https://reviews.llvm.org/D40686 which addresses this issue.


Repository:
  rL LLVM

https://reviews.llvm.org/D15075



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


[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

2017-12-01 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: test/clang-tidy/nolintnextline.cpp:14
+
+// NOLINTNEXTLINE(not-closed-bracket-is-treated-as-skip-all
+class C2 { C2(int i); };

xgsa wrote:
> JonasToth wrote:
> > missing `)`
> No, it's intentionally: it's a test for case when `)` is missing
It was early, i didn't read properly. Sorry for that.

A testcase for where all parens are missing would be nice, too. I assume that 
everything will be ignored, is that correct?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D40671



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


[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

2017-12-01 Thread Anton via Phabricator via cfe-commits
xgsa added inline comments.



Comment at: test/clang-tidy/nolintnextline.cpp:14
+
+// NOLINTNEXTLINE(not-closed-bracket-is-treated-as-skip-all
+class C2 { C2(int i); };

JonasToth wrote:
> xgsa wrote:
> > JonasToth wrote:
> > > missing `)`
> > No, it's intentionally: it's a test for case when `)` is missing
> It was early, i didn't read properly. Sorry for that.
> 
> A testcase for where all parens are missing would be nice, too. I assume that 
> everything will be ignored, is that correct?
There is such test case (for class "B") or did you mean something else?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D40671



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


[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

2017-12-01 Thread Anton via Phabricator via cfe-commits
xgsa updated this revision to Diff 125084.
xgsa added a comment.
Herald added a subscriber: xazax.hun.

Add comments to code as it was recommended.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D40671

Files:
  clang-tidy/ClangTidyDiagnosticConsumer.cpp
  test/clang-tidy/nolint.cpp
  test/clang-tidy/nolintnextline.cpp

Index: test/clang-tidy/nolint.cpp
===
--- test/clang-tidy/nolint.cpp
+++ test/clang-tidy/nolint.cpp
@@ -13,7 +13,16 @@
 
 class B { B(int i); }; // NOLINT
 
-class C { C(int i); }; // NOLINT(we-dont-care-about-categories-yet)
+class C { C(int i); }; // NOLINT(for-some-other-category)
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit
+
+class C1 { C1(int i); }; // NOLINT(*)
+
+class C2 { C2(int i); }; // NOLINT(not-closed-bracket-is-treated-as-skip-all
+
+class C3 { C3(int i); }; // NOLINT(google-explicit-constructor)
+
+class C4 { C4(int i); }; // NOLINT(some-category, google-explicit-constructor)
 
 void f() {
   int i;
@@ -35,4 +44,4 @@
 #define DOUBLE_MACRO MACRO(H) // NOLINT
 DOUBLE_MACRO
 
-// CHECK-MESSAGES: Suppressed 8 warnings (8 NOLINT)
+// CHECK-MESSAGES: Suppressed 11 warnings (11 NOLINT)
Index: test/clang-tidy/nolintnextline.cpp
===
--- test/clang-tidy/nolintnextline.cpp
+++ test/clang-tidy/nolintnextline.cpp
@@ -4,8 +4,21 @@
 // NOLINTNEXTLINE
 class B { B(int i); };
 
-// NOLINTNEXTLINE(we-dont-care-about-categories-yet)
+// NOLINTNEXTLINE(for-some-other-category)
 class C { C(int i); };
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit
+
+// NOLINTNEXTLINE(*)
+class C1 { C1(int i); };
+
+// NOLINTNEXTLINE(not-closed-bracket-is-treated-as-skip-all
+class C2 { C2(int i); };
+
+// NOLINTNEXTLINE(google-explicit-constructor)
+class C3 { C3(int i); };
+
+// NOLINTNEXTLINE(some-category, google-explicit-constructor)
+class C4 { C4(int i); };
 
 
 // NOLINTNEXTLINE
@@ -28,6 +41,6 @@
 // NOLINTNEXTLINE
 MACRO_NOARG
 
-// CHECK-MESSAGES: Suppressed 4 warnings (4 NOLINT)
+// CHECK-MESSAGES: Suppressed 7 warnings (7 NOLINT)
 
 // RUN: %check_clang_tidy %s google-explicit-constructor %t --
Index: clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -22,6 +22,7 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Frontend/DiagnosticRenderer.h"
 #include "llvm/ADT/SmallString.h"
+#include 
 #include 
 #include 
 using namespace clang;
@@ -289,8 +290,39 @@
   LastErrorRelatesToUserCode = false;
   LastErrorPassesLineFilter = false;
 }
-
-static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) {
+static bool IsNOLINTFound(StringRef NolintMacro, StringRef Line,
+  unsigned DiagID, const ClangTidyContext &Context) {
+  const auto NolintIndex = Line.find(NolintMacro);
+  if (NolintIndex != StringRef::npos) {
+auto BracketIndex = NolintIndex + NolintMacro.size();
+// Check if the specific checks are specified in brackets
+if (BracketIndex < Line.size() && Line[BracketIndex] == '(') {
+  ++BracketIndex;
+  const auto BracketEndIndex = Line.find(')', BracketIndex);
+  if (BracketEndIndex != StringRef::npos) {
+auto ChecksStr =
+Line.substr(BracketIndex, BracketEndIndex - BracketIndex);
+// Allow disabling all the checks with "*"
+if (ChecksStr != "*") {
+  auto CheckName = Context.getCheckName(DiagID);
+  // Allow specifying a few check names, delimited with comma
+  SmallVector Checks;
+  ChecksStr.split(Checks, ',', -1, false);
+  for (auto &Check : Checks) {
+Check = Check.trim();
+  }
+  return std::find(Checks.begin(), Checks.end(), CheckName) !=
+ Checks.end();
+}
+  }
+}
+return true;
+  }
+  return false;
+}
+static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc,
+   unsigned DiagID,
+   const ClangTidyContext &Context) {
   bool Invalid;
   const char *CharacterData = SM.getCharacterData(Loc, &Invalid);
   if (Invalid)
@@ -301,8 +333,7 @@
   while (*P != '\0' && *P != '\r' && *P != '\n')
 ++P;
   StringRef RestOfLine(CharacterData, P - CharacterData + 1);
-  // FIXME: Handle /\bNOLINT\b(\([^)]*\))?/ as cpplint.py does.
-  if (RestOfLine.find("NOLINT") != StringRef::npos)
+  if (IsNOLINTFound("NOLINT", RestOfLine, DiagID, Context))
 return true;
 
   // Check if there's a NOLINTNEXTLINE on the previous line.
@@ -329,16 +360,17 @@
 --P;
 
   RestOfLine = StringRef(P, LineEnd - P + 1);
-  if (RestOfLine.find("NOLINTNEXTLINE") != StringRef::npos)
+  if (IsNOLINTFound("NOLINTNEXTLINE", RestOfLin

[PATCH] D40562: [Sema] Ignore decls in namespaces when global decls are not wanted.

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

In https://reviews.llvm.org/D40562#941570, @arphaman wrote:

> In https://reviews.llvm.org/D40562#940201, @ilya-biryukov wrote:
>
> > In https://reviews.llvm.org/D40562#939950, @arphaman wrote:
> >
> > > This change breaks cached completions for declarations in namespaces in 
> > > libclang. What exactly are you trying to achieve here? We could introduce 
> > > another flag maybe.
> >
> >
> > Am I right to assume this cache is there to reduce the amount of `Decl`s we 
> > need to deserialize from `Preamble`s? Maybe we could fix the cache to also 
> > include namespace-level `Decl`s? It should improve performance of the 
> > cached completions.
>
>
> I'm not actually 100% sure, but I would imagine that this one of the reasons, 
> yes. It would be nice to improve the cache to have things like 
> namespace-level `Decl`, although how will lookup work in that case? Btw, do 
> you think the cache can be reused in clangd as well?


I took a quick look at the completion cache and lookup code. I think the 
completion cache also assumes that top-level decls are only TU-level decls, and 
this assumption seems to be also built into the lookup code. At this point, I 
am inclined to add a separate completion option for what I want 
(`IgnoreDeclsInTUOrNamespaces`?). Regarding cache in clangd, I think it might 
be useful short-term, when we still use Sema's global code completion, but long 
term, we would use symbols from clangd's indexes, so the cache would not be 
useful anymore.


https://reviews.llvm.org/D40562



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


[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

2017-12-01 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: test/clang-tidy/nolintnextline.cpp:14
+
+// NOLINTNEXTLINE(not-closed-bracket-is-treated-as-skip-all
+class C2 { C2(int i); };

xgsa wrote:
> JonasToth wrote:
> > xgsa wrote:
> > > JonasToth wrote:
> > > > missing `)`
> > > No, it's intentionally: it's a test for case when `)` is missing
> > It was early, i didn't read properly. Sorry for that.
> > 
> > A testcase for where all parens are missing would be nice, too. I assume 
> > that everything will be ignored, is that correct?
> There is such test case (for class "B") or did you mean something else?
No i mean an errornous NOLINT.

Like `// NOLINT some_check, othercheck, blaa`. One might expect it to work, but 
the missing parens would inhibit that expected behaviour.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D40671



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


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

2017-12-01 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki created this revision.

[Parser] Diagnose storage classes in template parameter declarations

According to the C++ Standard [temp.param]p2:

  A storage class shall not be specified in a template-parameter
  declaration.

This patch implements a diagnostic for this restriction.


https://reviews.llvm.org/D40705

Files:
  include/clang/Basic/DiagnosticParseKinds.td
  lib/Parse/ParseTemplate.cpp
  test/CXX/temp/temp.param/p2.cpp


Index: test/CXX/temp/temp.param/p2.cpp
===
--- test/CXX/temp/temp.param/p2.cpp
+++ test/CXX/temp/temp.param/p2.cpp
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-// expected-no-diagnostics
 
 // There is no semantic difference between class and typename in a
 // template-parameter. typename followed by an unqualified-id names a
@@ -13,7 +12,8 @@
 template::type Value> struct Y1;
 
 // A storage class shall not be specified in a template-parameter declaration.
-template struct Z; // FIXME: expect an error
+template struct Z0; // expected-error {{storage class 
specified for template parameter 'Value'}}
+template struct Z1; // expected-error {{storage class specified 
for template parameter}}
 
 // Make sure that we properly disambiguate non-type template parameters that
 // start with 'class'.
Index: lib/Parse/ParseTemplate.cpp
===
--- lib/Parse/ParseTemplate.cpp
+++ lib/Parse/ParseTemplate.cpp
@@ -686,6 +686,22 @@
 return nullptr;
   }
 
+  // C++ [temp.param]p2:
+  //   A storage class shall not be specified in a template-parameter
+  //   declaration.
+  auto ReportStorageClass = [&](SourceLocation Loc) {
+if (ParamDecl.getIdentifier())
+  Diag(Loc, diag::err_storage_class_template_parameter)
+<< ParamDecl.getIdentifier() << FixItHint::CreateRemoval(Loc);
+else
+  Diag(Loc, diag::err_storage_class_template_parameter_anon)
+<< FixItHint::CreateRemoval(Loc);
+  };
+  if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
+ReportStorageClass(DS.getStorageClassSpecLoc());
+  if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified)
+ReportStorageClass(DS.getThreadStorageClassSpecLoc());
+
   // Recover from misplaced ellipsis.
   SourceLocation EllipsisLoc;
   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Index: include/clang/Basic/DiagnosticParseKinds.td
===
--- include/clang/Basic/DiagnosticParseKinds.td
+++ include/clang/Basic/DiagnosticParseKinds.td
@@ -668,6 +668,11 @@
 def warn_missing_dependent_template_keyword : ExtWarn<
   "use 'template' keyword to treat '%0' as a dependent template name">;
 
+def err_storage_class_template_parameter : Error<
+  "storage class specified for template parameter %0">;
+def err_storage_class_template_parameter_anon : Error<
+  "storage class specified for template parameter">;
+
 def ext_extern_template : Extension<
   "extern templates are a C++11 extension">, InGroup;
 def warn_cxx98_compat_extern_template : Warning<


Index: test/CXX/temp/temp.param/p2.cpp
===
--- test/CXX/temp/temp.param/p2.cpp
+++ test/CXX/temp/temp.param/p2.cpp
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-// expected-no-diagnostics
 
 // There is no semantic difference between class and typename in a
 // template-parameter. typename followed by an unqualified-id names a
@@ -13,7 +12,8 @@
 template::type Value> struct Y1;
 
 // A storage class shall not be specified in a template-parameter declaration.
-template struct Z; // FIXME: expect an error
+template struct Z0; // expected-error {{storage class specified for template parameter 'Value'}}
+template struct Z1; // expected-error {{storage class specified for template parameter}}
 
 // Make sure that we properly disambiguate non-type template parameters that
 // start with 'class'.
Index: lib/Parse/ParseTemplate.cpp
===
--- lib/Parse/ParseTemplate.cpp
+++ lib/Parse/ParseTemplate.cpp
@@ -686,6 +686,22 @@
 return nullptr;
   }
 
+  // C++ [temp.param]p2:
+  //   A storage class shall not be specified in a template-parameter
+  //   declaration.
+  auto ReportStorageClass = [&](SourceLocation Loc) {
+if (ParamDecl.getIdentifier())
+  Diag(Loc, diag::err_storage_class_template_parameter)
+<< ParamDecl.getIdentifier() << FixItHint::CreateRemoval(Loc);
+else
+  Diag(Loc, diag::err_storage_class_template_parameter_anon)
+<< FixItHint::CreateRemoval(Loc);
+  };
+  if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
+ReportStorageClass(DS.getStorageClassSpecLoc());
+  if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified)
+ReportStorageClass(DS.getThreadStorageClassSpecLoc());
+
   // Recover from misplaced ellipsis.
   SourceLocation EllipsisLoc;
   if (TryC

[PATCH] D40562: [Sema] Ignore decls in namespaces when global decls are not wanted.

2017-12-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In https://reviews.llvm.org/D40562#941570, @arphaman wrote:

> I'm not actually 100% sure, but I would imagine that this one of the reasons, 
> yes. It would be nice to improve the cache to have things like 
> namespace-level `Decl`, although how will lookup work in that case? Btw, do 
> you think the cache can be reused in clangd as well?


As Eric mentioned, we are planning to have project-global completion for 
namespace-level Decls (to have completion items not #included in the current 
file and add the #include directive properly).  So the cache is probably not 
that useful to clangd long-term.
For proper lookup in the cache that include all namespace-level Decls I'd go 
with tweaking `LookupVisibleDecls` so that it does not deserialize everything 
from the preamble, but rather provides a list of scopes that we need to get 
completion items from. Though sounds simple, it may be a non-trivial change and 
we shouldn't probably pursue it as part of this change.
(We'll probably need it for clangd too).

In https://reviews.llvm.org/D40562#941735, @ioeric wrote:

> I took a quick look at the completion cache and lookup code. I think the 
> completion cache also assumes that top-level decls are only TU-level decls, 
> and this assumption seems to be also built into the lookup code. At this 
> point, I am inclined to add a separate completion option for what I want 
> (`IgnoreDeclsInTUOrNamespaces`?). Regarding cache in clangd, I think it might 
> be useful short-term, when we still use Sema's global code completion, but 
> long term, we would use symbols from clangd's indexes, so the cache would not 
> be useful anymore.


+1 for having a separate flag. Maybe call it `IncludeNamespaceLevelDecls` 
instead? (I'd say TU is also a (global) namespace from completion's point of 
view).


https://reviews.llvm.org/D40562



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


[PATCH] D40707: [libcxx] Fix basic_stringbuf constructor

2017-12-01 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki created this revision.

[libcxx] Fix basic_stringbuf constructor

The C++ Standard [stringbuf.cons]p1 defines the effects of the basic_stringbuf
constructor that takes ios_base::openmode as follows:

  Effects: Constructs an object of class basic_stringbuf, initializing the
  base class with basic_streambuf(), and initializing mode with which.
  Postconditions: str() == "".

The default constructor of basic_streambuf shall initialize all its
pointer member objects to null pointers [streambuf.cons]p1.

Currently libc++ calls "str(string_type());" in the aforementioned constructor
setting basic_streambuf's pointers to a non-null value.

This patch removes the call (note that the postcondition str() == ""
remains valid because __str_ is default-initialized) and adds a test checking
that the basic_streambuf's pointers are null after construction.


https://reviews.llvm.org/D40707

Files:
  include/sstream
  test/std/input.output/string.streams/stringbuf/stringbuf.cons/default.pass.cpp


Index: 
test/std/input.output/string.streams/stringbuf/stringbuf.cons/default.pass.cpp
===
--- 
test/std/input.output/string.streams/stringbuf/stringbuf.cons/default.pass.cpp
+++ 
test/std/input.output/string.streams/stringbuf/stringbuf.cons/default.pass.cpp
@@ -17,6 +17,21 @@
 #include 
 #include 
 
+template
+struct testbuf
+: std::basic_stringbuf
+{
+void check()
+{
+assert(this->eback() == 0);
+assert(this->gptr() == 0);
+assert(this->egptr() == 0);
+assert(this->pbase() == 0);
+assert(this->pptr() == 0);
+assert(this->epptr() == 0);
+}
+};
+
 int main()
 {
 {
@@ -27,4 +42,12 @@
 std::wstringbuf buf;
 assert(buf.str() == L"");
 }
+{
+testbuf buf;
+buf.check();
+}
+{
+testbuf buf;
+buf.check();
+}
 }
Index: include/sstream
===
--- include/sstream
+++ include/sstream
@@ -243,7 +243,6 @@
 : __hm_(0),
   __mode_(__wch)
 {
-str(string_type());
 }
 
 template 


Index: test/std/input.output/string.streams/stringbuf/stringbuf.cons/default.pass.cpp
===
--- test/std/input.output/string.streams/stringbuf/stringbuf.cons/default.pass.cpp
+++ test/std/input.output/string.streams/stringbuf/stringbuf.cons/default.pass.cpp
@@ -17,6 +17,21 @@
 #include 
 #include 
 
+template
+struct testbuf
+: std::basic_stringbuf
+{
+void check()
+{
+assert(this->eback() == 0);
+assert(this->gptr() == 0);
+assert(this->egptr() == 0);
+assert(this->pbase() == 0);
+assert(this->pptr() == 0);
+assert(this->epptr() == 0);
+}
+};
+
 int main()
 {
 {
@@ -27,4 +42,12 @@
 std::wstringbuf buf;
 assert(buf.str() == L"");
 }
+{
+testbuf buf;
+buf.check();
+}
+{
+testbuf buf;
+buf.check();
+}
 }
Index: include/sstream
===
--- include/sstream
+++ include/sstream
@@ -243,7 +243,6 @@
 : __hm_(0),
   __mode_(__wch)
 {
-str(string_type());
 }
 
 template 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D40605: Better trade-off for excess characters vs. staying within the column limits.

2017-12-01 Thread Manuel Klimek via Phabricator via cfe-commits
klimek updated this revision to Diff 125094.
klimek marked an inline comment as done.
klimek added a comment.

Add test.


Repository:
  rC Clang

https://reviews.llvm.org/D40605

Files:
  lib/Format/ContinuationIndenter.cpp
  lib/Format/ContinuationIndenter.h
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -9934,8 +9934,8 @@
   Style.PenaltyExcessCharacter = 90;
   verifyFormat("int a; // the comment", Style);
   EXPECT_EQ("int a; // the comment\n"
-"   // aa",
-format("int a; // the comment aa", Style));
+"   // aaa",
+format("int a; // the comment aaa", Style));
   EXPECT_EQ("int a; /* first line\n"
 "* second line\n"
 "* third line\n"
@@ -9963,14 +9963,14 @@
Style));
 
   EXPECT_EQ("// foo bar baz bazfoo\n"
-"// foo bar\n",
+"// foo bar foo bar\n",
 format("// foo bar baz bazfoo\n"
-   "// foobar\n",
+   "// foo bar foo   bar\n",
Style));
   EXPECT_EQ("// foo bar baz bazfoo\n"
-"// foo bar\n",
+"// foo bar foo bar\n",
 format("// foo bar baz  bazfoo\n"
-   "// foobar\n",
+   "// foobar foo bar\n",
Style));
 
   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
@@ -9996,6 +9996,20 @@
"// foo bar baz  bazfoo bar\n"
"// foo   bar\n",
Style));
+
+  // Make sure we do not keep protruding characters if strict mode reflow is
+  // cheaper than keeping protruding characters.
+  Style.ColumnLimit = 21;
+  EXPECT_EQ("// foo foo foo foo\n"
+"// foo foo foo foo\n"
+"// foo foo foo foo\n",
+format("// foo foo foo foo foo foo foo foo foo foo foo foo\n",
+   Style));
+
+  EXPECT_EQ("int a = /* long block\n"
+"   comment */\n"
+"42;",
+format("int a = /* long block comment */ 42;", Style));
 }
 
 #define EXPECT_ALL_STYLES_EQUAL(Styles)\
Index: lib/Format/ContinuationIndenter.h
===
--- lib/Format/ContinuationIndenter.h
+++ lib/Format/ContinuationIndenter.h
@@ -123,14 +123,25 @@
   /// \brief If the current token sticks out over the end of the line, break
   /// it if possible.
   ///
-  /// \returns An extra penalty if a token was broken, otherwise 0.
+  /// \returns A pair (penalty, exceeded), where penalty is the extra penalty
+  /// when tokens are broken or lines exceed the column limit, and exceeded
+  /// indicates whether the algorithm purposefully left lines exceeding the
+  /// column limit.
   ///
   /// The returned penalty will cover the cost of the additional line breaks
   /// and column limit violation in all lines except for the last one. The
   /// penalty for the column limit violation in the last line (and in single
   /// line tokens) is handled in \c addNextStateToQueue.
-  unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
-bool AllowBreak, bool DryRun);
+  ///
+  /// \p Strict indicates whether reflowing is allowed to leave characters
+  /// protruding the column limit; if true, lines will be split strictly within
+  /// the column limit where possible; if false, words are allowed to protrude
+  /// over the column limit as long as the penalty is less than the penalty
+  /// of a break.
+  std::pair breakProtrudingToken(const FormatToken &Current,
+ LineState &State,
+ bool AllowBreak, bool DryRun,
+ bool Strict);
 
   /// \brief Returns the \c BreakableToken starting at \p Current, or nullptr
   /// if the current token cannot be broken.
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1390,7 +1390,36 @@
 Penalty = addMultilineToken(Current, State);
   } else if (State.Line->Type != LT_ImportStatement) {
 // We generally don't break import statements.
-Penalty = breakProtrudingToken(Current, State, AllowBreak, DryRun);
+LineState OriginalState = State;
+
+// Whether we force the reflowing algorithm to stay strictly within the
+// column limit.
+bool Strict = false;
+// Whether the first non-strict attempt at reflowing did intentionally
+// exceed the column limit.
+bool Exceeded = false;
+std::tie(Penalty, 

[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

2017-12-01 Thread Anton via Phabricator via cfe-commits
xgsa updated this revision to Diff 125096.
xgsa added a comment.

A few additional test cases were added.


https://reviews.llvm.org/D40671

Files:
  clang-tidy/ClangTidyDiagnosticConsumer.cpp
  test/clang-tidy/nolint.cpp
  test/clang-tidy/nolintnextline.cpp

Index: test/clang-tidy/nolint.cpp
===
--- test/clang-tidy/nolint.cpp
+++ test/clang-tidy/nolint.cpp
@@ -13,7 +13,18 @@
 
 class B { B(int i); }; // NOLINT
 
-class C { C(int i); }; // NOLINT(we-dont-care-about-categories-yet)
+class C { C(int i); }; // NOLINT(for-some-other-check)
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit
+
+class C1 { C1(int i); }; // NOLINT(*)
+
+class C2 { C2(int i); }; // NOLINT(not-closed-bracket-is-treated-as-skip-all
+
+class C3 { C3(int i); }; // NOLINT(google-explicit-constructor)
+
+class C4 { C4(int i); }; // NOLINT(some-check, google-explicit-constructor)
+
+class C5 { C5(int i); }; // NOLINT without-brackets-skip-all, another-check
 
 void f() {
   int i;
@@ -35,4 +46,4 @@
 #define DOUBLE_MACRO MACRO(H) // NOLINT
 DOUBLE_MACRO
 
-// CHECK-MESSAGES: Suppressed 8 warnings (8 NOLINT)
+// CHECK-MESSAGES: Suppressed 12 warnings (12 NOLINT)
Index: test/clang-tidy/nolintnextline.cpp
===
--- test/clang-tidy/nolintnextline.cpp
+++ test/clang-tidy/nolintnextline.cpp
@@ -4,8 +4,24 @@
 // NOLINTNEXTLINE
 class B { B(int i); };
 
-// NOLINTNEXTLINE(we-dont-care-about-categories-yet)
+// NOLINTNEXTLINE(for-some-other-check)
 class C { C(int i); };
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit
+
+// NOLINTNEXTLINE(*)
+class C1 { C1(int i); };
+
+// NOLINTNEXTLINE(not-closed-bracket-is-treated-as-skip-all
+class C2 { C2(int i); };
+
+// NOLINTNEXTLINE(google-explicit-constructor)
+class C3 { C3(int i); };
+
+// NOLINTNEXTLINE(some-check, google-explicit-constructor)
+class C4 { C4(int i); };
+
+// NOLINTNEXTLINE without-brackets-skip-all, another-check
+class C5 { C5(int i); };
 
 
 // NOLINTNEXTLINE
@@ -28,6 +44,6 @@
 // NOLINTNEXTLINE
 MACRO_NOARG
 
-// CHECK-MESSAGES: Suppressed 4 warnings (4 NOLINT)
+// CHECK-MESSAGES: Suppressed 8 warnings (8 NOLINT)
 
 // RUN: %check_clang_tidy %s google-explicit-constructor %t --
Index: clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -22,6 +22,7 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Frontend/DiagnosticRenderer.h"
 #include "llvm/ADT/SmallString.h"
+#include 
 #include 
 #include 
 using namespace clang;
@@ -289,8 +290,39 @@
   LastErrorRelatesToUserCode = false;
   LastErrorPassesLineFilter = false;
 }
-
-static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) {
+static bool IsNOLINTFound(StringRef NolintMacro, StringRef Line,
+  unsigned DiagID, const ClangTidyContext &Context) {
+  const auto NolintIndex = Line.find(NolintMacro);
+  if (NolintIndex != StringRef::npos) {
+auto BracketIndex = NolintIndex + NolintMacro.size();
+// Check if the specific checks are specified in brackets
+if (BracketIndex < Line.size() && Line[BracketIndex] == '(') {
+  ++BracketIndex;
+  const auto BracketEndIndex = Line.find(')', BracketIndex);
+  if (BracketEndIndex != StringRef::npos) {
+auto ChecksStr =
+Line.substr(BracketIndex, BracketEndIndex - BracketIndex);
+// Allow disabling all the checks with "*"
+if (ChecksStr != "*") {
+  auto CheckName = Context.getCheckName(DiagID);
+  // Allow specifying a few check names, delimited with comma
+  SmallVector Checks;
+  ChecksStr.split(Checks, ',', -1, false);
+  for (auto &Check : Checks) {
+Check = Check.trim();
+  }
+  return std::find(Checks.begin(), Checks.end(), CheckName) !=
+ Checks.end();
+}
+  }
+}
+return true;
+  }
+  return false;
+}
+static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc,
+   unsigned DiagID,
+   const ClangTidyContext &Context) {
   bool Invalid;
   const char *CharacterData = SM.getCharacterData(Loc, &Invalid);
   if (Invalid)
@@ -301,8 +333,7 @@
   while (*P != '\0' && *P != '\r' && *P != '\n')
 ++P;
   StringRef RestOfLine(CharacterData, P - CharacterData + 1);
-  // FIXME: Handle /\bNOLINT\b(\([^)]*\))?/ as cpplint.py does.
-  if (RestOfLine.find("NOLINT") != StringRef::npos)
+  if (IsNOLINTFound("NOLINT", RestOfLine, DiagID, Context))
 return true;
 
   // Check if there's a NOLINTNEXTLINE on the previous line.
@@ -329,16 +360,17 @@
 --P;
 
   RestOfLine = StringRef(P, LineEnd - P + 1);
-  if (RestOfLine.find("NOLINTNEXT

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

2017-12-01 Thread Faisal Vali via Phabricator via cfe-commits
faisalv added inline comments.



Comment at: lib/Parse/ParseTemplate.cpp:692
+  //   declaration.
+  auto ReportStorageClass = [&](SourceLocation Loc) {
+if (ParamDecl.getIdentifier())

I tend to prefer explicit captures (unless you have a good reason?) - favoring 
a clearer description of intention - and acknowledgement of required context - 
over programming convenience ...  


https://reviews.llvm.org/D40705



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


[PATCH] D40712: Add cc1 flag enabling the function stack size section that was added in r319430

2017-12-01 Thread Sean Eveson via Phabricator via cfe-commits
seaneveson created this revision.

Adds the -fstack-size-section flag to enable the .stack_sizes section. The flag 
defaults to on for the PS4 triple.

Follow up change from: https://reviews.llvm.org/D39788

Original RFC: http://lists.llvm.org/pipermail/llvm-dev/2017-August/117028.html


https://reviews.llvm.org/D40712

Files:
  include/clang/Driver/Options.td
  include/clang/Frontend/CodeGenOptions.def
  lib/CodeGen/BackendUtil.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/Driver/stack-size-section.c


Index: test/Driver/stack-size-section.c
===
--- test/Driver/stack-size-section.c
+++ test/Driver/stack-size-section.c
@@ -0,0 +1,11 @@
+// RUN: %clang -target x86_64-unknown %s -S -o %t
+// RUN: not grep '.stack_sizes' %t
+// RUN: %clang -target x86_64-unknown -fstack-size-section %s -S -o %t
+// RUN: grep '.stack_sizes' %t
+
+// RUN: %clang -target x86_64-scei-ps4 %s -S -o %t
+// RUN: grep '.stack_sizes' %t
+// RUN: %clang -target x86_64-scei-ps4 -fno-stack-size-section %s -S -o %t
+// RUN: not grep '.stack_sizes' %t
+
+int foo() { return 42; }
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -681,6 +681,8 @@
OPT_fno_function_sections, false);
   Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
OPT_fno_data_sections, false);
+  Opts.StackSizeSection = Args.hasFlag(
+  OPT_fstack_size_section, OPT_fno_stack_size_section, Triple.isPS4());
   Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
  OPT_fno_unique_section_names, true);
 
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3775,6 +3775,12 @@
 CmdArgs.push_back(A->getValue());
   }
 
+  if (Args.hasFlag(options::OPT_fstack_size_section,
+   options::OPT_fno_stack_size_section, RawTriple.isPS4()))
+CmdArgs.push_back("-fstack-size-section");
+  else
+CmdArgs.push_back("-fno-stack-size-section");
+
   CmdArgs.push_back("-ferror-limit");
   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
 CmdArgs.push_back(A->getValue());
Index: lib/CodeGen/BackendUtil.cpp
===
--- lib/CodeGen/BackendUtil.cpp
+++ lib/CodeGen/BackendUtil.cpp
@@ -439,6 +439,7 @@
   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
+  Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
 
   if (CodeGenOpts.EnableSplitDwarf)
 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Index: include/clang/Frontend/CodeGenOptions.def
===
--- include/clang/Frontend/CodeGenOptions.def
+++ include/clang/Frontend/CodeGenOptions.def
@@ -83,6 +83,7 @@
 
 CODEGENOPT(XRayInstrumentFunctions , 1, 0) ///< Set when -fxray-instrument is
///< enabled.
+CODEGENOPT(StackSizeSection  , 1, 0) ///< Set when -fstack-size-section is 
enabled.
 
 ///< Set when -fxray-always-emit-customevents is enabled.
 CODEGENOPT(XRayAlwaysEmitCustomEvents , 1, 0)
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1564,6 +1564,10 @@
  Flags<[CC1Option]>, HelpText<"Place each data in its own section (ELF Only)">;
 def fno_data_sections : Flag <["-"], "fno-data-sections">, Group,
   Flags<[CC1Option]>;
+def fstack_size_section : Flag<["-"], "fstack-size-section">, Group, 
Flags<[CC1Option]>,
+  HelpText<"Emit section containing metadata on function stack sizes">;
+def fno_stack_size_section : Flag<["-"], "fno-stack-size-section">, 
Group, Flags<[CC1Option]>,
+  HelpText<"Don't emit section containing metadata on function stack sizes">;
 
 def funique_section_names : Flag <["-"], "funique-section-names">,
   Group, Flags<[CC1Option]>,


Index: test/Driver/stack-size-section.c
===
--- test/Driver/stack-size-section.c
+++ test/Driver/stack-size-section.c
@@ -0,0 +1,11 @@
+// RUN: %clang -target x86_64-unknown %s -S -o %t
+// RUN: not grep '.stack_sizes' %t
+// RUN: %clang -target x86_64-unknown -fstack-size-section %s -S -o %t
+// RUN: grep '.stack_sizes' %t
+
+// RUN: %clang -target x86_64-scei-ps4 %s -S -o %t
+// RUN: grep '.stack_sizes' %t
+// RUN: %clang -target x86_64-scei-ps4 -fno-stack-size-section %s -S -o %t
+// RUN: not grep '.stack_sizes' %t
+
+int foo() { return 42; }
Index: 

[PATCH] D40715: [analyser] different.LabelInsideSwitch checker implementation

2017-12-01 Thread Alexey Knyshev via Phabricator via cfe-commits
alexey.knyshev created this revision.
alexey.knyshev added a project: clang.
Herald added subscribers: cfe-commits, mgorny.

Implementation of checker "different.LabelInsideSwitch" from potential checkers 
list (https://clang-analyzer.llvm.org/potential_checkers.html#different)


Repository:
  rC Clang

https://reviews.llvm.org/D40715

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/LabelInsideSwitchChecker.cpp
  test/Analysis/label-inside-switch.c

Index: test/Analysis/label-inside-switch.c
===
--- test/Analysis/label-inside-switch.c
+++ test/Analysis/label-inside-switch.c
@@ -0,0 +1,57 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core.LabelInsideSwitch -w -verify %s
+
+int caseAnddefaultMissprint(unsigned count) {
+  int res = 0;
+  switch(count) {
+  case 1:
+res = 1;
+break;
+  cas: // expected-warning {{label inside switch (did you mean 'case'?)}}
+  case 2:
+res = 5;
+break;
+  case 3:
+exit(1);
+  defaul: // expected-warning {{label inside switch (did you mean 'default'?)}}
+return -1;
+  }
+
+  return res;
+}
+
+int nestedSwitch(unsigned x, unsigned y) {
+  int res = 0;
+  switch (x) {
+  case 1:
+res = 1;
+break;
+  case 2:
+res = 5;
+break;
+  case 3:
+switch(y) {
+case 1:
+case 2:
+case 4:
+  res = x * y;
+  break;
+defaul:; // expected-warning {{label inside switch (did you mean 'default'?)}}
+}
+break;
+  default:;
+  }
+
+  return res;
+}
+
+int arbitaryLabelInSwitch(int arg) {
+  switch (arg)  {
+  case 1:
+  case 2:
+  label: // expected-warning {{label inside switch}}
+  case 3:
+break;
+  }
+
+  return 0;
+}
Index: lib/StaticAnalyzer/Checkers/LabelInsideSwitchChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/LabelInsideSwitchChecker.cpp
+++ lib/StaticAnalyzer/Checkers/LabelInsideSwitchChecker.cpp
@@ -0,0 +1,121 @@
+#include "clang/AST/StmtVisitor.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+  class LabelInsideSwitchChecker : public Checker< check::ASTCodeBody > {
+  public:
+void checkASTCodeBody(const Decl *D, AnalysisManager &mgr, BugReporter &BR) const;
+  };
+
+  static std::pair Suggest(const StringRef &Str, StringRef Exp);
+  static std::pair SuggestTypoFix(const StringRef &Str) {
+const auto S = Suggest(Str, "default");
+if (S.second)
+  return S;
+
+return Suggest(Str, "case");
+  }
+
+  class WalkAST : public ConstStmtVisitor {
+const CheckerBase *Checker;
+BugReporter &BR;
+AnalysisDeclContext *AC;
+
+  public:
+WalkAST(const CheckerBase *Checker, BugReporter &BR, AnalysisDeclContext *AC)
+: Checker(Checker), BR(BR), AC(AC) {}
+
+// Statement visitor methods.
+void VisitChildren(const Stmt *S, bool InSwitch) {
+  for (const Stmt *Child : S->children())
+if (Child)
+  Visit(Child, InSwitch);
+}
+
+void VisitStmt(const Stmt *S, bool InSwitch) {
+  if (!InSwitch && isa(S)) {
+InSwitch = true;
+  } else if (InSwitch && isa(S)) {
+const LabelStmt *L = cast(S);
+const auto Sug = SuggestTypoFix(L->getName());
+
+SmallString<256> SBuf;
+llvm::raw_svector_ostream OS(SBuf);
+OS << "label inside switch";
+if (Sug.second) {
+  OS << " (did you mean '" << Sug.first << "'?)";
+}
+
+PathDiagnosticLocation Loc =
+  PathDiagnosticLocation::createBegin(S, BR.getSourceManager(), AC);
+SourceRange Sr[1];
+Sr[0] = S->getSourceRange();
+BR.EmitBasicReport(AC->getDecl(), Checker, "Labeled statement inside switch",
+   categories::LogicError, OS.str(), Loc, Sr);
+  }
+  VisitChildren(S, InSwitch);
+}
+  };
+
+  std::pair Suggest(const StringRef &Str, StringRef Exp) {
+const size_t StrSize = Str.size();
+const size_t ExpSize = Exp.size();
+
+assert(StrSize);
+assert(ExpSize);
+
+size_t SizeDelta = 0;
+size_t MinSize = StrSize;
+
+if (StrSize < ExpSize) {
+  SizeDelta = ExpSize - StrSize;
+} else if (StrSize > ExpSize) {
+  SizeDelta = StrSize - ExpSize;
+  MinSize = ExpSize;
+}
+
+// We only accept size delta <= 1
+if (SizeDelta > 1)
+return std::make_pair("", false);
+
+size_t SameSymCount = 0;
+for (size_t i = 0; i < MinSize; i++)
+  if (Str[i] == Exp[i])
+SameSymCount++;
+
+if (SameSymCount > 0 && SameSymCount - SizeDelta >= ExpSize / 2)
+  return std::make_pair(Exp, true);
+
+// Str & Exp have the same size. No sence to check from back to front
+if (SizeDelta =

[PATCH] D38921: [analyzer] LoopUnrolling: update the matched assignment operators

2017-12-01 Thread Peter Szecsi via Phabricator via cfe-commits
szepet added reviewers: alexfh, aaron.ballman.
szepet added a comment.

Added Alexander and Aaron as reviewers for the matcher parts.


https://reviews.llvm.org/D38921



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


r319541 - Better trade-off for excess characters vs. staying within the column limits.

2017-12-01 Thread Manuel Klimek via cfe-commits
Author: klimek
Date: Fri Dec  1 05:28:08 2017
New Revision: 319541

URL: http://llvm.org/viewvc/llvm-project?rev=319541&view=rev
Log:
Better trade-off for excess characters vs. staying within the column limits.

When we break a long line like:
Column limit: 21
  |
  // foo foo foo foo foo foo foo foo foo foo foo foo

The local decision when to allow protruding vs. breaking can lead to this
outcome (2 excess characters, 2 breaks):
  // foo foo foo foo foo
  // foo foo foo foo foo
  // foo foo

While strictly staying within the column limit leads to this strictly better
outcome (fully below the column limit, 2 breaks):
  // foo foo foo foo
  // foo foo foo foo
  // foo foo foo foo

To get an optimal solution, we would need to consider all combinations of excess
characters vs. breaking for all lines, but that would lead to a significant
increase in the search space of the algorithm for little gain.

Instead, we blindly try both approches and·select the one that leads to the
overall lower penalty.

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

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/ContinuationIndenter.h
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=319541&r1=319540&r2=319541&view=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Fri Dec  1 05:28:08 2017
@@ -1390,7 +1390,36 @@ unsigned ContinuationIndenter::handleEnd
 Penalty = addMultilineToken(Current, State);
   } else if (State.Line->Type != LT_ImportStatement) {
 // We generally don't break import statements.
-Penalty = breakProtrudingToken(Current, State, AllowBreak, DryRun);
+LineState OriginalState = State;
+
+// Whether we force the reflowing algorithm to stay strictly within the
+// column limit.
+bool Strict = false;
+// Whether the first non-strict attempt at reflowing did intentionally
+// exceed the column limit.
+bool Exceeded = false;
+std::tie(Penalty, Exceeded) = breakProtrudingToken(
+Current, State, AllowBreak, /*DryRun=*/true, Strict);
+if (Exceeded) {
+  // If non-strict reflowing exceeds the column limit, try whether strict
+  // reflowing leads to an overall lower penalty.
+  LineState StrictState = OriginalState;
+  unsigned StrictPenalty =
+  breakProtrudingToken(Current, StrictState, AllowBreak,
+   /*DryRun=*/true, /*Strict=*/true)
+  .first;
+  Strict = StrictPenalty <= Penalty;
+  if (Strict) {
+Penalty = StrictPenalty;
+State = StrictState;
+  }
+}
+if (!DryRun) {
+  // If we're not in dry-run mode, apply the changes with the decision on
+  // strictness made above.
+  breakProtrudingToken(Current, OriginalState, AllowBreak, 
/*DryRun=*/false,
+   Strict);
+}
   }
   if (State.Column > getColumnLimit(State)) {
 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
@@ -1480,14 +1509,14 @@ std::unique_ptr Continua
   return nullptr;
 }
 
-unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
-LineState &State,
-bool AllowBreak,
-bool DryRun) {
+std::pair
+ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
+   LineState &State, bool AllowBreak,
+   bool DryRun, bool Strict) {
   std::unique_ptr Token =
   createBreakableToken(Current, State, AllowBreak);
   if (!Token)
-return 0;
+return {0, false};
   assert(Token->getLineCount() > 0);
   unsigned ColumnLimit = getColumnLimit(State);
   if (Current.is(TT_LineComment)) {
@@ -1495,13 +1524,16 @@ unsigned ContinuationIndenter::breakProt
 ColumnLimit = Style.ColumnLimit;
   }
   if (Current.UnbreakableTailLength >= ColumnLimit)
-return 0;
+return {0, false};
   // ColumnWidth was already accounted into State.Column before calling
   // breakProtrudingToken.
   unsigned StartColumn = State.Column - Current.ColumnWidth;
   unsigned NewBreakPenalty = Current.isStringLiteral()
  ? Style.PenaltyBreakString
  : Style.PenaltyBreakComment;
+  // Stores whether we intentionally decide to let a line exceed the column
+  // limit.
+  bool Exceeded = false;
   // Stores whether we introduce a break anywhere in the token.
   bool BreakInserted = Token->introducesBreakBeforeToken();
   // Store whether we inserted a new line break at the end of the previous
@@ -1612

[PATCH] D40605: Better trade-off for excess characters vs. staying within the column limits.

2017-12-01 Thread Manuel Klimek via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL319541: Better trade-off for excess characters vs. staying 
within the column limits. (authored by klimek).

Repository:
  rL LLVM

https://reviews.llvm.org/D40605

Files:
  cfe/trunk/lib/Format/ContinuationIndenter.cpp
  cfe/trunk/lib/Format/ContinuationIndenter.h
  cfe/trunk/unittests/Format/FormatTest.cpp

Index: cfe/trunk/lib/Format/ContinuationIndenter.h
===
--- cfe/trunk/lib/Format/ContinuationIndenter.h
+++ cfe/trunk/lib/Format/ContinuationIndenter.h
@@ -123,14 +123,25 @@
   /// \brief If the current token sticks out over the end of the line, break
   /// it if possible.
   ///
-  /// \returns An extra penalty if a token was broken, otherwise 0.
+  /// \returns A pair (penalty, exceeded), where penalty is the extra penalty
+  /// when tokens are broken or lines exceed the column limit, and exceeded
+  /// indicates whether the algorithm purposefully left lines exceeding the
+  /// column limit.
   ///
   /// The returned penalty will cover the cost of the additional line breaks
   /// and column limit violation in all lines except for the last one. The
   /// penalty for the column limit violation in the last line (and in single
   /// line tokens) is handled in \c addNextStateToQueue.
-  unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
-bool AllowBreak, bool DryRun);
+  ///
+  /// \p Strict indicates whether reflowing is allowed to leave characters
+  /// protruding the column limit; if true, lines will be split strictly within
+  /// the column limit where possible; if false, words are allowed to protrude
+  /// over the column limit as long as the penalty is less than the penalty
+  /// of a break.
+  std::pair breakProtrudingToken(const FormatToken &Current,
+ LineState &State,
+ bool AllowBreak, bool DryRun,
+ bool Strict);
 
   /// \brief Returns the \c BreakableToken starting at \p Current, or nullptr
   /// if the current token cannot be broken.
Index: cfe/trunk/lib/Format/ContinuationIndenter.cpp
===
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp
@@ -1390,7 +1390,36 @@
 Penalty = addMultilineToken(Current, State);
   } else if (State.Line->Type != LT_ImportStatement) {
 // We generally don't break import statements.
-Penalty = breakProtrudingToken(Current, State, AllowBreak, DryRun);
+LineState OriginalState = State;
+
+// Whether we force the reflowing algorithm to stay strictly within the
+// column limit.
+bool Strict = false;
+// Whether the first non-strict attempt at reflowing did intentionally
+// exceed the column limit.
+bool Exceeded = false;
+std::tie(Penalty, Exceeded) = breakProtrudingToken(
+Current, State, AllowBreak, /*DryRun=*/true, Strict);
+if (Exceeded) {
+  // If non-strict reflowing exceeds the column limit, try whether strict
+  // reflowing leads to an overall lower penalty.
+  LineState StrictState = OriginalState;
+  unsigned StrictPenalty =
+  breakProtrudingToken(Current, StrictState, AllowBreak,
+   /*DryRun=*/true, /*Strict=*/true)
+  .first;
+  Strict = StrictPenalty <= Penalty;
+  if (Strict) {
+Penalty = StrictPenalty;
+State = StrictState;
+  }
+}
+if (!DryRun) {
+  // If we're not in dry-run mode, apply the changes with the decision on
+  // strictness made above.
+  breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
+   Strict);
+}
   }
   if (State.Column > getColumnLimit(State)) {
 unsigned ExcessCharacters = State.Column - getColumnLimit(State);
@@ -1480,28 +1509,31 @@
   return nullptr;
 }
 
-unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
-LineState &State,
-bool AllowBreak,
-bool DryRun) {
+std::pair
+ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
+   LineState &State, bool AllowBreak,
+   bool DryRun, bool Strict) {
   std::unique_ptr Token =
   createBreakableToken(Current, State, AllowBreak);
   if (!Token)
-return 0;
+return {0, false};
   assert(Token->getLineCount() > 0);
   unsigned ColumnLimit = getColumnLimit(State);
   if (Current.is(TT_LineComment)) {
 // We don't insert backslashes when breaking line comments.
 ColumnLimit = Style.ColumnLimit;

[PATCH] D38921: [analyzer] LoopUnrolling: update the matched assignment operators

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

Aside from a request for another test, the matcher parts LGTM.




Comment at: unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp:1992
+  EXPECT_TRUE(matches("void x() { int a; a &= 3; }", AsOperator));
+  EXPECT_TRUE(notMatches("void x() { int a; if(a == 0) return; }", 
AsOperator));
+}

Can you also add a test like:
```
struct S { S& operator=(const S&); };
void x() { S s1, s2; s1 = s2; }
```


https://reviews.llvm.org/D38921



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


[PATCH] D33589: clang-format: consider not splitting tokens in optimization

2017-12-01 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

I think the difference between code and comments is that code "words" are 
easily 10 characters or more, whereas actual words (in comments) are very often 
less than 10 characters: so code overflowing by 10 characters is not very 
frequent. whereas small words in comment will often get closer to the "extra" 
limit.

That said, I tried with your latest change ("Restructure how we break tokens", 
sha1:64d42a2fb85ece5987111ffb908c6bc7f7431dd4). and it's working about fine 
now. For the most part it seems to wrap when I would expect it, great work!
I have seen 2 "issues" though:

- Often I see that the last word before reflowing is not wrapped (eventhough it 
overlaps the line length); I did not count penalties so I cannot confirm this 
is really an issue or just a borderline scenario.
- Alignment seems better than before, but since there is no penalty for 
breaking alignment it will always try to unindent to compensate for overflowing 
characters...

Seeing this, I guess this patch does not make much sense anymore, I'll see if I 
make some improvements for these two issues, in separate patches.


https://reviews.llvm.org/D33589



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


[PATCH] D33589: clang-format: consider not splitting tokens in optimization

2017-12-01 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

In https://reviews.llvm.org/D33589#941979, @Typz wrote:

> I think the difference between code and comments is that code "words" are 
> easily 10 characters or more, whereas actual words (in comments) are very 
> often less than 10 characters: so code overflowing by 10 characters is not 
> very frequent. whereas small words in comment will often get closer to the 
> "extra" limit.
>
> That said, I tried with your latest change ("Restructure how we break 
> tokens", sha1:64d42a2fb85ece5987111ffb908c6bc7f7431dd4). and it's working 
> about fine now. For the most part it seems to wrap when I would expect it, 
> great work!
>  I have seen 2 "issues" though:
>
> - Often I see that the last word before reflowing is not wrapped (eventhough 
> it overlaps the line length); I did not count penalties so I cannot confirm 
> this is really an issue or just a borderline scenario.
> - Alignment seems better than before, but since there is no penalty for 
> breaking alignment it will always try to unindent to compensate for 
> overflowing characters...
>
>   Seeing this, I guess this patch does not make much sense anymore, I'll see 
> if I make some improvements for these two issues, in separate patches.


Note that I just 10 mins ago landed another change (r319541) that should fix 
the main issue you raised, and which looks a lot like I wanted this change to 
look back when I first saw it (but of course all the underlying code made that 
impossible). Please give it a try and let me know what you think.


https://reviews.llvm.org/D33589



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


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

2017-12-01 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki updated this revision to Diff 125119.
miyuki added a comment.

Use explicit lambda capture list.


https://reviews.llvm.org/D40705

Files:
  include/clang/Basic/DiagnosticParseKinds.td
  lib/Parse/ParseTemplate.cpp
  test/CXX/temp/temp.param/p2.cpp


Index: test/CXX/temp/temp.param/p2.cpp
===
--- test/CXX/temp/temp.param/p2.cpp
+++ test/CXX/temp/temp.param/p2.cpp
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-// expected-no-diagnostics
 
 // There is no semantic difference between class and typename in a
 // template-parameter. typename followed by an unqualified-id names a
@@ -13,7 +12,8 @@
 template::type Value> struct Y1;
 
 // A storage class shall not be specified in a template-parameter declaration.
-template struct Z; // FIXME: expect an error
+template struct Z0; // expected-error {{storage class 
specified for template parameter 'Value'}}
+template struct Z1; // expected-error {{storage class specified 
for template parameter}}
 
 // Make sure that we properly disambiguate non-type template parameters that
 // start with 'class'.
Index: lib/Parse/ParseTemplate.cpp
===
--- lib/Parse/ParseTemplate.cpp
+++ lib/Parse/ParseTemplate.cpp
@@ -686,6 +686,22 @@
 return nullptr;
   }
 
+  // C++ [temp.param]p2:
+  //   A storage class shall not be specified in a template-parameter
+  //   declaration.
+  auto ReportStorageClass = [this, &ParamDecl](SourceLocation Loc) {
+if (ParamDecl.getIdentifier())
+  Diag(Loc, diag::err_storage_class_template_parameter)
+<< ParamDecl.getIdentifier() << FixItHint::CreateRemoval(Loc);
+else
+  Diag(Loc, diag::err_storage_class_template_parameter_anon)
+<< FixItHint::CreateRemoval(Loc);
+  };
+  if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
+ReportStorageClass(DS.getStorageClassSpecLoc());
+  if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified)
+ReportStorageClass(DS.getThreadStorageClassSpecLoc());
+
   // Recover from misplaced ellipsis.
   SourceLocation EllipsisLoc;
   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Index: include/clang/Basic/DiagnosticParseKinds.td
===
--- include/clang/Basic/DiagnosticParseKinds.td
+++ include/clang/Basic/DiagnosticParseKinds.td
@@ -668,6 +668,11 @@
 def warn_missing_dependent_template_keyword : ExtWarn<
   "use 'template' keyword to treat '%0' as a dependent template name">;
 
+def err_storage_class_template_parameter : Error<
+  "storage class specified for template parameter %0">;
+def err_storage_class_template_parameter_anon : Error<
+  "storage class specified for template parameter">;
+
 def ext_extern_template : Extension<
   "extern templates are a C++11 extension">, InGroup;
 def warn_cxx98_compat_extern_template : Warning<


Index: test/CXX/temp/temp.param/p2.cpp
===
--- test/CXX/temp/temp.param/p2.cpp
+++ test/CXX/temp/temp.param/p2.cpp
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-// expected-no-diagnostics
 
 // There is no semantic difference between class and typename in a
 // template-parameter. typename followed by an unqualified-id names a
@@ -13,7 +12,8 @@
 template::type Value> struct Y1;
 
 // A storage class shall not be specified in a template-parameter declaration.
-template struct Z; // FIXME: expect an error
+template struct Z0; // expected-error {{storage class specified for template parameter 'Value'}}
+template struct Z1; // expected-error {{storage class specified for template parameter}}
 
 // Make sure that we properly disambiguate non-type template parameters that
 // start with 'class'.
Index: lib/Parse/ParseTemplate.cpp
===
--- lib/Parse/ParseTemplate.cpp
+++ lib/Parse/ParseTemplate.cpp
@@ -686,6 +686,22 @@
 return nullptr;
   }
 
+  // C++ [temp.param]p2:
+  //   A storage class shall not be specified in a template-parameter
+  //   declaration.
+  auto ReportStorageClass = [this, &ParamDecl](SourceLocation Loc) {
+if (ParamDecl.getIdentifier())
+  Diag(Loc, diag::err_storage_class_template_parameter)
+<< ParamDecl.getIdentifier() << FixItHint::CreateRemoval(Loc);
+else
+  Diag(Loc, diag::err_storage_class_template_parameter_anon)
+<< FixItHint::CreateRemoval(Loc);
+  };
+  if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
+ReportStorageClass(DS.getStorageClassSpecLoc());
+  if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified)
+ReportStorageClass(DS.getThreadStorageClassSpecLoc());
+
   // Recover from misplaced ellipsis.
   SourceLocation EllipsisLoc;
   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Index: include/clang/Basic/DiagnosticParseKinds.td

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

2017-12-01 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

Definitely that would be much more expressive. But this approach is also 
incomplete: in case of namespace (and possibly others?), we also need to 
perform the reverse operation, e.g. to "generate" a macro call for rewriting 
the closing comment.

On top of this, I think that is really not trivial, I would prefer to move 
forward with these "simpler" patch, and change the whole macro configurations 
part in later commits...


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] D40719: [clangd] Split CodeComplete into a separate file. NFC

2017-12-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
Herald added subscribers: cfe-commits, mgorny, klimek.

Shared details of ClangdUnit and CodeComplete moved to a new Compiler file.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D40719

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.h
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/Compiler.cpp
  clangd/Compiler.h

Index: clangd/Compiler.h
===
--- /dev/null
+++ clangd/Compiler.h
@@ -0,0 +1,45 @@
+//===--- Compiler.h -*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===-===//
+//
+// Shared utilities for invoking the clang compiler.
+// ClangdUnit takes care of much of this, but some features like CodeComplete
+// run their own compile actions that share logic.
+//
+//===-===//
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_COMPILER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_COMPILER_H
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/PrecompiledPreamble.h"
+
+namespace clang {
+namespace clangd {
+
+class IgnoreDiagnostics : public DiagnosticConsumer {
+public:
+  void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
+const clang::Diagnostic &Info) override {}
+};
+
+/// Creates a CompilerInstance with the main file contens overridden.
+/// The preamble will be reused unless it is null.
+/// Note that the vfs::FileSystem inside returned instance may differ if
+/// additional file remappings occur in command-line arguments.
+/// On some errors, returns null. When non-null value is returned, it's expected
+/// to be consumed by the FrontendAction as it will have a pointer to the
+/// MainFile buffer that will only be deleted if BeginSourceFile is called.
+std::unique_ptr prepareCompilerInstance(
+std::unique_ptr, const PrecompiledPreamble *,
+std::unique_ptr MainFile,
+std::shared_ptr,
+IntrusiveRefCntPtr, DiagnosticConsumer &);
+
+} // namespace clangd
+} // namespace clang
+#endif
Index: clangd/Compiler.cpp
===
--- /dev/null
+++ clangd/Compiler.cpp
@@ -0,0 +1,65 @@
+//===--- Compiler.cpp ---*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===-===//
+#include "Compiler.h"
+#include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/PreprocessorOptions.h"
+
+namespace clang {
+namespace clangd {
+
+/// Creates a CompilerInstance from \p CI, with main buffer overriden to \p
+/// Buffer and arguments to read the PCH from \p Preamble, if \p Preamble is not
+/// null. Note that vfs::FileSystem inside returned instance may differ from \p
+/// VFS if additional file remapping were set in command-line arguments.
+/// On some errors, returns null. When non-null value is returned, it's expected
+/// to be consumed by the FrontendAction as it will have a pointer to the \p
+/// Buffer that will only be deleted if BeginSourceFile is called.
+std::unique_ptr
+prepareCompilerInstance(std::unique_ptr CI,
+const PrecompiledPreamble *Preamble,
+std::unique_ptr Buffer,
+std::shared_ptr PCHs,
+IntrusiveRefCntPtr VFS,
+DiagnosticConsumer &DiagsClient) {
+  assert(VFS && "VFS is null");
+  assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
+ "Setting RetainRemappedFileBuffers to true will cause a memory leak "
+ "of ContentsBuffer");
+
+  // NOTE: we use Buffer.get() when adding remapped files, so we have to make
+  // sure it will be released if no error is emitted.
+  if (Preamble) {
+Preamble->AddImplicitPreamble(*CI, VFS, Buffer.get());
+  } else {
+CI->getPreprocessorOpts().addRemappedFile(
+CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
+  }
+
+  auto Clang = llvm::make_unique(PCHs);
+  Clang->setInvocation(std::move(CI));
+  Clang->createDiagnostics(&DiagsClient, false);
+
+  if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
+  Clang->getInvocation(), Clang->getDiagnostics(), VFS))
+VFS = VFSWithRemapping;
+  Clang->setVirtualFileSystem(VFS);
+
+  Clang->setTarget(TargetInfo::CreateTargetInfo(
+  Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
+  if (!Clang->hasTarget())
+return nullp

[PATCH] D40720: No -fsanitize=function warning when calling noexcept function through non-noexcept pointer in C++17

2017-12-01 Thread Stephan Bergmann via Phabricator via cfe-commits
sberg created this revision.
Herald added a subscriber: kubamracek.

As discussed in the mail thread 
https://groups.google.com/a/isocpp.org/forum/#!topic/std-discussion/T64_dW3WKUk 
"Calling noexcept function throug non-noexcept pointer is undefined behavior?", 
such a call should not be UB.  However, Clang currently warns about it.

There is no cheap check whether two function type_infos only differ in 
noexcept, so pass those two type_infos as additional data to the 
function_type_mismatch handler (with the optimization of passing a null "static 
callee type" info when that is already noexcept, so the additional check can be 
avoided anyway).  For the Itanium ABI (which appears to only record noexcept 
information for pointer-to-function type_infos, not for function type_infos 
themselves), we then need to check the mangled names for occurrence of "Do" 
representing "noexcept".


https://reviews.llvm.org/D40720

Files:
  clang/lib/CodeGen/CGExpr.cpp
  compiler-rt/lib/ubsan/ubsan_handlers.cc
  compiler-rt/lib/ubsan/ubsan_handlers.h
  compiler-rt/test/ubsan/TestCases/TypeCheck/Function/function.cpp

Index: compiler-rt/test/ubsan/TestCases/TypeCheck/Function/function.cpp
===
--- compiler-rt/test/ubsan/TestCases/TypeCheck/Function/function.cpp
+++ compiler-rt/test/ubsan/TestCases/TypeCheck/Function/function.cpp
@@ -1,4 +1,4 @@
-// RUN: %clangxx -fsanitize=function %s -O3 -g -o %t
+// RUN: %clangxx -std=c++17 -fsanitize=function %s -O3 -g -o %t
 // RUN: %run %t 2>&1 | FileCheck %s
 // Verify that we can disable symbolization if needed:
 // RUN: %env_ubsan_opts=symbolize=0 %run %t 2>&1 | FileCheck %s --check-prefix=NOSYM
@@ -23,9 +23,47 @@
   reinterpret_cast(reinterpret_cast(f))(42);
 }
 
+void f1(int) {}
+void f2(unsigned int) {}
+void f3(int) noexcept {}
+void f4(unsigned int) noexcept {}
+
+void check_noexcept_calls() {
+  void (*p1)(int);
+  p1 = &f1;
+  p1(0);
+  p1 = reinterpret_cast(&f2);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f2(unsigned int) through pointer to incorrect function type 'void (*)(int)'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int)'
+  p1(0);
+  p1 = &f3;
+  p1(0);
+  p1 = reinterpret_cast(&f4);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f4(unsigned int) through pointer to incorrect function type 'void (*)(int)'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int)'
+  p1(0);
+
+  void (*p2)(int) noexcept;
+  p2 = reinterpret_cast(&f1);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f1(int) through pointer to incorrect function type 'void (*)(int) noexcept'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int) noexcept'
+  p2(0);
+  p2 = reinterpret_cast(&f2);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f2(unsigned int) through pointer to incorrect function type 'void (*)(int) noexcept'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int) noexcept'
+  p2(0);
+  p2 = &f3;
+  p2(0);
+  p2 = reinterpret_cast(&f4);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f4(unsigned int) through pointer to incorrect function type 'void (*)(int) noexcept'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int) noexcept'
+  p2(0);
+}
+
 int main(void) {
   make_valid_call();
   make_invalid_call();
+  check_noexcept_calls();
   // Check that no more errors will be printed.
   // CHECK-NOT: runtime error: call to function
   // NOSYM-NOT: runtime error: call to function
Index: compiler-rt/lib/ubsan/ubsan_handlers.h
===
--- compiler-rt/lib/ubsan/ubsan_handlers.h
+++ compiler-rt/lib/ubsan/ubsan_handlers.h
@@ -140,11 +140,12 @@
 struct FunctionTypeMismatchData {
   SourceLocation Loc;
   const TypeDescriptor &Type;
+  ValueHandle NonNoexceptRTTI;
 };
 
 RECOVERABLE(function_type_mismatch,
 FunctionTypeMismatchData *Data,
-ValueHandle Val)
+ValueHandle Val, ValueHandle RTTI)
 
 struct NonNullReturnData {
   SourceLocation AttrLoc;
Index: compiler-rt/lib/ubsan/ubsan_handlers.cc
===
--- compiler-rt/lib/ubsan/ubsan_handlers.cc
+++ compiler-rt/lib/ubsan/ubsan_handlers.cc
@@ -18,6 +18,9 @@
 
 #include "sanitizer_common/sanitizer_common.h"
 
+#include 
+#include 
+
 using namespace __sanitizer;
 using namespace __ubsan;
 
@@ -462,14 +465,50 @@
   Die();
 }
 
-static void handleFunctionTypeMismatch(FunctionTypeMism

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

2017-12-01 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

In https://reviews.llvm.org/D37813#941987, @Typz wrote:

> Definitely that would be much more expressive. But this approach is also 
> incomplete: in case of namespace (and possibly others?), we also need to 
> perform the reverse operation, e.g. to "generate" a macro call for rewriting 
> the closing comment.
>
> On top of this, I think that is really not trivial, I would prefer to move 
> forward with these "simpler" patch, and change the whole macro configurations 
> part in later commits...


Looking at the tests, I see what you mean, but I'd actually vote to not add 
non-namespace closing comments, or at least make closing comments configurable 
in a different way - it seems very much unrelated?


https://reviews.llvm.org/D37813



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


[clang-tools-extra] r319546 - [clangd] Remove no-op -fsyntax-only from fallback command. NFC

2017-12-01 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Dec  1 06:35:17 2017
New Revision: 319546

URL: http://llvm.org/viewvc/llvm-project?rev=319546&view=rev
Log:
[clangd] Remove no-op -fsyntax-only from fallback command. NFC

This has no effect because we explicitly choose our actions.
(If it had an effect, we'd want to add it to commands we get from a CDB)

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

Modified: clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp?rev=319546&r1=319545&r2=319546&view=diff
==
--- clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp (original)
+++ clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp Fri Dec  1 
06:35:17 2017
@@ -31,7 +31,7 @@ static void addExtraFlags(tooling::Compi
 }
 
 tooling::CompileCommand getDefaultCompileCommand(PathRef File) {
-  std::vector CommandLine{"clang", "-fsyntax-only", File.str()};
+  std::vector CommandLine{"clang", File.str()};
   return tooling::CompileCommand(llvm::sys::path::parent_path(File),
  llvm::sys::path::filename(File), CommandLine,
  /*Output=*/"");


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


[PATCH] D39903: [libclang] Allow pretty printing declarations

2017-12-01 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik updated this revision to Diff 125129.
nik added a comment.

Rebased only.


Repository:
  rC Clang

https://reviews.llvm.org/D39903

Files:
  include/clang-c/Index.h
  test/Index/print-display-names.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -176,6 +176,8 @@
 clang_getCursorCompletionString
 clang_getCursorDefinition
 clang_getCursorDisplayName
+clang_getCursorPrintingPolicy
+clang_getCursorPrettyPrinted
 clang_getCursorExtent
 clang_getCursorExceptionSpecificationType
 clang_getCursorKind
@@ -355,3 +357,56 @@
 clang_EvalResult_getAsDouble
 clang_EvalResult_getAsStr
 clang_EvalResult_dispose
+clang_PrintingPolicy_dispose
+clang_PrintingPolicy_getIndentation
+clang_PrintingPolicy_getSuppressSpecifiers
+clang_PrintingPolicy_getSuppressTagKeyword
+clang_PrintingPolicy_getIncludeTagDefinition
+clang_PrintingPolicy_getSuppressScope
+clang_PrintingPolicy_getSuppressUnwrittenScope
+clang_PrintingPolicy_getSuppressInitializers
+clang_PrintingPolicy_getConstantArraySizeAsWritten
+clang_PrintingPolicy_getAnonymousTagLocations
+clang_PrintingPolicy_getSuppressStrongLifetime
+clang_PrintingPolicy_getSuppressLifetimeQualifiers
+clang_PrintingPolicy_getSuppressTemplateArgsInCXXConstructors
+clang_PrintingPolicy_getBool
+clang_PrintingPolicy_getRestrict
+clang_PrintingPolicy_getAlignof
+clang_PrintingPolicy_getUnderscoreAlignof
+clang_PrintingPolicy_getUseVoidForZeroParams
+clang_PrintingPolicy_getTerseOutput
+clang_PrintingPolicy_getPolishForDeclaration
+clang_PrintingPolicy_getHalf
+clang_PrintingPolicy_getMSWChar
+clang_PrintingPolicy_getIncludeNewlines
+clang_PrintingPolicy_getMSVCFormatting
+clang_PrintingPolicy_getConstantsAsWritten
+clang_PrintingPolicy_getSuppressImplicitBase
+clang_PrintingPolicy_getFullyQualifiedName
+clang_PrintingPolicy_setIndentation
+clang_PrintingPolicy_setSuppressSpecifiers
+clang_PrintingPolicy_setSuppressTagKeyword
+clang_PrintingPolicy_setIncludeTagDefinition
+clang_PrintingPolicy_setSuppressScope
+clang_PrintingPolicy_setSuppressUnwrittenScope
+clang_PrintingPolicy_setSuppressInitializers
+clang_PrintingPolicy_setConstantArraySizeAsWritten
+clang_PrintingPolicy_setAnonymousTagLocations
+clang_PrintingPolicy_setSuppressStrongLifetime
+clang_PrintingPolicy_setSuppressLifetimeQualifiers
+clang_PrintingPolicy_setSuppressTemplateArgsInCXXConstructors
+clang_PrintingPolicy_setBool
+clang_PrintingPolicy_setRestrict
+clang_PrintingPolicy_setAlignof
+clang_PrintingPolicy_setUnderscoreAlignof
+clang_PrintingPolicy_setUseVoidForZeroParams
+clang_PrintingPolicy_setTerseOutput
+clang_PrintingPolicy_setPolishForDeclaration
+clang_PrintingPolicy_setHalf
+clang_PrintingPolicy_setMSWChar
+clang_PrintingPolicy_setIncludeNewlines
+clang_PrintingPolicy_setMSVCFormatting
+clang_PrintingPolicy_setConstantsAsWritten
+clang_PrintingPolicy_setSuppressImplicitBase
+clang_PrintingPolicy_setFullyQualifiedName
Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -4649,6 +4649,107 @@
   return cxstring::createSet(Manglings);
 }
 
+CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
+  if (clang_Cursor_isNull(C))
+return 0;
+  return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
+}
+
+void clang_PrintingPolicy_dispose(CXPrintingPolicy policy) {
+  if (policy)
+delete static_cast(policy);
+}
+
+#define DEFINE_PRINTING_POLICY_GETTER(name)\
+  unsigned clang_PrintingPolicy_get##name(CXPrintingPolicy policy) {   \
+if (!policy)   \
+  return 0;\
+return static_cast(policy)->name;\
+  }
+DEFINE_PRINTING_POLICY_GETTER(Indentation)
+DEFINE_PRINTING_POLICY_GETTER(SuppressSpecifiers)
+DEFINE_PRINTING_POLICY_GETTER(SuppressTagKeyword)
+DEFINE_PRINTING_POLICY_GETTER(IncludeTagDefinition)
+DEFINE_PRINTING_POLICY_GETTER(SuppressScope)
+DEFINE_PRINTING_POLICY_GETTER(SuppressUnwrittenScope)
+DEFINE_PRINTING_POLICY_GETTER(SuppressInitializers)
+DEFINE_PRINTING_POLICY_GETTER(ConstantArraySizeAsWritten)
+DEFINE_PRINTING_POLICY_GETTER(AnonymousTagLocations)
+DEFINE_PRINTING_POLICY_GETTER(SuppressStrongLifetime)
+DEFINE_PRINTING_POLICY_GETTER(SuppressLifetimeQualifiers)
+DEFINE_PRINTING_POLICY_GETTER(SuppressTemplateArgsInCXXConstructors)
+DEFINE_PRINTING_POLICY_GETTER(Bool)
+DEFINE_PRINTING_POLICY_GETTER(Restrict)
+DEFINE_PRINTING_POLICY_GETTER(Alignof)
+DEFINE_PRINTING_POLICY_GETTER(UnderscoreAlignof)
+DEFINE_PRINTING_POLICY_GETTER(UseVoidForZeroParams)
+DEFINE_PRINTING_POLICY_GETTER(TerseOutput)
+DEFINE_PRINTING_POLICY_GETTER(PolishForDeclaration)
+D

[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

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



Comment at: clang-tidy/ClangTidyDiagnosticConsumer.cpp:295
+  unsigned DiagID, const ClangTidyContext &Context) {
+  const auto NolintIndex = Line.find(NolintMacro);
+  if (NolintIndex != StringRef::npos) {

Only use `auto` when the type is spelled out explicitly in the initialization 
(usually through a cast or constructor). Same comment applies elsewhere.



Comment at: clang-tidy/ClangTidyDiagnosticConsumer.cpp:311-313
+  for (auto &Check : Checks) {
+Check = Check.trim();
+  }

`llvm::transform(Checks, Checks.begin(), [](StringRef S) { return S.trim(); });`



Comment at: clang-tidy/ClangTidyDiagnosticConsumer.cpp:314
+  }
+  return std::find(Checks.begin(), Checks.end(), CheckName) !=
+ Checks.end();

Can use `llvm::find(Checks, CheckName)`


https://reviews.llvm.org/D40671



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


[PATCH] D40572: [OpenMP] Make test robust against quotation, NFC.

2017-12-01 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld abandoned this revision.
Hahnfeld added a comment.

Not needed anymore for the accepted patch which gets rid of the separator 
completely.


https://reviews.llvm.org/D40572



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


[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

2017-12-01 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tidy/ClangTidyDiagnosticConsumer.cpp:293
 }
-
-static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) {
+static bool IsNOLINTFound(StringRef NolintMacro, StringRef Line,
+  unsigned DiagID, const ClangTidyContext &Context) {

Please separate with empty line.



Comment at: clang-tidy/ClangTidyDiagnosticConsumer.cpp:323
+}
+static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc,
+   unsigned DiagID,

Please separate with empty line.


https://reviews.llvm.org/D40671



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


[PATCH] D33589: clang-format: consider not splitting tokens in optimization

2017-12-01 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

Indeed, looks good, thanks!

Though that exacerbates the alignment issue, I now get things like this:

  enum {
SomeLongerEnum, // comment
SomeThing,  // comment
Foo, // something
  } 
  ^ (column limit)

The comment on 'Foo' would overflow a bit, but it gets unindented during 
"alingment" stage, which kind of 'breaks' the decision that was made earlier on 
*not* to break the comment...


https://reviews.llvm.org/D33589



___
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

2017-12-01 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

As far as "parsing" and formatting inside the block is concerned, this is 
indeed unrelated (and would totally work if all macros where specified with 
some preprocessor definitions).

But identifying the 'opening' token and generating the matching 'closing' 
comment are totally related; it would seem very strange to have an option to 
specify that TESTSUITE() macros are parsed as namespace, then another option to 
indicate that namespace declared by this macros are actually closed with 
another macro call...


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] D40671: [clang-tidy] Support specific checks for NOLINT directive

2017-12-01 Thread Anton via Phabricator via cfe-commits
xgsa updated this revision to Diff 125140.

https://reviews.llvm.org/D40671

Files:
  clang-tidy/ClangTidyDiagnosticConsumer.cpp
  test/clang-tidy/nolint.cpp
  test/clang-tidy/nolintnextline.cpp

Index: test/clang-tidy/nolint.cpp
===
--- test/clang-tidy/nolint.cpp
+++ test/clang-tidy/nolint.cpp
@@ -13,7 +13,18 @@
 
 class B { B(int i); }; // NOLINT
 
-class C { C(int i); }; // NOLINT(we-dont-care-about-categories-yet)
+class C { C(int i); }; // NOLINT(for-some-other-check)
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit
+
+class C1 { C1(int i); }; // NOLINT(*)
+
+class C2 { C2(int i); }; // NOLINT(not-closed-bracket-is-treated-as-skip-all
+
+class C3 { C3(int i); }; // NOLINT(google-explicit-constructor)
+
+class C4 { C4(int i); }; // NOLINT(some-check, google-explicit-constructor)
+
+class C5 { C5(int i); }; // NOLINT without-brackets-skip-all, another-check
 
 void f() {
   int i;
@@ -35,4 +46,4 @@
 #define DOUBLE_MACRO MACRO(H) // NOLINT
 DOUBLE_MACRO
 
-// CHECK-MESSAGES: Suppressed 8 warnings (8 NOLINT)
+// CHECK-MESSAGES: Suppressed 12 warnings (12 NOLINT)
Index: test/clang-tidy/nolintnextline.cpp
===
--- test/clang-tidy/nolintnextline.cpp
+++ test/clang-tidy/nolintnextline.cpp
@@ -4,8 +4,24 @@
 // NOLINTNEXTLINE
 class B { B(int i); };
 
-// NOLINTNEXTLINE(we-dont-care-about-categories-yet)
+// NOLINTNEXTLINE(for-some-other-check)
 class C { C(int i); };
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit
+
+// NOLINTNEXTLINE(*)
+class C1 { C1(int i); };
+
+// NOLINTNEXTLINE(not-closed-bracket-is-treated-as-skip-all
+class C2 { C2(int i); };
+
+// NOLINTNEXTLINE(google-explicit-constructor)
+class C3 { C3(int i); };
+
+// NOLINTNEXTLINE(some-check, google-explicit-constructor)
+class C4 { C4(int i); };
+
+// NOLINTNEXTLINE without-brackets-skip-all, another-check
+class C5 { C5(int i); };
 
 
 // NOLINTNEXTLINE
@@ -28,6 +44,6 @@
 // NOLINTNEXTLINE
 MACRO_NOARG
 
-// CHECK-MESSAGES: Suppressed 4 warnings (4 NOLINT)
+// CHECK-MESSAGES: Suppressed 8 warnings (8 NOLINT)
 
 // RUN: %check_clang_tidy %s google-explicit-constructor %t --
Index: clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/ASTDiagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Frontend/DiagnosticRenderer.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include 
 #include 
@@ -290,7 +291,38 @@
   LastErrorPassesLineFilter = false;
 }
 
-static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) {
+static bool IsNOLINTFound(StringRef NolintMacro, StringRef Line,
+  unsigned DiagID, const ClangTidyContext &Context) {
+  const size_t NolintIndex = Line.find(NolintMacro);
+  if (NolintIndex != StringRef::npos) {
+size_t BracketIndex = NolintIndex + NolintMacro.size();
+// Check if the specific checks are specified in brackets
+if (BracketIndex < Line.size() && Line[BracketIndex] == '(') {
+  ++BracketIndex;
+  const size_t BracketEndIndex = Line.find(')', BracketIndex);
+  if (BracketEndIndex != StringRef::npos) {
+StringRef ChecksStr =
+Line.substr(BracketIndex, BracketEndIndex - BracketIndex);
+// Allow disabling all the checks with "*"
+if (ChecksStr != "*") {
+  StringRef CheckName = Context.getCheckName(DiagID);
+  // Allow specifying a few check names, delimited with comma
+  SmallVector Checks;
+  ChecksStr.split(Checks, ',', -1, false);
+  llvm::transform(Checks, Checks.begin(),
+  [](StringRef S) { return S.trim(); });
+  return llvm::find(Checks, CheckName) != Checks.end();
+}
+  }
+}
+return true;
+  }
+  return false;
+}
+
+static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc,
+   unsigned DiagID,
+   const ClangTidyContext &Context) {
   bool Invalid;
   const char *CharacterData = SM.getCharacterData(Loc, &Invalid);
   if (Invalid)
@@ -301,8 +333,7 @@
   while (*P != '\0' && *P != '\r' && *P != '\n')
 ++P;
   StringRef RestOfLine(CharacterData, P - CharacterData + 1);
-  // FIXME: Handle /\bNOLINT\b(\([^)]*\))?/ as cpplint.py does.
-  if (RestOfLine.find("NOLINT") != StringRef::npos)
+  if (IsNOLINTFound("NOLINT", RestOfLine, DiagID, Context))
 return true;
 
   // Check if there's a NOLINTNEXTLINE on the previous line.
@@ -329,16 +360,17 @@
 --P;
 
   RestOfLine = StringRef(P, LineEnd - P + 1);
-  if (RestOfLine.find("NOLINTNEXTLINE") != StringRef::npos)
+  if (IsNOLINTFound("NOLINTNEXT

[PATCH] D33589: clang-format: consider not splitting tokens in optimization

2017-12-01 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

In https://reviews.llvm.org/D33589#942128, @Typz wrote:

> Indeed, looks good, thanks!
>
> Though that exacerbates the alignment issue, I now get things like this:
>
>   enum {
> SomeLongerEnum, // comment
> SomeThing,  // comment
> Foo, // something
>   } 
>   ^ (column limit)
>   
>
> The comment on 'Foo' would overflow a bit, but it gets unindented during 
> "alingment" stage, which kind of 'breaks' the decision that was made earlier 
> on *not* to break the comment...


Ok, that seems like a different bug that we can fix in alignment, though :)


https://reviews.llvm.org/D33589



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


r319549 - Remove duplicate, nonsense information from an attribute diagnostic. The NonParmVar subject does not need to mention functions, and the resulting diagnostic definitely does not need to menti

2017-12-01 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Fri Dec  1 07:54:29 2017
New Revision: 319549

URL: http://llvm.org/viewvc/llvm-project?rev=319549&view=rev
Log:
Remove duplicate, nonsense information from an attribute diagnostic. The 
NonParmVar subject does not need to mention functions, and the resulting 
diagnostic definitely does not need to mention functions twice.

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/test/Sema/attr-nodebug.c

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=319549&r1=319548&r2=319549&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Fri Dec  1 07:54:29 2017
@@ -87,7 +87,7 @@ def NormalVar : SubsetSubject;
 def NonParmVar : SubsetSubjectgetKind() != Decl::ParmVar}],
-   "variables and functions">;
+   "variables">;
 def NonBitField : SubsetSubjectisBitField()}],
 "non-bit-field non-static data members">;

Modified: cfe/trunk/test/Sema/attr-nodebug.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/attr-nodebug.c?rev=319549&r1=319548&r2=319549&view=diff
==
--- cfe/trunk/test/Sema/attr-nodebug.c (original)
+++ cfe/trunk/test/Sema/attr-nodebug.c Fri Dec  1 07:54:29 2017
@@ -2,7 +2,7 @@
 
 int a __attribute__((nodebug));
 
-void b(int p __attribute__((nodebug))) { // expected-warning {{'nodebug' 
attribute only applies to functions, function pointers, Objective-C methods, 
and variables and functions}}
+void b(int p __attribute__((nodebug))) { // expected-warning {{'nodebug' 
attribute only applies to functions, function pointers, Objective-C methods, 
and variables}}
   int b __attribute__((nodebug));
 }
 


___
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

2017-12-01 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

In https://reviews.llvm.org/D37813#942137, @Typz wrote:

> As far as "parsing" and formatting inside the block is concerned, this is 
> indeed unrelated (and would totally work if all macros where specified with 
> some preprocessor definitions).
>
> But identifying the 'opening' token and generating the matching 'closing' 
> comment are totally related; it would seem very strange to have an option to 
> specify that TESTSUITE() macros are parsed as namespace, then another option 
> to indicate that namespace declared by this macros are actually closed with 
> another macro call...


Putting the namespace into the macro gives the macro an abstraction - if 
somebody were to change, for example, the namespace portion with a class 
definition, would you still want the closing comments or not?


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] D40060: [clangd] Fuzzy match scorer

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




Comment at: clangd/FuzzyMatch.h:53
+
+  int PatN, WordN;   // Length of pattern and word.
+  char Pat[MaxPat], Word[MaxWord];   // Raw pattern and word data.

sammccall wrote:
> ilya-biryukov wrote:
> > Maybe we could split the data we store into two sections:
> > 1. Pattern-specific data. Initialized on construction, never changed later.
> > 2. Per-match data. Initialized per `match()` call.
> > 
> > Otherwise it is somewhat hard to certify whether everything is being 
> > initialized properly.
> This hides the parallels between the Pattern and Word data, I'm not sure I 
> like it better overall.
> 
> I've added a comment describing this split, reordered some variables, and 
> renamed IsSubstring to WordContainsPattern, which I think clarifies this a 
> bit. WDYT?
I'd prefer grouping the fields by their lifetime in that case, because it makes 
certifying that everything was properly initialized easier. Which is especially 
a big deal when changing code to avoid silly initialization-related bugs.
Grouping by meaning also makes lots of sense, of course, but logical relations 
are only hard to grasp when reading the code and don't usually cause subtle 
bugs when rewriting the code. And proper comments allow to reintroduce those 
logical parallels.

But that could be accounted to my personal preference, so feel free to leave 
the code as is. Just wanted to clarify my point a bit more.


https://reviews.llvm.org/D40060



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


[clang-tools-extra] r319459 - add new check to find NSError init invocation

2017-12-01 Thread Yan Zhang via cfe-commits
Author: wizard
Date: Thu Nov 30 11:05:08 2017
New Revision: 319459

URL: http://llvm.org/viewvc/llvm-project?rev=319459&view=rev
Log:
add new check to find NSError init invocation

Summary:
This check will find out improper initialization of NSError objects.

According to Apple developer document, we should always use factory method 
errorWithDomain:code:userInfo: to create new NSError objects instead of 
[NSError alloc] init]. Otherwise it will lead to a warning message during 
runtime in Xcode.

The corresponding information about NSError creation: 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html

Reviewers: hokein, benhamilton

Reviewed By: benhamilton

Subscribers: klimek, mgorny, cfe-commits

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

Added:
clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp
clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-avoid-nserror-init.rst
clang-tools-extra/trunk/test/clang-tidy/objc-avoid-nserror-init.m
Modified:
clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Added: clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp?rev=319459&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp (added)
+++ clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp Thu Nov 
30 11:05:08 2017
@@ -0,0 +1,37 @@
+//===--- AvoidNSErrorInitCheck.cpp - 
clang-tidy===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "AvoidNSErrorInitCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace objc {
+
+void AvoidNSErrorInitCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(objcMessageExpr(hasSelector("init"),
+ hasReceiverType(asString("NSError *")))
+ .bind("nserrorInit"),
+ this);
+}
+
+void AvoidNSErrorInitCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *MatchedExpr =
+  Result.Nodes.getNodeAs("nserrorInit");
+  diag(MatchedExpr->getLocStart(),
+   "use errorWithDomain:code:userInfo: or initWithDomain:code:userInfo: to 
"
+   "create a new NSError");
+}
+
+}  // namespace objc
+}  // namespace tidy
+}  // namespace clang

Added: clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h?rev=319459&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h (added)
+++ clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h Thu Nov 30 
11:05:08 2017
@@ -0,0 +1,36 @@
+//===--- AvoidNSErrorInitCheck.h - clang-tidy*- C++ 
-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_AVOIDNSERRORINITCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_AVOIDNSERRORINITCHECK_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace objc {
+
+/// Finds usages of [NSSError init]. It is not the proper way of creating
+/// NSError. errorWithDomain:code:userInfo: should be used instead.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/objc-avoid-nserror-init.html
+class AvoidNSErrorInitCheck : public ClangTidyCheck {
+ public:
+  AvoidNSErrorInitCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+};
+
+}  // namespace objc
+}  // namespace tidy
+}  // namespace clang
+
+#endif  // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_AVOIDNSERRORINITCHECK_H

Modified: clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-pr

[clang-tools-extra] r319460 - add new check to find NSError init invocation

2017-12-01 Thread Yan Zhang via cfe-commits
Author: wizard
Date: Thu Nov 30 11:05:09 2017
New Revision: 319460

URL: http://llvm.org/viewvc/llvm-project?rev=319460&view=rev
Log:
add new check to find NSError init invocation

Subscribers: klimek, mgorny, cfe-commits

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

Added:
clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp
  - copied, changed from r319459, 
clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp
clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.h
  - copied, changed from r319459, 
clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h
Removed:
clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp
clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h
Modified:
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Copied: clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp (from 
r319459, clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp)
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp?p2=clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp&p1=clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp&r1=319459&r2=319460&rev=319460&view=diff
==
(empty)

Copied: clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.h (from 
r319459, clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h)
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.h?p2=clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.h&p1=clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h&r1=319459&r2=319460&rev=319460&view=diff
==
(empty)

Removed: clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp?rev=319459&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.cpp (removed)
@@ -1,37 +0,0 @@
-//===--- AvoidNSErrorInitCheck.cpp - 
clang-tidy===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===--===//
-
-#include "AvoidNSErrorInitCheck.h"
-#include "clang/AST/ASTContext.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
-
-using namespace clang::ast_matchers;
-
-namespace clang {
-namespace tidy {
-namespace objc {
-
-void AvoidNSErrorInitCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(objcMessageExpr(hasSelector("init"),
- hasReceiverType(asString("NSError *")))
- .bind("nserrorInit"),
- this);
-}
-
-void AvoidNSErrorInitCheck::check(const MatchFinder::MatchResult &Result) {
-  const auto *MatchedExpr =
-  Result.Nodes.getNodeAs("nserrorInit");
-  diag(MatchedExpr->getLocStart(),
-   "use errorWithDomain:code:userInfo: or initWithDomain:code:userInfo: to 
"
-   "create a new NSError");
-}
-
-}  // namespace objc
-}  // namespace tidy
-}  // namespace clang

Removed: clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h?rev=319459&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h (original)
+++ clang-tools-extra/trunk/clang-tidy/objc/AvoidNserrorInitCheck.h (removed)
@@ -1,36 +0,0 @@
-//===--- AvoidNSErrorInitCheck.h - clang-tidy*- C++ 
-*-===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_AVOIDNSERRORINITCHECK_H
-#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_AVOIDNSERRORINITCHECK_H
-
-#include "../ClangTidy.h"
-
-namespace clang {
-namespace tidy {
-namespace objc {
-
-/// Finds usages of [NSSError init]. It is not the proper way of creating
-/// NSError. errorWithDomain:code:userInfo: should be used instead.
-///
-/// For the user-facing documentation see:
-/// http://clang.llvm.org/extra/clang-tidy/checks/objc-avoid-nserror-init.html
-class AvoidNSErrorInitCheck : public ClangTidyCheck {
- public:
-  AvoidNSErrorInitCheck(St

[PATCH] D40731: Integrate CHash into CLang

2017-12-01 Thread Christian Dietrich via Phabricator via cfe-commits
stettberger created this revision.
Herald added subscribers: cfe-commits, aprantl, mgorny.

The CHashVisitor can be used to determine a unique hash for a translation unit. 
The hash is stable across compiler invocations and if two translation units 
have the same hash, the resulting object file is semantically equal (code, 
data, etc. are equal; debug information may be different).


Repository:
  rC Clang

https://reviews.llvm.org/D40731

Files:
  include/clang/AST/AttrDataCollectors.td
  include/clang/AST/CHashVisitor.h
  include/clang/AST/CMakeLists.txt
  include/clang/AST/DeclDataCollectors.td
  include/clang/AST/StmtDataCollectors.td
  include/clang/AST/TypeDataCollectors.td
  unittests/AST/CHashTest.cpp
  unittests/AST/CMakeLists.txt

Index: unittests/AST/CMakeLists.txt
===
--- unittests/AST/CMakeLists.txt
+++ unittests/AST/CMakeLists.txt
@@ -18,6 +18,7 @@
   PostOrderASTVisitor.cpp
   SourceLocationTest.cpp
   StmtPrinterTest.cpp
+  CHashTest.cpp
   )
 
 target_link_libraries(ASTTests
Index: unittests/AST/CHashTest.cpp
===
--- /dev/null
+++ unittests/AST/CHashTest.cpp
@@ -0,0 +1,91 @@
+//===- unittests/AST/DataCollectionTest.cpp ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This file contains tests for the DataCollection module.
+//
+// They work by hashing the collected data of two nodes and asserting that the
+// hash values are equal iff the nodes are considered equal.
+//
+//===--===//
+
+#include "clang/AST/CHashVisitor.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+#include 
+
+using namespace clang;
+using namespace tooling;
+
+
+class CHashConsumer : public ASTConsumer {
+CompilerInstance &CI;
+llvm::MD5::MD5Result *ASTHash;
+
+public:
+CHashConsumer(CompilerInstance &CI, llvm::MD5::MD5Result *ASTHash)
+: CI(CI), ASTHash(ASTHash){}
+
+virtual void HandleTranslationUnit(clang::ASTContext &Context) override {
+TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
+
+// Traversing the translation unit decl via a RecursiveASTVisitor
+// will visit all nodes in the AST.
+CHashVisitor<> Visitor(Context);
+Visitor.TraverseDecl(TU);
+// Copy Away the resulting hash
+*ASTHash = *Visitor.getHash(TU);
+
+}
+~CHashConsumer() override {}
+
+};
+
+class CHashAction : public ASTFrontendAction {
+public: // We are all friends
+llvm::MD5::MD5Result *Hash;
+
+CHashAction(llvm::MD5::MD5Result *Hash) : Hash(Hash) {}
+
+std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
+   StringRef) override {
+return std::unique_ptr(new CHashConsumer(CI, Hash));
+}
+};
+
+static testing::AssertionResult
+isASTHashEqual(StringRef Code1, StringRef Code2) {
+llvm::MD5::MD5Result Hash1, Hash2;
+if (!runToolOnCode(new CHashAction(&Hash1), Code1)) {
+return testing::AssertionFailure()
+<< "Parsing error in (A)\"" << Code1.str() << "\"";
+}
+if (!runToolOnCode(new CHashAction(&Hash2), Code2)) {
+return testing::AssertionFailure()
+<< "Parsing error in (B) \"" << Code2.str() << "\"";
+}
+return testing::AssertionResult(Hash1 == Hash2);
+}
+
+TEST(CHashVisitor, TestRecordTypes) {
+ASSERT_TRUE(isASTHashEqual( // Unused struct
+ "struct foobar { int a0; char a1; unsigned long a2; };",
+ "struct foobar { int a0; char a1;};"
+ ));
+
+}
+
+TEST(CHashVisitor, TestSourceStructure) {
+ASSERT_FALSE(isASTHashEqual(
+ "void foo() { int c; if (0) { c = 1; } }",
+ "void foo() { int c; if (0) { } c = 1; }"));
+
+ASSERT_FALSE(isASTHashEqual(
+ "void f1() {} void f2() {   }",
+ "void f1() {} void f2() { f1(); }"));
+}
Index: include/clang/AST/TypeDataCollectors.td
===
--- include/clang/AST/TypeDataCollectors.td
+++ include/clang/AST/TypeDataCollectors.td
@@ -0,0 +1,66 @@
+//--- Types ---//
+class Type {
+  code Code = [{
+ addData(S->getTypeClass());
+  }];
+}
+
+class BuiltinType {
+   code Code = [{
+  addData(S->getKind());
+   }];
+}
+
+class ArrayType  {
+   code Code = [{
+  addData(S->getSizeModifier());
+  addData(S->getIndexTypeCVRQualifiers());
+   }];
+}
+
+class ConstantArrayType {
+   code Code = [{
+  addData(S->getSize().getZExtValue());
+

[PATCH] D40625: Harmonizing attribute GNU/C++ spellings

2017-12-01 Thread Devin Coughlin via Phabricator via cfe-commits
dcoughlin added a subscriber: alexfh.
dcoughlin added inline comments.



Comment at: include/clang/Basic/Attr.td:602
 def AnalyzerNoReturn : InheritableAttr {
-  let Spellings = [GNU<"analyzer_noreturn">];
+  let Spellings = [Clang<"analyzer_noreturn">];
   let Documentation = [Undocumented];

aaron.ballman wrote:
> rsmith wrote:
> > Hmm, should the clang static analyzer reuse the `clang::` namespace, or 
> > should it get its own?
> Good question, I don't have strong opinions on the answer here, but perhaps 
> @dcoughlin does?
> 
> If we want to use a separate namespace for the analyzer, would we want to use 
> that same namespace for any clang-tidy specific attributes? Or should 
> clang-tidy get its own namespace? (Do we ever plan to execute clang-tidy 
> through the clang driver? That might change our answer.)
How would this look if we added a special namespace for the clang static 
analyzer? Would this lead to duplication (say, 
[[clang_analyzer::analyzer_noreturn]]) so that we keep the "analyzer_" prefix 
for __attribute__((analyzer_noreturn))? Or could we have the "analyzer_" prefix 
only for GNU-style attributes but not for C++ (for example, 
[[clang_analyzer::noreturn]])?

As for clang-tidy, I think it probably makes sense for it to have its own 
namespace, but we should ask @alexfh.


https://reviews.llvm.org/D40625



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


[PATCH] D39882: [clangd] Filter completion results by fuzzy-matching identifiers.

2017-12-01 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/D39882



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


[PATCH] D40733: [clangd] GlobalCompilationDatabase interface changes

2017-12-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
Herald added subscribers: cfe-commits, klimek.

- GlobalCompilationDatabase now returns a single command (that's all we use)
- fallback flags are now part of the GlobalCompilationDatabase. There's a 
default implementation that they can optionally customize.
- this allows us to avoid invoking the fallback logic on two separate codepaths
- race on extra flags fixed by locking the mutex
- made GCD const-correct (DBGCD does have mutating methods)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D40733

Files:
  clangd/ClangdUnitStore.cpp
  clangd/GlobalCompilationDatabase.cpp
  clangd/GlobalCompilationDatabase.h
  unittests/clangd/ClangdTests.cpp

Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -212,21 +212,17 @@
   ExtraClangFlags.push_back("-ffreestanding");
   }
 
-  std::vector
-  getCompileCommands(PathRef File) override {
+  llvm::Optional
+  getCompileCommand(PathRef File) const override {
 if (ExtraClangFlags.empty())
-  return {};
-
-std::vector CommandLine;
-CommandLine.reserve(3 + ExtraClangFlags.size());
-CommandLine.insert(CommandLine.end(), {"clang", "-fsyntax-only"});
-CommandLine.insert(CommandLine.end(), ExtraClangFlags.begin(),
-   ExtraClangFlags.end());
-CommandLine.push_back(File.str());
+  return llvm::None;
 
+auto CommandLine = ExtraClangFlags;
+CommandLine.insert(CommandLine.begin(), "clang");
+CommandLine.insert(CommandLine.end(), File.str());
 return {tooling::CompileCommand(llvm::sys::path::parent_path(File),
 llvm::sys::path::filename(File),
-CommandLine, "")};
+std::move(CommandLine), "")};
   }
 
   std::vector ExtraClangFlags;
Index: clangd/GlobalCompilationDatabase.h
===
--- clangd/GlobalCompilationDatabase.h
+++ clangd/GlobalCompilationDatabase.h
@@ -27,16 +27,19 @@
 
 class Logger;
 
-/// Returns a default compile command to use for \p File.
-tooling::CompileCommand getDefaultCompileCommand(PathRef File);
-
 /// Provides compilation arguments used for parsing C and C++ files.
 class GlobalCompilationDatabase {
 public:
   virtual ~GlobalCompilationDatabase() = default;
 
-  virtual std::vector
-  getCompileCommands(PathRef File) = 0;
+  /// If there are any known-good commands for building this file, returns one.
+  virtual llvm::Optional
+  getCompileCommand(PathRef File) const = 0;
+
+  /// Makes a guess at how to build a file.
+  /// The default implementation just runs clang on the file.
+  /// Clangd should treat the results as unreliable.
+  virtual tooling::CompileCommand getFallbackCommand(PathRef File) const;
 
   /// FIXME(ibiryukov): add facilities to track changes to compilation flags of
   /// existing targets.
@@ -50,19 +53,26 @@
   DirectoryBasedGlobalCompilationDatabase(
   clangd::Logger &Logger, llvm::Optional CompileCommandsDir);
 
-  std::vector
-  getCompileCommands(PathRef File) override;
+  /// Scans File's parents looking for compilation databases.
+  /// Any extra flags will be added.
+  llvm::Optional
+  getCompileCommand(PathRef File) const override;
+
+  /// Uses the default fallback command, adding any extra flags.
+  tooling::CompileCommand getFallbackCommand(PathRef File) const override;
 
+  /// Sets the extra flags that should be added to a file.
   void setExtraFlagsForFile(PathRef File, std::vector ExtraFlags);
 
 private:
-  tooling::CompilationDatabase *getCompilationDatabase(PathRef File);
-  tooling::CompilationDatabase *tryLoadDatabaseFromPath(PathRef File);
+  tooling::CompilationDatabase *getCompilationDatabase(PathRef File) const;
+  tooling::CompilationDatabase *tryLoadDatabaseFromPath(PathRef File) const;
+  void addExtraFlags(PathRef File, tooling::CompileCommand &C) const;
 
-  std::mutex Mutex;
+  mutable std::mutex Mutex;
   /// Caches compilation databases loaded from directories(keys are
   /// directories).
-  llvm::StringMap>
+  mutable llvm::StringMap>
   CompilationDatabases;
 
   /// Stores extra flags per file.
Index: clangd/GlobalCompilationDatabase.cpp
===
--- clangd/GlobalCompilationDatabase.cpp
+++ clangd/GlobalCompilationDatabase.cpp
@@ -16,59 +16,63 @@
 namespace clang {
 namespace clangd {
 
-static void addExtraFlags(tooling::CompileCommand &Command,
-  const std::vector &ExtraFlags) {
-  if (ExtraFlags.empty())
-return;
-  assert(Command.CommandLine.size() >= 2 &&
- "Expected a command line containing at least 2 arguments, the "
- "compiler binary and the output file");
-  // The last argument of CommandLine is the name of the input file.
-  // Add ExtraFlags before it.
-  a

[PATCH] D40660: Enable auto-linking on Windows

2017-12-01 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai accepted this revision.
smeenai added a comment.
This revision is now accepted and ready to land.

I think it would make sense for this change to also have the conditional for 
the static C++ library selection. Basically something like

  #if defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_BUILDING_LIBRARY)
  # if defined(_DLL)
  #  pragma comment(lib, "c++.lib")
  # else
  #  pragma comment(lib, "libc++.lib")
  # endif
  #endif

If you wanna be super consistent with `use_ansi.h`, change the second condition 
to

  # if defined(_DLL) && !defined(_STATIC_CPPLIB)

LGTM with that.

Also, the diff needs more context :)




Comment at: include/__config:1267
+# if defined(_DLL) && !defined(_LIBCPP_BUILDING_LIBRARY)
+#   if defined(_LIBCPP_DEBUG)
+# pragma comment(lib, "c++d.lib")

compnerd wrote:
> smeenai wrote:
> > compnerd wrote:
> > > smeenai wrote:
> > > > I guess `_DLL` is appropriate here. Ideally though I think adding the 
> > > > pragma should be keyed on exactly the same conditional that determines 
> > > > whether we annotate with dllexport/dllimport, and right now that's only 
> > > > conditional on `_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS`.
> > > Its more complicated.  This is for the *user* not the library itself.  
> > > When building the shared library we need to ensure that it is not added 
> > > (`!defined(_LIBCPP_BUILDING_LIBRARY)`).  When using the headers as a 
> > > user, the `_DLL` tells you about the dynamic/static behavior.
> > I know, but the dllimport annotations are also for the *user*. If you're 
> > getting the dllimport annotations, you should also be getting the pragma, 
> > and vice-versa.
> Right, but `_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS` does not imply use of a 
> static libc++, but `!defined(_DLL)` does, unless Im missing something.  So 
> doesn't this do exactly what you were thinking of?
What I meant was, this is our current logic for determining whether dllimport 
annotations are used: 
https://reviews.llvm.org/diffusion/L/browse/libcxx/trunk/include/__config;319549$616-632.
 In other words, you get the dllimport annotations if 
`_LIBCPP_OBJECT_FORMAT_COFF && !_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS && 
!_LIBCPP_BUILDING_LIBRARY`.

I agree that semantically, `_DLL` is the right thing to key the pragma on. 
However, the condition for the pragma and the condition for dllimport 
annotations is now inconsistent, so we can end up in situations where we get 
the pragma but not the dllimport annotations, or vice versa, which seems wrong.

Making the conditionals consistent is hairy, however, because `_DLL` won't be 
defined for non-MSVC drivers, and the dllimport codepath is required for all of 
Windows. I'm fine with this as is, and we can think more about that consistency 
later.

Do you think you also wanna add a pragma for the non-DLL codepath 
(`libc++.lib`)? Could do that in a follow-up as well, but it seems natural to 
have that as part of this change, and it would be more consistent with how 
`use_ansi.h` does it.

Looks like msvcprt also has `_STATIC_CPPLIB` for forcing the use of the static 
C++ library even when `_DLL`. Idk if we care about supporting that.


Repository:
  rCXX libc++

https://reviews.llvm.org/D40660



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


[PATCH] D39882: [clangd] Filter completion results by fuzzy-matching identifiers.

2017-12-01 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL319552: [clangd] Filter completion results by fuzzy-matching 
identifiers. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D39882?vs=125009&id=125155#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D39882

Files:
  clang-tools-extra/trunk/clangd/ClangdUnit.cpp
  clang-tools-extra/trunk/test/clangd/completion-items-kinds.test
  clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
@@ -742,6 +742,61 @@
   EXPECT_FALSE(ContainsItem(Results, "CCC"));
 }
 
+TEST_F(ClangdCompletionTest, Filter) {
+  MockFSProvider FS;
+  MockCompilationDatabase CDB(/*AddFreestandingFlag=*/true);
+  CDB.ExtraClangFlags.push_back("-xc++");
+  ErrorCheckingDiagConsumer DiagConsumer;
+  clangd::CodeCompleteOptions Opts;
+  ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
+  /*StorePreamblesInMemory=*/true, Opts,
+  EmptyLogger::getInstance());
+
+  auto FooCpp = getVirtualTestFilePath("foo.cpp");
+  FS.Files[FooCpp] = "";
+  FS.ExpectedFile = FooCpp;
+  const char *Body = R"cpp(
+int Abracadabra;
+int Alakazam;
+struct S {
+  int FooBar;
+  int FooBaz;
+  int Qux;
+};
+  )cpp";
+  auto Complete = [&](StringRef Query) {
+StringWithPos Completion = parseTextMarker(
+formatv("{0} int main() { {1}{{complete}} }", Body, Query).str(),
+"complete");
+Server.addDocument(FooCpp, Completion.Text);
+return Server
+.codeComplete(FooCpp, Completion.MarkerPos, StringRef(Completion.Text))
+.get()
+.Value;
+  };
+
+  auto Foba = Complete("S().Foba");
+  EXPECT_TRUE(ContainsItem(Foba, "FooBar"));
+  EXPECT_TRUE(ContainsItem(Foba, "FooBaz"));
+  EXPECT_FALSE(ContainsItem(Foba, "Qux"));
+
+  auto FR = Complete("S().FR");
+  EXPECT_TRUE(ContainsItem(FR, "FooBar"));
+  EXPECT_FALSE(ContainsItem(FR, "FooBaz"));
+  EXPECT_FALSE(ContainsItem(FR, "Qux"));
+
+  auto Op = Complete("S().opr");
+  EXPECT_TRUE(ContainsItem(Op, "operator="));
+
+  auto Aaa = Complete("aaa");
+  EXPECT_TRUE(ContainsItem(Aaa, "Abracadabra"));
+  EXPECT_TRUE(ContainsItem(Aaa, "Alakazam"));
+
+  auto UA = Complete("_a");
+  EXPECT_TRUE(ContainsItem(UA, "static_cast"));
+  EXPECT_FALSE(ContainsItem(UA, "Abracadabra"));
+}
+
 TEST_F(ClangdCompletionTest, CompletionOptions) {
   MockFSProvider FS;
   ErrorCheckingDiagConsumer DiagConsumer;
Index: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp
@@ -446,13 +446,16 @@
   void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
   CodeCompletionResult *Results,
   unsigned NumResults) override final {
+StringRef Filter = S.getPreprocessor().getCodeCompletionFilter();
 std::priority_queue Candidates;
 for (unsigned I = 0; I < NumResults; ++I) {
   auto &Result = Results[I];
   if (!ClangdOpts.IncludeIneligibleResults &&
   (Result.Availability == CXAvailability_NotAvailable ||
Result.Availability == CXAvailability_NotAccessible))
 continue;
+  if (!Filter.empty() && !fuzzyMatch(S, Context, Filter, Result))
+continue;
   Candidates.emplace(Result);
   if (ClangdOpts.Limit && Candidates.size() > ClangdOpts.Limit) {
 Candidates.pop();
@@ -476,6 +479,39 @@
   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
 
 private:
+  bool fuzzyMatch(Sema &S, const CodeCompletionContext &CCCtx, StringRef Filter,
+  CodeCompletionResult Result) {
+switch (Result.Kind) {
+case CodeCompletionResult::RK_Declaration:
+  if (auto *ID = Result.Declaration->getIdentifier())
+return fuzzyMatch(Filter, ID->getName());
+  break;
+case CodeCompletionResult::RK_Keyword:
+  return fuzzyMatch(Filter, Result.Keyword);
+case CodeCompletionResult::RK_Macro:
+  return fuzzyMatch(Filter, Result.Macro->getName());
+case CodeCompletionResult::RK_Pattern:
+  return fuzzyMatch(Filter, Result.Pattern->getTypedText());
+}
+auto *CCS = Result.CreateCodeCompletionString(
+S, CCCtx, *Allocator, CCTUInfo, /*IncludeBriefComments=*/false);
+return fuzzyMatch(Filter, CCS->getTypedText());
+  }
+
+  // Checks whether Target matches the Filter.
+  // Currently just requires a case-insensitive subsequence match.
+  // FIXME: make stricter and word-based: 'unique_ptr' should not match 'que'.
+  // FIXME: return a score to be incorporated into ranki

[PATCH] D39882: [clangd] Filter completion results by fuzzy-matching identifiers.

2017-12-01 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE319552: [clangd] Filter completion results by 
fuzzy-matching identifiers. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D39882?vs=125009&id=125154#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D39882

Files:
  clangd/ClangdUnit.cpp
  test/clangd/completion-items-kinds.test
  unittests/clangd/ClangdTests.cpp

Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -742,6 +742,61 @@
   EXPECT_FALSE(ContainsItem(Results, "CCC"));
 }
 
+TEST_F(ClangdCompletionTest, Filter) {
+  MockFSProvider FS;
+  MockCompilationDatabase CDB(/*AddFreestandingFlag=*/true);
+  CDB.ExtraClangFlags.push_back("-xc++");
+  ErrorCheckingDiagConsumer DiagConsumer;
+  clangd::CodeCompleteOptions Opts;
+  ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
+  /*StorePreamblesInMemory=*/true, Opts,
+  EmptyLogger::getInstance());
+
+  auto FooCpp = getVirtualTestFilePath("foo.cpp");
+  FS.Files[FooCpp] = "";
+  FS.ExpectedFile = FooCpp;
+  const char *Body = R"cpp(
+int Abracadabra;
+int Alakazam;
+struct S {
+  int FooBar;
+  int FooBaz;
+  int Qux;
+};
+  )cpp";
+  auto Complete = [&](StringRef Query) {
+StringWithPos Completion = parseTextMarker(
+formatv("{0} int main() { {1}{{complete}} }", Body, Query).str(),
+"complete");
+Server.addDocument(FooCpp, Completion.Text);
+return Server
+.codeComplete(FooCpp, Completion.MarkerPos, StringRef(Completion.Text))
+.get()
+.Value;
+  };
+
+  auto Foba = Complete("S().Foba");
+  EXPECT_TRUE(ContainsItem(Foba, "FooBar"));
+  EXPECT_TRUE(ContainsItem(Foba, "FooBaz"));
+  EXPECT_FALSE(ContainsItem(Foba, "Qux"));
+
+  auto FR = Complete("S().FR");
+  EXPECT_TRUE(ContainsItem(FR, "FooBar"));
+  EXPECT_FALSE(ContainsItem(FR, "FooBaz"));
+  EXPECT_FALSE(ContainsItem(FR, "Qux"));
+
+  auto Op = Complete("S().opr");
+  EXPECT_TRUE(ContainsItem(Op, "operator="));
+
+  auto Aaa = Complete("aaa");
+  EXPECT_TRUE(ContainsItem(Aaa, "Abracadabra"));
+  EXPECT_TRUE(ContainsItem(Aaa, "Alakazam"));
+
+  auto UA = Complete("_a");
+  EXPECT_TRUE(ContainsItem(UA, "static_cast"));
+  EXPECT_FALSE(ContainsItem(UA, "Abracadabra"));
+}
+
 TEST_F(ClangdCompletionTest, CompletionOptions) {
   MockFSProvider FS;
   ErrorCheckingDiagConsumer DiagConsumer;
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -446,13 +446,16 @@
   void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
   CodeCompletionResult *Results,
   unsigned NumResults) override final {
+StringRef Filter = S.getPreprocessor().getCodeCompletionFilter();
 std::priority_queue Candidates;
 for (unsigned I = 0; I < NumResults; ++I) {
   auto &Result = Results[I];
   if (!ClangdOpts.IncludeIneligibleResults &&
   (Result.Availability == CXAvailability_NotAvailable ||
Result.Availability == CXAvailability_NotAccessible))
 continue;
+  if (!Filter.empty() && !fuzzyMatch(S, Context, Filter, Result))
+continue;
   Candidates.emplace(Result);
   if (ClangdOpts.Limit && Candidates.size() > ClangdOpts.Limit) {
 Candidates.pop();
@@ -476,6 +479,39 @@
   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
 
 private:
+  bool fuzzyMatch(Sema &S, const CodeCompletionContext &CCCtx, StringRef Filter,
+  CodeCompletionResult Result) {
+switch (Result.Kind) {
+case CodeCompletionResult::RK_Declaration:
+  if (auto *ID = Result.Declaration->getIdentifier())
+return fuzzyMatch(Filter, ID->getName());
+  break;
+case CodeCompletionResult::RK_Keyword:
+  return fuzzyMatch(Filter, Result.Keyword);
+case CodeCompletionResult::RK_Macro:
+  return fuzzyMatch(Filter, Result.Macro->getName());
+case CodeCompletionResult::RK_Pattern:
+  return fuzzyMatch(Filter, Result.Pattern->getTypedText());
+}
+auto *CCS = Result.CreateCodeCompletionString(
+S, CCCtx, *Allocator, CCTUInfo, /*IncludeBriefComments=*/false);
+return fuzzyMatch(Filter, CCS->getTypedText());
+  }
+
+  // Checks whether Target matches the Filter.
+  // Currently just requires a case-insensitive subsequence match.
+  // FIXME: make stricter and word-based: 'unique_ptr' should not match 'que'.
+  // FIXME: return a score to be incorporated into ranking.
+  static bool fuzzyMatch(StringRef Filter, StringRef Target) {
+size_t TPos = 0;
+for (char C : Filter) {
+  TPos = Target.find_lower(C, TPos);
+  if (TPos == StringRef::npos)
+return f

[clang-tools-extra] r319552 - [clangd] Filter completion results by fuzzy-matching identifiers.

2017-12-01 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Dec  1 08:35:50 2017
New Revision: 319552

URL: http://llvm.org/viewvc/llvm-project?rev=319552&view=rev
Log:
[clangd] Filter completion results by fuzzy-matching identifiers.

Summary:
This allows us to limit the number of results we return and still allow them
to be surfaced by refining a query (D39852).

The initial algorithm is very conservative - it accepts a completion if the
filter is any case-insensitive sub-sequence. It does not attempt to rank items
based on match quality.

Reviewers: ilya-biryukov

Subscribers: cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/ClangdUnit.cpp
clang-tools-extra/trunk/test/clangd/completion-items-kinds.test
clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=319552&r1=319551&r2=319552&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Fri Dec  1 08:35:50 2017
@@ -446,6 +446,7 @@ public:
   void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
   CodeCompletionResult *Results,
   unsigned NumResults) override final {
+StringRef Filter = S.getPreprocessor().getCodeCompletionFilter();
 std::priority_queue Candidates;
 for (unsigned I = 0; I < NumResults; ++I) {
   auto &Result = Results[I];
@@ -453,6 +454,8 @@ public:
   (Result.Availability == CXAvailability_NotAvailable ||
Result.Availability == CXAvailability_NotAccessible))
 continue;
+  if (!Filter.empty() && !fuzzyMatch(S, Context, Filter, Result))
+continue;
   Candidates.emplace(Result);
   if (ClangdOpts.Limit && Candidates.size() > ClangdOpts.Limit) {
 Candidates.pop();
@@ -476,6 +479,39 @@ public:
   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
 
 private:
+  bool fuzzyMatch(Sema &S, const CodeCompletionContext &CCCtx, StringRef 
Filter,
+  CodeCompletionResult Result) {
+switch (Result.Kind) {
+case CodeCompletionResult::RK_Declaration:
+  if (auto *ID = Result.Declaration->getIdentifier())
+return fuzzyMatch(Filter, ID->getName());
+  break;
+case CodeCompletionResult::RK_Keyword:
+  return fuzzyMatch(Filter, Result.Keyword);
+case CodeCompletionResult::RK_Macro:
+  return fuzzyMatch(Filter, Result.Macro->getName());
+case CodeCompletionResult::RK_Pattern:
+  return fuzzyMatch(Filter, Result.Pattern->getTypedText());
+}
+auto *CCS = Result.CreateCodeCompletionString(
+S, CCCtx, *Allocator, CCTUInfo, /*IncludeBriefComments=*/false);
+return fuzzyMatch(Filter, CCS->getTypedText());
+  }
+
+  // Checks whether Target matches the Filter.
+  // Currently just requires a case-insensitive subsequence match.
+  // FIXME: make stricter and word-based: 'unique_ptr' should not match 'que'.
+  // FIXME: return a score to be incorporated into ranking.
+  static bool fuzzyMatch(StringRef Filter, StringRef Target) {
+size_t TPos = 0;
+for (char C : Filter) {
+  TPos = Target.find_lower(C, TPos);
+  if (TPos == StringRef::npos)
+return false;
+}
+return true;
+  }
+
   CompletionItem
   ProcessCodeCompleteResult(const CompletionCandidate &Candidate,
 const CodeCompletionString &CCS) const {

Modified: clang-tools-extra/trunk/test/clangd/completion-items-kinds.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/completion-items-kinds.test?rev=319552&r1=319551&r2=319552&view=diff
==
--- clang-tools-extra/trunk/test/clangd/completion-items-kinds.test (original)
+++ clang-tools-extra/trunk/test/clangd/completion-items-kinds.test Fri Dec  1 
08:35:50 2017
@@ -30,7 +30,7 @@ Content-Length: 148
 # CHECK-SAME: ]}}
 Content-Length: 146
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"whi"}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"nam"}}}
 Content-Length: 148
 
 
{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":3}}}

Modified: clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp?rev=319552&r1=319551&r2=319552&view=diff
==
--- clang-tools-extra/trun

[PATCH] D40720: No -fsanitize=function warning when calling noexcept function through non-noexcept pointer in C++17

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

(Diff 125121 had accidentally contained a spurious "}". Fixed that now.)


https://reviews.llvm.org/D40720

Files:
  clang/lib/CodeGen/CGExpr.cpp
  compiler-rt/lib/ubsan/ubsan_handlers.cc
  compiler-rt/lib/ubsan/ubsan_handlers.h
  compiler-rt/test/ubsan/TestCases/TypeCheck/Function/function.cpp

Index: compiler-rt/test/ubsan/TestCases/TypeCheck/Function/function.cpp
===
--- compiler-rt/test/ubsan/TestCases/TypeCheck/Function/function.cpp
+++ compiler-rt/test/ubsan/TestCases/TypeCheck/Function/function.cpp
@@ -1,4 +1,4 @@
-// RUN: %clangxx -fsanitize=function %s -O3 -g -o %t
+// RUN: %clangxx -std=c++17 -fsanitize=function %s -O3 -g -o %t
 // RUN: %run %t 2>&1 | FileCheck %s
 // Verify that we can disable symbolization if needed:
 // RUN: %env_ubsan_opts=symbolize=0 %run %t 2>&1 | FileCheck %s --check-prefix=NOSYM
@@ -23,9 +23,47 @@
   reinterpret_cast(reinterpret_cast(f))(42);
 }
 
+void f1(int) {}
+void f2(unsigned int) {}
+void f3(int) noexcept {}
+void f4(unsigned int) noexcept {}
+
+void check_noexcept_calls() {
+  void (*p1)(int);
+  p1 = &f1;
+  p1(0);
+  p1 = reinterpret_cast(&f2);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f2(unsigned int) through pointer to incorrect function type 'void (*)(int)'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int)'
+  p1(0);
+  p1 = &f3;
+  p1(0);
+  p1 = reinterpret_cast(&f4);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f4(unsigned int) through pointer to incorrect function type 'void (*)(int)'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int)'
+  p1(0);
+
+  void (*p2)(int) noexcept;
+  p2 = reinterpret_cast(&f1);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f1(int) through pointer to incorrect function type 'void (*)(int) noexcept'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int) noexcept'
+  p2(0);
+  p2 = reinterpret_cast(&f2);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f2(unsigned int) through pointer to incorrect function type 'void (*)(int) noexcept'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int) noexcept'
+  p2(0);
+  p2 = &f3;
+  p2(0);
+  p2 = reinterpret_cast(&f4);
+  // CHECK: function.cpp:[[@LINE+2]]:3: runtime error: call to function f4(unsigned int) through pointer to incorrect function type 'void (*)(int) noexcept'
+  // NOSYM: function.cpp:[[@LINE+1]]:3: runtime error: call to function (unknown) through pointer to incorrect function type 'void (*)(int) noexcept'
+  p2(0);
+}
+
 int main(void) {
   make_valid_call();
   make_invalid_call();
+  check_noexcept_calls();
   // Check that no more errors will be printed.
   // CHECK-NOT: runtime error: call to function
   // NOSYM-NOT: runtime error: call to function
Index: compiler-rt/lib/ubsan/ubsan_handlers.h
===
--- compiler-rt/lib/ubsan/ubsan_handlers.h
+++ compiler-rt/lib/ubsan/ubsan_handlers.h
@@ -140,11 +140,12 @@
 struct FunctionTypeMismatchData {
   SourceLocation Loc;
   const TypeDescriptor &Type;
+  ValueHandle NonNoexceptRTTI;
 };
 
 RECOVERABLE(function_type_mismatch,
 FunctionTypeMismatchData *Data,
-ValueHandle Val)
+ValueHandle Val, ValueHandle RTTI)
 
 struct NonNullReturnData {
   SourceLocation AttrLoc;
Index: compiler-rt/lib/ubsan/ubsan_handlers.cc
===
--- compiler-rt/lib/ubsan/ubsan_handlers.cc
+++ compiler-rt/lib/ubsan/ubsan_handlers.cc
@@ -18,6 +18,9 @@
 
 #include "sanitizer_common/sanitizer_common.h"
 
+#include 
+#include 
+
 using namespace __sanitizer;
 using namespace __ubsan;
 
@@ -462,14 +465,50 @@
   Die();
 }
 
-static void handleFunctionTypeMismatch(FunctionTypeMismatchData *Data,
-   ValueHandle Function,
+// Check that TI2 represents the same function type as TI1, except that TI2 has
+// "noexcept" and TI1 does not.
+static bool checkForAddedNoexcept(const std::type_info *TI1,
+  const std::type_info *TI2) {
+  const char *Mangled1 = TI1->name();
+  const char *Mangled2 = TI2->name();
+
+  // Skip .
+  if (*Mangled1 == 'V') {
+if (*Mangled2 != 'V')
+  return false;
+++Mangled1;
+++Mangled2;
+  }
+  if (*Mangled1 == 'K') {
+if (*Mangled2 != 'K')
+  return false;
+++Mangled1;
+++Mangled2;
+  }
+
+  // Check for "Do" .
+  if (*Mangled2++ != 'D' || *Mangled2++ != 'o')
+return false;
+
+  // Check remaind

[PATCH] D39279: Stringizing raw string literals containing newline

2017-12-01 Thread Jan Korous via Phabricator via cfe-commits
jkorous-apple added a comment.

Thank you for your patience @twoh and sorry for the delay.
I have few suggestions about doxygen annotations but otherwise LGTM.




Comment at: include/clang/Lex/Lexer.h:247
+  /// add surrounding ""'s to the string. If Charify is true, this escapes the
+  /// ' character instead of ".
   static std::string Stringify(StringRef Str, bool Charify = false);

Shouldn't we put all the details from implementation annotation here as well 
(since this is the public interface that people will actually use)?



Comment at: include/clang/Lex/Lexer.h:251
+  /// Stringify - Convert the specified string into a C string. This does not
+  /// add surrounding ""'s to the string.
   static void Stringify(SmallVectorImpl &Str);

Shouldn't we put all the details from implementation annotation here as well 
(since this is the public interface that people will actually use)?



Comment at: lib/Lex/Lexer.cpp:214
+/// specified string into a C string by i) escaping '\' and " characters and
+/// ii) replacing newline character(s) with "\n".
+template 

I am not sure I understand this correctly but wouldn't it be more precise if 
these literals are escaped?
... escaping '\' ... -> ...escaping '\\' ... 
... with "\n" ... -> ... with "\\n"

Alternatively we could use R"(\)" and R"(\n)".


https://reviews.llvm.org/D39279



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


r319555 - Disallow a cleanup attribute from appertaining to a parameter (the attribute only appertains to local variables and is silently a noop on parameters). This repurposes the unused (and syntact

2017-12-01 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Fri Dec  1 08:53:49 2017
New Revision: 319555

URL: http://llvm.org/viewvc/llvm-project?rev=319555&view=rev
Log:
Disallow a cleanup attribute from appertaining to a parameter (the attribute 
only appertains to local variables and is silently a noop on parameters). This 
repurposes the unused (and syntactically incorrect) NormalVar attribute subject.

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/test/Sema/attr-cleanup.c

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=319555&r1=319554&r2=319555&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Fri Dec  1 08:53:49 2017
@@ -77,13 +77,8 @@ class SubsetSubjectgetStorageClass() != VarDecl::Register &&
-S->getKind() != Decl::ImplicitParam &&
-S->getKind() != Decl::ParmVar &&
-S->getKind() != Decl::NonTypeTemplateParm}],
+def LocalVar : SubsetSubjecthasLocalStorage() && !isa(S)}],
   "local variables">;
 def NonParmVar : SubsetSubjectgetKind() != Decl::ParmVar}],
@@ -533,7 +528,6 @@ def Alias : Attr {
 def Aligned : InheritableAttr {
   let Spellings = [GCC<"aligned">, Declspec<"align">, Keyword<"alignas">,
Keyword<"_Alignas">];
-//  let Subjects = SubjectList<[NonBitField, NormalVar, Tag]>;
   let Args = [AlignedArgument<"Alignment", 1>];
   let Accessors = [Accessor<"isGNU", [GCC<"aligned">]>,
Accessor<"isC11", [Keyword<"_Alignas">]>,
@@ -768,7 +762,7 @@ def CFConsumed : InheritableParamAttr {
 def Cleanup : InheritableAttr {
   let Spellings = [GCC<"cleanup">];
   let Args = [FunctionArgument<"FunctionDecl">];
-  let Subjects = SubjectList<[Var]>;
+  let Subjects = SubjectList<[LocalVar]>;
   let Documentation = [Undocumented];
 }
 

Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=319555&r1=319554&r2=319555&view=diff
==
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Fri Dec  1 08:53:49 2017
@@ -3067,12 +3067,6 @@ static void handleTargetAttr(Sema &S, De
 }
 
 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
-  VarDecl *VD = cast(D);
-  if (!VD->hasLocalStorage()) {
-S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
-return;
-  }
-
   Expr *E = Attr.getArgAsExpr(0);
   SourceLocation Loc = E->getExprLoc();
   FunctionDecl *FD = nullptr;
@@ -3115,7 +3109,7 @@ static void handleCleanupAttr(Sema &S, D
 
   // We're currently more strict than GCC about what function types we accept.
   // If this ever proves to be a problem it should be easy to fix.
-  QualType Ty = S.Context.getPointerType(VD->getType());
+  QualType Ty = S.Context.getPointerType(cast(D)->getType());
   QualType ParamTy = FD->getParamDecl(0)->getType();
   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
ParamTy, Ty) != Sema::Compatible) {

Modified: cfe/trunk/test/Sema/attr-cleanup.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/attr-cleanup.c?rev=319555&r1=319554&r2=319555&view=diff
==
--- cfe/trunk/test/Sema/attr-cleanup.c (original)
+++ cfe/trunk/test/Sema/attr-cleanup.c Fri Dec  1 08:53:49 2017
@@ -2,16 +2,16 @@
 
 void c1(int *a);
 
-extern int g1 __attribute((cleanup(c1))); // expected-warning {{'cleanup' 
attribute ignored}}
-int g2 __attribute((cleanup(c1))); // expected-warning {{'cleanup' attribute 
ignored}}
-static int g3 __attribute((cleanup(c1))); // expected-warning {{'cleanup' 
attribute ignored}}
+extern int g1 __attribute((cleanup(c1))); // expected-warning {{'cleanup' 
attribute only applies to local variables}}
+int g2 __attribute((cleanup(c1))); // expected-warning {{'cleanup' attribute 
only applies to local variables}}
+static int g3 __attribute((cleanup(c1))); // expected-warning {{'cleanup' 
attribute only applies to local variables}}
 
 void t1()
 {
 int v1 __attribute((cleanup)); // expected-error {{'cleanup' attribute 
takes one argument}}
 int v2 __attribute((cleanup(1, 2))); // expected-error {{'cleanup' 
attribute takes one argument}}
 
-static int v3 __attribute((cleanup(c1))); // expected-warning {{'cleanup' 
attribute ignored}}
+static int v3 __attribute((cleanup(c1))); // expected-warning {{'cleanup' 
attribute only applies to local variables}}
 
 int v4 __attribute((cleanup(h))); // expected-error {{use of undeclared 
identifier 'h'}}
 
@@ -46,3 +46,5 @@ void t5() {
 void t6(void) {
 

[PATCH] D15406: Add warning for attribute-cleanup on function parameter.

2017-12-01 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

I committed a different fix for this in r319555.


https://reviews.llvm.org/D15406



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


[PATCH] D40625: Harmonizing attribute GNU/C++ spellings

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



Comment at: include/clang/Basic/Attr.td:602
 def AnalyzerNoReturn : InheritableAttr {
-  let Spellings = [GNU<"analyzer_noreturn">];
+  let Spellings = [Clang<"analyzer_noreturn">];
   let Documentation = [Undocumented];

dcoughlin wrote:
> aaron.ballman wrote:
> > rsmith wrote:
> > > Hmm, should the clang static analyzer reuse the `clang::` namespace, or 
> > > should it get its own?
> > Good question, I don't have strong opinions on the answer here, but perhaps 
> > @dcoughlin does?
> > 
> > If we want to use a separate namespace for the analyzer, would we want to 
> > use that same namespace for any clang-tidy specific attributes? Or should 
> > clang-tidy get its own namespace? (Do we ever plan to execute clang-tidy 
> > through the clang driver? That might change our answer.)
> How would this look if we added a special namespace for the clang static 
> analyzer? Would this lead to duplication (say, 
> [[clang_analyzer::analyzer_noreturn]]) so that we keep the "analyzer_" prefix 
> for __attribute__((analyzer_noreturn))? Or could we have the "analyzer_" 
> prefix only for GNU-style attributes but not for C++ (for example, 
> [[clang_analyzer::noreturn]])?
> 
> As for clang-tidy, I think it probably makes sense for it to have its own 
> namespace, but we should ask @alexfh.
> How would this look if we added a special namespace for the clang static 
> analyzer? Would this lead to duplication (say, 
> [[clang_analyzer::analyzer_noreturn]]) so that we keep the "analyzer_" prefix 
> for attribute((analyzer_noreturn))? Or could we have the "analyzer_" prefix 
> only for GNU-style attributes but not for C++ (for example, 
> [[clang_analyzer::noreturn]])?

We have the ability to do whatever we'd like there. Given that the semantics 
are so similar to `[[noreturn]]`, I think it would be reasonable to use 
`[[clang_analyzer::noreturn]]` and `__attribute__((analyzer_noreturn))` if 
that's the direction you think is best.

> As for clang-tidy, I think it probably makes sense for it to have its own 
> namespace, but we should ask @alexfh.

I'm less enthusiastic about giving clang-tidy a vendor namespace that's 
separate from the static analyzer, should the need arise. My biggest concern 
there is that I would *really* like to see clang-tidy be more tightly 
integrated with the clang driver (so users don't have to manually execute a 
secondary tool). If that were to happen, then the user experience would be that 
there are two vendor namespaces both related to analyzer attributes.

That said, I would also not be opposed to putting all of these attributes under 
the `clang` vendor namespace and not having a separate vendor for the analyzer 
or clang-tidy.


https://reviews.llvm.org/D40625



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


[PATCH] D40060: [clangd] Fuzzy match scorer

2017-12-01 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rL319557: [clangd] Fuzzy match scorer (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D40060?vs=124968&id=125159#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D40060

Files:
  clang-tools-extra/trunk/clangd/CMakeLists.txt
  clang-tools-extra/trunk/clangd/FuzzyMatch.cpp
  clang-tools-extra/trunk/clangd/FuzzyMatch.h
  clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
  clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp

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
@@ -10,6 +10,7 @@
 
 add_extra_unittest(ClangdTests
   ClangdTests.cpp
+  FuzzyMatchTests.cpp
   JSONExprTests.cpp
   TraceTests.cpp
   )
Index: clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp
@@ -0,0 +1,252 @@
+//===-- FuzzyMatchTests.cpp - String fuzzy matcher tests *- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "FuzzyMatch.h"
+
+#include "llvm/ADT/StringExtras.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+using namespace llvm;
+using testing::Not;
+
+struct ExpectedMatch {
+  ExpectedMatch(StringRef Annotated) : Word(Annotated), Annotated(Annotated) {
+for (char C : "[]")
+  Word.erase(std::remove(Word.begin(), Word.end(), C), Word.end());
+  }
+  std::string Word;
+  StringRef Annotated;
+};
+raw_ostream &operator<<(raw_ostream &OS, const ExpectedMatch &M) {
+  return OS << "'" << M.Word << "' as " << M.Annotated;
+}
+
+struct MatchesMatcher : public testing::MatcherInterface {
+  ExpectedMatch Candidate;
+  MatchesMatcher(ExpectedMatch Candidate) : Candidate(std::move(Candidate)) {}
+
+  void DescribeTo(::std::ostream *OS) const override {
+raw_os_ostream(*OS) << "Matches " << Candidate;
+  }
+
+  bool MatchAndExplain(StringRef Pattern,
+   testing::MatchResultListener *L) const override {
+std::unique_ptr OS(
+L->stream() ? (raw_ostream *)(new raw_os_ostream(*L->stream()))
+: new raw_null_ostream());
+FuzzyMatcher Matcher(Pattern);
+auto Result = Matcher.match(Candidate.Word);
+auto AnnotatedMatch = Matcher.dumpLast(*OS << "\n");
+return Result && AnnotatedMatch == Candidate.Annotated;
+  }
+};
+
+// Accepts patterns that match a given word.
+// Dumps the debug tables on match failure.
+testing::Matcher matches(StringRef M) {
+  return testing::MakeMatcher(new MatchesMatcher(M));
+}
+
+TEST(FuzzyMatch, Matches) {
+  EXPECT_THAT("u_p", matches("[u]nique[_p]tr"));
+  EXPECT_THAT("up", matches("[u]nique_[p]tr"));
+  EXPECT_THAT("uq", matches("[u]ni[q]ue_ptr"));
+  EXPECT_THAT("qp", Not(matches("unique_ptr")));
+  EXPECT_THAT("log", Not(matches("SVGFEMorphologyElement")));
+
+  EXPECT_THAT("tit", matches("win.[tit]"));
+  EXPECT_THAT("title", matches("win.[title]"));
+  EXPECT_THAT("WordCla", matches("[Word]Character[Cla]ssifier"));
+  EXPECT_THAT("WordCCla", matches("[WordC]haracter[Cla]ssifier"));
+
+  EXPECT_THAT("dete", Not(matches("editor.quickSuggestionsDelay")));
+
+  EXPECT_THAT("highlight", matches("editorHover[Highlight]"));
+  EXPECT_THAT("hhighlight", matches("editor[H]over[Highlight]"));
+  EXPECT_THAT("dhhighlight", Not(matches("editorHoverHighlight")));
+
+  EXPECT_THAT("-moz", matches("[-moz]-foo"));
+  EXPECT_THAT("moz", matches("-[moz]-foo"));
+  EXPECT_THAT("moza", matches("-[moz]-[a]nimation"));
+
+  EXPECT_THAT("ab", matches("[ab]A"));
+  EXPECT_THAT("ccm", matches("[c]a[cm]elCase"));
+  EXPECT_THAT("bti", Not(matches("the_black_knight")));
+  EXPECT_THAT("ccm", Not(matches("camelCase")));
+  EXPECT_THAT("cmcm", Not(matches("camelCase")));
+  EXPECT_THAT("BK", matches("the_[b]lack_[k]night"));
+  EXPECT_THAT("KeyboardLayout=", Not(matches("KeyboardLayout")));
+  EXPECT_THAT("LLL", matches("SVisual[L]ogger[L]ogs[L]ist"));
+  EXPECT_THAT("", Not(matches("SVilLoLosLi")));
+  EXPECT_THAT("", Not(matches("SVisualLoggerLogsList")));
+  EXPECT_THAT("TEdit", matches("[T]ext[Edit]"));
+  EXPECT_THAT("TEdit", matches("[T]ext[Edit]or"));
+  EXPECT_THAT("TEdit", matches("[Te]xte[dit]"));
+  EXPECT_THAT("TEdit", matches("[t]ext_[edit]"));
+  EXPECT_THAT("TEditDit", matches("[T]ext[Edit]or[D]ecorat[i]on[T]ype"));
+  EXPECT_THAT("TEdit", matches("

[clang-tools-extra] r319557 - [clangd] Fuzzy match scorer

2017-12-01 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Dec  1 09:08:02 2017
New Revision: 319557

URL: http://llvm.org/viewvc/llvm-project?rev=319557&view=rev
Log:
[clangd] Fuzzy match scorer

Summary:
This will be used for rescoring code completion results based on partial
identifiers.
Short-term use:
  - we want to limit the number of code completion results returned to
  improve performance of global completion. The scorer will be used to
  rerank the results to return when the user has applied a filter.
Long-term use case:
  - ranking of completion results from in-memory index
  - merging of completion results from multiple sources (merging usually
  works best when done at the component-score level, rescoring the
  fuzzy-match quality avoids different backends needing to have
  comparable scores)

Reviewers: ilya-biryukov

Subscribers: cfe-commits, mgorny

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

Added:
clang-tools-extra/trunk/clangd/FuzzyMatch.cpp
clang-tools-extra/trunk/clangd/FuzzyMatch.h
clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=319557&r1=319556&r2=319557&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Fri Dec  1 09:08:02 2017
@@ -8,6 +8,7 @@ add_clang_library(clangDaemon
   ClangdUnit.cpp
   ClangdUnitStore.cpp
   DraftStore.cpp
+  FuzzyMatch.cpp
   GlobalCompilationDatabase.cpp
   JSONExpr.cpp
   JSONRPCDispatcher.cpp

Added: clang-tools-extra/trunk/clangd/FuzzyMatch.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FuzzyMatch.cpp?rev=319557&view=auto
==
--- clang-tools-extra/trunk/clangd/FuzzyMatch.cpp (added)
+++ clang-tools-extra/trunk/clangd/FuzzyMatch.cpp Fri Dec  1 09:08:02 2017
@@ -0,0 +1,373 @@
+//===--- FuzzyMatch.h - Approximate identifier matching  -*- 
C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// To check for a match between a Pattern ('u_p') and a Word ('unique_ptr'),
+// we consider the possible partial match states:
+//
+// u n i q u e _ p t r
+//   +-
+//   |A . . . . . . . . . .
+//  u|
+//   |. . . . . . . . . . .
+//  _|
+//   |. . . . . . . O . . .
+//  p|
+//   |. . . . . . . . . . B
+//
+// Each dot represents some prefix of the pattern being matched against some
+// prefix of the word.
+//   - A is the initial state: '' matched against ''
+//   - O is an intermediate state: 'u_' matched against 'unique_'
+//   - B is the target state: 'u_p' matched against 'unique_ptr'
+//
+// We aim to find the best path from A->B.
+//  - Moving right (consuming a word character)
+//Always legal: not all word characters must match.
+//  - Moving diagonally (consuming both a word and pattern character)
+//Legal if the characters match.
+//  - Moving down (consuming a pattern character) is never legal.
+//Never legal: all pattern characters must match something.
+//
+// The scoring is based on heuristics:
+//  - when matching a character, apply a bonus or penalty depending on the
+//match quality (does case match, do word segments align, etc)
+//  - when skipping a character, apply a penalty if it hurts the match
+//(it starts a word segment, or splits the matched region, etc)
+//
+// These heuristics require the ability to "look backward" one character, to
+// see whether it was matched or not. Therefore the dynamic-programming matrix
+// has an extra dimension (last character matched).
+// Each entry also has an additional flag indicating whether the last-but-one
+// character matched, which is needed to trace back through the scoring table
+// and reconstruct the match.
+//
+// We treat strings as byte-sequences, so only ASCII has first-class support.
+//
+// This algorithm was inspired by VS code's client-side filtering, and aims
+// to be mostly-compatible.
+//
+//===--===//
+
+#include "FuzzyMatch.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/Support/Format.h"
+
+using namespace llvm;
+using namespace clang::clangd;
+
+const int FuzzyMatcher::MaxPat;
+const int FuzzyMatcher::MaxWord;
+
+static char lower(char C) { return C >= 'A' && C <= 'Z' ? C + ('a' - 'A') : C; 
}
+// A "negative infinity" score that won't overflow.
+// We use this to mark unreachable states and forbidden solutions.
+// Sc

[PATCH] D40060: [clangd] Fuzzy match scorer

2017-12-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added a comment.

I'd broken the scoring scale with the last few tweaks:

- The harsh pattern-split penalty was driving too many decent matches to 0 score
- The case-insensitive change resulted in some perfect prefix matches not 
getting perfect scores

Added tweaks to address these. Match quality is now 0-3, with default being 1.
Happy to make followup changes, but this seems unlikely to be controversial :-)




Comment at: clangd/FuzzyMatch.h:53
+
+  int PatN, WordN;   // Length of pattern and word.
+  char Pat[MaxPat], Word[MaxWord];   // Raw pattern and word data.

ilya-biryukov wrote:
> sammccall wrote:
> > ilya-biryukov wrote:
> > > Maybe we could split the data we store into two sections:
> > > 1. Pattern-specific data. Initialized on construction, never changed 
> > > later.
> > > 2. Per-match data. Initialized per `match()` call.
> > > 
> > > Otherwise it is somewhat hard to certify whether everything is being 
> > > initialized properly.
> > This hides the parallels between the Pattern and Word data, I'm not sure I 
> > like it better overall.
> > 
> > I've added a comment describing this split, reordered some variables, and 
> > renamed IsSubstring to WordContainsPattern, which I think clarifies this a 
> > bit. WDYT?
> I'd prefer grouping the fields by their lifetime in that case, because it 
> makes certifying that everything was properly initialized easier. Which is 
> especially a big deal when changing code to avoid silly 
> initialization-related bugs.
> Grouping by meaning also makes lots of sense, of course, but logical 
> relations are only hard to grasp when reading the code and don't usually 
> cause subtle bugs when rewriting the code. And proper comments allow to 
> reintroduce those logical parallels.
> 
> But that could be accounted to my personal preference, so feel free to leave 
> the code as is. Just wanted to clarify my point a bit more.
Makes sense. I've split the fields as you  suggest, it also reads well.


https://reviews.llvm.org/D40060



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


[PATCH] D38845: [ASTImporter] Support importing UnresolvedMemberExpr, DependentNameType, DependentScopeDeclRefExpr

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

Hello Peter. Please set the dependencies for the patch - it cannot be applied 
clearly and even if I add ImportTemplateArgumentListInfo, tests still fail - 
looks like FunctionTemplateDecl patch should be applied first.


https://reviews.llvm.org/D38845



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


[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

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

This feature should probably be mentioned in the release notes.


https://reviews.llvm.org/D40671



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


r319560 - [OPENMP] Do not allow variables to be first|last-privates in

2017-12-01 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Fri Dec  1 09:40:15 2017
New Revision: 319560

URL: http://llvm.org/viewvc/llvm-project?rev=319560&view=rev
Log:
[OPENMP] Do not allow variables to be first|last-privates in
distribute directives.

OpenMP standard does not allow to mark the variables as firstprivate and 
lastprivate at the same time in distribute-based directives. Patch fixes this 
problem.

Modified:
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_ast_print.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_simd_ast_print.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_simd_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_simd_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_simd_loop_messages.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_simd_misc_messages.c
cfe/trunk/test/OpenMP/distribute_simd_ast_print.cpp
cfe/trunk/test/OpenMP/distribute_simd_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/distribute_simd_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_loop_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_misc_messages.c

cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_firstprivate_messages.cpp

cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_loop_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_misc_messages.c

cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_simd_firstprivate_messages.cpp

cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_simd_lastprivate_messages.cpp

cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_simd_loop_messages.cpp

cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_simd_misc_messages.c
cfe/trunk/test/OpenMP/target_teams_distribute_simd_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_simd_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_simd_loop_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_simd_misc_messages.c
cfe/trunk/test/OpenMP/teams_distribute_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_loop_messages.cpp

cfe/trunk/test/OpenMP/teams_distribute_parallel_for_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_parallel_for_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_parallel_for_loop_messages.cpp

cfe/trunk/test/OpenMP/teams_distribute_parallel_for_simd_firstprivate_messages.cpp

cfe/trunk/test/OpenMP/teams_distribute_parallel_for_simd_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_parallel_for_simd_loop_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_simd_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_simd_lastprivate_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_simd_loop_messages.cpp

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=319560&r1=319559&r2=319560&view=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Fri Dec  1 09:40:15 2017
@@ -9146,7 +9146,8 @@ OMPClause *Sema::ActOnOpenMPFirstprivate
   // A list item may appear in a firstprivate or lastprivate clause but not
   // both.
   if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
-  (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
+  (isOpenMPDistributeDirective(CurrDir) ||
+   DVar.CKind != OMPC_lastprivate) &&
   DVar.RefExpr) {
 Diag(ELoc, diag::err_omp_wrong_dsa)
 << getOpenMPClauseName(DVar.CKind)
@@ -9240,14 +9241,7 @@ OMPClause *Sema::ActOnOpenMPFirstprivate
   // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
   // A list item cannot appear in both a map clause and a data-sharing
   // attribute clause on the same construct
-  if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
-  CurrDir == OMPD_target_teams || 
-  CurrDir == OMPD_target_teams_distribute ||
-  CurrDir == OMPD_target_teams_distribute_parallel_for ||
-  CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
-  CurrDir == OMPD_target_teams_distribute_simd ||
-  CurrDir == OMPD_target_parallel_for_simd ||
-  CurrDir == OMPD_target_parallel_for)

[PATCH] D40687: [compiler-rt] Switch to add_llvm_install_targets

2017-12-01 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

This change isn't safe. Compiler-RT is buildable without LLVM's modules as long 
as you disable the tests, so you can't use an AddLLVM function inside 
AddCompilerRT unless it is only used when tests are disabled.


https://reviews.llvm.org/D40687



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


[PATCH] D40580: [clang-tidy] Adding Fuchsia checker for multiple inheritance

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



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:35
+  StringRef Name = Node->getIdentifier()->getName();
+  auto Pair = InterfaceMap.find(Name);
+  if (Pair == InterfaceMap.end())

Don't use `auto` as the type is not spelled out explicitly in the 
initialization.



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:60
+  // To be an interface, all base classes must be interfaces as well.
+  for (const auto &I : Node->bases()) {
+const auto *Ty = I.getType()->getAs();

What about virtual bases (`Node->vbases()`)? This would also be worth some test 
cases.



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:77
+  // Match declarations which have definitions.
+  Finder->addMatcher(cxxRecordDecl(hasDefinition()).bind("decl"), this);
+}

It might be nice to not bother matching class definitions that have no bases or 
virtual bases rather than matching every class definition. However, this could 
be done in a follow-up patch (it likely requires adding an AST matcher).



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:85
+unsigned NumConcrete = 0;
+for (const auto &I : D->bases()) {
+  const auto *Ty = I.getType()->getAs();

And virtual bases?



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:88
+  assert(Ty && "RecordType of base class is unknown");
+  const auto *Base = cast(Ty->getDecl()->getDefinition());
+  if (!isInterface(Base)) NumConcrete++;

It might make sense to add a degenerate case here to ensure a base class 
without a definition doesn't cause a null pointer dereference. e.g.,
```
struct B;

struct D : B {}; // compile error, B is not a complete type
```
I'm not certain whether Clang's AST will contain the base or not.



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.h:34-36
+  bool getInterfaceStatus(const CXXRecordDecl *Node, bool &isInterface);
+  bool isCurrentClassInterface(const CXXRecordDecl *Node);
+  bool isInterface(const CXXRecordDecl *Node);

I believe all these methods can be marked `const`.



Comment at: test/clang-tidy/fuchsia-multiple-inheritance.cpp:80
+};
+
+int main(void) {

Please add a test case consisting of only data members, e.g.,
```
struct B1 {
  int x;
};

struct B2 {
  int x;
};

struct D : B1, B2 {};
```


https://reviews.llvm.org/D40580



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


[PATCH] D40673: Add _Float128 as alias to __float128 to enable compilations on Fedora27/glibc2-26

2017-12-01 Thread Melanie Blower via Phabricator via cfe-commits
mibintc abandoned this revision.
mibintc added a comment.

Thanks for all your reviews


https://reviews.llvm.org/D40673



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


[PATCH] D40737: [clang-tidy] Resubmit hicpp-multiway-paths-covered without breaking test

2017-12-01 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth created this revision.
Herald added subscribers: cfe-commits, xazax.hun, mgorny.

The original check did break the green buildbot in the sanitizer build.
It took a while to redroduce and understand the issue.

There occured a stackoverflow while parsing the AST. The testcase with
256 case labels was the problem because each case label added another
stackframe. It seemed that the issue occured only in 'RelWithDebInfo' builds
and not in normal sanitizer builds.

To simplify the matchers the recognition for the different kinds of switch
statements has been moved into a seperate function and will not be done with
ASTMatchers. This is an attempt to reduce recursion and stacksize as well.

The new check removed this big testcase. Covering all possible values is still
implemented for bitfields and works there. The same logic on integer types
will lead to the issue.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D40737

Files:
  clang-tidy/hicpp/CMakeLists.txt
  clang-tidy/hicpp/HICPPTidyModule.cpp
  clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
  clang-tidy/hicpp/MultiwayPathsCoveredCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/hicpp-multiway-paths-covered.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/hicpp-multiway-paths-covered-else.cpp
  test/clang-tidy/hicpp-multiway-paths-covered.cpp

Index: test/clang-tidy/hicpp-multiway-paths-covered.cpp
===
--- /dev/null
+++ test/clang-tidy/hicpp-multiway-paths-covered.cpp
@@ -0,0 +1,206 @@
+// RUN: %check_clang_tidy %s hicpp-multiway-paths-covered %t
+
+enum OS { Mac,
+  Windows,
+  Linux };
+
+struct Bitfields {
+  unsigned UInt : 3;
+  int SInt : 1;
+};
+
+int return_integer() { return 42; }
+
+void bad_switch(int i) {
+  switch (i) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: switch with only one case; use an if statement
+  case 0:
+break;
+  }
+  // No default in this switch
+  switch (i) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered code path; add a default label
+  case 0:
+break;
+  case 1:
+break;
+  case 2:
+break;
+  }
+
+  // degenerate, maybe even warning
+  switch (i) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: degenerated switch without labels
+  }
+
+  switch (int j = return_integer()) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered code path; add a default label
+  case 0:
+  case 1:
+  case 2:
+break;
+  }
+
+  // Degenerated, only default case.
+  switch (i) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: degenerated switch with default label only
+  default:
+break;
+  }
+
+  // Degenerated, only one case label and default case -> Better as if-stmt.
+  switch (i) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: switch could be better written as an if/else statement
+  case 0:
+break;
+  default:
+break;
+  }
+
+  unsigned long long BigNumber = 0;
+  switch (BigNumber) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered code path; add a default label
+  case 0:
+  case 1:
+break;
+  }
+
+  const int &IntRef = i;
+  switch (IntRef) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered code path; add a default label
+  case 0:
+  case 1:
+break;
+  }
+
+  char C = 'A';
+  switch (C) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered code path; add a default label
+  case 'A':
+break;
+  case 'B':
+break;
+  }
+
+  Bitfields Bf;
+  // UInt has 3 bits size.
+  switch (Bf.UInt) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered code path; add a default label
+  case 0:
+  case 1:
+break;
+  }
+  // All paths explicitly covered.
+  switch (Bf.UInt) {
+  case 0:
+  case 1:
+  case 2:
+  case 3:
+  case 4:
+  case 5:
+  case 6:
+  case 7:
+break;
+  }
+  // SInt has 1 bit size, so this is somewhat degenerated.
+  switch (Bf.SInt) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: switch with only one case; use an if statement
+  case 0:
+break;
+  }
+  // All paths explicitly covered.
+  switch (Bf.SInt) {
+  case 0:
+  case 1:
+break;
+  }
+
+  // Some paths are covered by the switch and a default case is present.
+  int c = 1;
+  switch (c) {
+  case 1:
+  case 2:
+  case 3:
+  default:
+break;
+  }
+
+  bool Flag = false;
+  switch (Flag) {
+// CHECK-MESSAGES:[[@LINE-1]]:3: warning: switch with only one case; use an if statement
+  case true:
+break;
+  }
+
+  switch (Flag) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: degenerated switch with default label only
+  default:
+break;
+  }
+
+  // This `switch` will create a frontend warning from '-Wswitch-bool' but is
+  // ok for this check.
+  switch (Flag) {
+  case true:
+break;
+  case false:
+break;
+  }
+}
+
+OS return_enumerator() {
+  return Linux;
+}
+
+// Enumpaths are already covered by a warning, this is just to ensure, that there is
+// no interference or fals

[PATCH] D40580: [clang-tidy] Adding Fuchsia checker for multiple inheritance

2017-12-01 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:35
+  StringRef Name = Node->getIdentifier()->getName();
+  auto Pair = InterfaceMap.find(Name);
+  if (Pair == InterfaceMap.end())

aaron.ballman wrote:
> Don't use `auto` as the type is not spelled out explicitly in the 
> initialization.
But such cases are included in modernize-use-auto.


https://reviews.llvm.org/D40580



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


[PATCH] D34082: [Frontend] 'Show hotness' can be used with a sampling profile

2017-12-01 Thread Adam Nemet via Phabricator via cfe-commits
anemet added a subscriber: davide.
anemet added a comment.

@modocache, @davide, are you guys sure this feature is working?  The test does 
not actually check whether hotness is included in the remarks and when I run it 
manually they are missing.  In https://reviews.llvm.org/D40678, I am filtering 
out remarks with no hotness when any threshold is set all the remarks are 
filtered out in this new test.

So either the test is incorrect or somehow with sample-based profiling we don't 
get hotness info.

Any ideas?  I am inclined to just remove this test for now and file a bug to 
fix this in order to unblock https://reviews.llvm.org/D40678.


https://reviews.llvm.org/D34082



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


[PATCH] D40580: [clang-tidy] Adding Fuchsia checker for multiple inheritance

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



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:35
+  StringRef Name = Node->getIdentifier()->getName();
+  auto Pair = InterfaceMap.find(Name);
+  if (Pair == InterfaceMap.end())

Eugene.Zelenko wrote:
> aaron.ballman wrote:
> > Don't use `auto` as the type is not spelled out explicitly in the 
> > initialization.
> But such cases are included in modernize-use-auto.
Hmm, I suppose you could maybe make a case that `StringMap::iterator` is 
"complex enough" and that the returned type is sufficiently clear to warrant 
using `auto`...


https://reviews.llvm.org/D40580



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


[PATCH] D40738: Don't use Wasm function sections for more than one function

2017-12-01 Thread Nicholas Wilson via Phabricator via cfe-commits
ncw created this revision.
Herald added subscribers: cfe-commits, aheejin, sbc100, dschuff, jfb.

Fixes Bugzilla https://bugs.llvm.org/show_bug.cgi?id=35467

If a Wasm function section is created with more than one symbol, 
WasmObjectWriter fails with the following message: "function sections must 
contain one function each".

Currently, if a C++ file contains multiple static initialisers, they'll all be 
put in the same function section, triggering the error.

I think this change here is safe - it seems to be a spurious optimisation. In 
fact, I'm not even sure how it's intended to optimise the output...?


Repository:
  rC Clang

https://reviews.llvm.org/D40738

Files:
  lib/Basic/Targets/OSTargets.h
  test/CodeGenCXX/static-init-wasm.cpp


Index: test/CodeGenCXX/static-init-wasm.cpp
===
--- test/CodeGenCXX/static-init-wasm.cpp
+++ test/CodeGenCXX/static-init-wasm.cpp
@@ -43,12 +43,12 @@
 
 A theA;
 
-// WEBASSEMBLY32: define internal void @__cxx_global_var_init() #3 section 
".text.__startup" {
+// WEBASSEMBLY32: define internal void @__cxx_global_var_init() #3 {
 // WEBASSEMBLY32: call %struct.A* @_ZN1AC1Ev(%struct.A* @theA)
-// WEBASSEMBLY32: define internal void @_GLOBAL__sub_I_static_init_wasm.cpp() 
#3 section ".text.__startup" {
+// WEBASSEMBLY32: define internal void @_GLOBAL__sub_I_static_init_wasm.cpp() 
#3 {
 // WEBASSEMBLY32: call void @__cxx_global_var_init()
 //
-// WEBASSEMBLY64: define internal void @__cxx_global_var_init() #3 section 
".text.__startup" {
+// WEBASSEMBLY64: define internal void @__cxx_global_var_init() #3 {
 // WEBASSEMBLY64: call %struct.A* @_ZN1AC1Ev(%struct.A* @theA)
-// WEBASSEMBLY64: define internal void @_GLOBAL__sub_I_static_init_wasm.cpp() 
#3 section ".text.__startup" {
+// WEBASSEMBLY64: define internal void @_GLOBAL__sub_I_static_init_wasm.cpp() 
#3 {
 // WEBASSEMBLY64: call void @__cxx_global_var_init()
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -711,11 +711,6 @@
   Builder.defineMacro("_GNU_SOURCE");
   }
 
-  // As an optimization, group static init code together in a section.
-  const char *getStaticInitSectionSpecifier() const final {
-return ".text.__startup";
-  }
-
 public:
   explicit WebAssemblyOSTargetInfo(const llvm::Triple &Triple,
const TargetOptions &Opts)


Index: test/CodeGenCXX/static-init-wasm.cpp
===
--- test/CodeGenCXX/static-init-wasm.cpp
+++ test/CodeGenCXX/static-init-wasm.cpp
@@ -43,12 +43,12 @@
 
 A theA;
 
-// WEBASSEMBLY32: define internal void @__cxx_global_var_init() #3 section ".text.__startup" {
+// WEBASSEMBLY32: define internal void @__cxx_global_var_init() #3 {
 // WEBASSEMBLY32: call %struct.A* @_ZN1AC1Ev(%struct.A* @theA)
-// WEBASSEMBLY32: define internal void @_GLOBAL__sub_I_static_init_wasm.cpp() #3 section ".text.__startup" {
+// WEBASSEMBLY32: define internal void @_GLOBAL__sub_I_static_init_wasm.cpp() #3 {
 // WEBASSEMBLY32: call void @__cxx_global_var_init()
 //
-// WEBASSEMBLY64: define internal void @__cxx_global_var_init() #3 section ".text.__startup" {
+// WEBASSEMBLY64: define internal void @__cxx_global_var_init() #3 {
 // WEBASSEMBLY64: call %struct.A* @_ZN1AC1Ev(%struct.A* @theA)
-// WEBASSEMBLY64: define internal void @_GLOBAL__sub_I_static_init_wasm.cpp() #3 section ".text.__startup" {
+// WEBASSEMBLY64: define internal void @_GLOBAL__sub_I_static_init_wasm.cpp() #3 {
 // WEBASSEMBLY64: call void @__cxx_global_var_init()
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -711,11 +711,6 @@
   Builder.defineMacro("_GNU_SOURCE");
   }
 
-  // As an optimization, group static init code together in a section.
-  const char *getStaticInitSectionSpecifier() const final {
-return ".text.__startup";
-  }
-
 public:
   explicit WebAssemblyOSTargetInfo(const llvm::Triple &Triple,
const TargetOptions &Opts)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34082: [Frontend] 'Show hotness' can be used with a sampling profile

2017-12-01 Thread Davide Italiano via Phabricator via cfe-commits
davide added a comment.

In https://reviews.llvm.org/D34082#942420, @anemet wrote:

> @modocache, @davide, are you guys sure this feature is working?  The test 
> does not actually check whether hotness is included in the remarks and when I 
> run it manually they are missing.  In https://reviews.llvm.org/D40678, I am 
> filtering out remarks with no hotness when any threshold is set all the 
> remarks are filtered out in this new test.
>
> So either the test is incorrect or somehow with sample-based profiling we 
> don't get hotness info.
>
> Any ideas?  I am inclined to just remove this test for now and file a bug to 
> fix this in order to unblock https://reviews.llvm.org/D40678.


I don't know, I haven't reviewed this feature, but I can take a look later 
today.


https://reviews.llvm.org/D34082



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


[PATCH] D40739: Pass through --undefined to Wasm LLD

2017-12-01 Thread Nicholas Wilson via Phabricator via cfe-commits
ncw created this revision.
Herald added subscribers: cfe-commits, sunfish, aheejin, jgravelle-google, 
dschuff, jfb, klimek.

This is a follow-on to https://reviews.llvm.org/D40724 (Wasm entrypoint changes 
#1, add `--undefined` argument to LLD).


Repository:
  rC Clang

https://reviews.llvm.org/D40739

Files:
  lib/Driver/ToolChains/WebAssembly.cpp
  lib/Format/ContinuationIndenter.cpp
  lib/Format/ContinuationIndenter.h
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -9934,8 +9934,8 @@
   Style.PenaltyExcessCharacter = 90;
   verifyFormat("int a; // the comment", Style);
   EXPECT_EQ("int a; // the comment\n"
-"   // aa",
-format("int a; // the comment aa", Style));
+"   // aaa",
+format("int a; // the comment aaa", Style));
   EXPECT_EQ("int a; /* first line\n"
 "* second line\n"
 "* third line\n"
@@ -9963,14 +9963,14 @@
Style));
 
   EXPECT_EQ("// foo bar baz bazfoo\n"
-"// foo bar\n",
+"// foo bar foo bar\n",
 format("// foo bar baz bazfoo\n"
-   "// foobar\n",
+   "// foo bar foo   bar\n",
Style));
   EXPECT_EQ("// foo bar baz bazfoo\n"
-"// foo bar\n",
+"// foo bar foo bar\n",
 format("// foo bar baz  bazfoo\n"
-   "// foobar\n",
+   "// foobar foo bar\n",
Style));
 
   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
@@ -9996,6 +9996,20 @@
"// foo bar baz  bazfoo bar\n"
"// foo   bar\n",
Style));
+
+  // Make sure we do not keep protruding characters if strict mode reflow is
+  // cheaper than keeping protruding characters.
+  Style.ColumnLimit = 21;
+  EXPECT_EQ("// foo foo foo foo\n"
+"// foo foo foo foo\n"
+"// foo foo foo foo\n",
+format("// foo foo foo foo foo foo foo foo foo foo foo foo\n",
+   Style));
+
+  EXPECT_EQ("int a = /* long block\n"
+"   comment */\n"
+"42;",
+format("int a = /* long block comment */ 42;", Style));
 }
 
 #define EXPECT_ALL_STYLES_EQUAL(Styles)\
Index: lib/Format/ContinuationIndenter.h
===
--- lib/Format/ContinuationIndenter.h
+++ lib/Format/ContinuationIndenter.h
@@ -123,14 +123,25 @@
   /// \brief If the current token sticks out over the end of the line, break
   /// it if possible.
   ///
-  /// \returns An extra penalty if a token was broken, otherwise 0.
+  /// \returns A pair (penalty, exceeded), where penalty is the extra penalty
+  /// when tokens are broken or lines exceed the column limit, and exceeded
+  /// indicates whether the algorithm purposefully left lines exceeding the
+  /// column limit.
   ///
   /// The returned penalty will cover the cost of the additional line breaks
   /// and column limit violation in all lines except for the last one. The
   /// penalty for the column limit violation in the last line (and in single
   /// line tokens) is handled in \c addNextStateToQueue.
-  unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
-bool AllowBreak, bool DryRun);
+  ///
+  /// \p Strict indicates whether reflowing is allowed to leave characters
+  /// protruding the column limit; if true, lines will be split strictly within
+  /// the column limit where possible; if false, words are allowed to protrude
+  /// over the column limit as long as the penalty is less than the penalty
+  /// of a break.
+  std::pair breakProtrudingToken(const FormatToken &Current,
+ LineState &State,
+ bool AllowBreak, bool DryRun,
+ bool Strict);
 
   /// \brief Returns the \c BreakableToken starting at \p Current, or nullptr
   /// if the current token cannot be broken.
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1390,7 +1390,36 @@
 Penalty = addMultilineToken(Current, State);
   } else if (State.Line->Type != LT_ImportStatement) {
 // We generally don't break import statements.
-Penalty = breakProtrudingToken(Current, State, AllowBreak, DryRun);
+LineState OriginalState = State;
+
+// Whether we force the reflowing algorithm to stay strictly within the
+// column limit.
+bool Strict = f

[PATCH] D40739: Pass through --undefined to Wasm LLD

2017-12-01 Thread Nicholas Wilson via Phabricator via cfe-commits
ncw updated this revision to Diff 125176.
ncw added a comment.

(D'oh, more trouble with arcane commands getting diffs into phabricator... 
sorry for the spam.)


Repository:
  rC Clang

https://reviews.llvm.org/D40739

Files:
  lib/Driver/ToolChains/WebAssembly.cpp


Index: lib/Driver/ToolChains/WebAssembly.cpp
===
--- lib/Driver/ToolChains/WebAssembly.cpp
+++ lib/Driver/ToolChains/WebAssembly.cpp
@@ -47,6 +47,7 @@
 CmdArgs.push_back("--strip-all");
 
   Args.AddAllArgs(CmdArgs, options::OPT_L);
+  Args.AddAllArgs(CmdArgs, options::OPT_u);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))


Index: lib/Driver/ToolChains/WebAssembly.cpp
===
--- lib/Driver/ToolChains/WebAssembly.cpp
+++ lib/Driver/ToolChains/WebAssembly.cpp
@@ -47,6 +47,7 @@
 CmdArgs.push_back("--strip-all");
 
   Args.AddAllArgs(CmdArgs, options::OPT_L);
+  Args.AddAllArgs(CmdArgs, options::OPT_u);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D40687: [compiler-rt] Switch to add_llvm_install_targets

2017-12-01 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added a comment.

Ah, that's a bummer.

compiler-rt's CMakeLists has this big shiny comment up top:

  # This build assumes that CompilerRT is checked out into the
  # 'projects/compiler-rt' or 'runtimes/compiler-rt' inside of an LLVM tree.
  # Standalone build system for CompilerRT is not yet ready.

I assume that's out of date then?


https://reviews.llvm.org/D40687



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


[PATCH] D40687: [compiler-rt] Switch to add_llvm_install_targets

2017-12-01 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

Yes, that comment is very out of date. The compiler-rt standalone build is 
essential to many of the users. It is quite common to build and use compiler-rt 
without LLVM (like sanitizer support in gcc).


https://reviews.llvm.org/D40687



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


[PATCH] D40738: Don't use Wasm function sections for more than one function

2017-12-01 Thread Dan Gohman via Phabricator via cfe-commits
sunfish accepted this revision.
sunfish added a comment.
This revision is now accepted and ready to land.

I think that was copied from LinuxTargetInfo before we figured out our current 
object file strategy. On native platforms, it's an icache optimization, because 
startup functions are all called around the same time, and then never used 
again. However, this doesn't really apply to WebAssembly. It is possible that 
WebAssembly may eventually want to put everything called during startup at the 
beginning, so that clever browser engines can start running code even before 
the whole module is downloaded, however the optimization here wouldn't be 
sufficient. So this change looks good.


Repository:
  rC Clang

https://reviews.llvm.org/D40738



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


[PATCH] D36836: [clang-tidy] Implement sonarsource-function-cognitive-complexity check

2017-12-01 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 125178.
lebedev.ri changed the repository for this revision from rL LLVM to rCTE Clang 
Tools Extra.
lebedev.ri added a comment.

Rebased.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D36836

Files:
  LICENSE.TXT
  clang-tidy/CMakeLists.txt
  clang-tidy/plugin/CMakeLists.txt
  clang-tidy/sonarsource/CMakeLists.txt
  clang-tidy/sonarsource/FunctionCognitiveComplexityCheck.cpp
  clang-tidy/sonarsource/FunctionCognitiveComplexityCheck.h
  clang-tidy/sonarsource/LICENSE.TXT
  clang-tidy/sonarsource/SONARSOURCETidyModule.cpp
  clang-tidy/tool/CMakeLists.txt
  clang-tidy/tool/ClangTidyMain.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/sonarsource-function-cognitive-complexity.rst
  test/clang-tidy/sonarsource-function-cognitive-complexity.cpp

Index: test/clang-tidy/sonarsource-function-cognitive-complexity.cpp
===
--- /dev/null
+++ test/clang-tidy/sonarsource-function-cognitive-complexity.cpp
@@ -0,0 +1,954 @@
+// RUN: %check_clang_tidy %s sonarsource-function-cognitive-complexity %t -- -config='{CheckOptions: [{key: sonarsource-function-cognitive-complexity.Threshold, value: 0}]}' -- -std=c++11 -w
+
+// any function should be checked.
+
+extern int ext_func(int x = 0);
+
+int some_func(int x = 0);
+
+static int some_other_func(int x = 0) {}
+
+template void some_templ_func(T x = 0) {}
+
+class SomeClass {
+public:
+  int *begin(int x = 0);
+  int *end(int x = 0);
+  static int func(int x = 0);
+  template void some_templ_func(T x = 0) {}
+  SomeClass() = default;
+  SomeClass(SomeClass&) = delete;
+};
+
+// nothing ever decreases cognitive complexity, so we can check all the things
+// in one go. none of the following should increase cognitive complexity:
+void unittest_false() {
+  {};
+  ext_func();
+  some_func();
+  some_other_func();
+  some_templ_func();
+  some_templ_func();
+  SomeClass::func();
+  SomeClass C;
+  C.some_templ_func();
+  C.some_templ_func();
+  C.func();
+  C.end();
+  int i = some_func();
+  i = i;
+  i++;
+  --i;
+  i < 0;
+  int j = 0 ?: 1;
+  auto k = new int;
+  delete k;
+  throw i;
+  {
+throw i;
+  }
+end:
+  return;
+}
+
+#if 1
+#define CC100
+#else
+// this macro has cognitive complexity of 100.
+// it is needed to be able to compare the testcases with the
+// reference Sonar implementation. please place it right after the first
+// CHECK-NOTES in each function
+#define CC100 if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){if(1){}if(1){}
+#endif
+
+////
+//-- B1. Increments --//
+////
+// Check that every thing listed in B1 of the specification does indeed   //
+// recieve the base increment, and that not-body does not increase nesting//
+////
+
+// break does not increase cognitive complexity.
+// only  break LABEL  does, but it is unavaliable in C or C++
+
+// continue does not increase cognitive complexity.
+// only  continue LABEL  does, but it is unavaliable in C or C++
+
+void unittest_b1_00() {
+// CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'unittest_b1_00' has cognitive complexity of 33 (threshold 0) [sonarsource-function-cognitive-complexity]
+  CC100;
+
+  if (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:3: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:9: note: +1, including nesting penalty of 0, nesting level increased to 1{{$}}
+
+if (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:11: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}}
+} else if (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:12: note: +1, nesting level increased to 2{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:18: note: +3, including nesting penalty of 2, nesting level increased to 3{{$}}
+} else {
+// CHECK-NOTES: :[[@LINE-1]]:7: note: +1, nesting level increased to 2{{$}}
+}
+  } else if (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:10: note: +1, nesting level increased to 1{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:16: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}}
+
+if (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:11: note: +2, including nesting penalty of 1, nesting level increased to 2{{$}}
+} else if (1 ? 1 : 0) {
+// CHECK-NOTES: :[[@LINE-1]]:12: note: +1, nesting level increased to 2{{$}}
+// CHECK-NOTES: :[[@LINE-2]]:18: note: +3, including nesting penalty of 2, nesting lev

[PATCH] D40687: [compiler-rt] Add install-*-stripped targets

2017-12-01 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai updated this revision to Diff 125180.
smeenai retitled this revision from "[compiler-rt] Switch to 
add_llvm_install_targets" to "[compiler-rt] Add install-*-stripped targets".
smeenai edited the summary of this revision.
smeenai added a comment.

Add targets manually


https://reviews.llvm.org/D40687

Files:
  cmake/Modules/AddCompilerRT.cmake
  cmake/base-config-ix.cmake


Index: cmake/base-config-ix.cmake
===
--- cmake/base-config-ix.cmake
+++ cmake/base-config-ix.cmake
@@ -11,6 +11,7 @@
 # Top level target used to build all compiler-rt libraries.
 add_custom_target(compiler-rt ALL)
 add_custom_target(install-compiler-rt)
+add_custom_target(install-compiler-rt-stripped)
 set_target_properties(compiler-rt PROPERTIES FOLDER "Compiler-RT Misc")
 
 # Setting these variables from an LLVM build is sufficient that compiler-rt can
Index: cmake/Modules/AddCompilerRT.cmake
===
--- cmake/Modules/AddCompilerRT.cmake
+++ cmake/Modules/AddCompilerRT.cmake
@@ -210,9 +210,18 @@
 COMMAND "${CMAKE_COMMAND}"
 -DCMAKE_INSTALL_COMPONENT=${LIB_PARENT_TARGET}
 -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
+  add_custom_target(install-${LIB_PARENT_TARGET}-stripped
+DEPENDS ${LIB_PARENT_TARGET}
+COMMAND "${CMAKE_COMMAND}"
+-DCMAKE_INSTALL_COMPONENT=${LIB_PARENT_TARGET}
+-DCMAKE_INSTALL_DO_STRIP=1
+-P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
   set_target_properties(install-${LIB_PARENT_TARGET} PROPERTIES
 FOLDER "Compiler-RT Misc")
+  set_target_properties(install-${LIB_PARENT_TARGET}-stripped PROPERTIES
+FOLDER "Compiler-RT Misc")
   add_dependencies(install-compiler-rt install-${LIB_PARENT_TARGET})
+  add_dependencies(install-compiler-rt-stripped 
install-${LIB_PARENT_TARGET}-stripped)
 endif()
   endif()
 
@@ -267,10 +276,17 @@
 COMMAND "${CMAKE_COMMAND}"
 -DCMAKE_INSTALL_COMPONENT=${libname}
 -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
+  add_custom_target(install-${libname}-stripped
+DEPENDS ${libname}
+COMMAND "${CMAKE_COMMAND}"
+-DCMAKE_INSTALL_COMPONENT=${libname}
+-DCMAKE_INSTALL_DO_STRIP=1
+-P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
   # If you have a parent target specified, we bind the new install target
   # to the parent install target.
   if(LIB_PARENT_TARGET)
 add_dependencies(install-${LIB_PARENT_TARGET} install-${libname})
+add_dependencies(install-${LIB_PARENT_TARGET}-stripped 
install-${libname}-stripped)
   endif()
 endif()
 if(APPLE)


Index: cmake/base-config-ix.cmake
===
--- cmake/base-config-ix.cmake
+++ cmake/base-config-ix.cmake
@@ -11,6 +11,7 @@
 # Top level target used to build all compiler-rt libraries.
 add_custom_target(compiler-rt ALL)
 add_custom_target(install-compiler-rt)
+add_custom_target(install-compiler-rt-stripped)
 set_target_properties(compiler-rt PROPERTIES FOLDER "Compiler-RT Misc")
 
 # Setting these variables from an LLVM build is sufficient that compiler-rt can
Index: cmake/Modules/AddCompilerRT.cmake
===
--- cmake/Modules/AddCompilerRT.cmake
+++ cmake/Modules/AddCompilerRT.cmake
@@ -210,9 +210,18 @@
 COMMAND "${CMAKE_COMMAND}"
 -DCMAKE_INSTALL_COMPONENT=${LIB_PARENT_TARGET}
 -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
+  add_custom_target(install-${LIB_PARENT_TARGET}-stripped
+DEPENDS ${LIB_PARENT_TARGET}
+COMMAND "${CMAKE_COMMAND}"
+-DCMAKE_INSTALL_COMPONENT=${LIB_PARENT_TARGET}
+-DCMAKE_INSTALL_DO_STRIP=1
+-P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
   set_target_properties(install-${LIB_PARENT_TARGET} PROPERTIES
 FOLDER "Compiler-RT Misc")
+  set_target_properties(install-${LIB_PARENT_TARGET}-stripped PROPERTIES
+FOLDER "Compiler-RT Misc")
   add_dependencies(install-compiler-rt install-${LIB_PARENT_TARGET})
+  add_dependencies(install-compiler-rt-stripped install-${LIB_PARENT_TARGET}-stripped)
 endif()
   endif()
 
@@ -267,10 +276,17 @@
 COMMAND "${CMAKE_COMMAND}"
 -DC

[PATCH] D40740: [compiler-rt] Remove out of date comment

2017-12-01 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai created this revision.
Herald added subscribers: mgorny, dberris.

Per beanz, building compiler-rt standalone is a pretty important use
case, so the comment is very out of date.


https://reviews.llvm.org/D40740

Files:
  CMakeLists.txt


Index: CMakeLists.txt
===
--- CMakeLists.txt
+++ CMakeLists.txt
@@ -1,9 +1,5 @@
 # CMake build for CompilerRT.
 #
-# This build assumes that CompilerRT is checked out into the
-# 'projects/compiler-rt' or 'runtimes/compiler-rt' inside of an LLVM tree.
-# Standalone build system for CompilerRT is not yet ready.
-#
 # An important constraint of the build is that it only produces libraries
 # based on the ability of the host toolchain to target various platforms.
 


Index: CMakeLists.txt
===
--- CMakeLists.txt
+++ CMakeLists.txt
@@ -1,9 +1,5 @@
 # CMake build for CompilerRT.
 #
-# This build assumes that CompilerRT is checked out into the
-# 'projects/compiler-rt' or 'runtimes/compiler-rt' inside of an LLVM tree.
-# Standalone build system for CompilerRT is not yet ready.
-#
 # An important constraint of the build is that it only produces libraries
 # based on the ability of the host toolchain to target various platforms.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D40739: Pass through --undefined to Wasm LLD

2017-12-01 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 added a comment.

I'm a little confused by this.  I was assuming you would do "-Wl,-u,foo" or 
"-Xlinker".I wasn't aware -u was a valid compiler flag itself.  It doesn't 
show up in --help.


Repository:
  rC Clang

https://reviews.llvm.org/D40739



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


[PATCH] D40687: [compiler-rt] Add install-*-stripped targets

2017-12-01 Thread Chris Bieneman via Phabricator via cfe-commits
beanz accepted this revision.
beanz added a comment.
This revision is now accepted and ready to land.

LGTM.


https://reviews.llvm.org/D40687



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


[PATCH] D40740: [compiler-rt] Remove out of date comment

2017-12-01 Thread Chris Bieneman via Phabricator via cfe-commits
beanz accepted this revision.
beanz added a comment.
This revision is now accepted and ready to land.

LGTM


https://reviews.llvm.org/D40740



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


[PATCH] D40687: [compiler-rt] Add install-*-stripped targets

2017-12-01 Thread Shoaib Meenai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL319569: [compiler-rt] Add install-*-stripped targets 
(authored by smeenai).

Repository:
  rL LLVM

https://reviews.llvm.org/D40687

Files:
  compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
  compiler-rt/trunk/cmake/base-config-ix.cmake


Index: compiler-rt/trunk/cmake/base-config-ix.cmake
===
--- compiler-rt/trunk/cmake/base-config-ix.cmake
+++ compiler-rt/trunk/cmake/base-config-ix.cmake
@@ -11,6 +11,7 @@
 # Top level target used to build all compiler-rt libraries.
 add_custom_target(compiler-rt ALL)
 add_custom_target(install-compiler-rt)
+add_custom_target(install-compiler-rt-stripped)
 set_target_properties(compiler-rt PROPERTIES FOLDER "Compiler-RT Misc")
 
 # Setting these variables from an LLVM build is sufficient that compiler-rt can
Index: compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
@@ -210,9 +210,18 @@
 COMMAND "${CMAKE_COMMAND}"
 -DCMAKE_INSTALL_COMPONENT=${LIB_PARENT_TARGET}
 -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
+  add_custom_target(install-${LIB_PARENT_TARGET}-stripped
+DEPENDS ${LIB_PARENT_TARGET}
+COMMAND "${CMAKE_COMMAND}"
+-DCMAKE_INSTALL_COMPONENT=${LIB_PARENT_TARGET}
+-DCMAKE_INSTALL_DO_STRIP=1
+-P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
   set_target_properties(install-${LIB_PARENT_TARGET} PROPERTIES
 FOLDER "Compiler-RT Misc")
+  set_target_properties(install-${LIB_PARENT_TARGET}-stripped PROPERTIES
+FOLDER "Compiler-RT Misc")
   add_dependencies(install-compiler-rt install-${LIB_PARENT_TARGET})
+  add_dependencies(install-compiler-rt-stripped 
install-${LIB_PARENT_TARGET}-stripped)
 endif()
   endif()
 
@@ -267,10 +276,17 @@
 COMMAND "${CMAKE_COMMAND}"
 -DCMAKE_INSTALL_COMPONENT=${libname}
 -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
+  add_custom_target(install-${libname}-stripped
+DEPENDS ${libname}
+COMMAND "${CMAKE_COMMAND}"
+-DCMAKE_INSTALL_COMPONENT=${libname}
+-DCMAKE_INSTALL_DO_STRIP=1
+-P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
   # If you have a parent target specified, we bind the new install target
   # to the parent install target.
   if(LIB_PARENT_TARGET)
 add_dependencies(install-${LIB_PARENT_TARGET} install-${libname})
+add_dependencies(install-${LIB_PARENT_TARGET}-stripped 
install-${libname}-stripped)
   endif()
 endif()
 if(APPLE)


Index: compiler-rt/trunk/cmake/base-config-ix.cmake
===
--- compiler-rt/trunk/cmake/base-config-ix.cmake
+++ compiler-rt/trunk/cmake/base-config-ix.cmake
@@ -11,6 +11,7 @@
 # Top level target used to build all compiler-rt libraries.
 add_custom_target(compiler-rt ALL)
 add_custom_target(install-compiler-rt)
+add_custom_target(install-compiler-rt-stripped)
 set_target_properties(compiler-rt PROPERTIES FOLDER "Compiler-RT Misc")
 
 # Setting these variables from an LLVM build is sufficient that compiler-rt can
Index: compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
@@ -210,9 +210,18 @@
 COMMAND "${CMAKE_COMMAND}"
 -DCMAKE_INSTALL_COMPONENT=${LIB_PARENT_TARGET}
 -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
+  add_custom_target(install-${LIB_PARENT_TARGET}-stripped
+DEPENDS ${LIB_PARENT_TARGET}
+COMMAND "${CMAKE_COMMAND}"
+-DCMAKE_INSTALL_COMPONENT=${LIB_PARENT_TARGET}
+-DCMAKE_INSTALL_DO_STRIP=1
+-P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
   set_target_properties(install-${LIB_PARENT_TARGET} PROPERTIES
 FOLDER "Compiler-RT Misc")
+  set_target_properties(install-${LIB_PARENT_TARGET}-stripped PROPERTIES
+FOLDER "Compiler-RT Misc")
   add_dependencies(install-compiler-rt install-${LIB_PARENT_TARGET})
+  add_dependencies(install-compiler-rt-stripped install-

[PATCH] D40740: [compiler-rt] Remove out of date comment

2017-12-01 Thread Shoaib Meenai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL319570: [compiler-rt] Remove out of date comment (authored 
by smeenai).

Repository:
  rL LLVM

https://reviews.llvm.org/D40740

Files:
  compiler-rt/trunk/CMakeLists.txt


Index: compiler-rt/trunk/CMakeLists.txt
===
--- compiler-rt/trunk/CMakeLists.txt
+++ compiler-rt/trunk/CMakeLists.txt
@@ -1,9 +1,5 @@
 # CMake build for CompilerRT.
 #
-# This build assumes that CompilerRT is checked out into the
-# 'projects/compiler-rt' or 'runtimes/compiler-rt' inside of an LLVM tree.
-# Standalone build system for CompilerRT is not yet ready.
-#
 # An important constraint of the build is that it only produces libraries
 # based on the ability of the host toolchain to target various platforms.
 


Index: compiler-rt/trunk/CMakeLists.txt
===
--- compiler-rt/trunk/CMakeLists.txt
+++ compiler-rt/trunk/CMakeLists.txt
@@ -1,9 +1,5 @@
 # CMake build for CompilerRT.
 #
-# This build assumes that CompilerRT is checked out into the
-# 'projects/compiler-rt' or 'runtimes/compiler-rt' inside of an LLVM tree.
-# Standalone build system for CompilerRT is not yet ready.
-#
 # An important constraint of the build is that it only produces libraries
 # based on the ability of the host toolchain to target various platforms.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34082: [Frontend] 'Show hotness' can be used with a sampling profile

2017-12-01 Thread Adam Nemet via Phabricator via cfe-commits
anemet added a comment.

Looks like it's a test problem.  When I tweak the sample profile file according 
to https://clang.llvm.org/docs/UsersManual.html#sample-profile-text-format, I 
do get hotness on the remarks.


https://reviews.llvm.org/D34082



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


[PATCH] D40739: Pass through --undefined to Wasm LLD

2017-12-01 Thread Nicholas Wilson via Phabricator via cfe-commits
ncw added a comment.

I didn't know it existed either, and you're right it's odd that it doesn't 
appear in the help text... However it duly exists and is implemented in 
clang/lib/Driver/ToolChains/Gnu.cpp, without any note that it's deprecated. 
`man gcc` documents it.


Repository:
  rC Clang

https://reviews.llvm.org/D40739



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


[PATCH] D40562: [Sema] Ignore decls in namespaces when global decls are not wanted.

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

In https://reviews.llvm.org/D40562#941753, @ilya-biryukov wrote:

> In https://reviews.llvm.org/D40562#941570, @arphaman wrote:
>
> > I'm not actually 100% sure, but I would imagine that this one of the 
> > reasons, yes. It would be nice to improve the cache to have things like 
> > namespace-level `Decl`, although how will lookup work in that case? Btw, do 
> > you think the cache can be reused in clangd as well?
>
>
> As Eric mentioned, we are planning to have project-global completion for 
> namespace-level Decls (to have completion items not #included in the current 
> file and add the #include directive properly).  So the cache is probably not 
> that useful to clangd long-term.


Interesting, thanks! Will this be something that clients of clangd can opt-out 
from? Or at least configure certain aspects of the behaviour?

> For proper lookup in the cache that include all namespace-level Decls I'd go 
> with tweaking `LookupVisibleDecls` so that it does not deserialize everything 
> from the preamble, but rather provides a list of scopes that we need to get 
> completion items from. Though sounds simple, it may be a non-trivial change 
> and we shouldn't probably pursue it as part of this change.
>  (We'll probably need it for clangd too).
> 
> In https://reviews.llvm.org/D40562#941735, @ioeric wrote:
> 
>> I took a quick look at the completion cache and lookup code. I think the 
>> completion cache also assumes that top-level decls are only TU-level decls, 
>> and this assumption seems to be also built into the lookup code. At this 
>> point, I am inclined to add a separate completion option for what I want 
>> (`IgnoreDeclsInTUOrNamespaces`?). Regarding cache in clangd, I think it 
>> might be useful short-term, when we still use Sema's global code completion, 
>> but long term, we would use symbols from clangd's indexes, so the cache 
>> would not be useful anymore.
> 
> 
> +1 for having a separate flag. Maybe call it `IncludeNamespaceLevelDecls` 
> instead? (I'd say TU is also a (global) namespace from completion's point of 
> view).

I agree with the new flag as well. I would also like to see a followup patch 
where this change is used before this is committed.


https://reviews.llvm.org/D40562



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


[PATCH] D40731: Integrate CHash into CLang

2017-12-01 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

Please run Clang-format and Clang-tidy modernize over newly added code.




Comment at: include/clang/AST/CHashVisitor.h:1
+#ifndef __CHASH_VISITOR
+#define __CHASH_VISITOR

Please loon onto other headers for inclusion guards style.



Comment at: include/clang/AST/CHashVisitor.h:9
+#include "llvm/Support/MD5.h"
+
+

No empty lines between header groups.



Comment at: include/clang/AST/CHashVisitor.h:14
+#include 
+
+

Unnecessary empty line.



Comment at: include/clang/AST/CHashVisitor.h:18
+
+namespace CHashConstants {
+enum  {

Please add empty line below.



Comment at: include/clang/AST/CHashVisitor.h:153
+};
+}
+

} // namespace CHashConstants

Please add empty line above.



Comment at: include/clang/AST/CHashVisitor.h:159
+
+typedef clang::RecursiveASTVisitor> Inherited;
+public:

Please use using instead of typedef same in other places.



Comment at: include/clang/AST/CHashVisitor.h:160
+typedef clang::RecursiveASTVisitor> Inherited;
+public:
+typedef H Hash;

Please add empty line above.



Comment at: include/clang/AST/CHashVisitor.h:446
+Hash &topHash() { return HashStack.back(); }
+
+

Unnecessary lines.



Comment at: include/clang/AST/CHashVisitor.h:450
+
+}
+#endif

} // namespace clang



Comment at: include/clang/AST/CHashVisitor.h:451
+}
+#endif

#endif // 


Repository:
  rC Clang

https://reviews.llvm.org/D40731



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


[PATCH] D40739: Pass through --undefined to Wasm LLD

2017-12-01 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 added a comment.

Oh I see.  lgtm.   Do we need to update any tests?   I see we won't have a 
wasm-ld.c test yet?   We should add one?


Repository:
  rC Clang

https://reviews.llvm.org/D40739



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


[PATCH] D40739: Pass through --undefined to Wasm LLD

2017-12-01 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 added a comment.

By the way, thank you for all these wasm patches!


Repository:
  rC Clang

https://reviews.llvm.org/D40739



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


[PATCH] D40731: Integrate CHash into CLang

2017-12-01 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

We already have mechanisms to hash the AST. I'm strongly opposed to adding 
another one (and requiring AST modifications to update yet more such 
mechanisms).

Please look at the work that Richard Trieu has been doing recently to create 
stable-across-TUs hashes of statements and declarations, start a conversation 
on cfe-dev about integrating your approach and the existing Profile approach, 
and try to reach consensus on a way forward that doesn't leave us with multiple 
different hashing mechanisms. Replacing the Profile mechanism with a 
tablegen-driven one such as the one in this patch (and then generating the 
various hashing functions with their distinct requirements from that shared 
description) does seem like it could be a reasonable approach to me, but it 
needs to be a replacement rather than keeping both mechanisms around.


Repository:
  rC Clang

https://reviews.llvm.org/D40731



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


[PATCH] D36357: Added a better diagnostic when using the delete operator with lambdas

2017-12-01 Thread Nicolas Lesser via Phabricator via cfe-commits
Rakete updated this revision to Diff 125189.
Rakete added a comment.

Updated error message, added a FixItHint + a rebase and friendly ping :)


https://reviews.llvm.org/D36357

Files:
  include/clang/Basic/DiagnosticParseKinds.td
  lib/Parse/ParseExprCXX.cpp
  test/Parser/cxx0x-lambda-expressions.cpp
  test/SemaCXX/new-delete-0x.cpp

Index: test/SemaCXX/new-delete-0x.cpp
===
--- test/SemaCXX/new-delete-0x.cpp
+++ test/SemaCXX/new-delete-0x.cpp
@@ -34,6 +34,7 @@
 void bad_deletes()
 {
   // 'delete []' is always array delete, per [expr.delete]p1.
-  // FIXME: Give a better diagnostic.
-  delete []{ return (int*)0; }(); // expected-error {{expected expression}}
+  delete []{ return (int*)0; }(); // expected-error {{'[]' after delete interpreted as 'delete[]'}}
+  // expected-note@-1 {{add parentheses around the lambda}}
 }
+
Index: test/Parser/cxx0x-lambda-expressions.cpp
===
--- test/Parser/cxx0x-lambda-expressions.cpp
+++ test/Parser/cxx0x-lambda-expressions.cpp
@@ -53,7 +53,8 @@
   void delete_lambda(int *p) {
 delete [] p;
 delete [] (int*) { new int }; // ok, compound-literal, not lambda
-delete [] { return new int; } (); // expected-error{{expected expression}}
+delete [] { return new int; } (); // expected-error {{'[]' after delete interpreted as 'delete[]'}}
+// expected-note@-1 {{add parentheses around the lambda}}
 delete [&] { return new int; } (); // ok, lambda
   }
 
Index: lib/Parse/ParseExprCXX.cpp
===
--- lib/Parse/ParseExprCXX.cpp
+++ lib/Parse/ParseExprCXX.cpp
@@ -2896,15 +2896,45 @@
 //   [Footnote: A lambda expression with a lambda-introducer that consists
 //  of empty square brackets can follow the delete keyword if
 //  the lambda expression is enclosed in parentheses.]
-// FIXME: Produce a better diagnostic if the '[]' is unambiguously a
-//lambda-introducer.
-ArrayDelete = true;
-BalancedDelimiterTracker T(*this, tok::l_square);
+TentativeParsingAction TPA(*this);
 
-T.consumeOpen();
-T.consumeClose();
-if (T.getCloseLocation().isInvalid())
-  return ExprError();
+// Basic lookahead to check if we have a lambda expression. If we
+// encounter two braces with a semicolon, we can be pretty sure
+// that this is a lambda, not say a compound literal. 
+if (!SkipUntil(tok::l_brace, SkipUntilFlags::StopAtSemi) ||
+(NextToken().isNot(tok::r_brace) && !SkipUntil(tok::semi)) ||
+!SkipUntil(tok::r_brace, SkipUntilFlags::StopAtSemi)) {
+  TPA.Revert();
+  ArrayDelete = true;
+  BalancedDelimiterTracker T(*this, tok::l_square);
+
+  T.consumeOpen();
+  T.consumeClose();
+  if (T.getCloseLocation().isInvalid())
+return ExprError();
+} else {
+  TPA.Revert();
+
+  // Warn if the non-capturing lambda isn't surrounded by parenthesis
+  // to disambiguate it from 'delete[]'.
+  ExprResult Lambda = TryParseLambdaExpression();
+  if (!Lambda.isInvalid()) {
+SourceLocation StartLoc = Lambda.get()->getLocStart();
+Diag(Start, diag::err_lambda_after_delete)
+<< SourceRange(Start, StartLoc.getLocWithOffset(1));
+
+SourceLocation BeforeBracket = StartLoc.getLocWithOffset(-1);
+Diag(BeforeBracket, diag::note_lambda_after_delete)
+<< FixItHint::CreateInsertion(BeforeBracket, "(")
+<< FixItHint::CreateInsertion(
+   Lambda.get()->getLocEnd().getLocWithOffset(1), ")");
+
+// Evaluate any postfix expressions used on the lambda.
+Lambda = ParsePostfixExpressionSuffix(Lambda);
+return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
+  Lambda.get());
+  }
+}
   }
 
   ExprResult Operand(ParseCastExpression(false));
Index: include/clang/Basic/DiagnosticParseKinds.td
===
--- include/clang/Basic/DiagnosticParseKinds.td
+++ include/clang/Basic/DiagnosticParseKinds.td
@@ -99,6 +99,10 @@
   InGroup, DefaultIgnore;
 def ext_alignof_expr : ExtWarn<
   "%0 applied to an expression is a GNU extension">, InGroup;
+def err_lambda_after_delete : Error<
+  "'[]' after delete interpreted as 'delete[]'">;
+def note_lambda_after_delete : Note<
+  "add parentheses around the lambda">;
 
 def warn_microsoft_dependent_exists : Warning<
   "dependent %select{__if_not_exists|__if_exists}0 declarations are ignored">, 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r319576 - Partially fix comment in test broken in r306079 and r306948

2017-12-01 Thread Adam Nemet via cfe-commits
Author: anemet
Date: Fri Dec  1 11:59:37 2017
New Revision: 319576

URL: http://llvm.org/viewvc/llvm-project?rev=319576&view=rev
Log:
Partially fix comment in test broken in r306079 and r306948

A RUN line was referring to the previous RUN line but a new test was added in
between them.  Just reorder the lines.

Note this still does not completely fix this the brokenness of the comment as
the driver-based test gained a new hotness-threshold argument in r306948 but
I'll fix that is a separate commit.

Modified:
cfe/trunk/test/Frontend/optimization-remark-with-hotness.c

Modified: cfe/trunk/test/Frontend/optimization-remark-with-hotness.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Frontend/optimization-remark-with-hotness.c?rev=319576&r1=319575&r2=319576&view=diff
==
--- cfe/trunk/test/Frontend/optimization-remark-with-hotness.c (original)
+++ cfe/trunk/test/Frontend/optimization-remark-with-hotness.c Fri Dec  1 
11:59:37 2017
@@ -11,12 +11,6 @@
 // RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \
 // RUN: -Rpass-analysis=inline -Rpass-missed=inline \
 // RUN: -fdiagnostics-show-hotness -verify
-// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \
-// RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \
-// RUN: -fprofile-sample-use=%t-sample.profdata -Rpass=inline \
-// RUN: -Rpass-analysis=inline -Rpass-missed=inline \
-// RUN: -fdiagnostics-show-hotness -fdiagnostics-hotness-threshold=10 \
-// RUN: -verify
 // The clang version of the previous test.
 // RUN: %clang -target x86_64-apple-macosx10.9 %s -c -emit-llvm -o /dev/null \
 // RUN: -fprofile-instr-use=%t.profdata -Rpass=inline \
@@ -25,6 +19,12 @@
 // RUN: -Xclang -verify
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \
 // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \
+// RUN: -fprofile-sample-use=%t-sample.profdata -Rpass=inline \
+// RUN: -Rpass-analysis=inline -Rpass-missed=inline \
+// RUN: -fdiagnostics-show-hotness -fdiagnostics-hotness-threshold=10 \
+// RUN: -verify
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \
+// RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \
 // RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \
 // RUN: -Rpass-analysis=inline 2>&1 | FileCheck -check-prefix=HOTNESS_OFF 
%s
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \


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


r319577 - Fix opt-remark with hotness testcase for sample-based PGO

2017-12-01 Thread Adam Nemet via cfe-commits
Author: anemet
Date: Fri Dec  1 11:59:42 2017
New Revision: 319577

URL: http://llvm.org/viewvc/llvm-project?rev=319577&view=rev
Log:
Fix opt-remark with hotness testcase for sample-based PGO

1. Require hotness on all remark lines with -verify.

3. Fix the samplePGO file to actually produce hotness on each line.

The second remark has hotness 60 rather 30 which I don't quite understand but
testing this is strictly better than before.  It also unblocks the commit of
D40678.

Modified:

cfe/trunk/test/Frontend/Inputs/optimization-remark-with-hotness-sample.proftext
cfe/trunk/test/Frontend/optimization-remark-with-hotness.c

Modified: 
cfe/trunk/test/Frontend/Inputs/optimization-remark-with-hotness-sample.proftext
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Frontend/Inputs/optimization-remark-with-hotness-sample.proftext?rev=319577&r1=319576&r2=319577&view=diff
==
--- 
cfe/trunk/test/Frontend/Inputs/optimization-remark-with-hotness-sample.proftext 
(original)
+++ 
cfe/trunk/test/Frontend/Inputs/optimization-remark-with-hotness-sample.proftext 
Fri Dec  1 11:59:42 2017
@@ -1,7 +1,7 @@
-foo:0:0
- 0: 0
+foo:29:29
+ 0: 29
 bar:29:29
- 9: foo:0
-main:0:0
- 0: 0 bar:0
+ 8: 29 foo:29
+main:29:1
+ 3: 29 bar:29
 

Modified: cfe/trunk/test/Frontend/optimization-remark-with-hotness.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Frontend/optimization-remark-with-hotness.c?rev=319577&r1=319576&r2=319577&view=diff
==
--- cfe/trunk/test/Frontend/optimization-remark-with-hotness.c (original)
+++ cfe/trunk/test/Frontend/optimization-remark-with-hotness.c Fri Dec  1 
11:59:42 2017
@@ -56,13 +56,13 @@ void bar(int x) {
   // THRESHOLD-NOT: hotness
   // NO_PGO: '-fdiagnostics-show-hotness' requires profile-guided optimization 
information
   // NO_PGO: '-fdiagnostics-hotness-threshold=' requires profile-guided 
optimization information
-  // expected-remark@+1 {{foo inlined into bar with cost=always}}
+  // expected-remark@+1 {{foo inlined into bar with cost=always (hotness:}}
   sum += foo(x, x - 2);
 }
 
 int main(int argc, const char *argv[]) {
   for (int i = 0; i < 30; i++)
-// expected-remark@+1 {{bar not inlined into main because it should never 
be inlined}}
+// expected-remark@+1 {{bar not inlined into main because it should never 
be inlined (cost=never) (hotness:}}
 bar(argc);
   return sum;
 }


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


r319578 - Fix the second part of the broken comment from r306079

2017-12-01 Thread Adam Nemet via cfe-commits
Author: anemet
Date: Fri Dec  1 11:59:45 2017
New Revision: 319578

URL: http://llvm.org/viewvc/llvm-project?rev=319578&view=rev
Log:
Fix the second part of the broken comment from r306079

The driver-based test is still not identical to the front-end line, remove the
hotness threshold from there and add a new front-end based test with
threshold.

Modified:
cfe/trunk/test/Frontend/optimization-remark-with-hotness.c

Modified: cfe/trunk/test/Frontend/optimization-remark-with-hotness.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Frontend/optimization-remark-with-hotness.c?rev=319578&r1=319577&r2=319578&view=diff
==
--- cfe/trunk/test/Frontend/optimization-remark-with-hotness.c (original)
+++ cfe/trunk/test/Frontend/optimization-remark-with-hotness.c Fri Dec  1 
11:59:45 2017
@@ -15,8 +15,7 @@
 // RUN: %clang -target x86_64-apple-macosx10.9 %s -c -emit-llvm -o /dev/null \
 // RUN: -fprofile-instr-use=%t.profdata -Rpass=inline \
 // RUN: -Rpass-analysis=inline -Rpass-missed=inline \
-// RUN: -fdiagnostics-show-hotness -fdiagnostics-hotness-threshold=10 \
-// RUN: -Xclang -verify
+// RUN: -fdiagnostics-show-hotness -Xclang -verify
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \
 // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \
 // RUN: -fprofile-sample-use=%t-sample.profdata -Rpass=inline \
@@ -26,6 +25,11 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \
 // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \
 // RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \
+// RUN: -Rpass-analysis=inline -Rpass-missed=inline \
+// RUN: -fdiagnostics-show-hotness -fdiagnostics-hotness-threshold=10 
-verify
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \
+// RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \
+// RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \
 // RUN: -Rpass-analysis=inline 2>&1 | FileCheck -check-prefix=HOTNESS_OFF 
%s
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \
 // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \


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


[clang-tools-extra] r319579 - [clangd] Define constants in the right namespace. NFC

2017-12-01 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Dec  1 12:03:19 2017
New Revision: 319579

URL: http://llvm.org/viewvc/llvm-project?rev=319579&view=rev
Log:
[clangd] Define constants in the right namespace. NFC

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

Modified: clang-tools-extra/trunk/clangd/FuzzyMatch.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FuzzyMatch.cpp?rev=319579&r1=319578&r2=319579&view=diff
==
--- clang-tools-extra/trunk/clangd/FuzzyMatch.cpp (original)
+++ clang-tools-extra/trunk/clangd/FuzzyMatch.cpp Fri Dec  1 12:03:19 2017
@@ -58,8 +58,9 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/Support/Format.h"
 
+namespace clang {
+namespace clangd {
 using namespace llvm;
-using namespace clang::clangd;
 
 const int FuzzyMatcher::MaxPat;
 const int FuzzyMatcher::MaxWord;
@@ -371,3 +372,6 @@ llvm::SmallString<256> FuzzyMatcher::dum
 
   return Result;
 }
+
+} // namespace clangd
+} // namespace clang


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


[PATCH] D34082: [Frontend] 'Show hotness' can be used with a sampling profile

2017-12-01 Thread Adam Nemet via Phabricator via cfe-commits
anemet added a comment.

Sorted these out in https://reviews.llvm.org/rL319576, 
https://reviews.llvm.org/rL319577 and https://reviews.llvm.org/rL319578.


https://reviews.llvm.org/D34082



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


[PATCH] D40671: [clang-tidy] Support specific checks for NOLINT directive

2017-12-01 Thread Anton via Phabricator via cfe-commits
xgsa updated this revision to Diff 125190.
xgsa added a comment.

An item to release notes was added.

Also I have added a paragraph about NOLINT to the main documentation page, 
because I suppose it's useful information and it's related to the feature. 
Please, let me know if it should be added with a separate commit or shouldn't 
be added at all.


https://reviews.llvm.org/D40671

Files:
  clang-tidy/ClangTidyDiagnosticConsumer.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/index.rst
  test/clang-tidy/nolint.cpp
  test/clang-tidy/nolintnextline.cpp

Index: docs/clang-tidy/index.rst
===
--- docs/clang-tidy/index.rst
+++ docs/clang-tidy/index.rst
@@ -250,6 +250,27 @@
   value:   'some value'
   ...
 
+Generally, there is no need to suppress :program:`clang-tidy` diagnostics. If
+there are false positives, either a bug should be reported or the code should be
+updated to be clear for both tool and developer. However, if there is a need to
+silent some diagnostics for a line of code, the ``NOLINT`` or ``NOLINTNEXTLINE``
+comments can be used. For example:
+
+.. code-block:: c++
+
+  class Foo
+  {
+// Skip all the diagnostics for the line
+Foo(int param); // NOLINT
+
+// Skip only the specified checks for the line
+Foo(double param); // NOLINT(google-explicit-constructor, google-runtime-int)
+
+// Skip only the specified diagnostics for the next line
+// NOLINTNEXTLINE (google-explicit-constructor, google-runtime-int)
+Foo(bool param); 
+  };
+
 .. _LibTooling: http://clang.llvm.org/docs/LibTooling.html
 .. _How To Setup Tooling For LLVM: http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
 
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -256,6 +256,9 @@
   - `hicpp-use-nullptr `_
   - `hicpp-vararg `_
 
+- The ``NOLINT`` and ``NOLINTNEXTLINE`` suppression comments were extended to support the list of checks
+  to disable in parentheses.
+
 Improvements to include-fixer
 -
 
Index: test/clang-tidy/nolint.cpp
===
--- test/clang-tidy/nolint.cpp
+++ test/clang-tidy/nolint.cpp
@@ -13,7 +13,18 @@
 
 class B { B(int i); }; // NOLINT
 
-class C { C(int i); }; // NOLINT(we-dont-care-about-categories-yet)
+class C { C(int i); }; // NOLINT(for-some-other-check)
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit
+
+class C1 { C1(int i); }; // NOLINT(*)
+
+class C2 { C2(int i); }; // NOLINT(not-closed-bracket-is-treated-as-skip-all
+
+class C3 { C3(int i); }; // NOLINT(google-explicit-constructor)
+
+class C4 { C4(int i); }; // NOLINT(some-check, google-explicit-constructor)
+
+class C5 { C5(int i); }; // NOLINT without-brackets-skip-all, another-check
 
 void f() {
   int i;
@@ -35,4 +46,4 @@
 #define DOUBLE_MACRO MACRO(H) // NOLINT
 DOUBLE_MACRO
 
-// CHECK-MESSAGES: Suppressed 8 warnings (8 NOLINT)
+// CHECK-MESSAGES: Suppressed 12 warnings (12 NOLINT)
Index: test/clang-tidy/nolintnextline.cpp
===
--- test/clang-tidy/nolintnextline.cpp
+++ test/clang-tidy/nolintnextline.cpp
@@ -4,8 +4,24 @@
 // NOLINTNEXTLINE
 class B { B(int i); };
 
-// NOLINTNEXTLINE(we-dont-care-about-categories-yet)
+// NOLINTNEXTLINE(for-some-other-check)
 class C { C(int i); };
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit
+
+// NOLINTNEXTLINE(*)
+class C1 { C1(int i); };
+
+// NOLINTNEXTLINE(not-closed-bracket-is-treated-as-skip-all
+class C2 { C2(int i); };
+
+// NOLINTNEXTLINE(google-explicit-constructor)
+class C3 { C3(int i); };
+
+// NOLINTNEXTLINE(some-check, google-explicit-constructor)
+class C4 { C4(int i); };
+
+// NOLINTNEXTLINE without-brackets-skip-all, another-check
+class C5 { C5(int i); };
 
 
 // NOLINTNEXTLINE
@@ -28,6 +44,6 @@
 // NOLINTNEXTLINE
 MACRO_NOARG
 
-// CHECK-MESSAGES: Suppressed 4 warnings (4 NOLINT)
+// CHECK-MESSAGES: Suppressed 8 warnings (8 NOLINT)
 
 // RUN: %check_clang_tidy %s google-explicit-constructor %t --
Index: clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/ASTDiagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Frontend/DiagnosticRenderer.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include 
 #include 
@@ -290,7 +291,38 @@
   LastErrorPassesLineFilter = false;
 }
 
-static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) {
+static bool I

[PATCH] D40743: Make rehash(0) work with ubsan's unsigned-integer-overflow.

2017-12-01 Thread Dan Albert via Phabricator via cfe-commits
danalbert created this revision.

Repository:
  rCXX libc++

https://reviews.llvm.org/D40743

Files:
  include/__hash_table


Index: include/__hash_table
===
--- include/__hash_table
+++ include/__hash_table
@@ -2136,7 +2136,7 @@
 void
 __hash_table<_Tp, _Hash, _Equal, _Alloc>::rehash(size_type __n)
 {
-if (__n == 1)
+if (__n < 2)
 __n = 2;
 else if (__n & (__n - 1))
 __n = __next_prime(__n);


Index: include/__hash_table
===
--- include/__hash_table
+++ include/__hash_table
@@ -2136,7 +2136,7 @@
 void
 __hash_table<_Tp, _Hash, _Equal, _Alloc>::rehash(size_type __n)
 {
-if (__n == 1)
+if (__n < 2)
 __n = 2;
 else if (__n & (__n - 1))
 __n = __next_prime(__n);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D40044: [CodeGen] convert math libcalls/builtins to equivalent LLVM intrinsics

2017-12-01 Thread Eli Friedman via Phabricator via cfe-commits
efriedma accepted this revision.
efriedma added a comment.
This revision is now accepted and ready to land.

LGTM.


https://reviews.llvm.org/D40044



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


[PATCH] D40746: Correctly handle line directives without filenames that come first in the file

2017-12-01 Thread Hans Wennborg via Phabricator via cfe-commits
hans created this revision.

The comment in LineTableInfo::AddLineNote says "An unspecified
FilenameID means use the last filename if available, or the main source
file otherwise.", but the second part of that sentence was never
actually implemented. This lead to asserts when writing the line table
to a PCH file.

(Chromium runs into this when building with the latest MS SDK.)


https://reviews.llvm.org/D40746

Files:
  include/clang/Basic/SourceManagerInternals.h
  lib/Basic/SourceManager.cpp
  test/PCH/line-directive-nofilename.c
  test/PCH/line-directive-nofilename.h


Index: test/PCH/line-directive-nofilename.h
===
--- /dev/null
+++ test/PCH/line-directive-nofilename.h
@@ -0,0 +1,5 @@
+#line 42
+int foo; // This should appear as at line-directive-nofilename.h:42
+
+#line 100 "foobar.h"
+int bar; // This should appear as at foobar.h:100
Index: test/PCH/line-directive-nofilename.c
===
--- /dev/null
+++ test/PCH/line-directive-nofilename.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -emit-pch -o %t %S/line-directive-nofilename.h
+// RUN: not %clang_cc1 -include-pch %t -fsyntax-only %s 2>&1 | FileCheck %s
+
+// This causes an "error: redefinition" diagnostic. The notes will have the
+// locations of the declarations from the PCH file.
+double foo, bar;
+
+// CHECK: line-directive-nofilename.h:42:5: note: previous definition is here
+// CHECK: foobar.h:100:5: note: previous definition is here
Index: lib/Basic/SourceManager.cpp
===
--- lib/Basic/SourceManager.cpp
+++ lib/Basic/SourceManager.cpp
@@ -207,13 +207,19 @@
 /// system header or extern C system header.
 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
 int FilenameID, unsigned EntryExit,
-SrcMgr::CharacteristicKind FileKind) {
+SrcMgr::CharacteristicKind FileKind,
+const SourceManager &SM) {
   std::vector &Entries = LineEntries[FID];
 
   // An unspecified FilenameID means use the last filename if available, or the
   // main source file otherwise.
-  if (FilenameID == -1 && !Entries.empty())
-FilenameID = Entries.back().FilenameID;
+  if (FilenameID == -1) {
+if (!Entries.empty())
+  FilenameID = Entries.back().FilenameID;
+else
+  FilenameID = 
getLineTableFilenameID(SM.getFileEntryForID(FID)->getName());
+  }
+  assert(FilenameID != -1);
 
   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
  "Adding line entries out of order!");
@@ -297,7 +303,7 @@
 EntryExit = 2;
 
   LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
- EntryExit, FileKind);
+ EntryExit, FileKind, *this);
 }
 
 LineTableInfo &SourceManager::getLineTable() {
Index: include/clang/Basic/SourceManagerInternals.h
===
--- include/clang/Basic/SourceManagerInternals.h
+++ include/clang/Basic/SourceManagerInternals.h
@@ -108,10 +108,9 @@
 
   unsigned getNumFilenames() const { return FilenamesByID.size(); }
 
-  void AddLineNote(FileID FID, unsigned Offset,
-   unsigned LineNo, int FilenameID,
-   unsigned EntryExit, SrcMgr::CharacteristicKind FileKind);
-
+  void AddLineNote(FileID FID, unsigned Offset, unsigned LineNo, int 
FilenameID,
+   unsigned EntryExit, SrcMgr::CharacteristicKind FileKind,
+   const SourceManager &SM);
 
   /// \brief Find the line entry nearest to FID that is before it.
   ///


Index: test/PCH/line-directive-nofilename.h
===
--- /dev/null
+++ test/PCH/line-directive-nofilename.h
@@ -0,0 +1,5 @@
+#line 42
+int foo; // This should appear as at line-directive-nofilename.h:42
+
+#line 100 "foobar.h"
+int bar; // This should appear as at foobar.h:100
Index: test/PCH/line-directive-nofilename.c
===
--- /dev/null
+++ test/PCH/line-directive-nofilename.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -emit-pch -o %t %S/line-directive-nofilename.h
+// RUN: not %clang_cc1 -include-pch %t -fsyntax-only %s 2>&1 | FileCheck %s
+
+// This causes an "error: redefinition" diagnostic. The notes will have the
+// locations of the declarations from the PCH file.
+double foo, bar;
+
+// CHECK: line-directive-nofilename.h:42:5: note: previous definition is here
+// CHECK: foobar.h:100:5: note: previous definition is here
Index: lib/Basic/SourceManager.cpp
===
--- lib/Basic/SourceManager.cpp
+++ lib/Basic/SourceManager.cpp
@@ -207,13 +207,19 @@
 /// system header or extern C system header.
 void LineTableInfo::AddLineNote(Fil

[PATCH] D40748: [ThinLTO] Enable importing of aliases as copy of aliasee

2017-12-01 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson created this revision.
Herald added a subscriber: inglorion.

Clang side changes to go with LLVM change to import aliases as
a copy of their aliasee. Simply refactor out some handling that
is moved to LLVM for use elsewhere.

Depends on https://reviews.llvm.org/D40747.


Repository:
  rC Clang

https://reviews.llvm.org/D40748

Files:
  lib/CodeGen/BackendUtil.cpp


Index: lib/CodeGen/BackendUtil.cpp
===
--- lib/CodeGen/BackendUtil.cpp
+++ lib/CodeGen/BackendUtil.cpp
@@ -1038,23 +1038,8 @@
   // we should only invoke this using the individual indexes written out
   // via a WriteIndexesThinBackend.
   FunctionImporter::ImportMapTy ImportList;
-  for (auto &GlobalList : *CombinedIndex) {
-// Ignore entries for undefined references.
-if (GlobalList.second.SummaryList.empty())
-  continue;
-
-auto GUID = GlobalList.first;
-assert(GlobalList.second.SummaryList.size() == 1 &&
-   "Expected individual combined index to have one summary per GUID");
-auto &Summary = GlobalList.second.SummaryList[0];
-// Skip the summaries for the importing module. These are included to
-// e.g. record required linkage changes.
-if (Summary->modulePath() == M->getModuleIdentifier())
-  continue;
-// Doesn't matter what value we plug in to the map, just needs an entry
-// to provoke importing by thinBackend.
-ImportList[Summary->modulePath()][GUID] = 1;
-  }
+  llvm::ComputeCrossModuleImportForModuleFromIndex(M->getModuleIdentifier(),
+   *CombinedIndex, ImportList);
 
   std::vector> OwnedImports;
   MapVector ModuleMap;


Index: lib/CodeGen/BackendUtil.cpp
===
--- lib/CodeGen/BackendUtil.cpp
+++ lib/CodeGen/BackendUtil.cpp
@@ -1038,23 +1038,8 @@
   // we should only invoke this using the individual indexes written out
   // via a WriteIndexesThinBackend.
   FunctionImporter::ImportMapTy ImportList;
-  for (auto &GlobalList : *CombinedIndex) {
-// Ignore entries for undefined references.
-if (GlobalList.second.SummaryList.empty())
-  continue;
-
-auto GUID = GlobalList.first;
-assert(GlobalList.second.SummaryList.size() == 1 &&
-   "Expected individual combined index to have one summary per GUID");
-auto &Summary = GlobalList.second.SummaryList[0];
-// Skip the summaries for the importing module. These are included to
-// e.g. record required linkage changes.
-if (Summary->modulePath() == M->getModuleIdentifier())
-  continue;
-// Doesn't matter what value we plug in to the map, just needs an entry
-// to provoke importing by thinBackend.
-ImportList[Summary->modulePath()][GUID] = 1;
-  }
+  llvm::ComputeCrossModuleImportForModuleFromIndex(M->getModuleIdentifier(),
+   *CombinedIndex, ImportList);
 
   std::vector> OwnedImports;
   MapVector ModuleMap;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35894: [clangd] Code hover for Clangd

2017-12-01 Thread William Enright via Phabricator via cfe-commits
Nebiroth marked 9 inline comments as done.
Nebiroth added inline comments.



Comment at: clangd/Protocol.h:26
 #include "llvm/ADT/Optional.h"
-#include 
+#include "llvm/Support/YAMLParser.h"
 #include 

malaperle wrote:
> revert this change?
#include  is not needed.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D35894



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


  1   2   >