[PATCH] D44539: [Sema][Objective-C] Add check to warn when property of objc type has assign attribute

2018-08-22 Thread Alfred Zien via Phabricator via cfe-commits
QF5690 added a comment.

In https://reviews.llvm.org/D44539#1207982, @rjmccall wrote:

> LGTM.


Thanks! What I should do next? Haven't found any info in docs about it :)


Repository:
  rC Clang

https://reviews.llvm.org/D44539



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


[PATCH] D50993: [clangd] Increase stack size of the new threads on macOS

2018-08-22 Thread Dmitry via Phabricator via cfe-commits
Dmitry.Kozhevnikov added a comment.

In https://reviews.llvm.org/D50993#1207757, @jfb wrote:

> Isn't this duplicating code in lib/Support/Unix/Threading.inc with a 
> different implementation?


It's definitely duplicating how the thread is created, however, here it's a bit 
more complicated as some dance with the passed function lifetime is required, 
while `llvm_execute_on_thread` just uses a local variable since it blocks till 
the thread is terminated.

Still, I see that it's desirable to have the new code in Support/Threading, 
I'll move it there.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50993



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


[clang-tools-extra] r340388 - [clangd] Cleanup after D50897

2018-08-22 Thread Kirill Bobyrev via cfe-commits
Author: omtcyfz
Date: Wed Aug 22 00:17:59 2018
New Revision: 340388

URL: http://llvm.org/viewvc/llvm-project?rev=340388&view=rev
Log:
[clangd] Cleanup after D50897

The wrong diff that was uploaded to Phabricator was building the wrong
index.

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

Modified: clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp?rev=340388&r1=340387&r2=340388&view=diff
==
--- clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp Wed Aug 22 00:17:59 
2018
@@ -70,7 +70,7 @@ void DexIndex::build(std::shared_ptr DexIndex::build(SymbolSlab Slab) {
-  auto Idx = llvm::make_unique();
+  auto Idx = llvm::make_unique();
   Idx->build(getSymbolsFromSlab(std::move(Slab)));
   return std::move(Idx);
 }


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


[PATCH] D44539: [Sema][Objective-C] Add check to warn when property of objc type has assign attribute

2018-08-22 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In https://reviews.llvm.org/D44539#1208780, @QF5690 wrote:

> In https://reviews.llvm.org/D44539#1207982, @rjmccall wrote:
>
> > LGTM.
>
>
> Thanks! What I should do next? Haven't found any info in docs about it :)


https://llvm.org/docs/Contributing.html

It's up to you.  We can certainly commit it for you, but if you're likely to 
work on more patches, you can ask for commit privileges yourself.


Repository:
  rC Clang

https://reviews.llvm.org/D44539



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


[PATCH] D50502: [clangd] Initial cancellation mechanism for LSP requests.

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

LG, just a few last nits




Comment at: clangd/Cancellation.cpp:30
+
+TaskHandle createTaskHandle() { return std::make_shared(); }
+

NIT: maybe consider inlining it? Since Task has a public default constructor, I 
don't think having this method buys us anything



Comment at: clangd/Cancellation.h:22
+//  function)> Callback) {
+//   // Make sure Taskr is created before starting the thread. Otherwise
+//   // CancellationToken might not get copied into thread.

s/Taskr/Task



Comment at: clangd/Cancellation.h:23
+//   // Make sure Taskr is created before starting the thread. Otherwise
+//   // CancellationToken might not get copied into thread.
+//   auto TH = createTaskHandle();

remove mentions of CancellationToken



Comment at: clangd/Cancellation.h:49
+// The worker code itself (3) should check for cancellations using
+// `CancellationToken` that can be retrieved via
+// `CancellationToken::isCancelled()`.

s/CancellationToken/getCurrentTask().isCancelled()



Comment at: clangd/ClangdLSPServer.cpp:76
+  CancelParams CP;
+  fromJSON(json::Object{{"id", ID}}, CP);
+  return CP.ID;

Maybe extract the relevant code into a helper to avoid creating the unrelated 
class (`CancelParams`)?



Comment at: clangd/ClangdLSPServer.cpp:621
+  const auto &it = TaskHandles.find(Params.ID);
+  if (it != TaskHandles.end()) {
+it->second->cancel();

Invert condition to reduce nesting?
See [LLVM Style 
Guide](https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50502



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


[PATCH] D44539: [Sema][Objective-C] Add check to warn when property of objc type has assign attribute

2018-08-22 Thread Alfred Zien via Phabricator via cfe-commits
QF5690 added a comment.

> you can ask for commit privileges yourself.

Ok, how do I do it?


Repository:
  rC Clang

https://reviews.llvm.org/D44539



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


[PATCH] D50967: [Preamble] Fix an undefined behavior when checking an empty preamble can be reused.

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 161891.
hokein added a comment.

Use the std::equal to replace the memcmp.


Repository:
  rC Clang

https://reviews.llvm.org/D50967

Files:
  lib/Frontend/PrecompiledPreamble.cpp


Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -426,8 +426,8 @@
   // new main file.
   if (PreambleBytes.size() != Bounds.Size ||
   PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
-  memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
- Bounds.Size) != 0)
+  !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
+  MainFileBuffer->getBuffer().begin()))
 return false;
   // The preamble has not changed. We may be able to re-use the precompiled
   // preamble.


Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -426,8 +426,8 @@
   // new main file.
   if (PreambleBytes.size() != Bounds.Size ||
   PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
-  memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
- Bounds.Size) != 0)
+  !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
+  MainFileBuffer->getBuffer().begin()))
 return false;
   // The preamble has not changed. We may be able to re-use the precompiled
   // preamble.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D50619: [clang-tidy] Handle unresolved expressions in ExprMutationAnalyzer

2018-08-22 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

Sure, thanks for the fast fix :)

Am 22.08.2018 um 00:04 schrieb Shuai Wang via Phabricator:

> shuaiwang added a comment.
> 
> In https://reviews.llvm.org/D50619#1207785, @JonasToth wrote:
> 
>> @shuaiwang Unfortunatly the analysis does not pass and fails on an assertion
>> 
>>   → ~/opt/llvm/build/bin/clang-tidy 
>> -checks=-*,cppcoreguidelines-const-correctness ItaniumDemangle.cpp --
>>   clang-tidy: ../tools/clang/include/clang/AST/ExprCXX.h:3581: clang::Expr* 
>> clang::CXXDependentScopeMemberExpr::getBase() const: Assertion 
>> `!isImplicitAccess()' failed.
>>   Abgebrochen (Speicherabzug geschrieben)
>> 
>> I did not investigate further, sorry for the long time to try it out.
> 
> https://reviews.llvm.org/D50617 updated, could you help try again? Thanks!
> 
> Repository:
> 
>   rCTE Clang Tools Extra
> 
> https://reviews.llvm.org/D50619


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50619



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


[PATCH] D51041: [clang-tidy] Don't run misc-unused-using-decls check in C++17.

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 161893.
hokein added a comment.

Remove redundant CPlusPlus2a.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51041

Files:
  clang-tidy/misc/UnusedUsingDeclsCheck.cpp
  test/clang-tidy/misc-unused-using-decls-cxx17.cpp


Index: test/clang-tidy/misc-unused-using-decls-cxx17.cpp
===
--- /dev/null
+++ test/clang-tidy/misc-unused-using-decls-cxx17.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- -- 
-fno-delayed-template-parsing -std=gnu++17
+
+namespace ns {
+template 
+class KV {
+public:
+  KV(K, V);
+};
+}
+
+using ns::KV;
+
+void f() {
+  KV(1, 2);
+}
Index: clang-tidy/misc/UnusedUsingDeclsCheck.cpp
===
--- clang-tidy/misc/UnusedUsingDeclsCheck.cpp
+++ clang-tidy/misc/UnusedUsingDeclsCheck.cpp
@@ -29,6 +29,11 @@
 }
 
 void UnusedUsingDeclsCheck::registerMatchers(MatchFinder *Finder) {
+  // FIXME: make the check support C++17 or later. The check relies on the fact
+  // that the used declarations are visited after the "using" declaration, but
+  // it is not ture in C++17's template argument deduction.
+  if (!getLangOpts().CPlusPlus || getLangOpts().CPlusPlus17)
+return;
   Finder->addMatcher(usingDecl(isExpansionInMainFile()).bind("using"), this);
   auto DeclMatcher = hasDeclaration(namedDecl().bind("used"));
   Finder->addMatcher(loc(enumType(DeclMatcher)), this);


Index: test/clang-tidy/misc-unused-using-decls-cxx17.cpp
===
--- /dev/null
+++ test/clang-tidy/misc-unused-using-decls-cxx17.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- -- -fno-delayed-template-parsing -std=gnu++17
+
+namespace ns {
+template 
+class KV {
+public:
+  KV(K, V);
+};
+}
+
+using ns::KV;
+
+void f() {
+  KV(1, 2);
+}
Index: clang-tidy/misc/UnusedUsingDeclsCheck.cpp
===
--- clang-tidy/misc/UnusedUsingDeclsCheck.cpp
+++ clang-tidy/misc/UnusedUsingDeclsCheck.cpp
@@ -29,6 +29,11 @@
 }
 
 void UnusedUsingDeclsCheck::registerMatchers(MatchFinder *Finder) {
+  // FIXME: make the check support C++17 or later. The check relies on the fact
+  // that the used declarations are visited after the "using" declaration, but
+  // it is not ture in C++17's template argument deduction.
+  if (!getLangOpts().CPlusPlus || getLangOpts().CPlusPlus17)
+return;
   Finder->addMatcher(usingDecl(isExpansionInMainFile()).bind("using"), this);
   auto DeclMatcher = hasDeclaration(namedDecl().bind("used"));
   Finder->addMatcher(loc(enumType(DeclMatcher)), this);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D51041: [clang-tidy] Don't run misc-unused-using-decls check in C++17.

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tidy/misc/UnusedUsingDeclsCheck.cpp:35
+  // it is not ture in C++17's template argument deduction.
+  if (!getLangOpts().CPlusPlus || getLangOpts().CPlusPlus17 ||
+  getLangOpts().CPlusPlus2a)

xazax.hun wrote:
> Isn't the check for `getLangOpts().CPlusPlus2a` redundant? Shouldn't it imply 
> the C++17 flag?
Didn't notice it. Yeah, you are right. If `CPlusCplus2a` also indicates C++17.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51041



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


[PATCH] D50862: [clang-tidy] Abseil: faster strsplit delimiter check

2018-08-22 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

LGTM


https://reviews.llvm.org/D50862



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


[PATCH] D51061: [clang-tidy] abseil-str-cat-append

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Please make sure the code follows the LLVM code style, e.g. the variable name 
format "CamelName".


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51061



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


[PATCH] D44539: [Sema][Objective-C] Add check to warn when property of objc type has assign attribute

2018-08-22 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Please read the developer policy: https://llvm.org/docs/DeveloperPolicy.html

The information is on that page.


Repository:
  rC Clang

https://reviews.llvm.org/D44539



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


[PATCH] D51088: [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added reviewers: ioeric, kbobyrev.
Herald added subscribers: kadircet, jfb, arphaman, jkorous, MaskRay.

Replace them with suffix mappings.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51088

Files:
  clangd/index/CanonicalIncludes.cpp
  clangd/index/CanonicalIncludes.h

Index: clangd/index/CanonicalIncludes.h
===
--- clangd/index/CanonicalIncludes.h
+++ clangd/index/CanonicalIncludes.h
@@ -41,7 +41,7 @@
   void addMapping(llvm::StringRef Path, llvm::StringRef CanonicalPath);
 
   /// Maps all files matching \p RE to \p CanonicalPath
-  void addRegexMapping(llvm::StringRef RE, llvm::StringRef CanonicalPath);
+  void addSuffixMapping(llvm::StringRef Suffix, llvm::StringRef CanonicalPath);
 
   /// Sets the canonical include for any symbol with \p QualifiedName.
   /// Symbol mappings take precedence over header mappings.
@@ -55,17 +55,14 @@
 llvm::StringRef QualifiedName) const;
 
 private:
-  // A map from header patterns to header names. This needs to be mutable so
-  // that we can match again a Regex in a const function member.
-  // FIXME(ioeric): All the regexes we have so far are suffix matches. The
-  // performance could be improved by allowing only suffix matches instead of
-  // arbitrary regexes.
-  mutable std::vector>
-  RegexHeaderMappingTable;
-  // A map from fully qualified symbol names to header names.
+  /// A map from full include path to a canonical path.
+  llvm::StringMap FullPathMapping;
+  /// A map from a suffix (one or components of a path) to a canonical path.
+  llvm::StringMap SuffixHeaderMapping;
+  /// Maximum number of path components stored in a key of SuffixHeaderMapping.
+  int MaxSuffixComponents = 0;
+  /// A map from fully qualified symbol names to header names.
   llvm::StringMap SymbolMapping;
-  // Guards Regex matching as it's not thread-safe.
-  mutable std::mutex RegexMutex;
 };
 
 /// Returns a CommentHandler that parses pragma comment on include files to
Index: clangd/index/CanonicalIncludes.cpp
===
--- clangd/index/CanonicalIncludes.cpp
+++ clangd/index/CanonicalIncludes.cpp
@@ -10,23 +10,29 @@
 #include "CanonicalIncludes.h"
 #include "../Headers.h"
 #include "clang/Driver/Types.h"
-#include "llvm/Support/Regex.h"
+#include "llvm/Support/Path.h"
 
 namespace clang {
 namespace clangd {
 namespace {
 const char IWYUPragma[] = "// IWYU pragma: private, include ";
 } // namespace
 
-void CanonicalIncludes::addMapping(llvm::StringRef Path,
-   llvm::StringRef CanonicalPath) {
-  addRegexMapping((llvm::Twine("^") + llvm::Regex::escape(Path) + "$").str(),
-  CanonicalPath);
+void CanonicalIncludes::addSuffixMapping(llvm::StringRef Suffix,
+ llvm::StringRef CanonicalPath) {
+  int Components = 0;
+  for (auto It = llvm::sys::path::begin(Suffix),
+End = llvm::sys::path::end(Suffix);
+   It != End; ++It)
+++Components;
+
+  MaxSuffixComponents = std::max(MaxSuffixComponents, Components);
+  SuffixHeaderMapping[Suffix] = CanonicalPath;
 }
 
-void CanonicalIncludes::addRegexMapping(llvm::StringRef RE,
-llvm::StringRef CanonicalPath) {
-  this->RegexHeaderMappingTable.emplace_back(llvm::Regex(RE), CanonicalPath);
+void CanonicalIncludes::addMapping(llvm::StringRef Path,
+   llvm::StringRef CanonicalPath) {
+  FullPathMapping[Path] = CanonicalPath;
 }
 
 void CanonicalIncludes::addSymbolMapping(llvm::StringRef QualifiedName,
@@ -41,7 +47,6 @@
   auto SE = SymbolMapping.find(QualifiedName);
   if (SE != SymbolMapping.end())
 return SE->second;
-  std::lock_guard Lock(RegexMutex);
   // Find the first header such that the extension is not '.inc', and isn't a
   // recognized non-header file
   auto I =
@@ -62,13 +67,23 @@
   if ((ExtType != driver::types::TY_INVALID) &&
   !driver::types::onlyPrecompileType(ExtType))
 return Headers[0];
-  for (auto &Entry : RegexHeaderMappingTable) {
-#ifndef NDEBUG
-std::string Dummy;
-assert(Entry.first.isValid(Dummy) && "Regex should never be invalid!");
-#endif
-if (Entry.first.match(Header))
-  return Entry.second;
+
+  auto MapIt = FullPathMapping.find(Header);
+  if (MapIt != FullPathMapping.end())
+return MapIt->second;
+
+  int Components = 0;
+  for (auto It = llvm::sys::path::rbegin(Header),
+End = llvm::sys::path::rend(Header);
+   It != End; ++It) {
+++Components;
+if (MaxSuffixComponents < Components)
+  break;
+
+auto SubPath = Header.substr(It->data() - Header.begin());
+auto MappingIt = SuffixHeaderMapping.find(SubPath);
+if (MappingIt != SuffixHeaderMapping.end())
+  return MappingIt->second;
   }
   return Header;
 }
@@ -153,660 +168,660 @@

[PATCH] D50847: [clangd] Add callbacks on parsed AST in addition to parsed preambles

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Thanks! Looks good.




Comment at: clangd/ClangdServer.cpp:73
+
+  void onPreambleAST(PathRef Path, ASTContext &Ctx,
+ std::shared_ptr PP) override {

ilya-biryukov wrote:
> hokein wrote:
> > I think `Ctx` should be a `pointer` which gives us a way (passing a 
> > nullptr) to clean up the `FileIndex`, the same as `ParsedAST` below.
> > 
> > And I discover that we don't cleanup dynamic index when a file is being 
> > closed, is it expected or a bug?
> I suggest we add an extra method to `DynamicIndex` that we call when the file 
> is closed. I don't think it's intentional that we don't clean up the index 
> for the closed files.
> Not sure what's the best way to handle invalid ASTs, but we're never calling 
> the current callback with `nullptr` anyway, so I suggest we keep it a 
> reference to better reflect that callbacks don't actually handle any errors 
> for us.
SG, and it is out of scope of this patch. Let's figure it out in the 
clean-up-index patch.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50847



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


[PATCH] D50455: Continue emitting diagnostics after a fatal error

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.
Herald added a subscriber: kadircet.

Sorry for the delay with this one




Comment at: unittests/clangd/ClangdTests.cpp:1002
+
+  auto MainFileCI = buildCompilerInvocation(PI);
+  auto AST =

Just reuse `PreambleCI`?



Comment at: unittests/clangd/ClangdTests.cpp:1009
+
+  ASSERT_EQ(AST->getDiagnostics().size(), 4u);
+  EXPECT_THAT(AST->getDiagnostics()[0].Message, HasSubstr("preamble1"));

Maybe fold all asserts into one, e.g.:
```EXPECT_THAT(AST->getDiagnostics(), ElementsAre(Field(&Diag::Message, 
HasSubstr("preamble1")), ...)```

Could be made shorter by introducing a matcher for `Field(&Diag::Message, 
HasSubstr(...`


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50455



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


[PATCH] D51038: [clang] Make sure codecompletion is called for calls even when inside a token.

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Maybe add tests? Lit tests for code completion (`clang/test/CodeCompletion`) 
should be a good fit




Comment at: include/clang/Parse/Parser.h:2971
+  /// signature help working even when it is triggered inside a token.
+  bool CalledOverloadCompletion = false;
 };

Maybe put the field closer to the existing ones?



Comment at: lib/Parse/ParseExpr.cpp:2820
 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
+  CalledOverloadCompletion = true;
   cutOffParsing();

Why should we set this flag here? Can it be handled by `Completer` function 
that we pass into `ParseExperssionList` instead?


Repository:
  rC Clang

https://reviews.llvm.org/D51038



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


[PATCH] D50616: [Fixed Point Arithmetic] FixedPointCast

2018-08-22 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added subscribers: NoQ, a.sidorin.
a.sidorin added a comment.

Accidentally noticed about this review via cfe-commits. @NoQ, the change in the 
ExprEngine looks a bit dangerous to me. Could you please check?




Comment at: lib/StaticAnalyzer/Core/ExprEngineC.cpp:419
+  case CK_LValueBitCast:
+  case CK_FixedPointCast: {
 state =

Should we consider this construction as unsupported rather than supported as a 
normal cast?


Repository:
  rC Clang

https://reviews.llvm.org/D50616



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


[PATCH] D49674: [AArch64] Add Tiny Code Model for AArch64

2018-08-22 Thread Peter Smith via Phabricator via cfe-commits
peter.smith accepted this revision.
peter.smith added a comment.
This revision is now accepted and ready to land.

Looks good to me now that LLVM support has been approved in 
https://reviews.llvm.org/D49673


https://reviews.llvm.org/D49674



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


[PATCH] D50771: [clang-tblgen] Add -print-records and -dump-json modes.

2018-08-22 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle accepted this revision.
nhaehnle added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rC Clang

https://reviews.llvm.org/D50771



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


[PATCH] D51077: [clangd] send diagnostic categories only when 'categorySupport' capability was given by the client

2018-08-22 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. Thanks!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51077



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


[PATCH] D50771: [clang-tblgen] Add -print-records and -dump-json modes.

2018-08-22 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL340390: [clang-tblgen] Add -print-records and -dump-json 
modes. (authored by statham, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D50771

Files:
  cfe/trunk/utils/TableGen/TableGen.cpp


Index: cfe/trunk/utils/TableGen/TableGen.cpp
===
--- cfe/trunk/utils/TableGen/TableGen.cpp
+++ cfe/trunk/utils/TableGen/TableGen.cpp
@@ -23,6 +23,8 @@
 using namespace clang;
 
 enum ActionType {
+  PrintRecords,
+  DumpJSON,
   GenClangAttrClasses,
   GenClangAttrParserStringSwitches,
   GenClangAttrSubjectMatchRulesParserStringSwitches,
@@ -66,6 +68,10 @@
 cl::opt Action(
 cl::desc("Action to perform:"),
 cl::values(
+clEnumValN(PrintRecords, "print-records",
+   "Print all records to stdout (default)"),
+clEnumValN(DumpJSON, "dump-json",
+   "Dump all records as machine-readable JSON"),
 clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
"Generate clang attribute clases"),
 clEnumValN(GenClangAttrParserStringSwitches,
@@ -164,6 +170,12 @@
 
 bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
   switch (Action) {
+  case PrintRecords:
+OS << Records;   // No argument, dump all contents
+break;
+  case DumpJSON:
+EmitJSON(Records, OS);
+break;
   case GenClangAttrClasses:
 EmitClangAttrClass(Records, OS);
 break;


Index: cfe/trunk/utils/TableGen/TableGen.cpp
===
--- cfe/trunk/utils/TableGen/TableGen.cpp
+++ cfe/trunk/utils/TableGen/TableGen.cpp
@@ -23,6 +23,8 @@
 using namespace clang;
 
 enum ActionType {
+  PrintRecords,
+  DumpJSON,
   GenClangAttrClasses,
   GenClangAttrParserStringSwitches,
   GenClangAttrSubjectMatchRulesParserStringSwitches,
@@ -66,6 +68,10 @@
 cl::opt Action(
 cl::desc("Action to perform:"),
 cl::values(
+clEnumValN(PrintRecords, "print-records",
+   "Print all records to stdout (default)"),
+clEnumValN(DumpJSON, "dump-json",
+   "Dump all records as machine-readable JSON"),
 clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
"Generate clang attribute clases"),
 clEnumValN(GenClangAttrParserStringSwitches,
@@ -164,6 +170,12 @@
 
 bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
   switch (Action) {
+  case PrintRecords:
+OS << Records;   // No argument, dump all contents
+break;
+  case DumpJSON:
+EmitJSON(Records, OS);
+break;
   case GenClangAttrClasses:
 EmitClangAttrClass(Records, OS);
 break;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D51090: [clangd] Add index benchmarks

2018-08-22 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added reviewers: ioeric, ilya-biryukov, sammccall.
kbobyrev added a project: clang-tools-extra.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay, mgorny.

This patch introduces index benchmarks on top of the proposed LLVM benchmark 
pull.

The preliminary results are here (benchmark invocation is given LLVM + Clang + 
Clang-Tools-Extra + libc++ symbol database):

2018-08-22 11:12:34
Run on (72 X 3700 MHz CPU s)
CPU Caches:

  L1 Data 32K (x36)
  L1 Instruction 32K (x36)
  L2 Unified 1024K (x36)
  L3 Unified 25344K (x2)

---

BenchmarkTime   CPU Iterations
--

BuildMem6042296009 ns 6041974540 ns  1
MemAdHocQueries  117140353 ns  117134140 ns  6
BuildDex8902015670 ns 8901575912 ns  1
DexAdHocQueries5137288 ns5137076 ns132

Dex is about 22 times faster compared to MemIndex despite actually processing 
100x more items since `ItemsToRetrieve = 100 * Req.MaxCandidateCount`. When 
setting `ItemsToRetrieve = Req.MaxCandidateCount`, it is up to 1000x faster.


https://reviews.llvm.org/D51090

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/benchmarks/CMakeLists.txt
  clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
  clang-tools-extra/clangd/index/SymbolYAML.cpp
  clang-tools-extra/clangd/index/SymbolYAML.h
  clang-tools-extra/clangd/index/dex/DexIndex.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp

Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -38,24 +38,6 @@
 
 enum class PCHStorageFlag { Disk, Memory };
 
-// Build an in-memory static index for global symbols from a YAML-format file.
-// The size of global symbols should be relatively small, so that all symbols
-// can be managed in memory.
-std::unique_ptr buildStaticIndex(llvm::StringRef YamlSymbolFile) {
-  auto Buffer = llvm::MemoryBuffer::getFile(YamlSymbolFile);
-  if (!Buffer) {
-llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
-return nullptr;
-  }
-  auto Slab = symbolsFromYAML(Buffer.get()->getBuffer());
-  SymbolSlab::Builder SymsBuilder;
-  for (auto Sym : Slab)
-SymsBuilder.insert(Sym);
-
-  return UseDex ? dex::DexIndex::build(std::move(SymsBuilder).build())
-: MemIndex::build(std::move(SymsBuilder).build());
-}
-
 } // namespace
 
 static llvm::cl::opt CompileCommandsDir(
@@ -294,7 +276,7 @@
   Opts.BuildDynamicSymbolIndex = EnableIndex;
   std::unique_ptr StaticIdx;
   if (EnableIndex && !YamlSymbolFile.empty()) {
-StaticIdx = buildStaticIndex(YamlSymbolFile);
+StaticIdx = buildStaticIndex(YamlSymbolFile, UseDex);
 Opts.StaticIndex = StaticIdx.get();
   }
   Opts.AsyncThreadsCount = WorkerThreadsCount;
Index: clang-tools-extra/clangd/index/dex/DexIndex.cpp
===
--- clang-tools-extra/clangd/index/dex/DexIndex.cpp
+++ clang-tools-extra/clangd/index/dex/DexIndex.cpp
@@ -161,7 +161,6 @@
   }
 }
 
-
 void DexIndex::findOccurrences(
 const OccurrencesRequest &Req,
 llvm::function_ref Callback) const {
Index: clang-tools-extra/clangd/index/SymbolYAML.h
===
--- clang-tools-extra/clangd/index/SymbolYAML.h
+++ clang-tools-extra/clangd/index/SymbolYAML.h
@@ -42,6 +42,12 @@
 // The YAML result is safe to concatenate if you have multiple symbol slabs.
 void SymbolsToYAML(const SymbolSlab &Symbols, llvm::raw_ostream &OS);
 
+// Build an in-memory static index for global symbols from a YAML-format file.
+// The size of global symbols should be relatively small, so that all symbols
+// can be managed in memory.
+std::unique_ptr buildStaticIndex(llvm::StringRef YamlSymbolFile,
+  bool UseDex);
+
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/clangd/index/SymbolYAML.cpp
===
--- clang-tools-extra/clangd/index/SymbolYAML.cpp
+++ clang-tools-extra/clangd/index/SymbolYAML.cpp
@@ -9,6 +9,7 @@
 
 #include "SymbolYAML.h"
 #include "Index.h"
+#include "dex/DexIndex.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -203,5 +204,21 @@
   return OS.str();
 }
 
+std::unique_ptr buildStaticIndex(llvm::StringRef YamlSymbolFile,
+  bool UseDex) {
+  auto Buffer = llvm::MemoryBuffer::getFile(YamlSymbolFile);
+  if (!Buffer) {
+llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
+return nullptr;
+  }
+  auto Slab = symbolsFromYAML(Buffer.get()->getBuffer());
+  SymbolSlab::Builder SymsBuilder;
+  for (auto Sym : S

[PATCH] D51090: [clangd] Add index benchmarks

2018-08-22 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev planned changes to this revision.
kbobyrev added a comment.

The current diff is rather messy and it is also blocked by the parent revision 
(https://reviews.llvm.org/D50894). It is likely to change if the parent CMake 
structure is changed.


https://reviews.llvm.org/D51090



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


r340391 - [clang][mips] Set __mips_fpr correctly for -mfpxx

2018-08-22 Thread Stefan Maksimovic via cfe-commits
Author: smaksimovic
Date: Wed Aug 22 02:26:25 2018
New Revision: 340391

URL: http://llvm.org/viewvc/llvm-project?rev=340391&view=rev
Log:
[clang][mips] Set __mips_fpr correctly for -mfpxx

Set __mips_fpr to 0 if o32 ABI is used with either -mfpxx
or none of -mfp32, -mfpxx, -mfp64 being specified.

Introduce additional checks:
-mfpxx is only to be used in conjunction with the o32 ABI.
report an error when incompatible options are provided.

Formerly no errors were raised when combining n32/n64 ABIs
with -mfp32 and -mfpxx.

There are other cases when __mips_fpr should be set to 0
that are not covered, ex. using o32 on a mips64 cpu
which is valid but not supported in the backend as of yet.

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticCommonKinds.td
cfe/trunk/lib/Basic/Targets/Mips.cpp
cfe/trunk/lib/Basic/Targets/Mips.h
cfe/trunk/test/Preprocessor/init.c

Modified: cfe/trunk/include/clang/Basic/DiagnosticCommonKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticCommonKinds.td?rev=340391&r1=340390&r2=340391&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticCommonKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticCommonKinds.td Wed Aug 22 02:26:25 
2018
@@ -199,6 +199,9 @@ def err_target_unknown_abi : Error<"unkn
 def err_target_unsupported_abi : Error<"ABI '%0' is not supported on CPU 
'%1'">;
 def err_target_unsupported_abi_for_triple : Error<
   "ABI '%0' is not supported for '%1'">;
+def err_unsupported_abi_for_opt : Error<"'%0' can only be used with the '%1' 
ABI">;
+def err_mips_fp64_req : Error<
+"'%0' can only be used if the target supports the mfhc1 and mthc1 
instructions">;
 def err_target_unknown_fpmath : Error<"unknown FP unit '%0'">;
 def err_target_unsupported_fpmath : Error<
 "the '%0' unit is not supported with this instruction set">;

Modified: cfe/trunk/lib/Basic/Targets/Mips.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/Mips.cpp?rev=340391&r1=340390&r2=340391&view=diff
==
--- cfe/trunk/lib/Basic/Targets/Mips.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/Mips.cpp Wed Aug 22 02:26:25 2018
@@ -59,6 +59,16 @@ void MipsTargetInfo::fillValidCPUList(
   Values.append(std::begin(ValidCPUNames), std::end(ValidCPUNames));
 }
 
+unsigned MipsTargetInfo::getISARev() const {
+  return llvm::StringSwitch(getCPU())
+ .Cases("mips32", "mips64", 1)
+ .Cases("mips32r2", "mips64r2", 2)
+ .Cases("mips32r3", "mips64r3", 3)
+ .Cases("mips32r5", "mips64r5", 5)
+ .Cases("mips32r6", "mips64r6", 6)
+ .Default(0);
+}
+
 void MipsTargetInfo::getTargetDefines(const LangOptions &Opts,
   MacroBuilder &Builder) const {
   if (BigEndian) {
@@ -84,13 +94,8 @@ void MipsTargetInfo::getTargetDefines(co
 Builder.defineMacro("_MIPS_ISA", "_MIPS_ISA_MIPS64");
   }
 
-  const std::string ISARev = llvm::StringSwitch(getCPU())
- .Cases("mips32", "mips64", "1")
- .Cases("mips32r2", "mips64r2", "2")
- .Cases("mips32r3", "mips64r3", "3")
- .Cases("mips32r5", "mips64r5", "5")
- .Cases("mips32r6", "mips64r6", "6")
- .Default("");
+  const std::string ISARev = std::to_string(getISARev());
+
   if (!ISARev.empty())
 Builder.defineMacro("__mips_isa_rev", ISARev);
 
@@ -129,9 +134,22 @@ void MipsTargetInfo::getTargetDefines(co
   if (IsSingleFloat)
 Builder.defineMacro("__mips_single_float", Twine(1));
 
-  Builder.defineMacro("__mips_fpr", HasFP64 ? Twine(64) : Twine(32));
-  Builder.defineMacro("_MIPS_FPSET",
-  Twine(32 / (HasFP64 || IsSingleFloat ? 1 : 2)));
+  switch (FPMode) {
+  case FPXX:
+Builder.defineMacro("__mips_fpr", Twine(0));
+break;
+  case FP32:
+Builder.defineMacro("__mips_fpr", Twine(32));
+break;
+  case FP64:
+Builder.defineMacro("__mips_fpr", Twine(64));
+break;
+}
+
+  if (FPMode == FP64 || IsSingleFloat)
+Builder.defineMacro("_MIPS_FPSET", Twine(32));
+  else
+Builder.defineMacro("_MIPS_FPSET", Twine(16));
 
   if (IsMips16)
 Builder.defineMacro("__mips16", Twine(1));
@@ -189,7 +207,7 @@ void MipsTargetInfo::getTargetDefines(co
 bool MipsTargetInfo::hasFeature(StringRef Feature) const {
   return llvm::StringSwitch(Feature)
   .Case("mips", true)
-  .Case("fp64", HasFP64)
+  .Case("fp64", FPMode == FP64)
   .Default(false);
 }
 
@@ -235,5 +253,30 @@ bool MipsTargetInfo::validateTarget(Diag
 return false;
   }
 
+  // -fpxx is valid only for the o32 ABI
+  if (FPMode == FPXX && (ABI == "n32" || ABI == "n64")) {
+D

[PATCH] D50557: [clang][mips] Set __mips_fpr correctly for -mfpxx

2018-08-22 Thread Stefan Maksimovic via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL340391: [clang][mips] Set __mips_fpr correctly for -mfpxx 
(authored by smaksimovic, committed by ).
Herald added subscribers: llvm-commits, jrtc27.

Changed prior to commit:
  https://reviews.llvm.org/D50557?vs=161690&id=161907#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D50557

Files:
  cfe/trunk/include/clang/Basic/DiagnosticCommonKinds.td
  cfe/trunk/lib/Basic/Targets/Mips.cpp
  cfe/trunk/lib/Basic/Targets/Mips.h
  cfe/trunk/test/Preprocessor/init.c

Index: cfe/trunk/lib/Basic/Targets/Mips.cpp
===
--- cfe/trunk/lib/Basic/Targets/Mips.cpp
+++ cfe/trunk/lib/Basic/Targets/Mips.cpp
@@ -59,6 +59,16 @@
   Values.append(std::begin(ValidCPUNames), std::end(ValidCPUNames));
 }
 
+unsigned MipsTargetInfo::getISARev() const {
+  return llvm::StringSwitch(getCPU())
+ .Cases("mips32", "mips64", 1)
+ .Cases("mips32r2", "mips64r2", 2)
+ .Cases("mips32r3", "mips64r3", 3)
+ .Cases("mips32r5", "mips64r5", 5)
+ .Cases("mips32r6", "mips64r6", 6)
+ .Default(0);
+}
+
 void MipsTargetInfo::getTargetDefines(const LangOptions &Opts,
   MacroBuilder &Builder) const {
   if (BigEndian) {
@@ -84,13 +94,8 @@
 Builder.defineMacro("_MIPS_ISA", "_MIPS_ISA_MIPS64");
   }
 
-  const std::string ISARev = llvm::StringSwitch(getCPU())
- .Cases("mips32", "mips64", "1")
- .Cases("mips32r2", "mips64r2", "2")
- .Cases("mips32r3", "mips64r3", "3")
- .Cases("mips32r5", "mips64r5", "5")
- .Cases("mips32r6", "mips64r6", "6")
- .Default("");
+  const std::string ISARev = std::to_string(getISARev());
+
   if (!ISARev.empty())
 Builder.defineMacro("__mips_isa_rev", ISARev);
 
@@ -129,9 +134,22 @@
   if (IsSingleFloat)
 Builder.defineMacro("__mips_single_float", Twine(1));
 
-  Builder.defineMacro("__mips_fpr", HasFP64 ? Twine(64) : Twine(32));
-  Builder.defineMacro("_MIPS_FPSET",
-  Twine(32 / (HasFP64 || IsSingleFloat ? 1 : 2)));
+  switch (FPMode) {
+  case FPXX:
+Builder.defineMacro("__mips_fpr", Twine(0));
+break;
+  case FP32:
+Builder.defineMacro("__mips_fpr", Twine(32));
+break;
+  case FP64:
+Builder.defineMacro("__mips_fpr", Twine(64));
+break;
+}
+
+  if (FPMode == FP64 || IsSingleFloat)
+Builder.defineMacro("_MIPS_FPSET", Twine(32));
+  else
+Builder.defineMacro("_MIPS_FPSET", Twine(16));
 
   if (IsMips16)
 Builder.defineMacro("__mips16", Twine(1));
@@ -189,7 +207,7 @@
 bool MipsTargetInfo::hasFeature(StringRef Feature) const {
   return llvm::StringSwitch(Feature)
   .Case("mips", true)
-  .Case("fp64", HasFP64)
+  .Case("fp64", FPMode == FP64)
   .Default(false);
 }
 
@@ -235,5 +253,30 @@
 return false;
   }
 
+  // -fpxx is valid only for the o32 ABI
+  if (FPMode == FPXX && (ABI == "n32" || ABI == "n64")) {
+Diags.Report(diag::err_unsupported_abi_for_opt) << "-mfpxx" << "o32";
+return false;
+  }
+
+  // -mfp32 and n32/n64 ABIs are incompatible
+  if (FPMode != FP64 && FPMode != FPXX && !IsSingleFloat &&
+  (ABI == "n32" || ABI == "n64")) {
+Diags.Report(diag::err_opt_not_valid_with_opt) << "-mfpxx" << CPU;
+return false;
+  }
+  // Mips revision 6 and -mfp32 are incompatible
+  if (FPMode != FP64 && FPMode != FPXX && (CPU == "mips32r6" ||
+  CPU == "mips64r6")) {
+Diags.Report(diag::err_opt_not_valid_with_opt) << "-mfp32" << CPU;
+return false;
+  }
+  // Option -mfp64 permitted on Mips32 iff revision 2 or higher is present
+  if (FPMode == FP64 && (CPU == "mips1" || CPU == "mips2" ||
+  getISARev() < 2) && ABI == "o32") {
+Diags.Report(diag::err_mips_fp64_req) << "-mfp64";
+return false;
+  }
+
   return true;
 }
Index: cfe/trunk/lib/Basic/Targets/Mips.h
===
--- cfe/trunk/lib/Basic/Targets/Mips.h
+++ cfe/trunk/lib/Basic/Targets/Mips.h
@@ -57,16 +57,16 @@
   bool UseIndirectJumpHazard;
 
 protected:
-  bool HasFP64;
+  enum FPModeEnum { FPXX, FP32, FP64 } FPMode;
   std::string ABI;
 
 public:
   MipsTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
   : TargetInfo(Triple), IsMips16(false), IsMicromips(false),
 IsNan2008(false), IsAbs2008(false), IsSingleFloat(false),
 IsNoABICalls(false), CanUseBSDABICalls(false), FloatABI(HardFloat),
 DspRev(NoDSP), HasMSA(false), DisableMadd4(false),
-UseIndirectJumpHazard(false), HasFP64(false) {
+UseIndirectJumpHazard(false), FPMode(FPXX) {
 TheCXXABI.set(TargetCXXABI::GenericMIPS);
 
 setABI(getTriple().isMIPS32() ? "o32" : "n64");
@@ -181,6 +181,8 @@
 return TargetInfo::initF

[PATCH] D50993: [clangd] Increase stack size of the new threads on macOS

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

WRT to the configuration argument, using stack size suggested by @arphaman 
seems like a better option. So let's not add any extra options to clangd.




Comment at: clangd/Threading.cpp:76
+
+  if (::pthread_attr_setstacksize(&Attr, 8 * 1024 * 1024) != 0)
+return;

arphaman wrote:
> please use clang::DesiredStackSize instead.
Oh, cool! TIL we have this. Thanks for mentioning it.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50993



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


[PATCH] D50967: [Preamble] Fix an undefined behavior when checking an empty preamble can be reused.

2018-08-22 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. Thanks!


Repository:
  rC Clang

https://reviews.llvm.org/D50967



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


[PATCH] D44539: [Sema][Objective-C] Add check to warn when property of objc type has assign attribute

2018-08-22 Thread Alfred Zien via Phabricator via cfe-commits
QF5690 added a comment.

In https://reviews.llvm.org/D44539#1208838, @rjmccall wrote:

> Please read the developer policy: https://llvm.org/docs/DeveloperPolicy.html
>
> The information is on that page.




> We grant commit access to contributors with a track record of submitting high 
> quality patches.

I don't think I'm quite fitting these criteria yet :) Can you please commit 
this patch for me?


Repository:
  rC Clang

https://reviews.llvm.org/D44539



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


[PATCH] D50502: [clangd] Initial cancellation mechanism for LSP requests.

2018-08-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 161908.
kadircet marked 6 inline comments as done.
kadircet added a comment.

- Resolve discussions.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50502

Files:
  clangd/CMakeLists.txt
  clangd/Cancellation.cpp
  clangd/Cancellation.h
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/ProtocolHandlers.cpp
  clangd/ProtocolHandlers.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/CancellationTests.cpp

Index: unittests/clangd/CancellationTests.cpp
===
--- /dev/null
+++ unittests/clangd/CancellationTests.cpp
@@ -0,0 +1,74 @@
+#include "Cancellation.h"
+#include "Context.h"
+#include "Threading.h"
+#include "llvm/Support/Error.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TEST(CancellationTest, CancellationTest) {
+  TaskHandle TH = Task::createHandle();
+  WithContext ContextWithCancellation(setCurrentTask(TH));
+  EXPECT_FALSE(isCancelled());
+  TH->cancel();
+  EXPECT_TRUE(isCancelled());
+}
+
+TEST(CancellationTest, TaskTestHandleDiesContextLives) {
+  llvm::Optional ContextWithCancellation;
+  {
+TaskHandle TH = Task::createHandle();
+ContextWithCancellation.emplace(setCurrentTask(TH));
+EXPECT_FALSE(isCancelled());
+TH->cancel();
+EXPECT_TRUE(isCancelled());
+  }
+  EXPECT_TRUE(isCancelled());
+}
+
+TEST(CancellationTest, TaskContextDiesHandleLives) {
+  TaskHandle TH = Task::createHandle();
+  {
+WithContext ContextWithCancellation(setCurrentTask(TH));
+EXPECT_FALSE(isCancelled());
+TH->cancel();
+EXPECT_TRUE(isCancelled());
+  }
+  // Still should be able to cancel without any problems.
+  TH->cancel();
+}
+
+TEST(CancellationTest, CancellationToken) {
+  TaskHandle TH = Task::createHandle();
+  WithContext ContextWithCancellation(setCurrentTask(TH));
+  const auto &CT = getCurrentTask();
+  EXPECT_FALSE(CT.isCancelled());
+  TH->cancel();
+  EXPECT_TRUE(CT.isCancelled());
+}
+
+TEST(CancellationTest, AsynCancellationTest) {
+  std::atomic HasCancelled(false);
+  Notification Cancelled;
+  auto TaskToBeCancelled = [&](ConstTaskHandle CT) {
+WithContext ContextGuard(setCurrentTask(std::move(CT)));
+Cancelled.wait();
+HasCancelled = isCancelled();
+  };
+  TaskHandle TH = Task::createHandle();
+  std::thread AsyncTask(TaskToBeCancelled, TH);
+  TH->cancel();
+  Cancelled.notify();
+  AsyncTask.join();
+
+  EXPECT_TRUE(HasCancelled);
+}
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: unittests/clangd/CMakeLists.txt
===
--- unittests/clangd/CMakeLists.txt
+++ unittests/clangd/CMakeLists.txt
@@ -10,6 +10,7 @@
 
 add_extra_unittest(ClangdTests
   Annotations.cpp
+  CancellationTests.cpp
   ClangdTests.cpp
   ClangdUnitTests.cpp
   CodeCompleteTests.cpp
Index: clangd/ProtocolHandlers.h
===
--- clangd/ProtocolHandlers.h
+++ clangd/ProtocolHandlers.h
@@ -55,6 +55,7 @@
   virtual void onDocumentHighlight(TextDocumentPositionParams &Params) = 0;
   virtual void onHover(TextDocumentPositionParams &Params) = 0;
   virtual void onChangeConfiguration(DidChangeConfigurationParams &Params) = 0;
+  virtual void onCancelRequest(CancelParams &Params) = 0;
 };
 
 void registerCallbackHandlers(JSONRPCDispatcher &Dispatcher,
Index: clangd/ProtocolHandlers.cpp
===
--- clangd/ProtocolHandlers.cpp
+++ clangd/ProtocolHandlers.cpp
@@ -75,4 +75,5 @@
   Register("workspace/didChangeConfiguration",
&ProtocolCallbacks::onChangeConfiguration);
   Register("workspace/symbol", &ProtocolCallbacks::onWorkspaceSymbol);
+  Register("$/cancelRequest", &ProtocolCallbacks::onCancelRequest);
 }
Index: clangd/Protocol.h
===
--- clangd/Protocol.h
+++ clangd/Protocol.h
@@ -867,6 +867,22 @@
 llvm::json::Value toJSON(const DocumentHighlight &DH);
 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const DocumentHighlight &);
 
+struct CancelParams {
+  /// The request id to cancel.
+  /// This can be either a number or string, if it is a number simply print it
+  /// out and always use a string.
+  std::string ID;
+};
+llvm::json::Value toJSON(const CancelParams &);
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, const CancelParams &);
+bool fromJSON(const llvm::json::Value &, CancelParams &);
+
+/// Parses the Field in Params into Parsed. Params[Field] can be either of type
+/// string or number. Returns true if parsing was succesful. In case of a number
+/// converts it into a string.
+bool parseNumberOrString(const llvm::json

[PATCH] D50847: [clangd] Add callbacks on parsed AST in addition to parsed preambles

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/ClangdServer.cpp:73
+
+  void onPreambleAST(PathRef Path, ASTContext &Ctx,
+ std::shared_ptr PP) override {

hokein wrote:
> ilya-biryukov wrote:
> > hokein wrote:
> > > I think `Ctx` should be a `pointer` which gives us a way (passing a 
> > > nullptr) to clean up the `FileIndex`, the same as `ParsedAST` below.
> > > 
> > > And I discover that we don't cleanup dynamic index when a file is being 
> > > closed, is it expected or a bug?
> > I suggest we add an extra method to `DynamicIndex` that we call when the 
> > file is closed. I don't think it's intentional that we don't clean up the 
> > index for the closed files.
> > Not sure what's the best way to handle invalid ASTs, but we're never 
> > calling the current callback with `nullptr` anyway, so I suggest we keep it 
> > a reference to better reflect that callbacks don't actually handle any 
> > errors for us.
> SG, and it is out of scope of this patch. Let's figure it out in the 
> clean-up-index patch.
LG, I'll come up with a follow-up cleanup patch when done with these patches


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50847



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


[PATCH] D50970: [clangd] Implement BOOST iterator

2018-08-22 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 161909.
kbobyrev marked 4 inline comments as done.
kbobyrev added a subscriber: sammccall.
kbobyrev added a comment.

- Add more comments explaining the difference between `consume()` and 
`consumeAndBoost()` and their potential usecases for the clients
- Move `DEFAULT_BOOSTING_SCORE` to the header by making it `constexpr` and 
change its type to `float`


https://reviews.llvm.org/D50970

Files:
  clang-tools-extra/clangd/index/dex/Iterator.cpp
  clang-tools-extra/clangd/index/dex/Iterator.h
  clang-tools-extra/unittests/clangd/DexIndexTests.cpp

Index: clang-tools-extra/unittests/clangd/DexIndexTests.cpp
===
--- clang-tools-extra/unittests/clangd/DexIndexTests.cpp
+++ clang-tools-extra/unittests/clangd/DexIndexTests.cpp
@@ -178,53 +178,61 @@
 // FIXME(kbobyrev): The testcase below is similar to what is expected in real
 // queries. It should be updated once new iterators (such as boosting, limiting,
 // etc iterators) appear. However, it is not exhaustive and it would be
-// beneficial to implement automatic generation of query trees for more
-// comprehensive testing.
+// beneficial to implement automatic generation (e.g. fuzzing) of query trees
+// for more comprehensive testing.
 TEST(DexIndexIterators, QueryTree) {
-  // An example of more complicated query
   //
   //  +-+
   //  |And Iterator:1, 5|
   //  +++
   //   |
   //   |
-  // ++
+  // +-+--+
   // ||
   // ||
-  //  +--v--+  +--v-+
-  //  |And Iterator: 1, 5, 9|  |Or Iterator: 0, 1, 5|
-  //  +--+--+  +--+-+
+  //  +--v--+  +--v+
+  //  |And Iterator: 1, 5, 9|  |Or Iterator: 0, 1, 3, 5|
+  //  +--+--+  +--++
   // ||
-  //  +--+-++-+---+
+  //  +--+-++-+
   //  ||| |   |
-  //  +---v-+ +v-+   +--v--++-V--++---v---+
-  //  |1, 3, 5, 8, 9| |1, 5, 7, 9|   |Empty||0, 5||0, 1, 5|
-  //  +-+ +--+   +-++++---+
-
+  //  +---v-+ ++---+ +--v--+  +---v+ +v---+
+  //  |1, 3, 5, 8, 9| |Boost: 2| |Empty|  |Boost: 3| |Boost: 4|
+  //  +-+ ++---+ +-+  +---++ ++---+
+  //   |  |   |
+  //  +v-+  +-v--++---v---+
+  //  |1, 5, 7, 9|  |1, 5||0, 3, 5|
+  //  +--+  +++---+
+  //
   const PostingList L0 = {1, 3, 5, 8, 9};
   const PostingList L1 = {1, 5, 7, 9};
-  const PostingList L2 = {0, 5};
-  const PostingList L3 = {0, 1, 5};
-  const PostingList L4;
+  const PostingList L3;
+  const PostingList L4 = {1, 5};
+  const PostingList L5 = {0, 3, 5};
 
   // Root of the query tree: [1, 5]
   auto Root = createAnd(
   // Lower And Iterator: [1, 5, 9]
-  createAnd(create(L0), create(L1)),
+  createAnd(create(L0), createBoost(create(L1), 2U)),
   // Lower Or Iterator: [0, 1, 5]
-  createOr(create(L2), create(L3), create(L4)));
+  createOr(create(L3), createBoost(create(L4), 3U),
+   createBoost(create(L5), 4U)));
 
   EXPECT_FALSE(Root->reachedEnd());
   EXPECT_EQ(Root->peek(), 1U);
   Root->advanceTo(0);
   // Advance multiple times. Shouldn't do anything.
   Root->advanceTo(1);
   Root->advanceTo(0);
   EXPECT_EQ(Root->peek(), 1U);
+  auto ElementBoost = Root->boost(Root->peek());
+  EXPECT_THAT(ElementBoost, 6);
   Root->advance();
   EXPECT_EQ(Root->peek(), 5U);
   Root->advanceTo(5);
   EXPECT_EQ(Root->peek(), 5U);
+  ElementBoost = Root->boost(Root->peek());
+  EXPECT_THAT(ElementBoost, 8);
   Root->advanceTo(9000);
   EXPECT_TRUE(Root->reachedEnd());
 }
@@ -281,6 +289,34 @@
   EXPECT_THAT(consume(*AndIterator), ElementsAre(1, 2, 5));
 }
 
+TEST(DexIndexIterators, Boost) {
+  auto BoostIterator = createBoost(createTrue(5U), 42U);
+  EXPECT_FALSE(BoostIterator->reachedEnd());
+  auto ElementBoost = BoostIterator->boost(BoostIterator->peek());
+  EXPECT_THAT(ElementBoost, 42U);
+
+  const PostingList L0 = {2, 4};
+  const PostingList L1 = {1, 4};
+  auto Root = createOr

[PATCH] D50889: [clangd] Make FileIndex aware of the main file

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

lgtm


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50889



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


[PATCH] D51036: clang-format: Fix formatting C++ namespaces with preceding 'inline' or 'export' specifier

2018-08-22 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: lib/Format/UnwrappedLineParser.cpp:1066-1072
+if (Style.isCpp()) {
+  nextToken();
+  if (FormatTok->Tok.is(tok::kw_namespace)) {
+parseNamespace();
+return;
+  }
+}

owenpan wrote:
> ```
> if (!Style.isCpp())
>   break;
>   case tok::kw_inline:
> nextToken();
> if (FormatTok->Tok.is(tok::kw_namespace)) {
>   parseNamespace();
>   return;
> }
> ```
I forgot to include LLVM_FALLTHROUGH to suppress the warning:

```
if (!Style.isCpp())
  break;
LLVM_FALLTHROUGH;
  case tok::kw_inline:
nextToken();
if (FormatTok->Tok.is(tok::kw_namespace)) {
  parseNamespace();
  return;
}
```


Repository:
  rC Clang

https://reviews.llvm.org/D51036



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


[PATCH] D50617: [ASTMatchers] Let hasObjectExpression also support UnresolvedMemberExpr, CXXDependentScopeMemberExpr

2018-08-22 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

The fix was effective, the assertion does not fire anymore on the 
`ItaniumDemangle.cpp` file


Repository:
  rC Clang

https://reviews.llvm.org/D50617



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


r340394 - Fix Wdocumentation warnings. NFCI.

2018-08-22 Thread Simon Pilgrim via cfe-commits
Author: rksimon
Date: Wed Aug 22 03:08:53 2018
New Revision: 340394

URL: http://llvm.org/viewvc/llvm-project?rev=340394&view=rev
Log:
Fix Wdocumentation warnings. NFCI.

Modified:
cfe/trunk/include/clang/Lex/Lexer.h
cfe/trunk/include/clang/Lex/TokenLexer.h

Modified: cfe/trunk/include/clang/Lex/Lexer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/Lexer.h?rev=340394&r1=340393&r2=340394&view=diff
==
--- cfe/trunk/include/clang/Lex/Lexer.h (original)
+++ cfe/trunk/include/clang/Lex/Lexer.h Wed Aug 22 03:08:53 2018
@@ -711,16 +711,15 @@ private:
 
   bool isHexaLiteral(const char *Start, const LangOptions &LangOpts);
 
-
   /// Read a universal character name.
   ///
-  /// \param CurPtr The position in the source buffer after the initial '\'.
-  ///   If the UCN is syntactically well-formed (but not 
necessarily
-  ///   valid), this parameter will be updated to point to the
-  ///   character after the UCN.
+  /// \param StartPtr The position in the source buffer after the initial '\'.
+  /// If the UCN is syntactically well-formed (but not 
+  /// necessarily valid), this parameter will be updated to
+  /// point to the character after the UCN.
   /// \param SlashLoc The position in the source buffer of the '\'.
-  /// \param Tok The token being formed. Pass \c nullptr to suppress 
diagnostics
-  ///and handle token formation in the caller.
+  /// \param Result   The token being formed. Pass \c nullptr to suppress
+  /// diagnostics and handle token formation in the caller.
   ///
   /// \return The Unicode codepoint specified by the UCN, or 0 if the UCN is
   /// invalid.

Modified: cfe/trunk/include/clang/Lex/TokenLexer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/TokenLexer.h?rev=340394&r1=340393&r2=340394&view=diff
==
--- cfe/trunk/include/clang/Lex/TokenLexer.h (original)
+++ cfe/trunk/include/clang/Lex/TokenLexer.h Wed Aug 22 03:08:53 2018
@@ -191,7 +191,7 @@ private:
   /// them into a string.  \p VCtx is used to determine which token represents
   /// the first __VA_OPT__ replacement token.
   ///
-  /// \param[in,out] ReplacementToks - Contains the current Replacement Tokens
+  /// \param[in,out] ResultToks - Contains the current Replacement Tokens
   /// (prior to rescanning and token pasting), the tail end of which represents
   /// the tokens just expanded through __VA_OPT__ processing.  These (sub)
   /// sequence of tokens are folded into one stringified token.


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


[PATCH] D50970: [clangd] Implement BOOST iterator

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Summarizing the offline discussion with @kbobyrev, @ioeric and @sammccall in 
two comments.




Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:96
+  /// shouldn't apply any boosting to the consumed item.
+  virtual float boost(DocID ID) const = 0;
 

With limit iterator in mind, let's rename this to `consume()` and make it 
non-const.



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:137
+/// and BOOST iterators are actually present in the query.
+std::vector>
+consumeAndBoost(Iterator &It,

Let's remove this function and change the interface of consume to return a 
vector of pairs instead.


https://reviews.llvm.org/D50970



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


[PATCH] D51093: [ARM] Set __ARM_FEATURE_SIMD32 for +dsp cores

2018-08-22 Thread Sam Parker via Phabricator via cfe-commits
samparker created this revision.
samparker added reviewers: erichkeane, t.p.northover, SjoerdMeijer.
Herald added a reviewer: javed.absar.
Herald added subscribers: chrib, kristof.beyls.

__ARM_FEATURE_DSP is already set for targets with the +dsp feature. In the 
backend, this target feature is also used to represent the availability of the 
of the instructions that the ACLE guard through the __ARM_FEATURE_SIMD32 macro. 
So set this macro for cores later than V6 and that the target parser, or user, 
reports that the 'dsp' instructions are supported.


https://reviews.llvm.org/D51093

Files:
  lib/Basic/Targets/ARM.cpp
  test/Preprocessor/arm-acle-6.4.c


Index: test/Preprocessor/arm-acle-6.4.c
===
--- test/Preprocessor/arm-acle-6.4.c
+++ test/Preprocessor/arm-acle-6.4.c
@@ -174,10 +174,13 @@
 // CHECK-V7M: __ARM_FEATURE_SAT 1
 // CHECK-V7M: __ARM_FEATURE_UNALIGNED 1
 
-// RUN: %clang -target arm-none-linux-eabi -march=armv7e-m -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-V7EM
+// RUN: %clang -target arm-none-linux-eabi -march=armv7e-m -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m4 -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m7 -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m33 -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-M-DSP
 
-// CHECK-V7EM: __ARM_FEATURE_DSP 1
-// CHECK-V7EM: __ARM_FEATURE_SIMD32 1
+// CHECK-M-DSP: __ARM_FEATURE_DSP 1
+// CHECK-M-DSP: __ARM_FEATURE_SIMD32 1
 
 // RUN: %clang -target arm-none-linux-eabi -march=armv8-a -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-V8A
 
Index: lib/Basic/Targets/ARM.cpp
===
--- lib/Basic/Targets/ARM.cpp
+++ lib/Basic/Targets/ARM.cpp
@@ -661,7 +661,7 @@
   }
 
   // ACLE 6.4.9 32-bit SIMD instructions
-  if (ArchVersion >= 6 && (CPUProfile != "M" || CPUAttr == "7EM"))
+  if ((ArchVersion >= 6 && DSP))
 Builder.defineMacro("__ARM_FEATURE_SIMD32", "1");
 
   // ACLE 6.4.10 Hardware Integer Divide


Index: test/Preprocessor/arm-acle-6.4.c
===
--- test/Preprocessor/arm-acle-6.4.c
+++ test/Preprocessor/arm-acle-6.4.c
@@ -174,10 +174,13 @@
 // CHECK-V7M: __ARM_FEATURE_SAT 1
 // CHECK-V7M: __ARM_FEATURE_UNALIGNED 1
 
-// RUN: %clang -target arm-none-linux-eabi -march=armv7e-m -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-V7EM
+// RUN: %clang -target arm-none-linux-eabi -march=armv7e-m -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m4 -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m7 -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m33 -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
 
-// CHECK-V7EM: __ARM_FEATURE_DSP 1
-// CHECK-V7EM: __ARM_FEATURE_SIMD32 1
+// CHECK-M-DSP: __ARM_FEATURE_DSP 1
+// CHECK-M-DSP: __ARM_FEATURE_SIMD32 1
 
 // RUN: %clang -target arm-none-linux-eabi -march=armv8-a -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-V8A
 
Index: lib/Basic/Targets/ARM.cpp
===
--- lib/Basic/Targets/ARM.cpp
+++ lib/Basic/Targets/ARM.cpp
@@ -661,7 +661,7 @@
   }
 
   // ACLE 6.4.9 32-bit SIMD instructions
-  if (ArchVersion >= 6 && (CPUProfile != "M" || CPUAttr == "7EM"))
+  if ((ArchVersion >= 6 && DSP))
 Builder.defineMacro("__ARM_FEATURE_SIMD32", "1");
 
   // ACLE 6.4.10 Hardware Integer Divide
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D43630: [Driver] Fix search paths on x32

2018-08-22 Thread James Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Ping?


Repository:
  rC Clang

https://reviews.llvm.org/D43630



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


[PATCH] D50926: [SourceManager] Extract 'findFileIDsForFile' from 'translateFile' to allow mapping from one file entry to multiple FileIDs

2018-08-22 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: lib/Basic/SourceManager.cpp:1705
 
   // If we haven't found what we want yet, try again, but this time stat()
   // each of the files in case the files have changed since we originally

arphaman wrote:
> ioeric wrote:
> > Do we also need this in `findFileIDsForFile`?
> I don't really need this for my use case.
But it's not clear from the interface AFAICT. We should either handle this case 
(maybe controlled with a flag), or make it clear in the API (with a different 
name or documentation).


Repository:
  rC Clang

https://reviews.llvm.org/D50926



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


[PATCH] D51088: [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/index/CanonicalIncludes.h:44
   /// Maps all files matching \p RE to \p CanonicalPath
-  void addRegexMapping(llvm::StringRef RE, llvm::StringRef CanonicalPath);
+  void addSuffixMapping(llvm::StringRef Suffix, llvm::StringRef CanonicalPath);
 

It seems that this is only file path suffix matching (by components) now. We 
should probably rename the function to be explicit.



Comment at: clangd/index/CanonicalIncludes.h:62
+  llvm::StringMap SuffixHeaderMapping;
+  /// Maximum number of path components stored in a key of SuffixHeaderMapping.
+  int MaxSuffixComponents = 0;

It might be worth documenting why this is useful (i.e. the optimization).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51088



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


[PATCH] D49674: [AArch64] Add Tiny Code Model for AArch64

2018-08-22 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

Thanks


https://reviews.llvm.org/D49674



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


[PATCH] D49674: [AArch64] Add Tiny Code Model for AArch64

2018-08-22 Thread Dave Green via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC340398: [AArch64] Add Tiny Code Model for AArch64 (authored 
by dmgreen, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D49674

Files:
  include/clang/Driver/CC1Options.td
  lib/CodeGen/BackendUtil.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/Driver/code-model.c


Index: include/clang/Driver/CC1Options.td
===
--- include/clang/Driver/CC1Options.td
+++ include/clang/Driver/CC1Options.td
@@ -249,7 +249,7 @@
 def masm_verbose : Flag<["-"], "masm-verbose">,
   HelpText<"Generate verbose assembly output">;
 def mcode_model : Separate<["-"], "mcode-model">,
-  HelpText<"The code model to use">, Values<"small,kernel,medium,large">;
+  HelpText<"The code model to use">, Values<"tiny,small,kernel,medium,large">;
 def mdebug_pass : Separate<["-"], "mdebug-pass">,
   HelpText<"Enable additional debug output">;
 def mdisable_fp_elim : Flag<["-"], "mdisable-fp-elim">,
Index: test/Driver/code-model.c
===
--- test/Driver/code-model.c
+++ test/Driver/code-model.c
@@ -1,9 +1,11 @@
+// RUN: %clang -### -c -mcmodel=tiny %s 2>&1 | FileCheck -check-prefix 
CHECK-TINY %s
 // RUN: %clang -### -c -mcmodel=small %s 2>&1 | FileCheck -check-prefix 
CHECK-SMALL %s
 // RUN: %clang -### -S -mcmodel=kernel %s 2>&1 | FileCheck -check-prefix 
CHECK-KERNEL %s
 // RUN: %clang -### -c -mcmodel=medium %s 2>&1 | FileCheck -check-prefix 
CHECK-MEDIUM %s
 // RUN: %clang -### -S -mcmodel=large %s 2>&1 | FileCheck -check-prefix 
CHECK-LARGE %s
 // RUN: not %clang -c -mcmodel=lager %s 2>&1 | FileCheck -check-prefix 
CHECK-INVALID %s
 
+// CHECK-TINY: "-mcode-model" "tiny"
 // CHECK-SMALL: "-mcode-model" "small"
 // CHECK-KERNEL: "-mcode-model" "kernel"
 // CHECK-MEDIUM: "-mcode-model" "medium"
Index: lib/CodeGen/BackendUtil.cpp
===
--- lib/CodeGen/BackendUtil.cpp
+++ lib/CodeGen/BackendUtil.cpp
@@ -368,6 +368,7 @@
 static Optional
 getCodeModel(const CodeGenOptions &CodeGenOpts) {
   unsigned CodeModel = llvm::StringSwitch(CodeGenOpts.CodeModel)
+   .Case("tiny", llvm::CodeModel::Tiny)
.Case("small", llvm::CodeModel::Small)
.Case("kernel", llvm::CodeModel::Kernel)
.Case("medium", llvm::CodeModel::Medium)
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -370,7 +370,7 @@
   if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
 StringRef Value = A->getValue();
 if (Value == "small" || Value == "kernel" || Value == "medium" ||
-Value == "large")
+Value == "large" || Value == "tiny")
   return Value;
 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
   }


Index: include/clang/Driver/CC1Options.td
===
--- include/clang/Driver/CC1Options.td
+++ include/clang/Driver/CC1Options.td
@@ -249,7 +249,7 @@
 def masm_verbose : Flag<["-"], "masm-verbose">,
   HelpText<"Generate verbose assembly output">;
 def mcode_model : Separate<["-"], "mcode-model">,
-  HelpText<"The code model to use">, Values<"small,kernel,medium,large">;
+  HelpText<"The code model to use">, Values<"tiny,small,kernel,medium,large">;
 def mdebug_pass : Separate<["-"], "mdebug-pass">,
   HelpText<"Enable additional debug output">;
 def mdisable_fp_elim : Flag<["-"], "mdisable-fp-elim">,
Index: test/Driver/code-model.c
===
--- test/Driver/code-model.c
+++ test/Driver/code-model.c
@@ -1,9 +1,11 @@
+// RUN: %clang -### -c -mcmodel=tiny %s 2>&1 | FileCheck -check-prefix CHECK-TINY %s
 // RUN: %clang -### -c -mcmodel=small %s 2>&1 | FileCheck -check-prefix CHECK-SMALL %s
 // RUN: %clang -### -S -mcmodel=kernel %s 2>&1 | FileCheck -check-prefix CHECK-KERNEL %s
 // RUN: %clang -### -c -mcmodel=medium %s 2>&1 | FileCheck -check-prefix CHECK-MEDIUM %s
 // RUN: %clang -### -S -mcmodel=large %s 2>&1 | FileCheck -check-prefix CHECK-LARGE %s
 // RUN: not %clang -c -mcmodel=lager %s 2>&1 | FileCheck -check-prefix CHECK-INVALID %s
 
+// CHECK-TINY: "-mcode-model" "tiny"
 // CHECK-SMALL: "-mcode-model" "small"
 // CHECK-KERNEL: "-mcode-model" "kernel"
 // CHECK-MEDIUM: "-mcode-model" "medium"
Index: lib/CodeGen/BackendUtil.cpp
===
--- lib/CodeGen/BackendUtil.cpp
+++ lib/CodeGen/BackendUtil.cpp
@@ -368,6 +368,7 @@
 static Optional
 getCodeModel(const CodeGenOptions &CodeGenOpts) {
   unsigned CodeModel = llvm::StringSwitch(CodeGenOpts.CodeModel)
+   .Case("tiny", llvm::CodeModel::Tiny)
   

r340398 - [AArch64] Add Tiny Code Model for AArch64

2018-08-22 Thread David Green via cfe-commits
Author: dmgreen
Date: Wed Aug 22 04:34:28 2018
New Revision: 340398

URL: http://llvm.org/viewvc/llvm-project?rev=340398&view=rev
Log:
[AArch64] Add Tiny Code Model for AArch64

Adds a tiny code model to Clang along side rL340397.

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

Modified:
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/lib/CodeGen/BackendUtil.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/test/Driver/code-model.c

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=340398&r1=340397&r2=340398&view=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Wed Aug 22 04:34:28 2018
@@ -249,7 +249,7 @@ def new_struct_path_tbaa : Flag<["-"], "
 def masm_verbose : Flag<["-"], "masm-verbose">,
   HelpText<"Generate verbose assembly output">;
 def mcode_model : Separate<["-"], "mcode-model">,
-  HelpText<"The code model to use">, Values<"small,kernel,medium,large">;
+  HelpText<"The code model to use">, Values<"tiny,small,kernel,medium,large">;
 def mdebug_pass : Separate<["-"], "mdebug-pass">,
   HelpText<"Enable additional debug output">;
 def mdisable_fp_elim : Flag<["-"], "mdisable-fp-elim">,

Modified: cfe/trunk/lib/CodeGen/BackendUtil.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/BackendUtil.cpp?rev=340398&r1=340397&r2=340398&view=diff
==
--- cfe/trunk/lib/CodeGen/BackendUtil.cpp (original)
+++ cfe/trunk/lib/CodeGen/BackendUtil.cpp Wed Aug 22 04:34:28 2018
@@ -368,6 +368,7 @@ static CodeGenOpt::Level getCGOptLevel(c
 static Optional
 getCodeModel(const CodeGenOptions &CodeGenOpts) {
   unsigned CodeModel = llvm::StringSwitch(CodeGenOpts.CodeModel)
+   .Case("tiny", llvm::CodeModel::Tiny)
.Case("small", llvm::CodeModel::Small)
.Case("kernel", llvm::CodeModel::Kernel)
.Case("medium", llvm::CodeModel::Medium)

Modified: cfe/trunk/lib/Frontend/CompilerInvocation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInvocation.cpp?rev=340398&r1=340397&r2=340398&view=diff
==
--- cfe/trunk/lib/Frontend/CompilerInvocation.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp Wed Aug 22 04:34:28 2018
@@ -370,7 +370,7 @@ static StringRef getCodeModel(ArgList &A
   if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
 StringRef Value = A->getValue();
 if (Value == "small" || Value == "kernel" || Value == "medium" ||
-Value == "large")
+Value == "large" || Value == "tiny")
   return Value;
 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
   }

Modified: cfe/trunk/test/Driver/code-model.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/code-model.c?rev=340398&r1=340397&r2=340398&view=diff
==
--- cfe/trunk/test/Driver/code-model.c (original)
+++ cfe/trunk/test/Driver/code-model.c Wed Aug 22 04:34:28 2018
@@ -1,9 +1,11 @@
+// RUN: %clang -### -c -mcmodel=tiny %s 2>&1 | FileCheck -check-prefix 
CHECK-TINY %s
 // RUN: %clang -### -c -mcmodel=small %s 2>&1 | FileCheck -check-prefix 
CHECK-SMALL %s
 // RUN: %clang -### -S -mcmodel=kernel %s 2>&1 | FileCheck -check-prefix 
CHECK-KERNEL %s
 // RUN: %clang -### -c -mcmodel=medium %s 2>&1 | FileCheck -check-prefix 
CHECK-MEDIUM %s
 // RUN: %clang -### -S -mcmodel=large %s 2>&1 | FileCheck -check-prefix 
CHECK-LARGE %s
 // RUN: not %clang -c -mcmodel=lager %s 2>&1 | FileCheck -check-prefix 
CHECK-INVALID %s
 
+// CHECK-TINY: "-mcode-model" "tiny"
 // CHECK-SMALL: "-mcode-model" "small"
 // CHECK-KERNEL: "-mcode-model" "kernel"
 // CHECK-MEDIUM: "-mcode-model" "medium"


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


r340390 - [clang-tblgen] Add -print-records and -dump-json modes.

2018-08-22 Thread Simon Tatham via cfe-commits
Author: statham
Date: Wed Aug 22 02:20:39 2018
New Revision: 340390

URL: http://llvm.org/viewvc/llvm-project?rev=340390&view=rev
Log:
[clang-tblgen] Add -print-records and -dump-json modes.

Currently, if clang-tblgen is run without a mode option, it defaults
to the first mode in its 'enum Action', which happens to be
-gen-clang-attr-classes. I think it makes more sense for it to behave
the same way as llvm-tblgen, i.e. print a diagnostic dump if it's not
given any more specific instructions.

I've also added the same -dump-json that llvm-tblgen supports. This
means any tblgen command line (whether llvm- or clang-) can be
mechanically turned into one that processes the same input into JSON.

Reviewers: nhaehnle

Reviewed By: nhaehnle

Subscribers: cfe-commits

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

Modified:
cfe/trunk/utils/TableGen/TableGen.cpp

Modified: cfe/trunk/utils/TableGen/TableGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/TableGen/TableGen.cpp?rev=340390&r1=340389&r2=340390&view=diff
==
--- cfe/trunk/utils/TableGen/TableGen.cpp (original)
+++ cfe/trunk/utils/TableGen/TableGen.cpp Wed Aug 22 02:20:39 2018
@@ -23,6 +23,8 @@ using namespace llvm;
 using namespace clang;
 
 enum ActionType {
+  PrintRecords,
+  DumpJSON,
   GenClangAttrClasses,
   GenClangAttrParserStringSwitches,
   GenClangAttrSubjectMatchRulesParserStringSwitches,
@@ -66,6 +68,10 @@ namespace {
 cl::opt Action(
 cl::desc("Action to perform:"),
 cl::values(
+clEnumValN(PrintRecords, "print-records",
+   "Print all records to stdout (default)"),
+clEnumValN(DumpJSON, "dump-json",
+   "Dump all records as machine-readable JSON"),
 clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
"Generate clang attribute clases"),
 clEnumValN(GenClangAttrParserStringSwitches,
@@ -164,6 +170,12 @@ ClangComponent("clang-component",
 
 bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
   switch (Action) {
+  case PrintRecords:
+OS << Records;   // No argument, dump all contents
+break;
+  case DumpJSON:
+EmitJSON(Records, OS);
+break;
   case GenClangAttrClasses:
 EmitClangAttrClass(Records, OS);
 break;


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


[clang-tools-extra] r340401 - [clangd] Add callbacks on parsed AST in addition to parsed preambles

2018-08-22 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Aug 22 04:39:16 2018
New Revision: 340401

URL: http://llvm.org/viewvc/llvm-project?rev=340401&view=rev
Log:
[clangd] Add callbacks on parsed AST in addition to parsed preambles

Summary:
Will be used for updating the dynamic index on updates to the open files.
Currently we collect only information coming from the preamble
AST. This has a bunch of limitations:
  - Dynamic index misses important information from the body of the
file, e.g. locations of definitions.
  - XRefs cannot be collected at all, since we can only obtain full
information for the current file (preamble is parsed with skipped
function bodies, therefore not reliable).

This patch only adds the new callback, actually updates to the index
will be done in a follow-up patch.

Reviewers: hokein

Reviewed By: hokein

Subscribers: kadircet, javed.absar, ioeric, MaskRay, jkorous, arphaman, 
cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/TUScheduler.cpp
clang-tools-extra/trunk/clangd/TUScheduler.h
clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=340401&r1=340400&r2=340401&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Wed Aug 22 04:39:16 2018
@@ -66,6 +66,24 @@ public:
   Optional> Result;
 };
 
+class UpdateFileIndex : public ParsingCallbacks {
+public:
+  UpdateFileIndex(FileIndex *FileIdx) : FileIdx(FileIdx) {}
+
+  void onPreambleAST(PathRef Path, ASTContext &Ctx,
+ std::shared_ptr PP) override {
+if (FileIdx)
+  FileIdx->update(Path, &Ctx, std::move(PP));
+  }
+
+  void onMainAST(PathRef Path, ParsedAST &AST) override {
+// FIXME: merge results from the main file into the index too.
+  }
+
+private:
+  FileIndex *FileIdx;
+};
+
 } // namespace
 
 ClangdServer::Options ClangdServer::optsForTest() {
@@ -85,20 +103,16 @@ ClangdServer::ClangdServer(GlobalCompila
: getStandardResourceDir()),
   FileIdx(Opts.BuildDynamicSymbolIndex ? new FileIndex(Opts.URISchemes)
: nullptr),
+  FileIdxUpdater(llvm::make_unique(FileIdx.get())),
   PCHs(std::make_shared()),
   // Pass a callback into `WorkScheduler` to extract symbols from a newly
   // parsed file and rebuild the file index synchronously each time an AST
   // is parsed.
   // FIXME(ioeric): this can be slow and we may be able to index on less
   // critical paths.
-  WorkScheduler(
-  Opts.AsyncThreadsCount, Opts.StorePreamblesInMemory,
-  FileIdx
-  ? [this](PathRef Path, ASTContext &AST,
-   std::shared_ptr
-   PP) { FileIdx->update(Path, &AST, std::move(PP)); }
-  : PreambleParsedCallback(),
-  Opts.UpdateDebounce, Opts.RetentionPolicy) {
+  WorkScheduler(Opts.AsyncThreadsCount, Opts.StorePreamblesInMemory,
+*FileIdxUpdater, Opts.UpdateDebounce,
+Opts.RetentionPolicy) {
   if (FileIdx && Opts.StaticIndex) {
 MergedIndex = mergeIndex(FileIdx.get(), Opts.StaticIndex);
 Index = MergedIndex.get();

Modified: clang-tools-extra/trunk/clangd/ClangdServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.h?rev=340401&r1=340400&r2=340401&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.h Wed Aug 22 04:39:16 2018
@@ -223,6 +223,8 @@ private:
   SymbolIndex *Index;
   // If present, an up-to-date of symbols in open files. Read via Index.
   std::unique_ptr FileIdx;
+  /// Callbacks responsible for updating FileIdx.
+  std::unique_ptr FileIdxUpdater;
   // If present, a merged view of FileIdx and an external index. Read via 
Index.
   std::unique_ptr MergedIndex;
   // If set, this represents the workspace path.

Modified: clang-tools-extra/trunk/clangd/TUScheduler.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/TUScheduler.cpp?rev=340401&r1=340400&r2=340401&view=diff
==
--- clang-tools-extra/trunk/clangd/TUScheduler.cpp (original)
+++ clang-tools-extra/trunk/clangd/TUScheduler.cpp Wed Aug 22 04:39:16 2018
@@ -158,8 +158,7 @@ class ASTWorker {
 Semaphore &Barrier, bool RunSync,
 steady_clock::duration UpdateDebounce,
 std::shared_ptr PCHs,
-bool StorePreamb

[PATCH] D50847: [clangd] Add callbacks on parsed AST in addition to parsed preambles

2018-08-22 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL340401: [clangd] Add callbacks on parsed AST in addition to 
parsed preambles (authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D50847?vs=161717&id=161922#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D50847

Files:
  clang-tools-extra/trunk/clangd/ClangdServer.cpp
  clang-tools-extra/trunk/clangd/ClangdServer.h
  clang-tools-extra/trunk/clangd/TUScheduler.cpp
  clang-tools-extra/trunk/clangd/TUScheduler.h
  clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
@@ -17,10 +17,11 @@
 
 namespace clang {
 namespace clangd {
+namespace {
 
 using ::testing::_;
-using ::testing::Each;
 using ::testing::AnyOf;
+using ::testing::Each;
 using ::testing::Pair;
 using ::testing::Pointee;
 using ::testing::UnorderedElementsAre;
@@ -44,8 +45,7 @@
 
 TEST_F(TUSchedulerTests, MissingFiles) {
   TUScheduler S(getDefaultAsyncThreadsCount(),
-/*StorePreamblesInMemory=*/true,
-/*PreambleParsedCallback=*/nullptr,
+/*StorePreamblesInMemory=*/true, noopParsingCallbacks(),
 /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
 ASTRetentionPolicy());
 
@@ -101,8 +101,7 @@
 Notification Ready;
 TUScheduler S(
 getDefaultAsyncThreadsCount(),
-/*StorePreamblesInMemory=*/true,
-/*PreambleParsedCallback=*/nullptr,
+/*StorePreamblesInMemory=*/true, noopParsingCallbacks(),
 /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
 ASTRetentionPolicy());
 auto Path = testPath("foo.cpp");
@@ -130,8 +129,7 @@
   std::atomic CallbackCount(0);
   {
 TUScheduler S(getDefaultAsyncThreadsCount(),
-  /*StorePreamblesInMemory=*/true,
-  /*PreambleParsedCallback=*/nullptr,
+  /*StorePreamblesInMemory=*/true, noopParsingCallbacks(),
   /*UpdateDebounce=*/std::chrono::seconds(1),
   ASTRetentionPolicy());
 // FIXME: we could probably use timeouts lower than 1 second here.
@@ -162,8 +160,7 @@
   // Run TUScheduler and collect some stats.
   {
 TUScheduler S(getDefaultAsyncThreadsCount(),
-  /*StorePreamblesInMemory=*/true,
-  /*PreambleParsedCallback=*/nullptr,
+  /*StorePreamblesInMemory=*/true, noopParsingCallbacks(),
   /*UpdateDebounce=*/std::chrono::milliseconds(50),
   ASTRetentionPolicy());
 
@@ -261,7 +258,7 @@
   Policy.MaxRetainedASTs = 2;
   TUScheduler S(
   /*AsyncThreadsCount=*/1, /*StorePreambleInMemory=*/true,
-  PreambleParsedCallback(),
+  noopParsingCallbacks(),
   /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(), Policy);
 
   llvm::StringLiteral SourceContents = R"cpp(
@@ -311,7 +308,7 @@
 TEST_F(TUSchedulerTests, EmptyPreamble) {
   TUScheduler S(
   /*AsyncThreadsCount=*/4, /*StorePreambleInMemory=*/true,
-  PreambleParsedCallback(),
+  noopParsingCallbacks(),
   /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
   ASTRetentionPolicy());
 
@@ -358,7 +355,7 @@
   // the same time. All reads should get the same non-null preamble.
   TUScheduler S(
   /*AsyncThreadsCount=*/4, /*StorePreambleInMemory=*/true,
-  PreambleParsedCallback(),
+  noopParsingCallbacks(),
   /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
   ASTRetentionPolicy());
   auto Foo = testPath("foo.cpp");
@@ -391,7 +388,7 @@
 TEST_F(TUSchedulerTests, NoopOnEmptyChanges) {
   TUScheduler S(
   /*AsyncThreadsCount=*/getDefaultAsyncThreadsCount(),
-  /*StorePreambleInMemory=*/true, PreambleParsedCallback(),
+  /*StorePreambleInMemory=*/true, noopParsingCallbacks(),
   /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
   ASTRetentionPolicy());
 
@@ -444,7 +441,7 @@
 TEST_F(TUSchedulerTests, NoChangeDiags) {
   TUScheduler S(
   /*AsyncThreadsCount=*/getDefaultAsyncThreadsCount(),
-  /*StorePreambleInMemory=*/true, PreambleParsedCallback(),
+  /*StorePreambleInMemory=*/true, noopParsingCallbacks(),
   /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
   ASTRetentionPolicy());
 
@@ -475,5 +472,6 @@
   ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(1)));
 }
 
+} // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/trunk/clangd/ClangdServer.h
===
--- clang-tools-extra/trunk/clangd/ClangdServer.h
+++ clang-tools-extra/trunk/clangd/ClangdServ

[PATCH] D50451: [ASTImporter] Fix import of class templates partial specialization

2018-08-22 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL340402: Fix import of class templates partial specialization 
(authored by martong, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D50451?vs=161699&id=161923#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D50451

Files:
  cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
  cfe/trunk/lib/AST/ASTImporter.cpp
  cfe/trunk/lib/ASTMatchers/ASTMatchersInternal.cpp
  cfe/trunk/unittests/AST/ASTImporterTest.cpp

Index: cfe/trunk/unittests/AST/ASTImporterTest.cpp
===
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp
@@ -2955,19 +2955,276 @@
   auto *FromD = FirstDeclMatcher().match(
   FromTu, classTemplateDecl(hasName("declToImport")));
   auto *ToD = Import(FromD, Lang_CXX);
-  
+
   auto Pattern = classTemplateDecl(
   has(cxxRecordDecl(has(friendDecl(has(classTemplateDecl()));
   ASSERT_TRUE(MatchVerifier{}.match(FromD, Pattern));
   EXPECT_TRUE(MatchVerifier{}.match(ToD, Pattern));
-  
+
   auto *Class =
   FirstDeclMatcher().match(ToD, classTemplateDecl());
   auto *Friend = FirstDeclMatcher().match(ToD, friendDecl());
   EXPECT_NE(Friend->getFriendDecl(), Class);
   EXPECT_EQ(Friend->getFriendDecl()->getPreviousDecl(), Class);
 }
 
+TEST_P(ASTImporterTestBase, MergeFieldDeclsOfClassTemplateSpecialization) {
+  std::string ClassTemplate =
+  R"(
+  template 
+  struct X {
+  int a{0}; // FieldDecl with InitListExpr
+  X(char) : a(3) {} // (1)
+  X(int) {} // (2)
+  };
+  )";
+  Decl *ToTU = getToTuDecl(ClassTemplate +
+  R"(
+  void foo() {
+  // ClassTemplateSpec with ctor (1): FieldDecl without InitlistExpr
+  X xc('c');
+  }
+  )", Lang_CXX11);
+  auto *ToSpec = FirstDeclMatcher().match(
+  ToTU, classTemplateSpecializationDecl(hasName("X")));
+  // FieldDecl without InitlistExpr:
+  auto *ToField = *ToSpec->field_begin();
+  ASSERT_TRUE(ToField);
+  ASSERT_FALSE(ToField->getInClassInitializer());
+  Decl *FromTU = getTuDecl(ClassTemplate +
+  R"(
+  void bar() {
+  // ClassTemplateSpec with ctor (2): FieldDecl WITH InitlistExpr
+  X xc(1);
+  }
+  )", Lang_CXX11);
+  auto *FromSpec = FirstDeclMatcher().match(
+  FromTU, classTemplateSpecializationDecl(hasName("X")));
+  // FieldDecl with InitlistExpr:
+  auto *FromField = *FromSpec->field_begin();
+  ASSERT_TRUE(FromField);
+  ASSERT_TRUE(FromField->getInClassInitializer());
+
+  auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
+  ASSERT_TRUE(ImportedSpec);
+  EXPECT_EQ(ImportedSpec, ToSpec);
+  // After the import, the FieldDecl has to be merged, thus it should have the
+  // InitListExpr.
+  EXPECT_TRUE(ToField->getInClassInitializer());
+}
+
+TEST_P(ASTImporterTestBase, MergeFunctionOfClassTemplateSpecialization) {
+  std::string ClassTemplate =
+  R"(
+  template 
+  struct X {
+void f() {}
+void g() {}
+  };
+  )";
+  Decl *ToTU = getToTuDecl(ClassTemplate +
+  R"(
+  void foo() {
+  X x;
+  x.f();
+  }
+  )", Lang_CXX11);
+  Decl *FromTU = getTuDecl(ClassTemplate +
+  R"(
+  void bar() {
+  X x;
+  x.g();
+  }
+  )", Lang_CXX11);
+  auto *FromSpec = FirstDeclMatcher().match(
+  FromTU, classTemplateSpecializationDecl(hasName("X")));
+  auto FunPattern = functionDecl(hasName("g"),
+ hasParent(classTemplateSpecializationDecl()));
+  auto *FromFun =
+  FirstDeclMatcher().match(FromTU, FunPattern);
+  auto *ToFun =
+  FirstDeclMatcher().match(ToTU, FunPattern);
+  ASSERT_TRUE(FromFun->hasBody());
+  ASSERT_FALSE(ToFun->hasBody());
+  auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
+  ASSERT_TRUE(ImportedSpec);
+  auto *ToSpec = FirstDeclMatcher().match(
+  ToTU, classTemplateSpecializationDecl(hasName("X")));
+  EXPECT_EQ(ImportedSpec, ToSpec);
+  EXPECT_TRUE(ToFun->hasBody());
+}
+
+TEST_P(ASTImporterTestBase,
+   ODRViolationOfClassTemplateSpecializationsShouldBeReported) {
+  std::string ClassTemplate =
+  R"(
+  template 
+  struct X {};
+  )";
+  Decl *ToTU = getToTuDecl(ClassTemplate +
+   R"(
+  template <>
+  struct X {
+  int a;
+  };
+  void foo() {
+  X x;
+  }
+  )",
+   Lang_CXX11);
+  Decl *FromTU = getTuDecl(ClassTemplate +
+   R"(
+  template <>
+  struct X {
+  int b;
+  };
+  void foo() {
+  X x;
+  }
+  )",
+   Lang_CXX11);
+  auto *FromSpec = FirstDeclMatcher().match(
+  FromTU, classTemplateSpecializationDecl(hasName("X")));
+  auto *ImportedSpec = Import(FromSpec, Lang_CXX11

r340402 - Fix import of class templates partial specialization

2018-08-22 Thread Gabor Marton via cfe-commits
Author: martong
Date: Wed Aug 22 04:52:14 2018
New Revision: 340402

URL: http://llvm.org/viewvc/llvm-project?rev=340402&view=rev
Log:
Fix import of class templates partial specialization

Summary:
Currently there are several issues with the import of class template
specializations.  (1) Different TUs may have class template specializations
with the same template arguments, but with different set of instantiated
MethodDecls and FieldDecls.  In this patch we provide a fix to merge these
methods and fields.  (2) Currently, we search the partial template
specializations in the set of simple specializations and we add partial
specializations as simple specializations. This is bad, this patch fixes it.

Reviewers: a_sidorin, xazax.hun, r.stahl

Subscribers: rnkovacs, dkrupp, cfe-commits

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

Modified:
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/lib/ASTMatchers/ASTMatchersInternal.cpp
cfe/trunk/unittests/AST/ASTImporterTest.cpp

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h?rev=340402&r1=340401&r2=340402&view=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h Wed Aug 22 04:52:14 2018
@@ -420,6 +420,25 @@ extern const internal::VariadicDynCastAl
 Decl, ClassTemplateSpecializationDecl>
 classTemplateSpecializationDecl;
 
+/// Matches C++ class template partial specializations.
+///
+/// Given
+/// \code
+///   template
+///   class A {};
+///
+///   template
+///   class A {};
+///
+///   template<>
+///   class A {};
+/// \endcode
+/// classTemplatePartialSpecializationDecl()
+///   matches the specialization \c A but not \c A
+extern const internal::VariadicDynCastAllOfMatcher<
+Decl, ClassTemplatePartialSpecializationDecl>
+classTemplatePartialSpecializationDecl;
+
 /// Matches declarator declarations (field, variable, function
 /// and non-type template parameter declarations).
 ///

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=340402&r1=340401&r2=340402&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Wed Aug 22 04:52:14 2018
@@ -2890,6 +2890,22 @@ Decl *ASTNodeImporter::VisitFieldDecl(Fi
   if (Importer.IsStructurallyEquivalent(D->getType(),
 FoundField->getType())) {
 Importer.MapImported(D, FoundField);
+// In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
+// initializer of a FieldDecl might not had been instantiated in the
+// "To" context.  However, the "From" context might instantiated that,
+// thus we have to merge that.
+if (Expr *FromInitializer = D->getInClassInitializer()) {
+  // We don't have yet the initializer set.
+  if (FoundField->hasInClassInitializer() &&
+  !FoundField->getInClassInitializer()) {
+Expr *ToInitializer = Importer.Import(FromInitializer);
+if (!ToInitializer)
+  // We can't return a nullptr here,
+  // since we already mapped D as imported.
+  return FoundField;
+FoundField->setInClassInitializer(ToInitializer);
+  }
+}
 return FoundField;
   }
 
@@ -4544,27 +4560,50 @@ Decl *ASTNodeImporter::VisitClassTemplat
 
   // Try to find an existing specialization with these template arguments.
   void *InsertPos = nullptr;
-  ClassTemplateSpecializationDecl *D2
-= ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
-  if (D2) {
-// We already have a class template specialization with these template
-// arguments.
-
-// FIXME: Check for specialization vs. instantiation errors.
-
-if (RecordDecl *FoundDef = D2->getDefinition()) {
-  if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
-// The record types structurally match, or the "from" translation
-// unit only had a forward declaration anyway; call it the same
-// function.
-return Importer.MapImported(D, FoundDef);
-  }
-}
-  } else {
-// Create a new specialization.
-if (auto *PartialSpec =
-dyn_cast(D)) {
-  // Import TemplateArgumentListInfo
+  ClassTemplateSpecializationDecl *D2 = nullptr;
+  ClassTemplatePartialSpecializationDecl *PartialSpec =
+dyn_cast(D);
+  if (PartialSpec)
+D2 = ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos);
+  else
+D2 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
+  ClassTemplateSpecializationDecl * const PrevDecl

[PATCH] D50889: [clangd] Make FileIndex aware of the main file

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 161924.
ilya-biryukov added a comment.

- Rebase onto head


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50889

Files:
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/index/FileIndex.cpp
  clangd/index/FileIndex.h

Index: clangd/index/FileIndex.h
===
--- clangd/index/FileIndex.h
+++ clangd/index/FileIndex.h
@@ -64,7 +64,11 @@
   /// nullptr, this removes all symbols in the file.
   /// If \p AST is not null, \p PP cannot be null and it should be the
   /// preprocessor that was used to build \p AST.
-  void update(PathRef Path, ASTContext *AST, std::shared_ptr PP);
+  /// If \p TopLevelDecls is set, only these decls are indexed. Otherwise, all
+  /// top level decls obtained from \p AST are indexed.
+  void
+  update(PathRef Path, ASTContext *AST, std::shared_ptr PP,
+ llvm::Optional> TopLevelDecls = llvm::None);
 
   bool
   fuzzyFind(const FuzzyFindRequest &Req,
@@ -86,8 +90,12 @@
 /// Retrieves namespace and class level symbols in \p AST.
 /// Exposed to assist in unit tests.
 /// If URISchemes is empty, the default schemes in SymbolCollector will be used.
-SymbolSlab indexAST(ASTContext &AST, std::shared_ptr PP,
-llvm::ArrayRef URISchemes = {});
+/// If \p TopLevelDecls is set, only these decls are indexed. Otherwise, all top
+/// level decls obtained from \p AST are indexed.
+SymbolSlab
+indexAST(ASTContext &AST, std::shared_ptr PP,
+ llvm::Optional> TopLevelDecls = llvm::None,
+ llvm::ArrayRef URISchemes = {});
 
 } // namespace clangd
 } // namespace clang
Index: clangd/index/FileIndex.cpp
===
--- clangd/index/FileIndex.cpp
+++ clangd/index/FileIndex.cpp
@@ -8,15 +8,16 @@
 //===--===//
 
 #include "FileIndex.h"
-#include "SymbolCollector.h"
 #include "../Logger.h"
+#include "SymbolCollector.h"
 #include "clang/Index/IndexingAction.h"
 #include "clang/Lex/Preprocessor.h"
 
 namespace clang {
 namespace clangd {
 
 SymbolSlab indexAST(ASTContext &AST, std::shared_ptr PP,
+llvm::Optional> TopLevelDecls,
 llvm::ArrayRef URISchemes) {
   SymbolCollector::Options CollectorOpts;
   // FIXME(ioeric): we might also want to collect include headers. We would need
@@ -38,10 +39,14 @@
   index::IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly;
   IndexOpts.IndexFunctionLocals = false;
 
-  std::vector TopLevelDecls(
-  AST.getTranslationUnitDecl()->decls().begin(),
-  AST.getTranslationUnitDecl()->decls().end());
-  index::indexTopLevelDecls(AST, TopLevelDecls, Collector, IndexOpts);
+  std::vector DeclsToIndex;
+  if (TopLevelDecls)
+DeclsToIndex.assign(TopLevelDecls->begin(), TopLevelDecls->end());
+  else
+DeclsToIndex.assign(AST.getTranslationUnitDecl()->decls().begin(),
+AST.getTranslationUnitDecl()->decls().end());
+
+  index::indexTopLevelDecls(AST, DeclsToIndex, Collector, IndexOpts);
 
   return Collector.takeSymbols();
 }
@@ -81,13 +86,14 @@
 }
 
 void FileIndex::update(PathRef Path, ASTContext *AST,
-   std::shared_ptr PP) {
+   std::shared_ptr PP,
+   llvm::Optional> TopLevelDecls) {
   if (!AST) {
 FSymbols.update(Path, nullptr);
   } else {
 assert(PP);
 auto Slab = llvm::make_unique();
-*Slab = indexAST(*AST, PP, URISchemes);
+*Slab = indexAST(*AST, PP, TopLevelDecls, URISchemes);
 FSymbols.update(Path, std::move(Slab));
   }
   auto Symbols = FSymbols.allSymbols();
Index: clangd/ClangdServer.h
===
--- clangd/ClangdServer.h
+++ clangd/ClangdServer.h
@@ -99,6 +99,7 @@
   /// synchronize access to shared state.
   ClangdServer(GlobalCompilationDatabase &CDB, FileSystemProvider &FSProvider,
DiagnosticsConsumer &DiagConsumer, const Options &Opts);
+  ~ClangdServer();
 
   /// Set the root path of the workspace.
   void setRootPath(PathRef RootPath);
@@ -200,6 +201,7 @@
   formatCode(llvm::StringRef Code, PathRef File,
  ArrayRef Ranges);
 
+  class DynamicIndex;
   typedef uint64_t DocVersion;
 
   void consumeDiagnostics(PathRef File, DocVersion Version,
@@ -217,15 +219,14 @@
   Path ResourceDir;
   // The index used to look up symbols. This could be:
   //   - null (all index functionality is optional)
-  //   - the dynamic index owned by ClangdServer (FileIdx)
+  //   - the dynamic index owned by ClangdServer (DynamicIdx)
   //   - the static index passed to the constructor
   //   - a merged view of a static and dynamic index (MergedIndex)
   SymbolIndex *Index;
-  // If present, an up-to-date of symbols in open files. Read via Index.
-  std::unique_ptr FileIdx;
-  /// Callbacks responsible for updating FileIdx.
-  std::uniq

[PATCH] D51093: [ARM] Set __ARM_FEATURE_SIMD32 for +dsp cores

2018-08-22 Thread Sam Parker via Phabricator via cfe-commits
samparker updated this revision to Diff 161925.
samparker added a comment.

Added test for armv8m.main+dsp.


https://reviews.llvm.org/D51093

Files:
  lib/Basic/Targets/ARM.cpp
  test/Preprocessor/arm-acle-6.4.c


Index: test/Preprocessor/arm-acle-6.4.c
===
--- test/Preprocessor/arm-acle-6.4.c
+++ test/Preprocessor/arm-acle-6.4.c
@@ -174,10 +174,14 @@
 // CHECK-V7M: __ARM_FEATURE_SAT 1
 // CHECK-V7M: __ARM_FEATURE_UNALIGNED 1
 
-// RUN: %clang -target arm-none-linux-eabi -march=armv7e-m -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-V7EM
-
-// CHECK-V7EM: __ARM_FEATURE_DSP 1
-// CHECK-V7EM: __ARM_FEATURE_SIMD32 1
+// RUN: %clang -target arm-none-linux-eabi -march=armv7e-m -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m4 -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m7 -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m33 -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -march=armv8m.main+dsp -x c -E -dM 
%s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+
+// CHECK-M-DSP: __ARM_FEATURE_DSP 1
+// CHECK-M-DSP: __ARM_FEATURE_SIMD32 1
 
 // RUN: %clang -target arm-none-linux-eabi -march=armv8-a -x c -E -dM %s -o - 
| FileCheck %s -check-prefix CHECK-V8A
 
Index: lib/Basic/Targets/ARM.cpp
===
--- lib/Basic/Targets/ARM.cpp
+++ lib/Basic/Targets/ARM.cpp
@@ -661,7 +661,7 @@
   }
 
   // ACLE 6.4.9 32-bit SIMD instructions
-  if (ArchVersion >= 6 && (CPUProfile != "M" || CPUAttr == "7EM"))
+  if ((ArchVersion >= 6 && DSP))
 Builder.defineMacro("__ARM_FEATURE_SIMD32", "1");
 
   // ACLE 6.4.10 Hardware Integer Divide


Index: test/Preprocessor/arm-acle-6.4.c
===
--- test/Preprocessor/arm-acle-6.4.c
+++ test/Preprocessor/arm-acle-6.4.c
@@ -174,10 +174,14 @@
 // CHECK-V7M: __ARM_FEATURE_SAT 1
 // CHECK-V7M: __ARM_FEATURE_UNALIGNED 1
 
-// RUN: %clang -target arm-none-linux-eabi -march=armv7e-m -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-V7EM
-
-// CHECK-V7EM: __ARM_FEATURE_DSP 1
-// CHECK-V7EM: __ARM_FEATURE_SIMD32 1
+// RUN: %clang -target arm-none-linux-eabi -march=armv7e-m -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m4 -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m7 -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -mcpu=cortex-m33 -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+// RUN: %clang --target=arm-arm-none-eabi -march=armv8m.main+dsp -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-M-DSP
+
+// CHECK-M-DSP: __ARM_FEATURE_DSP 1
+// CHECK-M-DSP: __ARM_FEATURE_SIMD32 1
 
 // RUN: %clang -target arm-none-linux-eabi -march=armv8-a -x c -E -dM %s -o - | FileCheck %s -check-prefix CHECK-V8A
 
Index: lib/Basic/Targets/ARM.cpp
===
--- lib/Basic/Targets/ARM.cpp
+++ lib/Basic/Targets/ARM.cpp
@@ -661,7 +661,7 @@
   }
 
   // ACLE 6.4.9 32-bit SIMD instructions
-  if (ArchVersion >= 6 && (CPUProfile != "M" || CPUAttr == "7EM"))
+  if ((ArchVersion >= 6 && DSP))
 Builder.defineMacro("__ARM_FEATURE_SIMD32", "1");
 
   // ACLE 6.4.10 Hardware Integer Divide
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D50385: [clangd] Collect symbol occurrences from AST.

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 161927.
hokein added a comment.
Herald added a subscriber: kadircet.

Update the patch based on our offline discussion

- only one single clang intefaces implementation, and move finding references 
to current symbol collector;
- store references in SymbolSlab;


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50385

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -74,6 +74,14 @@
 MATCHER_P(ForCodeCompletion, IsIndexedForCodeCompletion, "") {
   return arg.IsIndexedForCodeCompletion == IsIndexedForCodeCompletion;
 }
+MATCHER(OccurrenceRange, "") {
+  const clang::clangd::SymbolOccurrence &Pos = testing::get<0>(arg);
+  const clang::clangd::Range &Range = testing::get<1>(arg);
+  return std::tie(Pos.Location.Start.Line, Pos.Location.Start.Column,
+  Pos.Location.End.Line, Pos.Location.End.Column) ==
+ std::tie(Range.start.line, Range.start.character, Range.end.line,
+  Range.end.character);
+}
 
 namespace clang {
 namespace clangd {
@@ -95,7 +103,7 @@
 assert(AST.hasValue());
 return SymbolCollector::shouldCollectSymbol(
 Qualified ? findDecl(*AST, Name) : findAnyDecl(*AST, Name),
-AST->getASTContext(), SymbolCollector::Options());
+AST->getASTContext());
   }
 
 protected:
@@ -162,8 +170,10 @@
 class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
 public:
   SymbolIndexActionFactory(SymbolCollector::Options COpts,
-   CommentHandler *PragmaHandler)
-  : COpts(std::move(COpts)), PragmaHandler(PragmaHandler) {}
+   CommentHandler *PragmaHandler,
+   index::IndexingOptions IndexOpts)
+  : COpts(std::move(COpts)), PragmaHandler(PragmaHandler),
+IndexOpts(IndexOpts) {}
 
   clang::FrontendAction *create() override {
 class WrappedIndexAction : public WrapperFrontendAction {
@@ -186,18 +196,16 @@
   index::IndexingOptions IndexOpts;
   CommentHandler *PragmaHandler;
 };
-index::IndexingOptions IndexOpts;
-IndexOpts.SystemSymbolFilter =
-index::IndexingOptions::SystemSymbolFilterKind::All;
-IndexOpts.IndexFunctionLocals = false;
 Collector = std::make_shared(COpts);
 return new WrappedIndexAction(Collector, std::move(IndexOpts),
   PragmaHandler);
   }
 
   std::shared_ptr Collector;
   SymbolCollector::Options COpts;
   CommentHandler *PragmaHandler;
+
+  index::IndexingOptions IndexOpts;
 };
 
 class SymbolCollectorTest : public ::testing::Test {
@@ -210,13 +218,52 @@
 TestFileURI = URI::createFile(TestFileName).toString();
   }
 
+  bool collectSymbols(StringRef HeaderCode, StringRef MainCode,
+  const std::vector &ExtraArgs = {}) {
+index::IndexingOptions IndexOpts;
+IndexOpts.SystemSymbolFilter =
+index::IndexingOptions::SystemSymbolFilterKind::All;
+IndexOpts.IndexFunctionLocals = false;
+CollectorOpts.SymOpts = &CollectSymOpts;
+CollectorOpts.OccurrenceOpts = nullptr;
+return runSymbolCollector(HeaderCode, MainCode, CollectorOpts, IndexOpts,
+  ExtraArgs);
+  }
+
+  bool collectOccurrences(StringRef HeaderCode, StringRef MainCode,
+  const std::vector &ExtraArgs = {}) {
+index::IndexingOptions IndexOpts;
+IndexOpts.SystemSymbolFilter =
+index::IndexingOptions::SystemSymbolFilterKind::All;
+IndexOpts.IndexFunctionLocals = true;
+CollectorOpts.SymOpts = nullptr;
+CollectorOpts.OccurrenceOpts = &CollectOccurrenceOpts;
+return runSymbolCollector(HeaderCode, MainCode, CollectorOpts, IndexOpts,
+  ExtraArgs);
+  }
+
+protected:
+  llvm::IntrusiveRefCntPtr InMemoryFileSystem;
+  std::string TestHeaderName;
+  std::string TestHeaderURI;
+  std::string TestFileName;
+  std::string TestFileURI;
+  SymbolSlab Symbols;
+  SymbolCollector::Options CollectorOpts;
+  SymbolCollector::Options::CollectSymbolOptions CollectSymOpts;
+  SymbolCollector::Options::CollectOccurrenceOptions CollectOccurrenceOpts;
+  std::unique_ptr PragmaHandler;
+
+private:
   bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode,
+  SymbolCollector::Options Opts,
+  index::IndexingOptions IndexOpts,
   const std::vector &ExtraArgs = {}) {
 llvm::IntrusiveRefCntPtr Files(
 new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
 auto Factory = llvm::make_unique(
-CollectorOpts, PragmaHandler.get());
+Opts

r340403 - [Preamble] Fix an undefined behavior when checking an empty preamble can be reused.

2018-08-22 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Aug 22 05:34:04 2018
New Revision: 340403

URL: http://llvm.org/viewvc/llvm-project?rev=340403&view=rev
Log:
[Preamble] Fix an undefined behavior when checking an empty preamble can be 
reused.

Summary: Passing nullptr to memcmp is UB.

Reviewers: ilya-biryukov

Reviewed By: ilya-biryukov

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp

Modified: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp?rev=340403&r1=340402&r2=340403&view=diff
==
--- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp (original)
+++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp Wed Aug 22 05:34:04 2018
@@ -426,8 +426,8 @@ bool PrecompiledPreamble::CanReuse(const
   // new main file.
   if (PreambleBytes.size() != Bounds.Size ||
   PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
-  memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
- Bounds.Size) != 0)
+  !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
+  MainFileBuffer->getBuffer().begin()))
 return false;
   // The preamble has not changed. We may be able to re-use the precompiled
   // preamble.


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


[PATCH] D50967: [Preamble] Fix an undefined behavior when checking an empty preamble can be reused.

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL340403: [Preamble] Fix an undefined behavior when checking 
an empty preamble can be… (authored by hokein, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D50967

Files:
  cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp


Index: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
===
--- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
+++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
@@ -426,8 +426,8 @@
   // new main file.
   if (PreambleBytes.size() != Bounds.Size ||
   PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
-  memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
- Bounds.Size) != 0)
+  !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
+  MainFileBuffer->getBuffer().begin()))
 return false;
   // The preamble has not changed. We may be able to re-use the precompiled
   // preamble.


Index: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
===
--- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
+++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
@@ -426,8 +426,8 @@
   // new main file.
   if (PreambleBytes.size() != Bounds.Size ||
   PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
-  memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
- Bounds.Size) != 0)
+  !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
+  MainFileBuffer->getBuffer().begin()))
 return false;
   // The preamble has not changed. We may be able to re-use the precompiled
   // preamble.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D50889: [clangd] Make FileIndex aware of the main file

2018-08-22 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE340404: [clangd] Make FileIndex aware of the main file 
(authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D50889?vs=161924&id=161930#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50889

Files:
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/index/FileIndex.cpp
  clangd/index/FileIndex.h

Index: clangd/ClangdServer.h
===
--- clangd/ClangdServer.h
+++ clangd/ClangdServer.h
@@ -99,6 +99,7 @@
   /// synchronize access to shared state.
   ClangdServer(GlobalCompilationDatabase &CDB, FileSystemProvider &FSProvider,
DiagnosticsConsumer &DiagConsumer, const Options &Opts);
+  ~ClangdServer();
 
   /// Set the root path of the workspace.
   void setRootPath(PathRef RootPath);
@@ -200,6 +201,7 @@
   formatCode(llvm::StringRef Code, PathRef File,
  ArrayRef Ranges);
 
+  class DynamicIndex;
   typedef uint64_t DocVersion;
 
   void consumeDiagnostics(PathRef File, DocVersion Version,
@@ -217,15 +219,14 @@
   Path ResourceDir;
   // The index used to look up symbols. This could be:
   //   - null (all index functionality is optional)
-  //   - the dynamic index owned by ClangdServer (FileIdx)
+  //   - the dynamic index owned by ClangdServer (DynamicIdx)
   //   - the static index passed to the constructor
   //   - a merged view of a static and dynamic index (MergedIndex)
   SymbolIndex *Index;
-  // If present, an up-to-date of symbols in open files. Read via Index.
-  std::unique_ptr FileIdx;
-  /// Callbacks responsible for updating FileIdx.
-  std::unique_ptr FileIdxUpdater;
-  // If present, a merged view of FileIdx and an external index. Read via Index.
+  /// If present, an up-to-date of symbols in open files. Read via Index.
+  std::unique_ptr DynamicIdx;
+  // If present, a merged view of DynamicIdx and an external index. Read via
+  // Index.
   std::unique_ptr MergedIndex;
   // If set, this represents the workspace path.
   llvm::Optional RootPath;
Index: clangd/index/FileIndex.h
===
--- clangd/index/FileIndex.h
+++ clangd/index/FileIndex.h
@@ -64,7 +64,11 @@
   /// nullptr, this removes all symbols in the file.
   /// If \p AST is not null, \p PP cannot be null and it should be the
   /// preprocessor that was used to build \p AST.
-  void update(PathRef Path, ASTContext *AST, std::shared_ptr PP);
+  /// If \p TopLevelDecls is set, only these decls are indexed. Otherwise, all
+  /// top level decls obtained from \p AST are indexed.
+  void
+  update(PathRef Path, ASTContext *AST, std::shared_ptr PP,
+ llvm::Optional> TopLevelDecls = llvm::None);
 
   bool
   fuzzyFind(const FuzzyFindRequest &Req,
@@ -86,8 +90,12 @@
 /// Retrieves namespace and class level symbols in \p AST.
 /// Exposed to assist in unit tests.
 /// If URISchemes is empty, the default schemes in SymbolCollector will be used.
-SymbolSlab indexAST(ASTContext &AST, std::shared_ptr PP,
-llvm::ArrayRef URISchemes = {});
+/// If \p TopLevelDecls is set, only these decls are indexed. Otherwise, all top
+/// level decls obtained from \p AST are indexed.
+SymbolSlab
+indexAST(ASTContext &AST, std::shared_ptr PP,
+ llvm::Optional> TopLevelDecls = llvm::None,
+ llvm::ArrayRef URISchemes = {});
 
 } // namespace clangd
 } // namespace clang
Index: clangd/index/FileIndex.cpp
===
--- clangd/index/FileIndex.cpp
+++ clangd/index/FileIndex.cpp
@@ -8,15 +8,16 @@
 //===--===//
 
 #include "FileIndex.h"
-#include "SymbolCollector.h"
 #include "../Logger.h"
+#include "SymbolCollector.h"
 #include "clang/Index/IndexingAction.h"
 #include "clang/Lex/Preprocessor.h"
 
 namespace clang {
 namespace clangd {
 
 SymbolSlab indexAST(ASTContext &AST, std::shared_ptr PP,
+llvm::Optional> TopLevelDecls,
 llvm::ArrayRef URISchemes) {
   SymbolCollector::Options CollectorOpts;
   // FIXME(ioeric): we might also want to collect include headers. We would need
@@ -38,10 +39,14 @@
   index::IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly;
   IndexOpts.IndexFunctionLocals = false;
 
-  std::vector TopLevelDecls(
-  AST.getTranslationUnitDecl()->decls().begin(),
-  AST.getTranslationUnitDecl()->decls().end());
-  index::indexTopLevelDecls(AST, TopLevelDecls, Collector, IndexOpts);
+  std::vector DeclsToIndex;
+  if (TopLevelDecls)
+DeclsToIndex.assign(TopLevelDecls->begin(), TopLevelDecls->end());
+  else
+DeclsToIndex.assign(AST.getTranslationUnitDecl()->decls().begin(),
+AST.getTranslationUnitDecl()->decls().end());
+
+  index::indexTopLevelDecls(AST, DeclsToIndex, Collector, IndexOpts);

[clang-tools-extra] r340404 - [clangd] Make FileIndex aware of the main file

2018-08-22 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Aug 22 05:43:17 2018
New Revision: 340404

URL: http://llvm.org/viewvc/llvm-project?rev=340404&view=rev
Log:
[clangd] Make FileIndex aware of the main file

Summary:
It was previously only indexing the preamble decls. The new
implementation will index both the preamble and the main AST and
report both sets of symbols, preferring the ones from the main AST
whenever the symbol is present in both.
The symbols in the main AST slab always store all information
available in the preamble symbols, possibly adding more,
e.g. definition locations.

Reviewers: hokein, ioeric

Reviewed By: ioeric

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

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

Modified:
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/index/FileIndex.cpp
clang-tools-extra/trunk/clangd/index/FileIndex.h

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=340404&r1=340403&r2=340404&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Wed Aug 22 05:43:17 2018
@@ -65,27 +65,39 @@ public:
 
   Optional> Result;
 };
+} // namespace
 
-class UpdateFileIndex : public ParsingCallbacks {
+/// Manages dynamic index for open files. Each file might contribute two sets
+/// of symbols to the dynamic index: symbols from the preamble and symbols
+/// from the file itself. Those have different lifetimes and we merge results
+/// from both
+class ClangdServer::DynamicIndex : public ParsingCallbacks {
 public:
-  UpdateFileIndex(FileIndex *FileIdx) : FileIdx(FileIdx) {}
+  DynamicIndex(std::vector URISchemes)
+  : PreambleIdx(URISchemes), MainFileIdx(URISchemes),
+MergedIndex(mergeIndex(&MainFileIdx, &PreambleIdx)) {}
+
+  SymbolIndex &index() const { return *MergedIndex; }
 
   void onPreambleAST(PathRef Path, ASTContext &Ctx,
  std::shared_ptr PP) override {
-if (FileIdx)
-  FileIdx->update(Path, &Ctx, std::move(PP));
+PreambleIdx.update(Path, &Ctx, PP, /*TopLevelDecls=*/llvm::None);
   }
 
   void onMainAST(PathRef Path, ParsedAST &AST) override {
-// FIXME: merge results from the main file into the index too.
+
+MainFileIdx.update(Path, &AST.getASTContext(), AST.getPreprocessorPtr(),
+   AST.getLocalTopLevelDecls());
   }
 
 private:
-  FileIndex *FileIdx;
+  FileIndex PreambleIdx;
+  FileIndex MainFileIdx;
+  /// Merged view into both indexes. Merges are performed in a similar manner
+  /// to the merges of dynamic and static index.
+  std::unique_ptr MergedIndex;
 };
 
-} // namespace
-
 ClangdServer::Options ClangdServer::optsForTest() {
   ClangdServer::Options Opts;
   Opts.UpdateDebounce = std::chrono::steady_clock::duration::zero(); // Faster!
@@ -101,9 +113,9 @@ ClangdServer::ClangdServer(GlobalCompila
 : CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
   ResourceDir(Opts.ResourceDir ? Opts.ResourceDir->str()
: getStandardResourceDir()),
-  FileIdx(Opts.BuildDynamicSymbolIndex ? new FileIndex(Opts.URISchemes)
-   : nullptr),
-  FileIdxUpdater(llvm::make_unique(FileIdx.get())),
+  DynamicIdx(Opts.BuildDynamicSymbolIndex
+ ? new DynamicIndex(Opts.URISchemes)
+ : nullptr),
   PCHs(std::make_shared()),
   // Pass a callback into `WorkScheduler` to extract symbols from a newly
   // parsed file and rebuild the file index synchronously each time an AST
@@ -111,19 +123,23 @@ ClangdServer::ClangdServer(GlobalCompila
   // FIXME(ioeric): this can be slow and we may be able to index on less
   // critical paths.
   WorkScheduler(Opts.AsyncThreadsCount, Opts.StorePreamblesInMemory,
-*FileIdxUpdater, Opts.UpdateDebounce,
-Opts.RetentionPolicy) {
-  if (FileIdx && Opts.StaticIndex) {
-MergedIndex = mergeIndex(FileIdx.get(), Opts.StaticIndex);
+DynamicIdx ? *DynamicIdx : noopParsingCallbacks(),
+Opts.UpdateDebounce, Opts.RetentionPolicy) {
+  if (DynamicIdx && Opts.StaticIndex) {
+MergedIndex = mergeIndex(&DynamicIdx->index(), Opts.StaticIndex);
 Index = MergedIndex.get();
-  } else if (FileIdx)
-Index = FileIdx.get();
+  } else if (DynamicIdx)
+Index = &DynamicIdx->index();
   else if (Opts.StaticIndex)
 Index = Opts.StaticIndex;
   else
 Index = nullptr;
 }
 
+// Destructor has to be in .cpp file to see the definition of
+// ClangdServer::DynamicIndex.
+ClangdServer::~ClangdServer() = default;
+
 void ClangdServer::setRootPath(PathRef RootPath) {
   auto FS = FSProvider.getFileSystem();

[PATCH] D51088: [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added inline comments.



Comment at: clangd/index/CanonicalIncludes.h:44
   /// Maps all files matching \p RE to \p CanonicalPath
-  void addRegexMapping(llvm::StringRef RE, llvm::StringRef CanonicalPath);
+  void addSuffixMapping(llvm::StringRef Suffix, llvm::StringRef CanonicalPath);
 

ioeric wrote:
> It seems that this is only file path suffix matching (by components) now. We 
> should probably rename the function to be explicit.
Renamed to addPathSuffixMapping, updated the doc.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51088



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


[PATCH] D51088: [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 161932.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- s/addSuffixMapping/addFileSuffixMapping
- Document the intention of MaxSuffixComponents


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51088

Files:
  clangd/index/CanonicalIncludes.cpp
  clangd/index/CanonicalIncludes.h

Index: clangd/index/CanonicalIncludes.h
===
--- clangd/index/CanonicalIncludes.h
+++ clangd/index/CanonicalIncludes.h
@@ -40,8 +40,10 @@
   /// Adds a string-to-string mapping from \p Path to \p CanonicalPath.
   void addMapping(llvm::StringRef Path, llvm::StringRef CanonicalPath);
 
-  /// Maps all files matching \p RE to \p CanonicalPath
-  void addRegexMapping(llvm::StringRef RE, llvm::StringRef CanonicalPath);
+  /// Maps files with last path components matching \p Suffix to \p
+  /// CanonicalPath.
+  void addPathSuffixMapping(llvm::StringRef Suffix,
+llvm::StringRef CanonicalPath);
 
   /// Sets the canonical include for any symbol with \p QualifiedName.
   /// Symbol mappings take precedence over header mappings.
@@ -55,17 +57,15 @@
 llvm::StringRef QualifiedName) const;
 
 private:
-  // A map from header patterns to header names. This needs to be mutable so
-  // that we can match again a Regex in a const function member.
-  // FIXME(ioeric): All the regexes we have so far are suffix matches. The
-  // performance could be improved by allowing only suffix matches instead of
-  // arbitrary regexes.
-  mutable std::vector>
-  RegexHeaderMappingTable;
-  // A map from fully qualified symbol names to header names.
+  /// A map from full include path to a canonical path.
+  llvm::StringMap FullPathMapping;
+  /// A map from a suffix (one or components of a path) to a canonical path.
+  llvm::StringMap SuffixHeaderMapping;
+  /// Maximum number of path components stored in a key of SuffixHeaderMapping.
+  /// Used to reduce the number of lookups into SuffixHeaderMapping.
+  int MaxSuffixComponents = 0;
+  /// A map from fully qualified symbol names to header names.
   llvm::StringMap SymbolMapping;
-  // Guards Regex matching as it's not thread-safe.
-  mutable std::mutex RegexMutex;
 };
 
 /// Returns a CommentHandler that parses pragma comment on include files to
Index: clangd/index/CanonicalIncludes.cpp
===
--- clangd/index/CanonicalIncludes.cpp
+++ clangd/index/CanonicalIncludes.cpp
@@ -10,23 +10,29 @@
 #include "CanonicalIncludes.h"
 #include "../Headers.h"
 #include "clang/Driver/Types.h"
-#include "llvm/Support/Regex.h"
+#include "llvm/Support/Path.h"
 
 namespace clang {
 namespace clangd {
 namespace {
 const char IWYUPragma[] = "// IWYU pragma: private, include ";
 } // namespace
 
-void CanonicalIncludes::addMapping(llvm::StringRef Path,
-   llvm::StringRef CanonicalPath) {
-  addRegexMapping((llvm::Twine("^") + llvm::Regex::escape(Path) + "$").str(),
-  CanonicalPath);
+void CanonicalIncludes::addPathSuffixMapping(llvm::StringRef Suffix,
+ llvm::StringRef CanonicalPath) {
+  int Components = 0;
+  for (auto It = llvm::sys::path::begin(Suffix),
+End = llvm::sys::path::end(Suffix);
+   It != End; ++It)
+++Components;
+
+  MaxSuffixComponents = std::max(MaxSuffixComponents, Components);
+  SuffixHeaderMapping[Suffix] = CanonicalPath;
 }
 
-void CanonicalIncludes::addRegexMapping(llvm::StringRef RE,
-llvm::StringRef CanonicalPath) {
-  this->RegexHeaderMappingTable.emplace_back(llvm::Regex(RE), CanonicalPath);
+void CanonicalIncludes::addMapping(llvm::StringRef Path,
+   llvm::StringRef CanonicalPath) {
+  FullPathMapping[Path] = CanonicalPath;
 }
 
 void CanonicalIncludes::addSymbolMapping(llvm::StringRef QualifiedName,
@@ -41,7 +47,6 @@
   auto SE = SymbolMapping.find(QualifiedName);
   if (SE != SymbolMapping.end())
 return SE->second;
-  std::lock_guard Lock(RegexMutex);
   // Find the first header such that the extension is not '.inc', and isn't a
   // recognized non-header file
   auto I =
@@ -62,13 +67,23 @@
   if ((ExtType != driver::types::TY_INVALID) &&
   !driver::types::onlyPrecompileType(ExtType))
 return Headers[0];
-  for (auto &Entry : RegexHeaderMappingTable) {
-#ifndef NDEBUG
-std::string Dummy;
-assert(Entry.first.isValid(Dummy) && "Regex should never be invalid!");
-#endif
-if (Entry.first.match(Header))
-  return Entry.second;
+
+  auto MapIt = FullPathMapping.find(Header);
+  if (MapIt != FullPathMapping.end())
+return MapIt->second;
+
+  int Components = 0;
+  for (auto It = llvm::sys::path::rbegin(Header),
+End = llvm::sys::path::rend(Header);
+   It != End; ++It) {
+++Components;
+

[PATCH] D51061: [clang-tidy] abseil-str-cat-append

2018-08-22 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: clang-tidy/abseil/StrCatAppendCheck.cpp:28
+  for (;;) {
+if (const auto *MTE = dyn_cast(E)) {
+  E = MTE->getTemporary();

You can ellide the braces for the single stmt ifs



Comment at: clang-tidy/abseil/StrCatAppendCheck.cpp:52
+
+  const std::string str_cat = "::absl::StrCat";
+  const std::string alpha_num = "::absl::AlphaNum";

The naming is ambigous. `str_cat` can easily be mixed with `strcat`. Is this 
constant even necessary or could you use the literal in the functionDecl 
matcher?



Comment at: clang-tidy/abseil/StrCatAppendCheck.cpp:85
+
+  // x = StrCat(x) does nothing.
+  if (call->getNumArgs() == 1) {

Please make this comment a full sentence



Comment at: clang-tidy/abseil/StrCatAppendCheck.cpp:87
+  if (call->getNumArgs() == 1) {
+diag(op->getBeginLoc(), "call to StrCat does nothing");
+return;

I think it would be better to include `absl::StrCat` in the diagnostic, as it 
is more clear.
Same opinion on the other diag.



Comment at: test/clang-tidy/abseil-str-cat-append.cpp:91
+
+void bar() {
+  std::string a, b;

What happens if `StrCat` is used e.g. in an `std::accumulate` call as the 
binary operator? (https://en.cppreference.com/w/cpp/algorithm/accumulate  the 
Example includes such a case)
Is this diagnosed, too?

The general case would be if `StrCat` is used as a template argument for a 
functor.



Comment at: test/clang-tidy/abseil-str-cat-append.cpp:114
+
+}  // namespace absl

Could you please add a testcase that is outside of the `absl` namespace.

```
void f() {
  std::string s;
  s = absl::StrCat(s,s);
}
```

and 
```
void g() {
  std::string s;
  using absl::StrCat;
  s = StrCat(s, s);
}
```

with better naming.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51061



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


[PATCH] D50970: [clangd] Implement BOOST iterator

2018-08-22 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 161936.
kbobyrev marked 2 inline comments as done.
kbobyrev added a comment.

Address remaining comments.


https://reviews.llvm.org/D50970

Files:
  clang-tools-extra/clangd/index/dex/DexIndex.cpp
  clang-tools-extra/clangd/index/dex/Iterator.cpp
  clang-tools-extra/clangd/index/dex/Iterator.h
  clang-tools-extra/unittests/clangd/DexIndexTests.cpp

Index: clang-tools-extra/unittests/clangd/DexIndexTests.cpp
===
--- clang-tools-extra/unittests/clangd/DexIndexTests.cpp
+++ clang-tools-extra/unittests/clangd/DexIndexTests.cpp
@@ -29,6 +29,15 @@
 namespace dex {
 namespace {
 
+std::vector
+consumeIDs(Iterator &It, size_t Limit = std::numeric_limits::max()) {
+  auto IDAndScore = consume(It, Limit);
+  std::vector IDs(IDAndScore.size());
+  for (size_t I = 0; I < IDAndScore.size(); ++I)
+IDs[I] = IDAndScore[I].first;
+  return IDs;
+}
+
 TEST(DexIndexIterators, DocumentIterator) {
   const PostingList L = {4, 7, 8, 20, 42, 100};
   auto DocIterator = create(L);
@@ -62,7 +71,7 @@
   auto AndWithEmpty = createAnd(create(L0), create(L1));
   EXPECT_TRUE(AndWithEmpty->reachedEnd());
 
-  EXPECT_THAT(consume(*AndWithEmpty), ElementsAre());
+  EXPECT_THAT(consumeIDs(*AndWithEmpty), ElementsAre());
 }
 
 TEST(DexIndexIterators, AndTwoLists) {
@@ -72,7 +81,7 @@
   auto And = createAnd(create(L1), create(L0));
 
   EXPECT_FALSE(And->reachedEnd());
-  EXPECT_THAT(consume(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
+  EXPECT_THAT(consumeIDs(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
 
   And = createAnd(create(L0), create(L1));
 
@@ -113,7 +122,7 @@
   auto OrWithEmpty = createOr(create(L0), create(L1));
   EXPECT_FALSE(OrWithEmpty->reachedEnd());
 
-  EXPECT_THAT(consume(*OrWithEmpty),
+  EXPECT_THAT(consumeIDs(*OrWithEmpty),
   ElementsAre(0U, 5U, 7U, 10U, 42U, 320U, 9000U));
 }
 
@@ -146,7 +155,7 @@
 
   Or = createOr(create(L0), create(L1));
 
-  EXPECT_THAT(consume(*Or),
+  EXPECT_THAT(consumeIDs(*Or),
   ElementsAre(0U, 4U, 5U, 7U, 10U, 30U, 42U, 60U, 320U, 9000U));
 }
 
@@ -178,53 +187,61 @@
 // FIXME(kbobyrev): The testcase below is similar to what is expected in real
 // queries. It should be updated once new iterators (such as boosting, limiting,
 // etc iterators) appear. However, it is not exhaustive and it would be
-// beneficial to implement automatic generation of query trees for more
-// comprehensive testing.
+// beneficial to implement automatic generation (e.g. fuzzing) of query trees
+// for more comprehensive testing.
 TEST(DexIndexIterators, QueryTree) {
-  // An example of more complicated query
   //
   //  +-+
   //  |And Iterator:1, 5|
   //  +++
   //   |
   //   |
-  // ++
+  // +-+--+
   // ||
   // ||
-  //  +--v--+  +--v-+
-  //  |And Iterator: 1, 5, 9|  |Or Iterator: 0, 1, 5|
-  //  +--+--+  +--+-+
+  //  +--v--+  +--v+
+  //  |And Iterator: 1, 5, 9|  |Or Iterator: 0, 1, 3, 5|
+  //  +--+--+  +--++
   // ||
-  //  +--+-++-+---+
+  //  +--+-++-+
   //  ||| |   |
-  //  +---v-+ +v-+   +--v--++-V--++---v---+
-  //  |1, 3, 5, 8, 9| |1, 5, 7, 9|   |Empty||0, 5||0, 1, 5|
-  //  +-+ +--+   +-++++---+
-
+  //  +---v-+ ++---+ +--v--+  +---v+ +v---+
+  //  |1, 3, 5, 8, 9| |Boost: 2| |Empty|  |Boost: 3| |Boost: 4|
+  //  +-+ ++---+ +-+  +---++ ++---+
+  //   |  |   |
+  //  +v-+  +-v--++---v---+
+  //  |1, 5, 7, 9|  |1, 5||0, 3, 5|
+  //  +--+  +++---+
+  //
   const PostingList L0 = {1, 3, 5, 8, 9};
   const PostingList L1 = {1, 5, 7, 9};
-  const PostingList L2 = {0, 5};
-  const PostingList L3 = {0, 1, 5};
-  const PostingList L4;
+  const PostingList L3;
+  const PostingList L4 = {1, 5};
+  const PostingList L5 = {0, 3, 5};
 
   // Root of the query tree: [1, 5]
   auto Root = createAnd(
   // Lower

[PATCH] D50962: [clangd] Speculative code completion index request before Sema is run.

2018-08-22 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 161937.
ioeric added a comment.

- minor cleanup.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50962

Files:
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/index/Index.cpp
  clangd/index/Index.h
  clangd/tool/ClangdMain.cpp
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/IndexTests.cpp

Index: unittests/clangd/IndexTests.cpp
===
--- unittests/clangd/IndexTests.cpp
+++ unittests/clangd/IndexTests.cpp
@@ -321,6 +321,21 @@
   EXPECT_EQ(M.Name, "right");
 }
 
+TEST(AsyncFuzzyFind, Simple) {
+  MemIndex Idx;
+  Idx.build(generateSymbols({"ns::abc", "ns::xyz"}));
+
+  FuzzyFindRequest Req;
+  Req.Query = "";
+  Req.Scopes = {"ns::"};
+
+  AsyncFuzzyFind Async(Idx, Req);
+
+  EXPECT_EQ(Async.getRequest(), Req);
+  EXPECT_THAT(Async.getResult(),
+  UnorderedElementsAre(Named("abc"), Named("xyz")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -923,7 +923,11 @@
llvm::function_ref
Callback) const override {}
 
-  const std::vector allRequests() const { return Requests; }
+  const std::vector consumeRequests() const {
+auto Reqs = std::move(Requests);
+Requests.clear();
+return Reqs;
+  }
 
 private:
   mutable std::vector Requests;
@@ -934,7 +938,7 @@
   IndexRequestCollector Requests;
   Opts.Index = &Requests;
   completions(Code, {}, Opts);
-  return Requests.allRequests();
+  return Requests.consumeRequests();
 }
 
 TEST(CompletionTest, UnqualifiedIdQuery) {
@@ -1700,6 +1704,75 @@
   }
 }
 
+TEST(SpeculateCompletionFilter, Filters) {
+  Annotations F(R"cpp($bof^
+  $bol^
+  ab$ab^
+  x.ab$dot^
+  x.$dotempty^
+  x::ab$scoped^
+  x::$scopedempty^
+
+  )cpp");
+  auto speculate = [&](StringRef PointName) {
+auto Filter = speculateCompletionFilter(F.code(), F.point(PointName));
+assert(Filter);
+return *Filter;
+  };
+  EXPECT_EQ(speculate("bof"), "");
+  EXPECT_EQ(speculate("bol"), "");
+  EXPECT_EQ(speculate("ab"), "ab");
+  EXPECT_EQ(speculate("dot"), "ab");
+  EXPECT_EQ(speculate("dotempty"), "");
+  EXPECT_EQ(speculate("scoped"), "ab");
+  EXPECT_EQ(speculate("scopedempty"), "");
+}
+
+TEST(CompletionTest, EnableSpeculativeIndexRequest) {
+  MockFSProvider FS;
+  MockCompilationDatabase CDB;
+  IgnoreDiagnostics DiagConsumer;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto File = testPath("foo.cpp");
+  Annotations Test(R"cpp(
+  namespace ns1 { int abc; }
+  namespace ns2 { int abc; }
+  void f() { ns1::ab$1^; ns1::ab$2^; }
+  void f() { ns2::ab$3^; }
+  )cpp");
+  runAddDocument(Server, File, Test.code());
+  clangd::CodeCompleteOptions Opts = {};
+
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+  Opts.SpeculativeIndexRequest = true;
+
+  auto CompleteAtPoint = [&](StringRef P) {
+cantFail(runCodeComplete(Server, File, Test.point(P), Opts));
+// Sleep for a while to make sure asynchronous call (if applicable) is also
+// triggered before callback is invoked.
+std::this_thread::sleep_for(std::chrono::milliseconds(100));
+  };
+
+  CompleteAtPoint("1");
+  auto Reqs1 = Requests.consumeRequests();
+  ASSERT_EQ(Reqs1.size(), 1u);
+  EXPECT_THAT(Reqs1[0].Scopes, UnorderedElementsAre("ns1::"));
+
+  CompleteAtPoint("2");
+  auto Reqs2 = Requests.consumeRequests();
+  // Speculation succeeded. Used speculative index result.
+  ASSERT_EQ(Reqs2.size(), 1u);
+  EXPECT_EQ(Reqs2[0], Reqs1[0]);
+
+  CompleteAtPoint("3");
+  // Speculation failed. Sent speculative index request and the new index
+  // request after sema.
+  auto Reqs3 = Requests.consumeRequests();
+  ASSERT_EQ(Reqs3.size(), 2u);
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -164,6 +164,20 @@
"an include line will be inserted or not."),
 llvm::cl::init(true));
 
+static llvm::cl::opt SpeculateCompletionIndexRequest(
+"speculative-completion-index-request",
+llvm::cl::desc(
+R"(If set to true and static index is enabled, this will send an
+asynchronous speculative index request, based on the index request for
+the last code completion on the same file and the filter text typed
+before the cursor, before sema code completion is invoked. This can
+reduce the code completion latency (by roughly latency of sema code
+completion) if the speculative request is the same as the one generated
+

[PATCH] D51088: [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added inline comments.
This revision is now accepted and ready to land.



Comment at: clangd/index/CanonicalIncludes.cpp:24
+  int Components = 0;
+  for (auto It = llvm::sys::path::begin(Suffix),
+End = llvm::sys::path::end(Suffix);

Would `int Components = begin(Suffix)  - end(Suffix);` work here?



Comment at: clangd/index/CanonicalIncludes.cpp:79
+   It != End; ++It) {
+++Components;
+if (MaxSuffixComponents < Components)

Maybe merge `Components` and break condition into `for loop` condition?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51088



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


[PATCH] D50898: [clangd] Suggest code-completions for overriding base class virtual methods.

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Looks good mostly, a few nits. We should make sure all related comments are 
updated accordingly




Comment at: clangd/CodeComplete.cpp:198
+static std::vector
+getVirtualNonOverridenMethods(const DeclContext *DC, Sema *S) {
+  const auto *CR = llvm::dyn_cast(DC);

Since we are returning `CodeCompletionResult`, maybe naming it like 
`getNonOverridenCompleteionResults` is clearer?



Comment at: clangd/CodeComplete.cpp:222
+  const std::string Name = Method->getNameAsString();
+  const auto it = Overrides.find(Name);
+  bool IsOverriden = false;

nit: Can't we use `Overrides.find(Method->getName())`  and the other places as 
well?



Comment at: clangd/CodeComplete.cpp:224
+  bool IsOverriden = false;
+  if (it != Overrides.end())
+for (auto *MD : it->second) {

nit: use `{}` around the body of `if` -- the one-line for statement is across 
line, adding `{}` around it will improve the readability. 



Comment at: clangd/CodeComplete.cpp:1238
 : SymbolSlab();
 // Merge Sema and Index results, score them, and pick the winners.
+const auto Overrides = getVirtualNonOverridenMethods(

nit: we need to update the comment accordingly.



Comment at: clangd/CodeComplete.cpp:1281
   // Groups overloads if desired, to form CompletionCandidate::Bundles.
   // The bundles are scored and top results are returned, best to worst.
   std::vector

here as well.



Comment at: clangd/CodeComplete.cpp:1322
   AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
+for (auto &OverrideResult : OverrideResults)
+  AddToBundles(&OverrideResult, CorrespondingIndexResult(OverrideResult),

IIUC, we are treating the override results the same `SemaResult`, it is safe as 
long as Sema doesn't provide these overrides in its code completion results, 
otherwise we will have duplicated completion items?

I think we probably need a proper comment explaining what's going on here.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50898



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


[PATCH] D48027: [analyzer] Improve `CallDescription` to handle c++ method.

2018-08-22 Thread Henry Wong via Phabricator via cfe-commits
MTC added a comment.

In https://reviews.llvm.org/D48027#1207645, @xazax.hun wrote:

> Sorry for the delay, I think this is OK to commit.
>  As a possible improvement, I can imagine making it slightly stricter, e.g. 
> you could only skip QualifiedNames for inline namespaces and the beginning. 
> Maybe add support for staring with `""` or `::` to even disable skipping 
> namespaces at the beginning?
>  But these are just nice to have features, I am perfectly ok with not having 
> them or doing it in a followup patch.


Thanks, Gábor!
I will land it first and do the improvement according to the mismatch case in 
the followup patch!


https://reviews.llvm.org/D48027



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


[libcxx] r340406 - Attempt to unbreak filesystem tests on certain linux distros.

2018-08-22 Thread Eric Fiselier via cfe-commits
Author: ericwf
Date: Wed Aug 22 06:29:52 2018
New Revision: 340406

URL: http://llvm.org/viewvc/llvm-project?rev=340406&view=rev
Log:
Attempt to unbreak filesystem tests on certain linux distros.

On some platforms clock_gettime is in librt, which we don't
link by default when building the tests. However it is required
by the filesystem tests.

This patch introduces a workaround which links librt whenever
the filesystem tests are enabled. The workaround should later
be replaced with a patch that selectively links both libc++fs
and librt only when building filesystem specific tests. However,
the way the test configuration is set up right now, this is
non-trivial.

Modified:
libcxx/trunk/utils/libcxx/test/target_info.py

Modified: libcxx/trunk/utils/libcxx/test/target_info.py
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/utils/libcxx/test/target_info.py?rev=340406&r1=340405&r2=340406&view=diff
==
--- libcxx/trunk/utils/libcxx/test/target_info.py (original)
+++ libcxx/trunk/utils/libcxx/test/target_info.py Wed Aug 22 06:29:52 2018
@@ -222,12 +222,17 @@ class LinuxLocalTI(DefaultTargetInfo):
   self.full_config.config.available_features)
 llvm_unwinder = self.full_config.get_lit_bool('llvm_unwinder', False)
 shared_libcxx = self.full_config.get_lit_bool('enable_shared', True)
+# FIXME: Remove the need to link -lrt in all the tests, and instead
+# limit it only to the filesystem tests. This ensures we don't cause an
+# implicit dependency on librt except when filesystem is needed.
+enable_fs = self.full_config.get_lit_bool('enable_filesystem',
+  default=False)
 flags += ['-lm']
 if not llvm_unwinder:
 flags += ['-lgcc_s', '-lgcc']
 if enable_threads:
 flags += ['-lpthread']
-if not shared_libcxx:
+if not shared_libcxx or enable_fs:
   flags += ['-lrt']
 flags += ['-lc']
 if llvm_unwinder:


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


[PATCH] D48027: [analyzer] Improve `CallDescription` to handle c++ method.

2018-08-22 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC340407: [analyzer] Improve `CallDescription` to handle c++ 
method. (authored by henrywong, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48027?vs=161217&id=161938#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48027

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
  lib/StaticAnalyzer/Core/CallEvent.cpp

Index: include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -80,24 +80,41 @@
 
   mutable IdentifierInfo *II = nullptr;
   mutable bool IsLookupDone = false;
-  StringRef FuncName;
+  // The list of the qualified names used to identify the specified CallEvent,
+  // e.g. "{a, b}" represent the qualified names, like "a::b".
+  std::vector QualifiedName;
   unsigned RequiredArgs;
 
 public:
   const static unsigned NoArgRequirement = std::numeric_limits::max();
 
   /// Constructs a CallDescription object.
   ///
+  /// @param QualifiedName The list of the qualified names of the function that
+  /// will be matched. It does not require the user to provide the full list of
+  /// the qualified name. The more details provided, the more accurate the
+  /// matching.
+  ///
+  /// @param RequiredArgs The number of arguments that is expected to match a
+  /// call. Omit this parameter to match every occurrence of call with a given
+  /// name regardless the number of arguments.
+  CallDescription(std::vector QualifiedName,
+  unsigned RequiredArgs = NoArgRequirement)
+  : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs) {}
+
+  /// Constructs a CallDescription object.
+  ///
   /// @param FuncName The name of the function that will be matched.
   ///
   /// @param RequiredArgs The number of arguments that is expected to match a
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
   CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
-  : FuncName(FuncName), RequiredArgs(RequiredArgs) {}
+  : CallDescription(std::vector({FuncName}), NoArgRequirement) {
+  }
 
   /// Get the name of the function that this object matches.
-  StringRef getFunctionName() const { return FuncName; }
+  StringRef getFunctionName() const { return QualifiedName.back(); }
 };
 
 template
Index: lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- lib/StaticAnalyzer/Core/CallEvent.cpp
+++ lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -359,11 +359,38 @@
 return false;
   if (!CD.IsLookupDone) {
 CD.IsLookupDone = true;
-CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName);
+CD.II = &getState()->getStateManager().getContext().Idents.get(
+CD.getFunctionName());
   }
   const IdentifierInfo *II = getCalleeIdentifier();
   if (!II || II != CD.II)
 return false;
+
+  const Decl *D = getDecl();
+  // If CallDescription provides prefix names, use them to improve matching
+  // accuracy.
+  if (CD.QualifiedName.size() > 1 && D) {
+const DeclContext *Ctx = D->getDeclContext();
+std::vector QualifiedName = CD.QualifiedName;
+QualifiedName.pop_back();
+for (; Ctx && isa(Ctx); Ctx = Ctx->getParent()) {
+  if (const auto *ND = dyn_cast(Ctx)) {
+if (!QualifiedName.empty() && ND->getName() == QualifiedName.back())
+  QualifiedName.pop_back();
+continue;
+  }
+
+  if (const auto *RD = dyn_cast(Ctx)) {
+if (!QualifiedName.empty() && RD->getName() == QualifiedName.back())
+  QualifiedName.pop_back();
+continue;
+  }
+}
+
+if (!QualifiedName.empty())
+  return false;
+  }
+
   return (CD.RequiredArgs == CallDescription::NoArgRequirement ||
   CD.RequiredArgs == getNumArgs());
 }
Index: lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
+++ lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
@@ -86,14 +86,20 @@
   };
 
   InnerPointerChecker()
-  : AppendFn("append"), AssignFn("assign"), ClearFn("clear"),
-CStrFn("c_str"), DataFn("data"), EraseFn("erase"), InsertFn("insert"),
-PopBackFn("pop_back"), PushBackFn("push_back"), ReplaceFn("replace"),
-ReserveFn("reserve"), ResizeFn("resize"),
-ShrinkToFitFn("shrink_to_fit"), SwapFn("swap") {}
-
-  /// Check if the object of this member function call is a `basic_string`.
-  bool isCalledOnStringObject(const CXXInstanceCall *ICall) const;
+  : AppendFn({"std", "basic_string", "append"}),
+AssignFn({"std", "basic_st

r340407 - [analyzer] Improve `CallDescription` to handle c++ method.

2018-08-22 Thread Henry Wong via cfe-commits
Author: henrywong
Date: Wed Aug 22 06:30:46 2018
New Revision: 340407

URL: http://llvm.org/viewvc/llvm-project?rev=340407&view=rev
Log:
[analyzer] Improve `CallDescription` to handle c++ method.

Summary:
`CallDecription` can only handle function for the time being. If we want to 
match c++ method, we can only use method name to match and can't improve the 
matching accuracy through the qualifiers. 

This patch add the support for `QualifiedName` matching to improve the matching 
accuracy.

Reviewers: xazax.hun, NoQ, george.karpenkov, rnkovacs

Reviewed By: xazax.hun, NoQ, rnkovacs

Subscribers: Szelethus, szepet, rnkovacs, a.sidorin, mikhail.ramalho, 
cfe-commits, MTC

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
cfe/trunk/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h?rev=340407&r1=340406&r2=340407&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h Wed 
Aug 22 06:30:46 2018
@@ -80,7 +80,9 @@ class CallDescription {
 
   mutable IdentifierInfo *II = nullptr;
   mutable bool IsLookupDone = false;
-  StringRef FuncName;
+  // The list of the qualified names used to identify the specified CallEvent,
+  // e.g. "{a, b}" represent the qualified names, like "a::b".
+  std::vector QualifiedName;
   unsigned RequiredArgs;
 
 public:
@@ -88,16 +90,31 @@ public:
 
   /// Constructs a CallDescription object.
   ///
+  /// @param QualifiedName The list of the qualified names of the function that
+  /// will be matched. It does not require the user to provide the full list of
+  /// the qualified name. The more details provided, the more accurate the
+  /// matching.
+  ///
+  /// @param RequiredArgs The number of arguments that is expected to match a
+  /// call. Omit this parameter to match every occurrence of call with a given
+  /// name regardless the number of arguments.
+  CallDescription(std::vector QualifiedName,
+  unsigned RequiredArgs = NoArgRequirement)
+  : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs) {}
+
+  /// Constructs a CallDescription object.
+  ///
   /// @param FuncName The name of the function that will be matched.
   ///
   /// @param RequiredArgs The number of arguments that is expected to match a
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
   CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
-  : FuncName(FuncName), RequiredArgs(RequiredArgs) {}
+  : CallDescription(std::vector({FuncName}), NoArgRequirement) {
+  }
 
   /// Get the name of the function that this object matches.
-  StringRef getFunctionName() const { return FuncName; }
+  StringRef getFunctionName() const { return QualifiedName.back(); }
 };
 
 template

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp?rev=340407&r1=340406&r2=340407&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp Wed Aug 22 
06:30:46 2018
@@ -86,14 +86,20 @@ public:
   };
 
   InnerPointerChecker()
-  : AppendFn("append"), AssignFn("assign"), ClearFn("clear"),
-CStrFn("c_str"), DataFn("data"), EraseFn("erase"), InsertFn("insert"),
-PopBackFn("pop_back"), PushBackFn("push_back"), ReplaceFn("replace"),
-ReserveFn("reserve"), ResizeFn("resize"),
-ShrinkToFitFn("shrink_to_fit"), SwapFn("swap") {}
-
-  /// Check if the object of this member function call is a `basic_string`.
-  bool isCalledOnStringObject(const CXXInstanceCall *ICall) const;
+  : AppendFn({"std", "basic_string", "append"}),
+AssignFn({"std", "basic_string", "assign"}),
+ClearFn({"std", "basic_string", "clear"}),
+CStrFn({"std", "basic_string", "c_str"}),
+DataFn({"std", "basic_string", "data"}),
+EraseFn({"std", "basic_string", "erase"}),
+InsertFn({"std", "basic_string", "insert"}),
+PopBackFn({"std", "basic_string", "pop_back"}),
+PushBackFn({"std", "basic_string", "push_back"}),
+ReplaceFn({"std", "basic_string", "replace"}),
+ReserveFn({"std", "basic_string", "reserve"}),
+ResizeFn({"std", "basic_string", "resize"}),
+ShrinkToFitFn({"std", "basic_string", "shrink_to_fi

[PATCH] D50385: [clangd] Collect symbol occurrences from AST.

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/index/Index.cpp:139
+std::sort(Occurrences.begin(), Occurrences.end(),
+  [](const SymbolOccurrence &L, const SymbolOccurrence &R) {
+return L < R;

NIT: remove the lambda? using `<` is the default.



Comment at: clangd/index/Index.cpp:145
+[](const SymbolOccurrence &L, const SymbolOccurrence &R) {
+  return L == R;
+}),

NIT: remove the lambda? Using `==` is the default.



Comment at: clangd/index/Index.cpp:158
+raw_ostream &operator<<(raw_ostream &OS, SymbolOccurrenceKind K) {
+  OS << static_cast(K);
+  return OS;

Is this used for debugging?
In that case maybe consider having a user-readable representation instead of 
the number?



Comment at: clangd/index/Index.h:46
+
+inline bool operator==(const SymbolLocation::Position &L,
+   const SymbolLocation::Position &R) {

NIT: having friend decls inside the classes themselves might prove to be more 
readable.
Not opposed to the current one too, feel free to ignore.



Comment at: clangd/index/Index.h:349
 llvm::DenseMap SymbolIndex;
+
+llvm::DenseMap> SymbolOccurrences;

Maybe add a comment or remove the empty line?



Comment at: clangd/index/Index.h:350
+
+llvm::DenseMap> SymbolOccurrences;
   };

Any store occurences in a file-centric manner?
E.g. 
```
/// Occurences inside a single file.
class FileOccurences {
  StringRef File;
  vector> Locations;
};

// 
DenseMap>  SymbolOccurences;
```

As discussed previously, this representation is better suited for both merging 
and serialization.



Comment at: clangd/index/SymbolCollector.cpp:272
+};
+if (static_cast(Opts.Filter) & Roles) {
+  if (auto ID = getSymbolID(D)) {

NIT: maybe use early exits and inverted conditions to keep the nesting down?



Comment at: clangd/index/SymbolCollector.cpp:321
+
+  const SymbolCollector::Options &CollectorOpts;
+  const SymbolCollector::Options::CollectSymbolOptions &Opts;

If we any `Options` here, why have an extra `CollectorSymbolOptions`?



Comment at: clangd/index/SymbolCollector.h:59
+  // If none, all symbol occurrences will be collected.
+  llvm::Optional> IDs = llvm::None;
+};

Could you elaborate on what this option will be used for? How do we know in 
advance which symbols we're interested in?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50385



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


[PATCH] D50580: [clang-tidy] Abseil: no namespace check

2018-08-22 Thread Deanna Garcia via Phabricator via cfe-commits
deannagarcia updated this revision to Diff 161939.
deannagarcia marked 2 inline comments as done.

https://reviews.llvm.org/D50580

Files:
  clang-tidy/abseil/AbseilMatcher.h
  clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tidy/abseil/CMakeLists.txt
  clang-tidy/abseil/NoNamespaceCheck.cpp
  clang-tidy/abseil/NoNamespaceCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/abseil-no-namespace.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/Inputs/absl/external-file.h
  test/clang-tidy/Inputs/absl/strings/internal-file.h
  test/clang-tidy/abseil-no-namespace.cpp

Index: test/clang-tidy/abseil-no-namespace.cpp
===
--- test/clang-tidy/abseil-no-namespace.cpp
+++ test/clang-tidy/abseil-no-namespace.cpp
@@ -0,0 +1,28 @@
+// RUN: %check_clang_tidy %s abseil-no-namespace %t -- -- -I %S/Inputs
+// RUN: clang-tidy -checks='-*, abseil-no-namespace' -header-filter='.*' %s -- -I %S/Inputs 2>&1 | FileCheck %s
+
+/// Warning will not be triggered on internal Abseil code that is included.
+#include "absl/strings/internal-file.h"
+// CHECK-NOT: warning:
+
+/// Warning will be triggered on code that is not internal that is included.
+#include "absl/external-file.h"
+// CHECK: absl/external-file.h:1:11: warning: namespace 'absl' is reserved
+// for implementation of the Abseil library and should not be opened in user
+// code [abseil-no-namespace]
+
+namespace absl {}
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'absl' is reserved for
+// implementation of the Abseil library and should not be opened in the user
+// code [abseil-no-namespace]
+
+namespace absl {
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: namespace 'absl'
+namespace std {
+int i = 5;
+}
+}
+
+// Things that shouldn't trigger the check
+int i = 5;
+namespace std {}
Index: test/clang-tidy/Inputs/absl/strings/internal-file.h
===
--- test/clang-tidy/Inputs/absl/strings/internal-file.h
+++ test/clang-tidy/Inputs/absl/strings/internal-file.h
@@ -0,0 +1 @@
+namespace absl {}
Index: test/clang-tidy/Inputs/absl/external-file.h
===
--- test/clang-tidy/Inputs/absl/external-file.h
+++ test/clang-tidy/Inputs/absl/external-file.h
@@ -0,0 +1 @@
+namespace absl {}
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -5,6 +5,7 @@
 
 .. toctree::
abseil-duration-division
+   abseil-no-namespace
abseil-string-find-startswith
android-cloexec-accept
android-cloexec-accept4
Index: docs/clang-tidy/checks/abseil-no-namespace.rst
===
--- docs/clang-tidy/checks/abseil-no-namespace.rst
+++ docs/clang-tidy/checks/abseil-no-namespace.rst
@@ -0,0 +1,21 @@
+.. title:: clang-tidy - abseil-no-namespace
+
+abseil-no-namespace
+===
+
+Ensures code does not open ``namespace absl`` as that violates Abseil's
+compatibility guidelines. Code should not open ``namespace absl`` as that
+conflicts with Abseil's compatibility guidelines and may result in breakage.
+
+Any code that uses:
+
+.. code-block:: c++
+
+ namespace absl {
+  ...
+ }
+
+will be prompted with a warning.
+
+See `the full Abseil compatibility guidelines `_ for more information.
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -64,6 +64,12 @@
   floating-point context, and recommends the use of a function that
   returns a floating-point value.
 
+- New :doc:`abseil-no-namespace
+  ` check.
+
+  Ensures code does not open ``namespace absl`` as that violates Abseil's
+  compatibility guidelines.
+
 - New :doc:`readability-magic-numbers
   ` check.
 
Index: clang-tidy/abseil/NoNamespaceCheck.h
===
--- clang-tidy/abseil/NoNamespaceCheck.h
+++ clang-tidy/abseil/NoNamespaceCheck.h
@@ -0,0 +1,36 @@
+//===--- NoNamespaceCheck.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_ABSEIL_NONAMESPACECHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_NONAMESPACECHECK_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace abseil {
+
+/// This check ensures users don't open namespace absl, as that violates
+/// Abseil's compatibility guidelines.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/abseil-no-namespace.html
+class NoNamespaceCheck : public ClangTi

[PATCH] D50970: [clangd] Implement BOOST iterator

2018-08-22 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


https://reviews.llvm.org/D50970



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


r340408 - [CodeGen] Look at the type of a block capture field rather than the type

2018-08-22 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Wed Aug 22 06:41:19 2018
New Revision: 340408

URL: http://llvm.org/viewvc/llvm-project?rev=340408&view=rev
Log:
[CodeGen] Look at the type of a block capture field rather than the type
of the captured variable when determining whether the capture needs
special handing when the block is copied or disposed.

This fixes bugs in the handling of variables captured by a block that is
nested inside a lambda that captures the variables by reference.

rdar://problem/43540889

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

Added:
cfe/trunk/test/CodeGenObjCXX/block-nested-in-lambda.mm
Removed:
cfe/trunk/test/CodeGenObjCXX/block-nested-in-lambda.cpp
Modified:
cfe/trunk/lib/CodeGen/CGBlocks.cpp

Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=340408&r1=340407&r2=340408&view=diff
==
--- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Wed Aug 22 06:41:19 2018
@@ -557,6 +557,10 @@ static void computeBlockInfo(CodeGenModu
   CharUnits align = CGM.getPointerAlign();
   maxFieldAlign = std::max(maxFieldAlign, align);
 
+  // Since a __block variable cannot be captured by lambdas, its type and
+  // the capture field type should always match.
+  assert(getCaptureFieldType(*CGF, CI) == variable->getType() &&
+ "capture type differs from the variable type");
   layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
 Qualifiers::OCL_None, &CI,
 CGM.VoidPtrTy, variable->getType()));
@@ -570,10 +574,11 @@ static void computeBlockInfo(CodeGenModu
   continue;
 }
 
+QualType VT = getCaptureFieldType(*CGF, CI);
+
 // If we have a lifetime qualifier, honor it for capture purposes.
 // That includes *not* copying it if it's __unsafe_unretained.
-Qualifiers::ObjCLifetime lifetime =
-  variable->getType().getObjCLifetime();
+Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
 if (lifetime) {
   switch (lifetime) {
   case Qualifiers::OCL_None: llvm_unreachable("impossible");
@@ -587,10 +592,10 @@ static void computeBlockInfo(CodeGenModu
   }
 
 // Block pointers require copy/dispose.  So do Objective-C pointers.
-} else if (variable->getType()->isObjCRetainableType()) {
+} else if (VT->isObjCRetainableType()) {
   // But honor the inert __unsafe_unretained qualifier, which doesn't
   // actually make it into the type system.
-   if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
+   if (VT->isObjCInertUnsafeUnretainedType()) {
 lifetime = Qualifiers::OCL_ExplicitNone;
   } else {
 info.NeedsCopyDispose = true;
@@ -602,21 +607,18 @@ static void computeBlockInfo(CodeGenModu
 } else if (CI.hasCopyExpr()) {
   info.NeedsCopyDispose = true;
   info.HasCXXObject = true;
-  if (!variable->getType()->getAsCXXRecordDecl()->isExternallyVisible())
+  if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
 info.CapturesNonExternalType = true;
 
 // So do C structs that require non-trivial copy construction or
 // destruction.
-} else if (variable->getType().isNonTrivialToPrimitiveCopy() ==
-   QualType::PCK_Struct ||
-   variable->getType().isDestructedType() ==
-   QualType::DK_nontrivial_c_struct) {
+} else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
+   VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
   info.NeedsCopyDispose = true;
 
 // And so do types with destructors.
 } else if (CGM.getLangOpts().CPlusPlus) {
-  if (const CXXRecordDecl *record =
-variable->getType()->getAsCXXRecordDecl()) {
+  if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
 if (!record->hasTrivialDestructor()) {
   info.HasCXXObject = true;
   info.NeedsCopyDispose = true;
@@ -626,7 +628,6 @@ static void computeBlockInfo(CodeGenModu
   }
 }
 
-QualType VT = getCaptureFieldType(*CGF, CI);
 CharUnits size = C.getTypeSizeInChars(VT);
 CharUnits align = C.getDeclAlign(variable);
 
@@ -1717,10 +1718,9 @@ static void findBlockCapturedManagedEnti
 if (Capture.isConstant())
   continue;
 
-auto CopyInfo =
-   computeCopyInfoForBlockCapture(CI, Variable->getType(), LangOpts);
-auto DisposeInfo =
-   computeDestroyInfoForBlockCapture(CI, Variable->getType(), LangOpts);
+QualType VT = Capture.fieldType();
+auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
+auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
 if (CopyInfo.first != BlockCaptureEntityKind::None ||
 DisposeInfo.first != BlockCaptureEntityKind::None)
   

[PATCH] D51025: [CodeGen] Fix handling of variables captured by a block that is nested inside a lambda

2018-08-22 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL340408: [CodeGen] Look at the type of a block capture field 
rather than the type (authored by ahatanak, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D51025?vs=161648&id=161941#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D51025

Files:
  cfe/trunk/lib/CodeGen/CGBlocks.cpp
  cfe/trunk/test/CodeGenObjCXX/block-nested-in-lambda.cpp
  cfe/trunk/test/CodeGenObjCXX/block-nested-in-lambda.mm

Index: cfe/trunk/test/CodeGenObjCXX/block-nested-in-lambda.mm
===
--- cfe/trunk/test/CodeGenObjCXX/block-nested-in-lambda.mm
+++ cfe/trunk/test/CodeGenObjCXX/block-nested-in-lambda.mm
@@ -0,0 +1,82 @@
+// RUN: %clang_cc1 -triple=x86_64-apple-darwin10 -emit-llvm -std=c++11 -fblocks -fobjc-arc -o - %s | FileCheck %s
+
+// CHECK: %[[STRUCT_BLOCK_DESCRIPTOR:.*]] = type { i64, i64 }
+
+// CHECK: %[[BLOCK_CAPTURED0:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>, <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>* %[[BLOCK:.*]], i32 0, i32 5
+// CHECK: %[[V0:.*]] = getelementptr inbounds %[[LAMBDA_CLASS:.*]], %[[LAMBDA_CLASS]]* %[[THIS:.*]], i32 0, i32 0
+// CHECK: %[[V1:.*]] = load i32*, i32** %[[V0]], align 8
+// CHECK: store i32* %[[V1]], i32** %[[BLOCK_CAPTURED0]], align 8
+// CHECK: %[[BLOCK_CAPTURED1:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>, <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>* %[[BLOCK]], i32 0, i32 6
+// CHECK: %[[V2:.*]] = getelementptr inbounds %[[LAMBDA_CLASS]], %[[LAMBDA_CLASS]]* %[[THIS]], i32 0, i32 1
+// CHECK: %[[V3:.*]] = load i32*, i32** %[[V2]], align 8
+// CHECK: store i32* %[[V3]], i32** %[[BLOCK_CAPTURED1]], align 8
+
+void foo1(int &, int &);
+
+void block_in_lambda(int &s1, int &s2) {
+  auto lambda = [&s1, &s2]() {
+auto block = ^{
+  foo1(s1, s2);
+};
+block();
+  };
+
+  lambda();
+}
+
+namespace CaptureByReference {
+
+id getObj();
+void use(id);
+
+// Block copy/dispose helpers aren't needed because 'a' is captured by
+// reference.
+
+// CHECK-LABEL: define void @_ZN18CaptureByReference5test0Ev(
+// CHECK-LABEL: define internal void @"_ZZN18CaptureByReference5test0EvENK3$_1clEv"(
+// CHECK: %[[BLOCK_DESCRIPTOR:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8** }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8** }>* %{{.*}}, i32 0, i32 4
+// CHECK: store %[[STRUCT_BLOCK_DESCRIPTOR]]* bitcast ({ i64, i64, i8*, i64 }* @"__block_descriptor_40_e5_v8@?0ls32l8" to %[[STRUCT_BLOCK_DESCRIPTOR]]*), %[[STRUCT_BLOCK_DESCRIPTOR]]** %[[BLOCK_DESCRIPTOR]], align 8
+
+void test0() {
+  id a = getObj();
+  [&]{ ^{ a = 0; }(); }();
+}
+
+// Block copy/dispose helpers shouldn't have to retain/release 'a' because it
+// is captured by reference.
+
+// CHECK-LABEL: define void @_ZN18CaptureByReference5test1Ev(
+// CHECK-LABEL: define internal void @"_ZZN18CaptureByReference5test1EvENK3$_2clEv"(
+// CHECK: %[[BLOCK_DESCRIPTOR:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>* %{{.*}}, i32 0, i32 4
+// CHECK: store %[[STRUCT_BLOCK_DESCRIPTOR]]* bitcast ({ i64, i64, i8*, i8*, i8*, i64 }* @"__block_descriptor_56_8_32s40s_e5_v8@?0l" to %[[STRUCT_BLOCK_DESCRIPTOR]]*), %[[STRUCT_BLOCK_DESCRIPTOR]]** %[[BLOCK_DESCRIPTOR]], align 8
+
+// CHECK-LABEL: define linkonce_odr hidden void @__copy_helper_block_8_32s40s(
+// CHECK-NOT: call void @objc_storeStrong(
+// CHECK: %[[V4:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>* %{{.*}}, i32 0, i32 5
+// CHECK: %[[V5:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>* %{{.*}}, i32 0, i32 5
+// CHECK: %[[BLOCKCOPY_SRC:.*]] = load i8*, i8** %[[V4]], align 8
+// CHECK: store i8* null, i8** %[[V5]], align 8
+// CHECK: call void @objc_storeStrong(i8** %[[V5]], i8* %[[BLOCKCOPY_SRC]])
+// CHECK: %[[V6:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>* %{{.*}}, i32 0, i32 6
+// CHECK: %[[V7:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8** }>* %{{.*}}, i32 0, i32 6
+// CHECK: %[[BLOCKCOPY_SRC2:.*]] = load i8*, i8** %[[V6]], align 8
+// CHECK: store i8* null, i8** %[[V7]], align 8
+// CHECK: call void @objc_storeStrong(i8** %[[V7]], i8* %[[BLOCKCOPY_S

[PATCH] D51100: [clang-tidy] Add Abseil prefix to documentation

2018-08-22 Thread Deanna Garcia via Phabricator via cfe-commits
deannagarcia created this revision.
deannagarcia added reviewers: aaron.ballman, hokein.
deannagarcia added a project: clang-tools-extra.
Herald added a subscriber: xazax.hun.

Adds the Abseil prefix to the list of prefixes in the documentation


https://reviews.llvm.org/D51100

Files:
  docs/clang-tidy/index.rst


Index: docs/clang-tidy/index.rst
===
--- docs/clang-tidy/index.rst
+++ docs/clang-tidy/index.rst
@@ -55,6 +55,7 @@
 == 
=
 Name prefixDescription
 == 
=
+``abseil-``Checks related to Abseil library.
 ``android-``   Checks related to Android.
 ``boost-`` Checks related to Boost library.
 ``bugprone-``  Checks that target bugprone code constructs.


Index: docs/clang-tidy/index.rst
===
--- docs/clang-tidy/index.rst
+++ docs/clang-tidy/index.rst
@@ -55,6 +55,7 @@
 == =
 Name prefixDescription
 == =
+``abseil-``Checks related to Abseil library.
 ``android-``   Checks related to Android.
 ``boost-`` Checks related to Boost library.
 ``bugprone-``  Checks that target bugprone code constructs.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r340409 - [clangd] Implement BOOST iterator

2018-08-22 Thread Kirill Bobyrev via cfe-commits
Author: omtcyfz
Date: Wed Aug 22 06:44:15 2018
New Revision: 340409

URL: http://llvm.org/viewvc/llvm-project?rev=340409&view=rev
Log:
[clangd] Implement BOOST iterator

This patch introduces BOOST iterator - a substantial block for efficient
and high-quality symbol retrieval. The concept of boosting allows
performing computationally inexpensive scoring on the query side so that
the final (expensive) scoring can only be applied on the items with the
highest preliminary score while eliminating the need to score too many
items.

Reviewed by: ilya-biryukov

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

Modified:
clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp
clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
clang-tools-extra/trunk/clangd/index/dex/Iterator.h
clang-tools-extra/trunk/unittests/clangd/DexIndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp?rev=340409&r1=340408&r2=340409&view=diff
==
--- clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/DexIndex.cpp Wed Aug 22 06:44:15 
2018
@@ -125,11 +125,15 @@ bool DexIndex::fuzzyFind(
 // using 100x of the requested number might not be good in practice, e.g.
 // when the requested number of items is small.
 const unsigned ItemsToRetrieve = 100 * Req.MaxCandidateCount;
-std::vector SymbolDocIDs = consume(*QueryIterator, ItemsToRetrieve);
+// FIXME(kbobyrev): Add boosting to the query and utilize retrieved
+// boosting scores.
+std::vector> SymbolDocIDs =
+consume(*QueryIterator, ItemsToRetrieve);
 
 // Retrieve top Req.MaxCandidateCount items.
 std::priority_queue> Top;
-for (const auto &SymbolDocID : SymbolDocIDs) {
+for (const auto &P : SymbolDocIDs) {
+  const DocID SymbolDocID = P.first;
   const auto *Sym = (*Symbols)[SymbolDocID];
   const llvm::Optional Score = Filter.match(Sym->Name);
   if (!Score)
@@ -161,7 +165,6 @@ void DexIndex::lookup(const LookupReques
   }
 }
 
-
 void DexIndex::findOccurrences(
 const OccurrencesRequest &Req,
 llvm::function_ref Callback) const {

Modified: clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp?rev=340409&r1=340408&r2=340409&view=diff
==
--- clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp Wed Aug 22 06:44:15 
2018
@@ -46,6 +46,8 @@ public:
 return *Index;
   }
 
+  float consume(DocID ID) override { return DEFAULT_BOOST_SCORE; }
+
 private:
   llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
 OS << '[';
@@ -103,6 +105,19 @@ public:
 
   DocID peek() const override { return Children.front()->peek(); }
 
+  // If not exhausted and points to the given item, consume() returns the
+  // product of Children->consume(ID). Otherwise, DEFAULT_BOOST_SCORE is
+  // returned.
+  float consume(DocID ID) override {
+if (reachedEnd() || peek() != ID)
+  return DEFAULT_BOOST_SCORE;
+return std::accumulate(
+begin(Children), end(Children), DEFAULT_BOOST_SCORE,
+[&](float Current, const std::unique_ptr &Child) {
+  return Current * Child->consume(ID);
+});
+  }
+
 private:
   llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
 OS << "(& ";
@@ -209,6 +224,20 @@ public:
 return Result;
   }
 
+  // Returns the maximum boosting score among all Children when iterator is not
+  // exhausted and points to the given ID, DEFAULT_BOOST_SCORE otherwise.
+  float consume(DocID ID) override {
+if (reachedEnd() || peek() != ID)
+  return DEFAULT_BOOST_SCORE;
+return std::accumulate(
+begin(Children), end(Children), DEFAULT_BOOST_SCORE,
+[&](float Current, const std::unique_ptr &Child) {
+  return (!Child->reachedEnd() && Child->peek() == ID)
+ ? std::max(Current, Child->consume(ID))
+ : Current;
+});
+  }
+
 private:
   llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
 OS << "(| ";
@@ -249,6 +278,8 @@ public:
 return Index;
   }
 
+  float consume(DocID) override { return DEFAULT_BOOST_SCORE; }
+
 private:
   llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
 OS << "(TRUE {" << Index << "} out of " << Size << ")";
@@ -260,13 +291,42 @@ private:
   DocID Size;
 };
 
+/// Boost iterator is a wrapper around its child which multiplies scores of
+/// each retrieved item by a given factor.
+class BoostIterator : public Iterator {
+public:
+  BoostIterator(std::unique_ptr Child, float Factor)
+  : Child(move(Child)), Factor(Fact

[PATCH] D50970: [clangd] Implement BOOST iterator

2018-08-22 Thread Kirill Bobyrev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE340409: [clangd] Implement BOOST iterator (authored by 
omtcyfz, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D50970?vs=161936&id=161944#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50970

Files:
  clangd/index/dex/DexIndex.cpp
  clangd/index/dex/Iterator.cpp
  clangd/index/dex/Iterator.h
  unittests/clangd/DexIndexTests.cpp

Index: unittests/clangd/DexIndexTests.cpp
===
--- unittests/clangd/DexIndexTests.cpp
+++ unittests/clangd/DexIndexTests.cpp
@@ -29,6 +29,15 @@
 namespace dex {
 namespace {
 
+std::vector
+consumeIDs(Iterator &It, size_t Limit = std::numeric_limits::max()) {
+  auto IDAndScore = consume(It, Limit);
+  std::vector IDs(IDAndScore.size());
+  for (size_t I = 0; I < IDAndScore.size(); ++I)
+IDs[I] = IDAndScore[I].first;
+  return IDs;
+}
+
 TEST(DexIndexIterators, DocumentIterator) {
   const PostingList L = {4, 7, 8, 20, 42, 100};
   auto DocIterator = create(L);
@@ -62,7 +71,7 @@
   auto AndWithEmpty = createAnd(create(L0), create(L1));
   EXPECT_TRUE(AndWithEmpty->reachedEnd());
 
-  EXPECT_THAT(consume(*AndWithEmpty), ElementsAre());
+  EXPECT_THAT(consumeIDs(*AndWithEmpty), ElementsAre());
 }
 
 TEST(DexIndexIterators, AndTwoLists) {
@@ -72,7 +81,7 @@
   auto And = createAnd(create(L1), create(L0));
 
   EXPECT_FALSE(And->reachedEnd());
-  EXPECT_THAT(consume(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
+  EXPECT_THAT(consumeIDs(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
 
   And = createAnd(create(L0), create(L1));
 
@@ -113,7 +122,7 @@
   auto OrWithEmpty = createOr(create(L0), create(L1));
   EXPECT_FALSE(OrWithEmpty->reachedEnd());
 
-  EXPECT_THAT(consume(*OrWithEmpty),
+  EXPECT_THAT(consumeIDs(*OrWithEmpty),
   ElementsAre(0U, 5U, 7U, 10U, 42U, 320U, 9000U));
 }
 
@@ -146,7 +155,7 @@
 
   Or = createOr(create(L0), create(L1));
 
-  EXPECT_THAT(consume(*Or),
+  EXPECT_THAT(consumeIDs(*Or),
   ElementsAre(0U, 4U, 5U, 7U, 10U, 30U, 42U, 60U, 320U, 9000U));
 }
 
@@ -178,53 +187,61 @@
 // FIXME(kbobyrev): The testcase below is similar to what is expected in real
 // queries. It should be updated once new iterators (such as boosting, limiting,
 // etc iterators) appear. However, it is not exhaustive and it would be
-// beneficial to implement automatic generation of query trees for more
-// comprehensive testing.
+// beneficial to implement automatic generation (e.g. fuzzing) of query trees
+// for more comprehensive testing.
 TEST(DexIndexIterators, QueryTree) {
-  // An example of more complicated query
   //
   //  +-+
   //  |And Iterator:1, 5|
   //  +++
   //   |
   //   |
-  // ++
+  // +-+--+
   // ||
   // ||
-  //  +--v--+  +--v-+
-  //  |And Iterator: 1, 5, 9|  |Or Iterator: 0, 1, 5|
-  //  +--+--+  +--+-+
+  //  +--v--+  +--v+
+  //  |And Iterator: 1, 5, 9|  |Or Iterator: 0, 1, 3, 5|
+  //  +--+--+  +--++
   // ||
-  //  +--+-++-+---+
+  //  +--+-++-+
   //  ||| |   |
-  //  +---v-+ +v-+   +--v--++-V--++---v---+
-  //  |1, 3, 5, 8, 9| |1, 5, 7, 9|   |Empty||0, 5||0, 1, 5|
-  //  +-+ +--+   +-++++---+
-
+  //  +---v-+ ++---+ +--v--+  +---v+ +v---+
+  //  |1, 3, 5, 8, 9| |Boost: 2| |Empty|  |Boost: 3| |Boost: 4|
+  //  +-+ ++---+ +-+  +---++ ++---+
+  //   |  |   |
+  //  +v-+  +-v--++---v---+
+  //  |1, 5, 7, 9|  |1, 5||0, 3, 5|
+  //  +--+  +++---+
+  //
   const PostingList L0 = {1, 3, 5, 8, 9};
   const PostingList L1 = {1, 5, 7, 9};
-  const PostingList L2 = {0, 5};
-  const PostingList L3 = {0, 1, 5};
-  const PostingList L4;
+  const PostingList L3;
+  const PostingList L4 = {1, 5};
+  const PostingList L5 = {0, 3, 5};
 
   // Root of the query tree: [1, 5]
   auto Root = 

[PATCH] D51088: [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 161945.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- Use std::distance instead of an explicit loop
- Merge break into loop condition


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51088

Files:
  clangd/index/CanonicalIncludes.cpp
  clangd/index/CanonicalIncludes.h

Index: clangd/index/CanonicalIncludes.h
===
--- clangd/index/CanonicalIncludes.h
+++ clangd/index/CanonicalIncludes.h
@@ -40,8 +40,10 @@
   /// Adds a string-to-string mapping from \p Path to \p CanonicalPath.
   void addMapping(llvm::StringRef Path, llvm::StringRef CanonicalPath);
 
-  /// Maps all files matching \p RE to \p CanonicalPath
-  void addRegexMapping(llvm::StringRef RE, llvm::StringRef CanonicalPath);
+  /// Maps files with last path components matching \p Suffix to \p
+  /// CanonicalPath.
+  void addPathSuffixMapping(llvm::StringRef Suffix,
+llvm::StringRef CanonicalPath);
 
   /// Sets the canonical include for any symbol with \p QualifiedName.
   /// Symbol mappings take precedence over header mappings.
@@ -55,17 +57,15 @@
 llvm::StringRef QualifiedName) const;
 
 private:
-  // A map from header patterns to header names. This needs to be mutable so
-  // that we can match again a Regex in a const function member.
-  // FIXME(ioeric): All the regexes we have so far are suffix matches. The
-  // performance could be improved by allowing only suffix matches instead of
-  // arbitrary regexes.
-  mutable std::vector>
-  RegexHeaderMappingTable;
-  // A map from fully qualified symbol names to header names.
+  /// A map from full include path to a canonical path.
+  llvm::StringMap FullPathMapping;
+  /// A map from a suffix (one or components of a path) to a canonical path.
+  llvm::StringMap SuffixHeaderMapping;
+  /// Maximum number of path components stored in a key of SuffixHeaderMapping.
+  /// Used to reduce the number of lookups into SuffixHeaderMapping.
+  int MaxSuffixComponents = 0;
+  /// A map from fully qualified symbol names to header names.
   llvm::StringMap SymbolMapping;
-  // Guards Regex matching as it's not thread-safe.
-  mutable std::mutex RegexMutex;
 };
 
 /// Returns a CommentHandler that parses pragma comment on include files to
Index: clangd/index/CanonicalIncludes.cpp
===
--- clangd/index/CanonicalIncludes.cpp
+++ clangd/index/CanonicalIncludes.cpp
@@ -10,23 +10,26 @@
 #include "CanonicalIncludes.h"
 #include "../Headers.h"
 #include "clang/Driver/Types.h"
-#include "llvm/Support/Regex.h"
+#include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace {
 const char IWYUPragma[] = "// IWYU pragma: private, include ";
 } // namespace
 
-void CanonicalIncludes::addMapping(llvm::StringRef Path,
-   llvm::StringRef CanonicalPath) {
-  addRegexMapping((llvm::Twine("^") + llvm::Regex::escape(Path) + "$").str(),
-  CanonicalPath);
+void CanonicalIncludes::addPathSuffixMapping(llvm::StringRef Suffix,
+ llvm::StringRef CanonicalPath) {
+  int Components = std::distance(llvm::sys::path::begin(Suffix),
+ llvm::sys::path::end(Suffix));
+  MaxSuffixComponents = std::max(MaxSuffixComponents, Components);
+  SuffixHeaderMapping[Suffix] = CanonicalPath;
 }
 
-void CanonicalIncludes::addRegexMapping(llvm::StringRef RE,
-llvm::StringRef CanonicalPath) {
-  this->RegexHeaderMappingTable.emplace_back(llvm::Regex(RE), CanonicalPath);
+void CanonicalIncludes::addMapping(llvm::StringRef Path,
+   llvm::StringRef CanonicalPath) {
+  FullPathMapping[Path] = CanonicalPath;
 }
 
 void CanonicalIncludes::addSymbolMapping(llvm::StringRef QualifiedName,
@@ -41,7 +44,6 @@
   auto SE = SymbolMapping.find(QualifiedName);
   if (SE != SymbolMapping.end())
 return SE->second;
-  std::lock_guard Lock(RegexMutex);
   // Find the first header such that the extension is not '.inc', and isn't a
   // recognized non-header file
   auto I =
@@ -62,13 +64,19 @@
   if ((ExtType != driver::types::TY_INVALID) &&
   !driver::types::onlyPrecompileType(ExtType))
 return Headers[0];
-  for (auto &Entry : RegexHeaderMappingTable) {
-#ifndef NDEBUG
-std::string Dummy;
-assert(Entry.first.isValid(Dummy) && "Regex should never be invalid!");
-#endif
-if (Entry.first.match(Header))
-  return Entry.second;
+
+  auto MapIt = FullPathMapping.find(Header);
+  if (MapIt != FullPathMapping.end())
+return MapIt->second;
+
+  int Components = 1;
+  for (auto It = llvm::sys::path::rbegin(Header),
+End = llvm::sys::path::rend(Header);
+   It != End && Components <= MaxSuffixComponents; ++It, ++Components) {
+au

[PATCH] D51088: [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/index/CanonicalIncludes.cpp:24
+  int Components = 0;
+  for (auto It = llvm::sys::path::begin(Suffix),
+End = llvm::sys::path::end(Suffix);

ioeric wrote:
> Would `int Components = begin(Suffix)  - end(Suffix);` work here?
Surprisingly, `operator -` gives byte difference.
But `std::distance` gives the expected result, added that.

Thanks!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51088



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


[PATCH] D51100: [clang-tidy] Add Abseil prefix to documentation

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

LGTM.


https://reviews.llvm.org/D51100



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


[PATCH] D50766: Fix false positive unsequenced access and modification warning in array subscript expression.

2018-08-22 Thread Mateusz Janek via Phabricator via cfe-commits
stryku updated this revision to Diff 161943.
stryku added a comment.

@Rakete Thank you for the comments. You're perfectly right, there was an 
issue in my code. I've fixed it and also E1 and E2 will be sequenced only in 
C++ >= 17.


https://reviews.llvm.org/D50766

Files:
  lib/Sema/SemaChecking.cpp


Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -11658,30 +11658,42 @@
   notePostUse(O, E);
   }
 
-  void VisitBinComma(BinaryOperator *BO) {
-// C++11 [expr.comma]p1:
-//   Every value computation and side effect associated with the left
-//   expression is sequenced before every value computation and side
-//   effect associated with the right expression.
-SequenceTree::Seq LHS = Tree.allocate(Region);
-SequenceTree::Seq RHS = Tree.allocate(Region);
+  void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
+SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
+SequenceTree::Seq AfterRegion = Tree.allocate(Region);
 SequenceTree::Seq OldRegion = Region;
 
 {
-  SequencedSubexpression SeqLHS(*this);
-  Region = LHS;
-  Visit(BO->getLHS());
+  SequencedSubexpression SeqBefore(*this);
+  Region = BeforeRegion;
+  Visit(SequencedBefore);
 }
 
-Region = RHS;
-Visit(BO->getRHS());
+Region = AfterRegion;
+Visit(SequencedAfter);
 
 Region = OldRegion;
 
-// Forget that LHS and RHS are sequenced. They are both unsequenced
-// with respect to other stuff.
-Tree.merge(LHS);
-Tree.merge(RHS);
+Tree.merge(BeforeRegion);
+Tree.merge(AfterRegion);
+  }
+
+  void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
+// C++17 [expr.sub]p1:
+//   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). 
The
+//   expression E1 is sequenced before the expression E2.
+if (SemaRef.getLangOpts().CPlusPlus17)
+  VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
+else
+  Base::VisitStmt(ASE);
+  }
+
+  void VisitBinComma(BinaryOperator *BO) {
+// C++11 [expr.comma]p1:
+//   Every value computation and side effect associated with the left
+//   expression is sequenced before every value computation and side
+//   effect associated with the right expression.
+VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
   }
 
   void VisitBinAssign(BinaryOperator *BO) {


Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -11658,30 +11658,42 @@
   notePostUse(O, E);
   }
 
-  void VisitBinComma(BinaryOperator *BO) {
-// C++11 [expr.comma]p1:
-//   Every value computation and side effect associated with the left
-//   expression is sequenced before every value computation and side
-//   effect associated with the right expression.
-SequenceTree::Seq LHS = Tree.allocate(Region);
-SequenceTree::Seq RHS = Tree.allocate(Region);
+  void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
+SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
+SequenceTree::Seq AfterRegion = Tree.allocate(Region);
 SequenceTree::Seq OldRegion = Region;
 
 {
-  SequencedSubexpression SeqLHS(*this);
-  Region = LHS;
-  Visit(BO->getLHS());
+  SequencedSubexpression SeqBefore(*this);
+  Region = BeforeRegion;
+  Visit(SequencedBefore);
 }
 
-Region = RHS;
-Visit(BO->getRHS());
+Region = AfterRegion;
+Visit(SequencedAfter);
 
 Region = OldRegion;
 
-// Forget that LHS and RHS are sequenced. They are both unsequenced
-// with respect to other stuff.
-Tree.merge(LHS);
-Tree.merge(RHS);
+Tree.merge(BeforeRegion);
+Tree.merge(AfterRegion);
+  }
+
+  void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
+// C++17 [expr.sub]p1:
+//   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
+//   expression E1 is sequenced before the expression E2.
+if (SemaRef.getLangOpts().CPlusPlus17)
+  VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
+else
+  Base::VisitStmt(ASE);
+  }
+
+  void VisitBinComma(BinaryOperator *BO) {
+// C++11 [expr.comma]p1:
+//   Every value computation and side effect associated with the left
+//   expression is sequenced before every value computation and side
+//   effect associated with the right expression.
+VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
   }
 
   void VisitBinAssign(BinaryOperator *BO) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r340410 - [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Aug 22 06:51:19 2018
New Revision: 340410

URL: http://llvm.org/viewvc/llvm-project?rev=340410&view=rev
Log:
[clangd] Get rid of regexes in CanonicalIncludes

Summary: Replace them with suffix mappings.

Reviewers: ioeric, kbobyrev

Reviewed By: ioeric

Subscribers: MaskRay, jkorous, arphaman, jfb, kadircet, cfe-commits

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

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

Modified: clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp?rev=340410&r1=340409&r2=340410&view=diff
==
--- clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/CanonicalIncludes.cpp Wed Aug 22 
06:51:19 2018
@@ -10,7 +10,8 @@
 #include "CanonicalIncludes.h"
 #include "../Headers.h"
 #include "clang/Driver/Types.h"
-#include "llvm/Support/Regex.h"
+#include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
@@ -18,15 +19,17 @@ namespace {
 const char IWYUPragma[] = "// IWYU pragma: private, include ";
 } // namespace
 
-void CanonicalIncludes::addMapping(llvm::StringRef Path,
-   llvm::StringRef CanonicalPath) {
-  addRegexMapping((llvm::Twine("^") + llvm::Regex::escape(Path) + "$").str(),
-  CanonicalPath);
+void CanonicalIncludes::addPathSuffixMapping(llvm::StringRef Suffix,
+ llvm::StringRef CanonicalPath) {
+  int Components = std::distance(llvm::sys::path::begin(Suffix),
+ llvm::sys::path::end(Suffix));
+  MaxSuffixComponents = std::max(MaxSuffixComponents, Components);
+  SuffixHeaderMapping[Suffix] = CanonicalPath;
 }
 
-void CanonicalIncludes::addRegexMapping(llvm::StringRef RE,
-llvm::StringRef CanonicalPath) {
-  this->RegexHeaderMappingTable.emplace_back(llvm::Regex(RE), CanonicalPath);
+void CanonicalIncludes::addMapping(llvm::StringRef Path,
+   llvm::StringRef CanonicalPath) {
+  FullPathMapping[Path] = CanonicalPath;
 }
 
 void CanonicalIncludes::addSymbolMapping(llvm::StringRef QualifiedName,
@@ -41,7 +44,6 @@ CanonicalIncludes::mapHeader(llvm::Array
   auto SE = SymbolMapping.find(QualifiedName);
   if (SE != SymbolMapping.end())
 return SE->second;
-  std::lock_guard Lock(RegexMutex);
   // Find the first header such that the extension is not '.inc', and isn't a
   // recognized non-header file
   auto I =
@@ -62,13 +64,19 @@ CanonicalIncludes::mapHeader(llvm::Array
   if ((ExtType != driver::types::TY_INVALID) &&
   !driver::types::onlyPrecompileType(ExtType))
 return Headers[0];
-  for (auto &Entry : RegexHeaderMappingTable) {
-#ifndef NDEBUG
-std::string Dummy;
-assert(Entry.first.isValid(Dummy) && "Regex should never be invalid!");
-#endif
-if (Entry.first.match(Header))
-  return Entry.second;
+
+  auto MapIt = FullPathMapping.find(Header);
+  if (MapIt != FullPathMapping.end())
+return MapIt->second;
+
+  int Components = 1;
+  for (auto It = llvm::sys::path::rbegin(Header),
+End = llvm::sys::path::rend(Header);
+   It != End && Components <= MaxSuffixComponents; ++It, ++Components) {
+auto SubPath = Header.substr(It->data() - Header.begin());
+auto MappingIt = SuffixHeaderMapping.find(SubPath);
+if (MappingIt != SuffixHeaderMapping.end())
+  return MappingIt->second;
   }
   return Header;
 }
@@ -153,660 +161,660 @@ void addSystemHeadersMapping(CanonicalIn
 
   static const std::vector>
   SystemHeaderMap = {
-  {"include/__stddef_max_align_t.h$", ""},
-  {"include/__wmmintrin_aes.h$", ""},
-  {"include/__wmmintrin_pclmul.h$", ""},
-  {"include/adxintrin.h$", ""},
-  {"include/ammintrin.h$", ""},
-  {"include/avx2intrin.h$", ""},
-  {"include/avx512bwintrin.h$", ""},
-  {"include/avx512cdintrin.h$", ""},
-  {"include/avx512dqintrin.h$", ""},
-  {"include/avx512erintrin.h$", ""},
-  {"include/avx512fintrin.h$", ""},
-  {"include/avx512ifmaintrin.h$", ""},
-  {"include/avx512ifmavlintrin.h$", ""},
-  {"include/avx512pfintrin.h$", ""},
-  {"include/avx512vbmiintrin.h$", ""},
-  {"include/avx512vbmivlintrin.h$", ""},
-  {"include/avx512vlbwintrin.h$", ""},
-  {"include/avx512vlcdintrin.h$", ""},
-  {"include/avx512vldqintrin.h$", ""},
-  {"include/avx512vlintrin.h$", ""},
-  {"include/avxintrin.h$", ""},
-  {"include/bmi2intrin.h$", ""},
-  {"include/bmiintrin.h$", ""},
-  {"include/emmintrin.h$", ""},
-  {"include/f16cintrin.h$", ""},
-

[PATCH] D51088: [clangd] Get rid of regexes in CanonicalIncludes

2018-08-22 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE340410: [clangd] Get rid of regexes in CanonicalIncludes 
(authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D51088?vs=161945&id=161946#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51088

Files:
  clangd/index/CanonicalIncludes.cpp
  clangd/index/CanonicalIncludes.h

Index: clangd/index/CanonicalIncludes.h
===
--- clangd/index/CanonicalIncludes.h
+++ clangd/index/CanonicalIncludes.h
@@ -40,8 +40,10 @@
   /// Adds a string-to-string mapping from \p Path to \p CanonicalPath.
   void addMapping(llvm::StringRef Path, llvm::StringRef CanonicalPath);
 
-  /// Maps all files matching \p RE to \p CanonicalPath
-  void addRegexMapping(llvm::StringRef RE, llvm::StringRef CanonicalPath);
+  /// Maps files with last path components matching \p Suffix to \p
+  /// CanonicalPath.
+  void addPathSuffixMapping(llvm::StringRef Suffix,
+llvm::StringRef CanonicalPath);
 
   /// Sets the canonical include for any symbol with \p QualifiedName.
   /// Symbol mappings take precedence over header mappings.
@@ -55,17 +57,15 @@
 llvm::StringRef QualifiedName) const;
 
 private:
-  // A map from header patterns to header names. This needs to be mutable so
-  // that we can match again a Regex in a const function member.
-  // FIXME(ioeric): All the regexes we have so far are suffix matches. The
-  // performance could be improved by allowing only suffix matches instead of
-  // arbitrary regexes.
-  mutable std::vector>
-  RegexHeaderMappingTable;
-  // A map from fully qualified symbol names to header names.
+  /// A map from full include path to a canonical path.
+  llvm::StringMap FullPathMapping;
+  /// A map from a suffix (one or components of a path) to a canonical path.
+  llvm::StringMap SuffixHeaderMapping;
+  /// Maximum number of path components stored in a key of SuffixHeaderMapping.
+  /// Used to reduce the number of lookups into SuffixHeaderMapping.
+  int MaxSuffixComponents = 0;
+  /// A map from fully qualified symbol names to header names.
   llvm::StringMap SymbolMapping;
-  // Guards Regex matching as it's not thread-safe.
-  mutable std::mutex RegexMutex;
 };
 
 /// Returns a CommentHandler that parses pragma comment on include files to
Index: clangd/index/CanonicalIncludes.cpp
===
--- clangd/index/CanonicalIncludes.cpp
+++ clangd/index/CanonicalIncludes.cpp
@@ -10,23 +10,26 @@
 #include "CanonicalIncludes.h"
 #include "../Headers.h"
 #include "clang/Driver/Types.h"
-#include "llvm/Support/Regex.h"
+#include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace {
 const char IWYUPragma[] = "// IWYU pragma: private, include ";
 } // namespace
 
-void CanonicalIncludes::addMapping(llvm::StringRef Path,
-   llvm::StringRef CanonicalPath) {
-  addRegexMapping((llvm::Twine("^") + llvm::Regex::escape(Path) + "$").str(),
-  CanonicalPath);
+void CanonicalIncludes::addPathSuffixMapping(llvm::StringRef Suffix,
+ llvm::StringRef CanonicalPath) {
+  int Components = std::distance(llvm::sys::path::begin(Suffix),
+ llvm::sys::path::end(Suffix));
+  MaxSuffixComponents = std::max(MaxSuffixComponents, Components);
+  SuffixHeaderMapping[Suffix] = CanonicalPath;
 }
 
-void CanonicalIncludes::addRegexMapping(llvm::StringRef RE,
-llvm::StringRef CanonicalPath) {
-  this->RegexHeaderMappingTable.emplace_back(llvm::Regex(RE), CanonicalPath);
+void CanonicalIncludes::addMapping(llvm::StringRef Path,
+   llvm::StringRef CanonicalPath) {
+  FullPathMapping[Path] = CanonicalPath;
 }
 
 void CanonicalIncludes::addSymbolMapping(llvm::StringRef QualifiedName,
@@ -41,7 +44,6 @@
   auto SE = SymbolMapping.find(QualifiedName);
   if (SE != SymbolMapping.end())
 return SE->second;
-  std::lock_guard Lock(RegexMutex);
   // Find the first header such that the extension is not '.inc', and isn't a
   // recognized non-header file
   auto I =
@@ -62,13 +64,19 @@
   if ((ExtType != driver::types::TY_INVALID) &&
   !driver::types::onlyPrecompileType(ExtType))
 return Headers[0];
-  for (auto &Entry : RegexHeaderMappingTable) {
-#ifndef NDEBUG
-std::string Dummy;
-assert(Entry.first.isValid(Dummy) && "Regex should never be invalid!");
-#endif
-if (Entry.first.match(Header))
-  return Entry.second;
+
+  auto MapIt = FullPathMapping.find(Header);
+  if (MapIt != FullPathMapping.end())
+return MapIt->second;
+
+  int Components = 1;
+  for (auto It = llvm::sys::path::rbegin(Header),
+End = llvm::sys::path::rend(Header);
+   It != End && Co

[PATCH] D50766: Fix false positive unsequenced access and modification warning in array subscript expression.

2018-08-22 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Test coverage?
Also, please always upload all patches with full context (`-U9`)


https://reviews.llvm.org/D50766



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


Re: r314872 - We allow implicit function declarations as an extension in all C dialects. Remove OpenCL special case.

2018-08-22 Thread Anastasia Stulova via cfe-commits
Hi Richard,

> This is incorrect. Implicit function declarations declare unprototyped 
> functions, which are *not* variadic, and are in fact supported by Clang's 
> OpenCL language mode.

We have removed the support for the unprototyped functions from the OpenCL as 
well. See commit: https://reviews.llvm.org/D33681. This is the reason why in 
the OpenCL mode we now generated empty parameter list instead of unprototyped 
function like for C in the examples I provided before (that is not governed now 
by any standard or any compiler extension).

> I would have sympathy for your position if we did not produce an extension 
> warning on this construct by default. But we do, and it says the construct is 
> invalid in OpenCL; moreover, in our strict conformance mode 
> (-pedantic-errors), we reject the code.

I understand the motivation for C to maintain the compatibility with the 
previous standards and other compilers (like gcc) to be able to support the 
legacy code. However, for OpenCL we don't have this requirement wrt older C 
standards. And therefore it is desirable to take advantage of this and remove 
problematic features that are generally confusing for developers or that can't 
be efficiently supported by the targets (especially if there is a little cost 
to that).
 

From: Richard Smith 
Sent: 21 August 2018 22:09:35
To: Anastasia Stulova
Cc: cfe-commits; nd
Subject: Re: r314872 - We allow implicit function declarations as an extension 
in all C dialects. Remove OpenCL special case.

On Tue, 21 Aug 2018 at 07:41, Anastasia Stulova via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:

If there are no objections I would like to revert this old commit that coverts 
error about implicit function declaration into a warning.


We have decided to generate an error for this https://reviews.llvm.org/D31745 
because for OpenCL variadic prototypes are disallowed (section 6.9.e, 
https://www.khronos.org/registry/OpenCL/specs/opencl-2.0-openclc.pdf) and the 
implicit prototype requires variadic support.

This is incorrect. Implicit function declarations declare unprototyped 
functions, which are *not* variadic, and are in fact supported by Clang's 
OpenCL language mode.

See C90 6.5.4.3 Semantics, last paragraph, and 6.3.2.2 Semantics, second 
paragraph.

So that argument does not appear to apply. The reason we accept 
implicitly-declared functions outside of our C89 mode is because this is an 
explicit, supported Clang extension. Generally, Clang intends to support using 
all of its extensions together, unless there is some fundamental reason why 
they cannot be combined. So, just as it doesn't make sense for our OpenCL 
language mode to conflict with, say, AltiVec vector extensions, it doesn't make 
sense for the OpenCL language mode to conflict with our implicitly-declared 
functions extension.

I would have sympathy for your position if we did not produce an extension 
warning on this construct by default. But we do, and it says the construct is 
invalid in OpenCL; moreover, in our strict conformance mode (-pedantic-errors), 
we reject the code.

As most vendors that support OpenCL don't support variadic functions it was 
decided to restrict this explicitly in the spec (section s6.9.u). There is a 
little bit of more history in https://reviews.llvm.org/D17438.


Currently the code that can't run correctly on most OpenCL targets compiles 
successfully. The problem can't be easily seen by the OpenCL developers since 
it's not very common to retrieve the compilation warning log during online 
compilation. Also generated IR doesn't seem to be correct if I compare with the 
similar code in C.

Example:
 1 typedef long long16 __attribute__((ext_vector_type(16)));
 2 void test_somefunc( __global int *d, __global void *s )
 3 {
 4   int i = get_global_id(0);
 5   d[i] = somefunc((( __global long16 *)s)[i]);
 6 }

Is generated to:

%call1 = call i32 (<16 x i64>*, ...) bitcast (i32 ()* @somefunc to i32 (<16 x 
i64>*, ...)*)(<16 x i64>* byval nonnull align 128 %indirect-arg-temp) #2
...

declare i32 @somefunc() local_unnamed_addr #1

Equivalent C code at least generates variadic function prototype correctly:

%call1 = call i32 (<16 x i64>*, ...) bitcast (i32 (...)* @somefunc to i32 (<16 
x i64>*, ...)*)(<16 x i64>* byval align 128 %indirect-arg-temp)
...
declare i32 @somefunc(...)

Anastasia

From: cfe-commits 
mailto:cfe-commits-boun...@lists.llvm.org>> 
on behalf of Richard Smith via cfe-commits 
mailto:cfe-commits@lists.llvm.org>>
Sent: 04 October 2017 02:58
To: cfe-commits@lists.llvm.org
Subject: r314872 - We allow implicit function declarations as an extension in 
all C dialects. Remove OpenCL special case.

Author: rsmith
Date: Tue Oct  3 18:58:22 2017
New Revision: 314872

URL: http://llvm.org/viewvc/llvm-project?rev=314872&view=rev
Log:
We allow implicit function declarations as an extension in all C dialec

[clang-tools-extra] r340411 - [clang-tidy] Abseil: faster strsplit delimiter check

2018-08-22 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Aug 22 06:58:25 2018
New Revision: 340411

URL: http://llvm.org/viewvc/llvm-project?rev=340411&view=rev
Log:
[clang-tidy] Abseil: faster strsplit delimiter check

This check is an abseil specific check that checks for code using single 
character string literals as delimiters and transforms the code into characters.

The check was developed internally and has been running at google, this is just
a move to open source the check. It was originally written by @sbenza.

Patch by Deanna Garcia!

Added:
clang-tools-extra/trunk/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
clang-tools-extra/trunk/clang-tidy/abseil/FasterStrsplitDelimiterCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/abseil-faster-strsplit-delimiter.rst
clang-tools-extra/trunk/test/clang-tidy/abseil-faster-strsplit-delimiter.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp?rev=340411&r1=340410&r2=340411&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp Wed Aug 22 
06:58:25 2018
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "DurationDivisionCheck.h"
+#include "FasterStrsplitDelimiterCheck.h"
 #include "StringFindStartswithCheck.h"
 
 namespace clang {
@@ -22,6 +23,8 @@ public:
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
 CheckFactories.registerCheck(
 "abseil-duration-division");
+CheckFactories.registerCheck(
+"abseil-faster-strsplit-delimiter");
 CheckFactories.registerCheck(
 "abseil-string-find-startswith");
   }

Modified: clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt?rev=340411&r1=340410&r2=340411&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt Wed Aug 22 
06:58:25 2018
@@ -3,6 +3,7 @@ set(LLVM_LINK_COMPONENTS support)
 add_clang_library(clangTidyAbseilModule
   AbseilTidyModule.cpp
   DurationDivisionCheck.cpp
+  FasterStrsplitDelimiterCheck.cpp
   StringFindStartswithCheck.cpp
 
   LINK_LIBS

Added: 
clang-tools-extra/trunk/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp?rev=340411&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp 
(added)
+++ clang-tools-extra/trunk/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp 
Wed Aug 22 06:58:25 2018
@@ -0,0 +1,131 @@
+//===--- FasterStrsplitDelimiterCheck.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 "FasterStrsplitDelimiterCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace abseil {
+
+namespace {
+
+AST_MATCHER(StringLiteral, lengthIsOne) { return Node.getLength() == 1; }
+
+::internal::Matcher
+constructExprWithArg(llvm::StringRef ClassName,
+ const ::internal::Matcher &Arg) {
+  auto ConstrExpr = cxxConstructExpr(hasType(recordDecl(hasName(ClassName))),
+ hasArgument(0, ignoringParenCasts(Arg)));
+
+  return anyOf(ConstrExpr, cxxBindTemporaryExpr(has(ConstrExpr)));
+}
+
+::internal::Matcher
+copyConstructExprWithArg(llvm::StringRef ClassName,
+ const ::internal::Matcher &Arg) {
+  return constructExprWithArg(ClassName, constructExprWithArg(ClassName, Arg));
+}
+
+llvm::Optional makeCharacterLiteral(const StringLiteral *Literal) 
{
+  std::string Result;
+  {
+llvm::raw_string_ostream Stream(Result);
+Literal->outputString(Stream);
+  }
+
+  // Special case: If the string contains a single quote, we just need to 
return
+  // a character of the single quote. This is a special case because we need to
+  // escape it in the character literal.
+  if (Result == R"("'")"

[PATCH] D51029: [clangd] Implement LIMIT iterator

2018-08-22 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 161947.
kbobyrev edited the summary of this revision.
kbobyrev added a reviewer: sammccall.
kbobyrev added a comment.

Rebase on top of BOOST iterator patch, update tests.


https://reviews.llvm.org/D51029

Files:
  clang-tools-extra/clangd/index/dex/Iterator.cpp
  clang-tools-extra/clangd/index/dex/Iterator.h
  clang-tools-extra/unittests/clangd/DexIndexTests.cpp

Index: clang-tools-extra/unittests/clangd/DexIndexTests.cpp
===
--- clang-tools-extra/unittests/clangd/DexIndexTests.cpp
+++ clang-tools-extra/unittests/clangd/DexIndexTests.cpp
@@ -265,24 +265,27 @@
 }
 
 TEST(DexIndexIterators, Limit) {
-  const PostingList L0 = {4, 7, 8, 20, 42, 100};
-  const PostingList L1 = {1, 3, 5, 8, 9};
-  const PostingList L2 = {1, 5, 7, 9};
-  const PostingList L3 = {0, 5};
-  const PostingList L4 = {0, 1, 5};
-  const PostingList L5;
+  const PostingList L0 = {3, 6, 7, 20, 42, 100};
+  const PostingList L1 = {1, 3, 5, 6, 7, 30, 100};
+  const PostingList L2 = {0, 3, 5, 7, 8, 100};
 
   auto DocIterator = create(L0);
-  EXPECT_THAT(consumeIDs(*DocIterator, 42), ElementsAre(4, 7, 8, 20, 42, 100));
+  EXPECT_THAT(consumeIDs(*DocIterator, 42),
+  ElementsAre(3, 6, 7, 20, 42, 100));
 
   DocIterator = create(L0);
-  EXPECT_THAT(consumeIDs(*DocIterator), ElementsAre(4, 7, 8, 20, 42, 100));
+  EXPECT_THAT(consumeIDs(*DocIterator), ElementsAre(3, 6, 7, 20, 42, 100));
 
   DocIterator = create(L0);
-  EXPECT_THAT(consumeIDs(*DocIterator, 3), ElementsAre(4, 7, 8));
+  EXPECT_THAT(consumeIDs(*DocIterator, 3), ElementsAre(3, 6, 7));
 
   DocIterator = create(L0);
   EXPECT_THAT(consumeIDs(*DocIterator, 0), ElementsAre());
+
+  auto AndIterator =
+  createAnd(createLimit(createTrue(9000), 343), createLimit(create(L0), 2),
+createLimit(create(L1), 3), createLimit(create(L2), 42));
+  EXPECT_THAT(consumeIDs(*AndIterator), ElementsAre(3, 7));
 }
 
 TEST(DexIndexIterators, True) {
Index: clang-tools-extra/clangd/index/dex/Iterator.h
===
--- clang-tools-extra/clangd/index/dex/Iterator.h
+++ clang-tools-extra/clangd/index/dex/Iterator.h
@@ -164,6 +164,10 @@
 /// trim Top K using retrieval score.
 std::unique_ptr createBoost(std::unique_ptr Child,
   float Factor);
+/// Returns LIMIT iterator, which is exhausted as soon requested number of items
+/// is consumed from the root of query tree.
+std::unique_ptr createLimit(std::unique_ptr Child,
+  size_t Limit);
 
 /// This allows createAnd(create(...), create(...)) syntax.
 template  std::unique_ptr createAnd(Args... args) {
Index: clang-tools-extra/clangd/index/dex/Iterator.cpp
===
--- clang-tools-extra/clangd/index/dex/Iterator.cpp
+++ clang-tools-extra/clangd/index/dex/Iterator.cpp
@@ -318,6 +318,41 @@
   float Factor;
 };
 
+/// This iterator is a wrapper around the underlying child which limits the
+/// number of elements which are retrieved from the whole iterator tree.
+class LimitIterator : public Iterator {
+public:
+  LimitIterator(std::unique_ptr Child, size_t Limit)
+  : Child(move(Child)), ItemsLeft(Limit) {}
+
+  bool reachedEnd() const override {
+return ItemsLeft == 0 || Child->reachedEnd();
+  }
+
+  void advance() override { Child->advance(); }
+
+  void advanceTo(DocID ID) override { Child->advanceTo(ID); }
+
+  DocID peek() const override { return Child->peek(); }
+
+  /// Decreases the limit in case the element consumed at top of the query tree
+  /// comes from the underlying iterator.
+  float consume(DocID ID) override {
+if (!reachedEnd() && peek() == ID)
+  --ItemsLeft;
+return Child->consume(ID);
+  }
+
+private:
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+OS << "(LIMIT items left " << ItemsLeft << *Child << ")";
+return OS;
+  }
+
+  std::unique_ptr Child;
+  size_t ItemsLeft;
+};
+
 } // end namespace
 
 std::vector> consume(Iterator &It, size_t Limit) {
@@ -353,6 +388,11 @@
   return llvm::make_unique(move(Child), Factor);
 }
 
+std::unique_ptr createLimit(std::unique_ptr Child,
+  size_t Size) {
+  return llvm::make_unique(move(Child), Size);
+}
+
 } // namespace dex
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D51038: [clang] Make sure codecompletion is called for calls even when inside a token.

2018-08-22 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Sorry, missed the dependent revision adding tests to clangd at first. Having 
another test in sema would still be great, to make sure we guard against 
regressions if someone does not have clang-tools-extra checked out.


Repository:
  rC Clang

https://reviews.llvm.org/D51038



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


[PATCH] D50862: [clang-tidy] Abseil: faster strsplit delimiter check

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein closed this revision.
hokein added a comment.

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


https://reviews.llvm.org/D50862



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


[clang-tools-extra] r340412 - [clang-tidy] Add Abseil prefix to documentation

2018-08-22 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Aug 22 07:03:30 2018
New Revision: 340412

URL: http://llvm.org/viewvc/llvm-project?rev=340412&view=rev
Log:
[clang-tidy] Add Abseil prefix to documentation

Summary: Adds the Abseil prefix to the list of prefixes in the documentation

Patch by Deanna Garcia!

Reviewers: aaron.ballman, hokein

Reviewed By: hokein

Subscribers: xazax.hun, cfe-commits

Tags: #clang-tools-extra

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

Modified:
clang-tools-extra/trunk/docs/clang-tidy/index.rst

Modified: clang-tools-extra/trunk/docs/clang-tidy/index.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/index.rst?rev=340412&r1=340411&r2=340412&view=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/index.rst (original)
+++ clang-tools-extra/trunk/docs/clang-tidy/index.rst Wed Aug 22 07:03:30 2018
@@ -55,6 +55,7 @@ There are currently the following groups
 == 
=
 Name prefixDescription
 == 
=
+``abseil-``Checks related to Abseil library.
 ``android-``   Checks related to Android.
 ``boost-`` Checks related to Boost library.
 ``bugprone-``  Checks that target bugprone code constructs.


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


[PATCH] D51100: [clang-tidy] Add Abseil prefix to documentation

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL340412: [clang-tidy] Add Abseil prefix to documentation 
(authored by hokein, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D51100?vs=161940&id=161949#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D51100

Files:
  clang-tools-extra/trunk/docs/clang-tidy/index.rst


Index: clang-tools-extra/trunk/docs/clang-tidy/index.rst
===
--- clang-tools-extra/trunk/docs/clang-tidy/index.rst
+++ clang-tools-extra/trunk/docs/clang-tidy/index.rst
@@ -55,6 +55,7 @@
 == 
=
 Name prefixDescription
 == 
=
+``abseil-``Checks related to Abseil library.
 ``android-``   Checks related to Android.
 ``boost-`` Checks related to Boost library.
 ``bugprone-``  Checks that target bugprone code constructs.


Index: clang-tools-extra/trunk/docs/clang-tidy/index.rst
===
--- clang-tools-extra/trunk/docs/clang-tidy/index.rst
+++ clang-tools-extra/trunk/docs/clang-tidy/index.rst
@@ -55,6 +55,7 @@
 == =
 Name prefixDescription
 == =
+``abseil-``Checks related to Abseil library.
 ``android-``   Checks related to Android.
 ``boost-`` Checks related to Boost library.
 ``bugprone-``  Checks that target bugprone code constructs.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D51029: [clangd] Implement LIMIT iterator

2018-08-22 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 161952.
kbobyrev added a comment.

Use better wording for internal `LimitIterator` documentation, perform minor 
code cleanup.


https://reviews.llvm.org/D51029

Files:
  clang-tools-extra/clangd/index/dex/Iterator.cpp
  clang-tools-extra/clangd/index/dex/Iterator.h
  clang-tools-extra/unittests/clangd/DexIndexTests.cpp

Index: clang-tools-extra/unittests/clangd/DexIndexTests.cpp
===
--- clang-tools-extra/unittests/clangd/DexIndexTests.cpp
+++ clang-tools-extra/unittests/clangd/DexIndexTests.cpp
@@ -265,24 +265,27 @@
 }
 
 TEST(DexIndexIterators, Limit) {
-  const PostingList L0 = {4, 7, 8, 20, 42, 100};
-  const PostingList L1 = {1, 3, 5, 8, 9};
-  const PostingList L2 = {1, 5, 7, 9};
-  const PostingList L3 = {0, 5};
-  const PostingList L4 = {0, 1, 5};
-  const PostingList L5;
+  const PostingList L0 = {3, 6, 7, 20, 42, 100};
+  const PostingList L1 = {1, 3, 5, 6, 7, 30, 100};
+  const PostingList L2 = {0, 3, 5, 7, 8, 100};
 
   auto DocIterator = create(L0);
-  EXPECT_THAT(consumeIDs(*DocIterator, 42), ElementsAre(4, 7, 8, 20, 42, 100));
+  EXPECT_THAT(consumeIDs(*DocIterator, 42),
+  ElementsAre(3, 6, 7, 20, 42, 100));
 
   DocIterator = create(L0);
-  EXPECT_THAT(consumeIDs(*DocIterator), ElementsAre(4, 7, 8, 20, 42, 100));
+  EXPECT_THAT(consumeIDs(*DocIterator), ElementsAre(3, 6, 7, 20, 42, 100));
 
   DocIterator = create(L0);
-  EXPECT_THAT(consumeIDs(*DocIterator, 3), ElementsAre(4, 7, 8));
+  EXPECT_THAT(consumeIDs(*DocIterator, 3), ElementsAre(3, 6, 7));
 
   DocIterator = create(L0);
   EXPECT_THAT(consumeIDs(*DocIterator, 0), ElementsAre());
+
+  auto AndIterator =
+  createAnd(createLimit(createTrue(9000), 343), createLimit(create(L0), 2),
+createLimit(create(L1), 3), createLimit(create(L2), 42));
+  EXPECT_THAT(consumeIDs(*AndIterator), ElementsAre(3, 7));
 }
 
 TEST(DexIndexIterators, True) {
Index: clang-tools-extra/clangd/index/dex/Iterator.h
===
--- clang-tools-extra/clangd/index/dex/Iterator.h
+++ clang-tools-extra/clangd/index/dex/Iterator.h
@@ -165,6 +165,11 @@
 std::unique_ptr createBoost(std::unique_ptr Child,
   float Factor);
 
+/// Returns LIMIT iterator, which is exhausted as soon requested number of items
+/// is consumed from the root of query tree.
+std::unique_ptr createLimit(std::unique_ptr Child,
+  size_t Limit);
+
 /// This allows createAnd(create(...), create(...)) syntax.
 template  std::unique_ptr createAnd(Args... args) {
   std::vector> Children;
Index: clang-tools-extra/clangd/index/dex/Iterator.cpp
===
--- clang-tools-extra/clangd/index/dex/Iterator.cpp
+++ clang-tools-extra/clangd/index/dex/Iterator.cpp
@@ -318,6 +318,43 @@
   float Factor;
 };
 
+/// This iterator limits the number of items retrieved from the child iterator
+/// on top of the query tree. To ensure that query tree with LIMIT iterators
+/// inside works correctly, users have to call Root->consume(Root->peek()) each
+/// time item is retrieved at the root of query tree.
+class LimitIterator : public Iterator {
+public:
+  LimitIterator(std::unique_ptr Child, size_t Limit)
+  : Child(move(Child)), ItemsLeft(Limit) {}
+
+  bool reachedEnd() const override {
+return ItemsLeft == 0 || Child->reachedEnd();
+  }
+
+  void advance() override { Child->advance(); }
+
+  void advanceTo(DocID ID) override { Child->advanceTo(ID); }
+
+  DocID peek() const override { return Child->peek(); }
+
+  /// Decreases the limit in case the element consumed at top of the query tree
+  /// comes from the underlying iterator.
+  float consume(DocID ID) override {
+if (!reachedEnd() && peek() == ID)
+  --ItemsLeft;
+return Child->consume(ID);
+  }
+
+private:
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+OS << "(LIMIT items left " << ItemsLeft << *Child << ")";
+return OS;
+  }
+
+  std::unique_ptr Child;
+  size_t ItemsLeft;
+};
+
 } // end namespace
 
 std::vector> consume(Iterator &It, size_t Limit) {
@@ -353,6 +390,11 @@
   return llvm::make_unique(move(Child), Factor);
 }
 
+std::unique_ptr createLimit(std::unique_ptr Child,
+  size_t Size) {
+  return llvm::make_unique(move(Child), Size);
+}
+
 } // namespace dex
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D51102: [clangd] Move function argument snippet disable mechanism from LSP rendering to internal clangd reprensentation.

2018-08-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added reviewers: ilya-biryukov, ioeric, hokein.
Herald added subscribers: cfe-commits, arphaman, jkorous, MaskRay.

We were handling the EnableFunctionArgSnippets only when we are producing LSP
response. Move that code into CompletionItem generation so that internal clients
can benefit from that as well.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51102

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

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -1140,7 +1140,7 @@
   // For now we just return one of the doc strings arbitrarily.
   EXPECT_THAT(A.Documentation, AnyOf(HasSubstr("Overload with int"),
  HasSubstr("Overload with bool")));
-  EXPECT_EQ(A.SnippetSuffix, "(${0})");
+  EXPECT_EQ(A.SnippetSuffix, "($0)");
 }
 
 TEST(CompletionTest, DocumentationFromChangedFileCrash) {
@@ -1648,55 +1648,35 @@
 SigDoc("Doc from sema";
 }
 
-TEST(CompletionTest, RenderWithSnippetsForFunctionArgsDisabled) {
+TEST(CompletionTest, CompletionFunctionArgsDisabled) {
   CodeCompleteOptions Opts;
-  Opts.EnableFunctionArgSnippets = true;
-  {
-CodeCompletion C;
-C.RequiredQualifier = "Foo::";
-C.Name = "x";
-C.SnippetSuffix = "()";
-
-auto R = C.render(Opts);
-EXPECT_EQ(R.textEdit->newText, "Foo::x");
-EXPECT_EQ(R.insertTextFormat, InsertTextFormat::PlainText);
-  }
-
   Opts.EnableSnippets = true;
   Opts.EnableFunctionArgSnippets = false;
+  const std::string Header =
+  R"cpp(
+  void xfoo();
+  void xfoo(int x, int y);
+  void xbar();
+  void f() {
+)cpp";
   {
-CodeCompletion C;
-C.RequiredQualifier = "Foo::";
-C.Name = "x";
-C.SnippetSuffix = "";
-
-auto R = C.render(Opts);
-EXPECT_EQ(R.textEdit->newText, "Foo::x");
-EXPECT_EQ(R.insertTextFormat, InsertTextFormat::Snippet);
+auto Results = completions(Header + "\nxfo^", {}, Opts);
+EXPECT_THAT(
+Results.Completions,
+UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("()")),
+ AllOf(Named("xfoo"), SnippetSuffix("($0)";
   }
-
   {
-CodeCompletion C;
-C.RequiredQualifier = "Foo::";
-C.Name = "x";
-C.SnippetSuffix = "()";
-C.Kind = CompletionItemKind::Method;
-
-auto R = C.render(Opts);
-EXPECT_EQ(R.textEdit->newText, "Foo::x()");
-EXPECT_EQ(R.insertTextFormat, InsertTextFormat::Snippet);
+auto Results = completions(Header + "\nxba^", {}, Opts);
+EXPECT_THAT(Results.Completions, UnorderedElementsAre(AllOf(
+ Named("xbar"), SnippetSuffix("()";
   }
-
   {
-CodeCompletion C;
-C.RequiredQualifier = "Foo::";
-C.Name = "x";
-C.SnippetSuffix = "(${0:bool})";
-C.Kind = CompletionItemKind::Function;
-
-auto R = C.render(Opts);
-EXPECT_EQ(R.textEdit->newText, "Foo::x(${0})");
-EXPECT_EQ(R.insertTextFormat, InsertTextFormat::Snippet);
+Opts.BundleOverloads = true;
+auto Results = completions(Header + "\nxfo^", {}, Opts);
+EXPECT_THAT(
+Results.Completions,
+UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("($0)";
   }
 }
 
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -269,7 +269,8 @@
 CodeCompletionString *SemaCCS,
 const IncludeInserter &Includes, StringRef FileName,
 const CodeCompleteOptions &Opts)
-  : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments) {
+  : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments),
+EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets) {
 add(C, SemaCCS);
 if (C.SemaResult) {
   Completion.Origin |= SymbolOrigin::AST;
@@ -385,10 +386,17 @@
   }
 
   std::string summarizeSnippet() const {
-if (auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>())
-  return *Snippet;
-// All bundles are function calls.
-return "(${0})";
+auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
+if (!Snippet)
+  // All bundles are function calls.
+  return "($0)";
+if (!Snippet->empty() && !EnableFunctionArgSnippets &&
+((Completion.Kind == CompletionItemKind::Function) ||
+ (Completion.Kind == CompletionItemKind::Method)) &&
+(Snippet->front() == '(') && (Snippet->back() == ')'))
+  // Check whether function has any parameters or not.
+  return Snippet->size() > 2 ? "($0)" : "()";
+return *Snippet;
   }
 
   std::string summarizeSignature() const {
@@ -402,6 +410,7 @@
   CodeCompletion Completion;
   SmallVector Bundled;
   bool ExtractDocumentation;
+  bool EnableFu

[PATCH] D50766: Fix false positive unsequenced access and modification warning in array subscript expression.

2018-08-22 Thread Mateusz Janek via Phabricator via cfe-commits
stryku added a comment.

Thanks for the advice. Should I update a new diff with `-U9`?

About tests. I've probably missed something but I looked through the project 
and didn't find any tests for unsequenced operations. If you know a place where 
such tests are placed, please point it and I'll add the one for this code.
If there are no tests for unsequenced operations, should I introduce them?


https://reviews.llvm.org/D50766



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


[PATCH] D9403: llvm.noalias - Clang CodeGen for local restrict-qualified pointers

2018-08-22 Thread Troy Johnson via Phabricator via cfe-commits
troyj added a comment.

Hi, I got here via llvm-dev => https://reviews.llvm.org/D9375 => 
https://reviews.llvm.org/D9403 (this) and have read through everything.  I see 
that this patch has been stalled for about a year and I would like to know its 
status.  Is it waiting on a resolution in LLVM for this problem that Jeroen 
mentioned on llvm-dev?

  "One of the bigger problems is, that some optimization passes optimize away 
some (but not all) of the llvm.noalias intrinsics in a function. Because of 
that, the alias analysis can get confused and can identify two pointers as 
not-aliasing where they should be aliasing."

That's an improper optimization though, right?  If the semantics of the 
intrinsic are that all of them or none of them must be present for correctness, 
then any optimization that removes some but not all is defective.  Is the issue 
that these optimizations cannot tell that they are doing anything wrong?

I am interested in seeing this patch merged, so I would like to know what the 
obstacles are.  Thanks.


https://reviews.llvm.org/D9403



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


[PATCH] D50993: [clangd] Increase stack size of the new threads on macOS

2018-08-22 Thread Dmitry via Phabricator via cfe-commits
Dmitry.Kozhevnikov updated this revision to Diff 161954.
Dmitry.Kozhevnikov added a comment.

I've moved the platform-specific implementation to LLVM/Support/Threading and 
created https://reviews.llvm.org/D51103.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50993

Files:
  clangd/Threading.cpp
  unittests/clangd/ClangdTests.cpp


Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -963,6 +963,27 @@
Field(&CodeCompletion::Name, "baz")));
 }
 
+TEST_F(ClangdVFSTest, TestStackOverflow) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  const auto SourceContents = R"cpp(
+constexpr int foo() { return foo(); }
+static_assert(foo());
+  )cpp";
+
+  auto FooCpp = testPath("foo.cpp");
+  FS.Files[FooCpp] = SourceContents;
+
+  Server.addDocument(FooCpp, SourceContents);
+  ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics";
+  // check that we got a constexpr depth error, and not crashed by stack
+  // overflow
+  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/Threading.cpp
===
--- clangd/Threading.cpp
+++ clangd/Threading.cpp
@@ -1,5 +1,6 @@
 #include "Threading.h"
 #include "Trace.h"
+#include "clang/Basic/Stack.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Threading.h"
@@ -67,16 +68,25 @@
 }
   });
 
-  std::thread(
-  [](std::string Name, decltype(Action) Action, decltype(CleanupTask)) {
-llvm::set_thread_name(Name);
-Action();
-// Make sure function stored by Action is destroyed before CleanupTask
-// is run.
-Action = nullptr;
-  },
-  Name.str(), std::move(Action), std::move(CleanupTask))
-  .detach();
+  // Manually capture Action and CleanupTask for the lack of C++14 generalized
+  // lambda captures
+  struct Callable {
+std::string ThreadName;
+decltype(Action) ThreadFunc;
+decltype(CleanupTask) Cleanup;
+
+void operator()() {
+  llvm::set_thread_name(ThreadName);
+  ThreadFunc();
+  // Make sure function stored by ThreadFunc is destroyed before Cleanup is
+  // run.
+  ThreadFunc = nullptr;
+}
+  };
+
+  llvm::llvm_execute_on_thread_async(
+  Callable{Name.str(), std::move(Action), std::move(CleanupTask)},
+  clang::DesiredStackSize);
 }
 
 Deadline timeoutSeconds(llvm::Optional Seconds) {


Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -963,6 +963,27 @@
Field(&CodeCompletion::Name, "baz")));
 }
 
+TEST_F(ClangdVFSTest, TestStackOverflow) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  const auto SourceContents = R"cpp(
+constexpr int foo() { return foo(); }
+static_assert(foo());
+  )cpp";
+
+  auto FooCpp = testPath("foo.cpp");
+  FS.Files[FooCpp] = SourceContents;
+
+  Server.addDocument(FooCpp, SourceContents);
+  ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics";
+  // check that we got a constexpr depth error, and not crashed by stack
+  // overflow
+  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/Threading.cpp
===
--- clangd/Threading.cpp
+++ clangd/Threading.cpp
@@ -1,5 +1,6 @@
 #include "Threading.h"
 #include "Trace.h"
+#include "clang/Basic/Stack.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Threading.h"
@@ -67,16 +68,25 @@
 }
   });
 
-  std::thread(
-  [](std::string Name, decltype(Action) Action, decltype(CleanupTask)) {
-llvm::set_thread_name(Name);
-Action();
-// Make sure function stored by Action is destroyed before CleanupTask
-// is run.
-Action = nullptr;
-  },
-  Name.str(), std::move(Action), std::move(CleanupTask))
-  .detach();
+  // Manually capture Action and CleanupTask for the lack of C++14 generalized
+  // lambda captures
+  struct Callable {
+std::string ThreadName;
+decltype(Action) ThreadFunc;
+decltype(CleanupTask) Cleanup;
+
+void operator()() {
+  llvm::set_thread_name(ThreadName);
+  ThreadFunc();
+  // Make sure function stored by ThreadFunc is destroyed before Cleanup is
+  // run.
+

[PATCH] D51036: clang-format: Fix formatting C++ namespaces with preceding 'inline' or 'export' specifier

2018-08-22 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 161960.
melver marked 8 inline comments as done.
melver added a comment.

Many thanks for the suggestions!

PTAL.


Repository:
  rC Clang

https://reviews.llvm.org/D51036

Files:
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/NamespaceEndCommentsFixer.cpp
  lib/Format/UnwrappedLineFormatter.cpp
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -200,6 +200,24 @@
"inti;\n"
"}",
getGoogleStyle()));
+  EXPECT_EQ("inline namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("inline namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
+  EXPECT_EQ("export namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("export namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
 "\n"
 "int i;\n"
@@ -1573,6 +1591,11 @@
"void f() { f(); }\n"
"}",
LLVMWithNoNamespaceFix);
+  verifyFormat("export namespace X {\n"
+   "class A {};\n"
+   "void f() { f(); }\n"
+   "}",
+   LLVMWithNoNamespaceFix);
   verifyFormat("using namespace some_namespace;\n"
"class A {};\n"
"void f() { f(); }",
@@ -7556,6 +7579,9 @@
   verifyFormat("inline namespace Foo\n"
"{};",
Style);
+  verifyFormat("export namespace Foo\n"
+   "{};",
+   Style);
   verifyFormat("namespace Foo\n"
"{\n"
"void Bar();\n"
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -989,13 +989,6 @@
   case tok::kw_namespace:
 parseNamespace();
 return;
-  case tok::kw_inline:
-nextToken();
-if (FormatTok->Tok.is(tok::kw_namespace)) {
-  parseNamespace();
-  return;
-}
-break;
   case tok::kw_public:
   case tok::kw_protected:
   case tok::kw_private:
@@ -1063,6 +1056,16 @@
   parseJavaScriptEs6ImportExport();
   return;
 }
+if (!Style.isCpp())
+  break;
+// Handle C++ "(inline|export) namespace".
+LLVM_FALLTHROUGH;
+  case tok::kw_inline:
+nextToken();
+if (FormatTok->Tok.is(tok::kw_namespace)) {
+  parseNamespace();
+  return;
+}
 break;
   case tok::identifier:
 if (FormatTok->is(TT_ForEachMacro)) {
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -529,7 +529,10 @@
 Tok->SpacesRequiredBefore = 0;
 Tok->CanBreakBefore = true;
 return 1;
-  } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
+  } else if (Limit != 0 &&
+ !(Line.startsWith(tok::kw_namespace) ||
+   Line.startsWith(tok::kw_inline, tok::kw_namespace) ||
+   Line.startsWith(tok::kw_export, tok::kw_namespace)) &&
  !startsExternCBlock(Line)) {
 // We don't merge short records.
 FormatToken *RecordTok = Line.First;
@@ -1154,7 +1157,9 @@
   // Remove empty lines after "{".
   if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
   PreviousLine->Last->is(tok::l_brace) &&
-  PreviousLine->First->isNot(tok::kw_namespace) &&
+  !(PreviousLine->startsWith(tok::kw_namespace) ||
+PreviousLine->startsWith(tok::kw_inline, tok::kw_namespace) ||
+PreviousLine->startsWith(tok::kw_export, tok::kw_namespace)) &&
   !startsExternCBlock(*PreviousLine))
 Newlines = 1;
 
Index: lib/Format/NamespaceEndCommentsFixer.cpp
===
--- lib/Format/NamespaceEndCommentsFixer.cpp
+++ lib/Format/NamespaceEndCommentsFixer.cpp
@@ -125,12 +125,7 @@
 if (StartLineIndex > 0)
   NamespaceTok = AnnotatedLines[StartLineIndex - 1]->First;
   }
-  // Detect "(inline)? namespace" in the beginning of a line.
-  if (NamespaceTok->is(tok::kw_inline))
-NamespaceTok = NamespaceTok->getNextNonComment();
-  if (!NamespaceTok || NamespaceTok->isNot(tok::kw_namespace))
-return nullptr;
-  return NamespaceTok;
+  return NamespaceTok->getNamespaceToken();
 }
 
 NamespaceEndCommentsFixer::NamespaceEndCommentsFixer(const Environment &Env,
Index: lib/Format/FormatToken.h
===

[PATCH] D50385: [clangd] Collect symbol occurrences from AST.

2018-08-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 161962.
hokein marked 6 inline comments as done.
hokein added a comment.

Address review comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50385

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -74,6 +74,14 @@
 MATCHER_P(ForCodeCompletion, IsIndexedForCodeCompletion, "") {
   return arg.IsIndexedForCodeCompletion == IsIndexedForCodeCompletion;
 }
+MATCHER(OccurrenceRange, "") {
+  const clang::clangd::SymbolOccurrence &Pos = testing::get<0>(arg);
+  const clang::clangd::Range &Range = testing::get<1>(arg);
+  return std::tie(Pos.Location.Start.Line, Pos.Location.Start.Column,
+  Pos.Location.End.Line, Pos.Location.End.Column) ==
+ std::tie(Range.start.line, Range.start.character, Range.end.line,
+  Range.end.character);
+}
 
 namespace clang {
 namespace clangd {
@@ -95,7 +103,7 @@
 assert(AST.hasValue());
 return SymbolCollector::shouldCollectSymbol(
 Qualified ? findDecl(*AST, Name) : findAnyDecl(*AST, Name),
-AST->getASTContext(), SymbolCollector::Options());
+AST->getASTContext());
   }
 
 protected:
@@ -162,8 +170,10 @@
 class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
 public:
   SymbolIndexActionFactory(SymbolCollector::Options COpts,
-   CommentHandler *PragmaHandler)
-  : COpts(std::move(COpts)), PragmaHandler(PragmaHandler) {}
+   CommentHandler *PragmaHandler,
+   index::IndexingOptions IndexOpts)
+  : COpts(std::move(COpts)), PragmaHandler(PragmaHandler),
+IndexOpts(IndexOpts) {}
 
   clang::FrontendAction *create() override {
 class WrappedIndexAction : public WrapperFrontendAction {
@@ -186,18 +196,16 @@
   index::IndexingOptions IndexOpts;
   CommentHandler *PragmaHandler;
 };
-index::IndexingOptions IndexOpts;
-IndexOpts.SystemSymbolFilter =
-index::IndexingOptions::SystemSymbolFilterKind::All;
-IndexOpts.IndexFunctionLocals = false;
 Collector = std::make_shared(COpts);
 return new WrappedIndexAction(Collector, std::move(IndexOpts),
   PragmaHandler);
   }
 
   std::shared_ptr Collector;
   SymbolCollector::Options COpts;
   CommentHandler *PragmaHandler;
+
+  index::IndexingOptions IndexOpts;
 };
 
 class SymbolCollectorTest : public ::testing::Test {
@@ -210,13 +218,52 @@
 TestFileURI = URI::createFile(TestFileName).toString();
   }
 
+  bool collectSymbols(StringRef HeaderCode, StringRef MainCode,
+  const std::vector &ExtraArgs = {}) {
+index::IndexingOptions IndexOpts;
+IndexOpts.SystemSymbolFilter =
+index::IndexingOptions::SystemSymbolFilterKind::All;
+IndexOpts.IndexFunctionLocals = false;
+CollectorOpts.SymOpts = &CollectSymOpts;
+CollectorOpts.OccurrenceOpts = nullptr;
+return runSymbolCollector(HeaderCode, MainCode, CollectorOpts, IndexOpts,
+  ExtraArgs);
+  }
+
+  bool collectOccurrences(StringRef HeaderCode, StringRef MainCode,
+  const std::vector &ExtraArgs = {}) {
+index::IndexingOptions IndexOpts;
+IndexOpts.SystemSymbolFilter =
+index::IndexingOptions::SystemSymbolFilterKind::All;
+IndexOpts.IndexFunctionLocals = true;
+CollectorOpts.SymOpts = nullptr;
+CollectorOpts.OccurrenceOpts = &CollectOccurrenceOpts;
+return runSymbolCollector(HeaderCode, MainCode, CollectorOpts, IndexOpts,
+  ExtraArgs);
+  }
+
+protected:
+  llvm::IntrusiveRefCntPtr InMemoryFileSystem;
+  std::string TestHeaderName;
+  std::string TestHeaderURI;
+  std::string TestFileName;
+  std::string TestFileURI;
+  SymbolSlab Symbols;
+  SymbolCollector::Options CollectorOpts;
+  SymbolCollector::Options::CollectSymbolOptions CollectSymOpts;
+  SymbolCollector::Options::CollectOccurrenceOptions CollectOccurrenceOpts;
+  std::unique_ptr PragmaHandler;
+
+private:
   bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode,
+  SymbolCollector::Options Opts,
+  index::IndexingOptions IndexOpts,
   const std::vector &ExtraArgs = {}) {
 llvm::IntrusiveRefCntPtr Files(
 new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
 auto Factory = llvm::make_unique(
-CollectorOpts, PragmaHandler.get());
+Opts, PragmaHandler.get(), std::move(IndexOpts));
 
 std::vector Args = {
 "symbol_collector", "-fsyntax-only", "-xc++",
@@ -239,16 +286,6 @@
 Symbols 

[PATCH] D50898: [clangd] Suggest code-completions for overriding base class virtual methods.

2018-08-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 161963.
kadircet marked 6 inline comments as done.
kadircet added a comment.

- Resolve discussions.
- Fix a bug inside summarizeOverride.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D50898

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

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -61,6 +61,7 @@
 MATCHER(InsertInclude, "") { return bool(arg.HeaderInsertion); }
 MATCHER_P(SnippetSuffix, Text, "") { return arg.SnippetSuffix == Text; }
 MATCHER_P(Origin, OriginSet, "") { return arg.Origin == OriginSet; }
+MATCHER(IsOverride, "") { return bool(arg.IsOverride); }
 
 // Shorthand for Contains(Named(Name)).
 Matcher &> Has(std::string Name) {
@@ -1700,6 +1701,58 @@
   }
 }
 
+TEST(CompletionTest, SuggestOverrides) {
+  constexpr const char *const Text(R"cpp(
+  class A {
+   public:
+virtual void vfunc(bool param);
+virtual void vfunc(bool param, int p);
+void func(bool param);
+  };
+  class B : public A {
+  virtual void ttt(bool param);
+  void vfunc(bool param, int p) override;
+  };
+  class C : public B {
+   public:
+void vfunc(bool param) override;
+^
+  };
+  )cpp");
+  const auto Results = completions(Text);
+  EXPECT_THAT(Results.Completions,
+  AllOf(Contains(AllOf(Named("vfunc"), IsOverride(),
+   Labeled("vfunc(bool param, int p)"))),
+Contains(AllOf(Named("ttt"), IsOverride(),
+   Labeled("ttt(bool param)"))),
+Not(Contains(AllOf(Named("vfunc"), IsOverride(),
+   Labeled("vfunc(bool param)"));
+}
+
+TEST(CompletionTest, RenderOverride) {
+  CodeCompletion C;
+  C.Name = "x";
+  C.Signature = "(bool) const";
+  C.SnippetSuffix = "(${0:bool})";
+  C.ReturnType = "int";
+  C.Documentation = "This is x().";
+  C.Kind = CompletionItemKind::Method;
+  C.Score.Total = 1.0;
+  C.Origin = SymbolOrigin::AST;
+  C.IsOverride = true;
+
+  CodeCompleteOptions Opts;
+  Opts.IncludeIndicator.NoInsert = "";
+  auto R = C.render(Opts);
+  EXPECT_EQ(R.label, "int x(bool) const override");
+  EXPECT_EQ(R.insertText, "int x(bool) const override");
+  EXPECT_EQ(R.insertTextFormat, InsertTextFormat::PlainText);
+  EXPECT_EQ(R.filterText, "x");
+  EXPECT_EQ(R.detail, "int");
+  EXPECT_EQ(R.documentation, "This is x().");
+  EXPECT_THAT(R.additionalTextEdits, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/CodeComplete.h
===
--- clangd/CodeComplete.h
+++ clangd/CodeComplete.h
@@ -131,6 +131,9 @@
   /// Holds the range of the token we are going to replace with this completion.
   Range CompletionTokenRange;
 
+  /// Whether this completion is for overriding a virtual method.
+  bool IsOverride = false;
+
   // Scores are used to rank completion items.
   struct Scores {
 // The score that items are ranked by.
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -188,14 +188,67 @@
   return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
 }
 
+// First traverses all method definitions inside current class/struct/union
+// definition. Than traverses base classes to find virtual methods that haven't
+// been overriden within current context.
+// FIXME(kadircet): Currently we cannot see declarations below completion point.
+// It is because Sema gets run only upto completion point. Need to find a
+// solution to run it for the whole class/struct/union definition.
+static std::vector
+getNonOverridenMethodCompletionResults(const DeclContext *DC, Sema *S) {
+  const auto *CR = llvm::dyn_cast(DC);
+  // If not inside a class/struct/union return empty.
+  if (!CR)
+return {};
+  // First store overrides within current class.
+  // These are stored by name to make querying fast in the later step.
+  llvm::StringMap> Overrides;
+  for (auto *Method : CR->methods()) {
+if (!Method->isVirtual())
+  continue;
+const std::string Name = Method->getNameAsString();
+Overrides[Name].push_back(Method);
+  }
+
+  std::vector Results;
+  for (const auto &Base : CR->bases()) {
+const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
+if (!BR)
+  continue;
+for (auto *Method : BR->methods()) {
+  if (!Method->isVirtual())
+continue;
+  const auto it = Overrides.find(Method->getName());
+  bool IsOverriden = false;
+  if (it != Overrides.end()) {
+for (auto *MD : it->second) {
+  // If the method in current body is not an overload of this virtual
+  // function, that it overrides this one.
+

[PATCH] D51038: [clang] Make sure codecompletion is called for calls even when inside a token.

2018-08-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 161966.
kadircet marked 2 inline comments as done.
kadircet added a comment.

- Resolve discussions.
- Add tests.
- Fix a bug noticed by lit tests.


Repository:
  rC Clang

https://reviews.llvm.org/D51038

Files:
  include/clang/Parse/Parser.h
  lib/Parse/ParseExpr.cpp
  test/CodeCompletion/function-overloads-inside-param.cpp
  test/CodeCompletion/function-overloads.cpp


Index: test/CodeCompletion/function-overloads.cpp
===
--- /dev/null
+++ test/CodeCompletion/function-overloads.cpp
@@ -0,0 +1,8 @@
+void f(int i, int j = 2, int k = 5);
+void f(float x, float y...);
+
+void test() {
+  ::f(
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:5:7 %s -o - | 
FileCheck -check-prefix=CHECK-CC1 %s
+  // CHECK-CC1: f(<#int i#>{#, <#int j = 2#>{#, <#int k = 5#>#}#})
+  // CHECK-CC1: f(<#float x#>, <#float y, ...#>)
Index: test/CodeCompletion/function-overloads-inside-param.cpp
===
--- /dev/null
+++ test/CodeCompletion/function-overloads-inside-param.cpp
@@ -0,0 +1,8 @@
+void f(int i, int j = 2, int k = 5);
+void f(float x, float y...);
+
+void test() {
+  ::f(1
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:5:8 %s -o - | 
FileCheck -check-prefix=CHECK-CC1 %s
+  // CHECK-CC1: f(<#int i#>{#, <#int j = 2#>{#, <#int k = 5#>#}#})
+  // CHECK-CC1: f(<#float x#>, <#float y, ...#>)
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -1657,10 +1657,21 @@
 
   if (OpKind == tok::l_paren || !LHS.isInvalid()) {
 if (Tok.isNot(tok::r_paren)) {
-  if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
-Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
- })) {
+  auto Completer = [&] {
+Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
+CalledOverloadCompletion = true;
+  };
+  if (ParseExpressionList(ArgExprs, CommaLocs, Completer)) {
 (void)Actions.CorrectDelayedTyposInExpr(LHS);
+// If we got an error when parsing expression list, we don't call
+// the CodeCompleteCall handler inside the parser. So call it here
+// to make sure we get overload suggestions even when we are in the
+// middle of a parameter. There is a different handling mechanism 
in
+// ObjC for that type of completion, so don't call completion and
+// let the parser do it instead.
+if (!getLangOpts().ObjC1 && PP.isCodeCompletionReached() &&
+!CalledOverloadCompletion)
+  Completer();
 LHS = ExprError();
   } else if (LHS.isInvalid()) {
 for (auto &E : ArgExprs)
Index: include/clang/Parse/Parser.h
===
--- include/clang/Parse/Parser.h
+++ include/clang/Parse/Parser.h
@@ -214,6 +214,10 @@
   /// should not be set directly.
   bool InMessageExpression;
 
+  /// Gets set to true after calling CodeCompleteCall, it is for a hack to make
+  /// signature help working even when it is triggered inside a token.
+  bool CalledOverloadCompletion = false;
+
   /// The "depth" of the template parameters currently being parsed.
   unsigned TemplateParameterDepth;
 


Index: test/CodeCompletion/function-overloads.cpp
===
--- /dev/null
+++ test/CodeCompletion/function-overloads.cpp
@@ -0,0 +1,8 @@
+void f(int i, int j = 2, int k = 5);
+void f(float x, float y...);
+
+void test() {
+  ::f(
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:5:7 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+  // CHECK-CC1: f(<#int i#>{#, <#int j = 2#>{#, <#int k = 5#>#}#})
+  // CHECK-CC1: f(<#float x#>, <#float y, ...#>)
Index: test/CodeCompletion/function-overloads-inside-param.cpp
===
--- /dev/null
+++ test/CodeCompletion/function-overloads-inside-param.cpp
@@ -0,0 +1,8 @@
+void f(int i, int j = 2, int k = 5);
+void f(float x, float y...);
+
+void test() {
+  ::f(1
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:5:8 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+  // CHECK-CC1: f(<#int i#>{#, <#int j = 2#>{#, <#int k = 5#>#}#})
+  // CHECK-CC1: f(<#float x#>, <#float y, ...#>)
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -1657,10 +1657,21 @@
 
   if (OpKind == tok::l_paren || !LHS.isInvalid()) {
 if (Tok.isNot(tok::r_paren)) {
-  if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
-Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
- })) {
+  auto Comp

[PATCH] D51061: [clang-tidy] abseil-str-cat-append

2018-08-22 Thread Hugo Gonzalez via Phabricator via cfe-commits
hugoeg updated this revision to Diff 161970.
hugoeg marked 11 inline comments as done.
hugoeg added a comment.

applied corrections from comments


https://reviews.llvm.org/D51061

Files:
  clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tidy/abseil/CMakeLists.txt
  clang-tidy/abseil/StrCatAppendCheck.cpp
  clang-tidy/abseil/StrCatAppendCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/abseil-str-cat-append.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/abseil-str-cat-append.cpp

Index: test/clang-tidy/abseil-str-cat-append.cpp
===
--- test/clang-tidy/abseil-str-cat-append.cpp
+++ test/clang-tidy/abseil-str-cat-append.cpp
@@ -0,0 +1,129 @@
+// RUN: %check_clang_tidy %s abseil-str-cat-append %t -- -- -I%S -std=c++11
+
+typedef unsigned __INT16_TYPE__ char16;
+typedef unsigned __INT32_TYPE__ char32;
+typedef __SIZE_TYPE__ size;
+
+namespace std {
+template 
+class allocator {};
+template 
+class char_traits {};
+template 
+struct basic_string {
+  typedef basic_string _Type;
+  basic_string();
+  basic_string(const C* p, const A& a = A());
+
+  const C* c_str() const;
+  const C* data() const;
+
+  _Type& append(const C* s);
+  _Type& append(const C* s, size n);
+  _Type& assign(const C* s);
+  _Type& assign(const C* s, size n);
+
+  int compare(const _Type&) const;
+  int compare(const C* s) const;
+  int compare(size pos, size len, const _Type&) const;
+  int compare(size pos, size len, const C* s) const;
+
+  size find(const _Type& str, size pos = 0) const;
+  size find(const C* s, size pos = 0) const;
+  size find(const C* s, size pos, size n) const;
+
+  _Type& insert(size pos, const _Type& str);
+  _Type& insert(size pos, const C* s);
+  _Type& insert(size pos, const C* s, size n);
+
+  _Type& operator+=(const _Type& str);
+  _Type& operator+=(const C* s);
+  _Type& operator=(const _Type& str);
+  _Type& operator=(const C* s);
+};
+
+typedef basic_string, std::allocator> string;
+typedef basic_string,
+ std::allocator>
+wstring;
+typedef basic_string, std::allocator>
+u16string;
+typedef basic_string, std::allocator>
+u32string;
+}  // namespace std
+
+std::string operator+(const std::string&, const std::string&);
+std::string operator+(const std::string&, const char*);
+std::string operator+(const char*, const std::string&);
+
+bool operator==(const std::string&, const std::string&);
+bool operator==(const std::string&, const char*);
+bool operator==(const char*, const std::string&);
+
+namespace llvm {
+struct StringRef {
+  StringRef(const char* p);
+  StringRef(const std::string&);
+};
+}  // namespace llvm
+
+namespace absl {
+
+struct AlphaNum {
+  AlphaNum(int i);
+  AlphaNum(double f);
+  AlphaNum(const char* c_str);
+  AlphaNum(const std::string& str);
+
+ private:
+  AlphaNum(const AlphaNum&);
+  AlphaNum& operator=(const AlphaNum&);
+};
+
+std::string StrCat(const AlphaNum& a);
+std::string StrCat(const AlphaNum& a, const AlphaNum& b);
+
+template 
+void foo(A& a) {
+  a = StrCat(a);
+}
+
+void bar() {
+  std::string a, b;
+  foo(a);
+
+  std::string c = StrCat(a);
+  a = StrCat(a);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: call to absl::StrCat does nothing
+  a = StrCat(a, b);
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: please use absl::StrAppend instead of absl::StrCat when appending to an existing string
+// CHECK-FIXES: {{^}}  StrAppend(&a, b);
+  b = StrCat(a, b);
+
+#define M(x) x = StrCat(x, a)
+  M(b);
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: please use absl::StrAppend instead of absl::StrCat when appending to an existing string
+// CHECK-FIXES: #define M(x) x = StrCat(x, a)
+}
+
+void Regression_SelfAppend() {
+  std::string a;
+  a = StrCat(a, a);
+}
+
+}  // namespace absl
+
+void OutsideAbsl() {
+  std::string a, b;
+  a = absl::StrCat(a, b);
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: please use absl::StrAppend instead of absl::StrCat when appending to an existing string
+// CHECK-FIXES: {{^}}  StrAppend(&a, b);
+}
+
+void OutisdeUsingAbsl() {
+  std::string a, b;
+  using absl::StrCat;
+  a = StrCat(a, b);
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: please use absl::StrAppend instead of absl::StrCat when appending to an existing string
+// CHECK-FIXES: {{^}}  StrAppend(&a, b);
+}
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -5,6 +5,7 @@
 
 .. toctree::
abseil-duration-division
+   abseil-str-cat-append
abseil-string-find-startswith
android-cloexec-accept
android-cloexec-accept4
Index: docs/clang-tidy/checks/abseil-str-cat-append.rst
===
--- docs/clang-tidy/checks/abseil-str-cat-append.rst
+++ docs/clang-tidy/checks/abseil-str-cat-append.rst
@@ -0,0 +1,11 @@
+.. title:: clang-tidy - abseil-str-cat-append
+
+abseil-str-cat-append
+

[PATCH] D51061: [clang-tidy] abseil-str-cat-append

2018-08-22 Thread Hugo Gonzalez via Phabricator via cfe-commits
hugoeg added inline comments.



Comment at: test/clang-tidy/abseil-str-cat-append.cpp:91
+
+void bar() {
+  std::string a, b;

JonasToth wrote:
> What happens if `StrCat` is used e.g. in an `std::accumulate` call as the 
> binary operator? (https://en.cppreference.com/w/cpp/algorithm/accumulate  the 
> Example includes such a case)
> Is this diagnosed, too?
> 
> The general case would be if `StrCat` is used as a template argument for a 
> functor.
it doesn't diagnose those cases. and diagnosing it doesn't seem to be worthwhile


https://reviews.llvm.org/D51061



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


  1   2   3   >