[PATCH] D70222: [clangd] Add support for .rsp files in compile_commands.json

2019-11-28 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: FAILURE - 
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70222



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


[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231359.
Herald added a subscriber: mgorny.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769

Files:
  clang/include/clang/Tooling/CompilationDatabase.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
  clang/lib/Tooling/JSONCompilationDatabase.cpp
  clang/unittests/Tooling/CompilationDatabaseTest.cpp

Index: clang/unittests/Tooling/CompilationDatabaseTest.cpp
===
--- clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -859,5 +859,36 @@
 "clang++ --driver-mode=g++ bar.cpp -D bar.cpp");
 }
 
+class ExpandResponseFilesTest : public MemDBTest {
+protected:
+  void SetUp() override {
+FS = new llvm::vfs::InMemoryFileSystem;
+ASSERT_TRUE(addFile(path(StringRef("rsp1.rsp")), "-Dflag"));
+  }
+
+  bool addFile(StringRef File, StringRef Context) {
+return FS->addFile(File, 0, llvm::MemoryBuffer::getMemBufferCopy(Context));
+  }
+
+  std::string getCommand(llvm::StringRef F) {
+auto Results = expandResponseFiles(std::make_unique(Entries),
+   FS)
+   ->getCompileCommands(path(F));
+if (Results.empty()) {
+  return "none";
+}
+return llvm::join(Results[0].CommandLine, " ");
+  }
+
+  llvm::IntrusiveRefCntPtr FS;
+};
+
+TEST_F(ExpandResponseFilesTest, ExpandResponseFiles) {
+  add("foo.cpp", "clang", "@rsp1.rsp");
+  add("bar.cpp", "clang", "-Dflag");
+  EXPECT_EQ(getCommand("foo.cpp"), "clang foo.cpp -D foo.cpp -Dflag");
+  EXPECT_EQ(getCommand("bar.cpp"), "clang bar.cpp -D bar.cpp -Dflag");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: clang/lib/Tooling/JSONCompilationDatabase.cpp
===
--- clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ clang/lib/Tooling/JSONCompilationDatabase.cpp
@@ -168,7 +168,9 @@
 auto Base = JSONCompilationDatabase::loadFromFile(
 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
 return Base ? inferTargetAndDriverMode(
-  inferMissingCompileCommands(std::move(Base)))
+  inferMissingCompileCommands(expandResponseFiles(
+  std::move(Base),
+  llvm::vfs::createPhysicalFileSystem().release(
 : nullptr;
   }
 };
Index: clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
===
--- /dev/null
+++ clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
@@ -0,0 +1,93 @@
+//===- ExpandResponseFileCompilationDataBase.cpp --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/CompilationDatabase.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ConvertUTF.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/StringSaver.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+class ExpandResponseFilesDatabase : public CompilationDatabase {
+public:
+  ExpandResponseFilesDatabase(
+  std::unique_ptr Base,
+  llvm::cl::TokenizerCallback Tokenizer,
+  llvm::IntrusiveRefCntPtr FS)
+  : Base(std::move(Base)), Tokenizer(Tokenizer), FS(std::move(FS)) {
+assert(this->Base != nullptr);
+assert(this->Tokenizer != nullptr);
+assert(this->FS != nullptr);
+  }
+
+  std::vector getAllFiles() const override {
+return Base->getAllFiles();
+  }
+
+  std::vector
+  getCompileCommands(StringRef FilePath) const override {
+return expand(Base->getCompileCommands(FilePath));
+  }
+
+  std::vector getAllCompileCommands() const override {
+return expand(Base->getAllCompileCommands());
+  }
+
+private:
+  std::vector expand(std::vector Cmds) const {
+for (auto &Cmd : Cmds) {
+  // FIXME: we should rather propagate the current directory into
+  // ExpandResponseFiles as well in addition to FS and someone can take a
+  // look at it later on.
+  if (std::error_code EC = FS->setCurrentWorkingDirectory(Cmd.Directory)) {
+llvm::consumeError(llvm::errorCodeToError(EC));
+continue;
+  }
+  bool SeenRSPFile = false;
+  llvm::SmallVector Argv;
+  Argv.reserve(Cmd.CommandLine.size());
+  for (auto &Arg : Cmd.CommandLine) {
+Argv.push_back(Arg.c_str());
+SeenRSPFile |= Arg.front() == '@';
+  }
+  if (!SeenRSPFile)
+

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: FAILURE - 
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231361.
lh123 added a comment.

Sorry, upload the wrong patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769

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

Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -37,6 +37,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -1046,11 +1047,19 @@
 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
TokenizerCallback Tokenizer,
SmallVectorImpl &NewArgv,
-   bool MarkEOLs, bool RelativeNames) {
-  ErrorOr> MemBufOrErr =
-  MemoryBuffer::getFile(FName);
-  if (!MemBufOrErr)
+   bool MarkEOLs, bool RelativeNames,
+   llvm::vfs::FileSystem &FS) {
+  llvm::ErrorOr CurrDirOrErr = FS.getCurrentWorkingDirectory();
+  if (!CurrDirOrErr) {
+llvm::consumeError(llvm::errorCodeToError(CurrDirOrErr.getError()));
 return false;
+  }
+  llvm::ErrorOr> MemBufOrErr =
+  FS.getBufferForFile(FName);
+  if (!MemBufOrErr) {
+llvm::consumeError(llvm::errorCodeToError(MemBufOrErr.getError()));
+return false;
+  }
   MemoryBuffer &MemBuf = *MemBufOrErr.get();
   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
 
@@ -1084,9 +1093,7 @@
 SmallString<128> ResponseFile;
 ResponseFile.append(1, '@');
 if (llvm::sys::path::is_relative(FName)) {
-  SmallString<128> curr_dir;
-  llvm::sys::fs::current_path(curr_dir);
-  ResponseFile.append(curr_dir.str());
+  ResponseFile.append(CurrDirOrErr.get());
 }
 llvm::sys::path::append(
 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
@@ -1101,8 +1108,8 @@
 /// Expand response files on a command line recursively using the given
 /// StringSaver and tokenization strategy.
 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
- SmallVectorImpl &Argv,
- bool MarkEOLs, bool RelativeNames) {
+ SmallVectorImpl &Argv, bool MarkEOLs,
+ bool RelativeNames, llvm::vfs::FileSystem &FS) {
   bool AllExpanded = true;
   struct ResponseFileRecord {
 const char *File;
@@ -1139,8 +1146,18 @@
 }
 
 const char *FName = Arg + 1;
-auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
-  return sys::fs::equivalent(RFile.File, FName);
+auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
+  llvm::ErrorOr LHS = FS.status(FName);
+  if (!LHS) {
+llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
+return false;
+  }
+  llvm::ErrorOr RHS = FS.status(RFile.File);
+  if (!RHS) {
+llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
+return false;
+  }
+  return LHS->equivalent(*RHS);
 };
 
 // Check for recursive response files.
@@ -1156,7 +1173,7 @@
 // contents.  Nested response files are expanded in subsequent iterations.
 SmallVector ExpandedArgv;
 if (!ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
-RelativeNames)) {
+RelativeNames, FS)) {
   // We couldn't read this file, so we leave it in the argument stream and
   // move on.
   AllExpanded = false;
@@ -1187,7 +1204,8 @@
 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
 SmallVectorImpl &Argv) {
   if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
-  /*MarkEOLs*/ false, /*RelativeNames*/ true))
+  /*MarkEOLs*/ false, /*RelativeNames*/ true,
+  *llvm::vfs::getRealFileSystem()))
 return false;
   return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
  /*MarkEOLs*/ false, /*RelativeNames*/ true);
Index: llvm/include/llvm/Support/CommandLine.h
===
--- llvm/include/llvm/Support/CommandLine.h
+++ llvm/include/llvm/Support/CommandLine.h
@@ -29,6 +29,7 @@
 #include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/ManagedStatic.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -1964,10 +1965,13 @@
 /// with nullptrs in the Argv vector.
 /// \p

[PATCH] D70222: [clangd] Add support for .rsp files in compile_commands.json

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231362.
lh123 added a comment.

fix bug.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70222

Files:
  clang/include/clang/Tooling/CompilationDatabase.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
  clang/lib/Tooling/JSONCompilationDatabase.cpp
  clang/unittests/Tooling/CompilationDatabaseTest.cpp

Index: clang/unittests/Tooling/CompilationDatabaseTest.cpp
===
--- clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -859,5 +859,36 @@
 "clang++ --driver-mode=g++ bar.cpp -D bar.cpp");
 }
 
+class ExpandResponseFilesTest : public MemDBTest {
+protected:
+  void SetUp() override {
+FS = new llvm::vfs::InMemoryFileSystem;
+ASSERT_TRUE(addFile(path(StringRef("rsp1.rsp")), "-Dflag"));
+  }
+
+  bool addFile(StringRef File, StringRef Context) {
+return FS->addFile(File, 0, llvm::MemoryBuffer::getMemBufferCopy(Context));
+  }
+
+  std::string getCommand(llvm::StringRef F) {
+auto Results = expandResponseFiles(std::make_unique(Entries),
+   FS)
+   ->getCompileCommands(path(F));
+if (Results.empty()) {
+  return "none";
+}
+return llvm::join(Results[0].CommandLine, " ");
+  }
+
+  llvm::IntrusiveRefCntPtr FS;
+};
+
+TEST_F(ExpandResponseFilesTest, ExpandResponseFiles) {
+  add("foo.cpp", "clang", "@rsp1.rsp");
+  add("bar.cpp", "clang", "-Dflag");
+  EXPECT_EQ(getCommand("foo.cpp"), "clang foo.cpp -D foo.cpp -Dflag");
+  EXPECT_EQ(getCommand("bar.cpp"), "clang bar.cpp -D bar.cpp -Dflag");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: clang/lib/Tooling/JSONCompilationDatabase.cpp
===
--- clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ clang/lib/Tooling/JSONCompilationDatabase.cpp
@@ -168,7 +168,9 @@
 auto Base = JSONCompilationDatabase::loadFromFile(
 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
 return Base ? inferTargetAndDriverMode(
-  inferMissingCompileCommands(std::move(Base)))
+  inferMissingCompileCommands(expandResponseFiles(
+  std::move(Base),
+  llvm::vfs::createPhysicalFileSystem().release(
 : nullptr;
   }
 };
Index: clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
===
--- /dev/null
+++ clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
@@ -0,0 +1,93 @@
+//===- ExpandResponseFileCompilationDataBase.cpp --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/CompilationDatabase.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ConvertUTF.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/StringSaver.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+class ExpandResponseFilesDatabase : public CompilationDatabase {
+public:
+  ExpandResponseFilesDatabase(
+  std::unique_ptr Base,
+  llvm::cl::TokenizerCallback Tokenizer,
+  llvm::IntrusiveRefCntPtr FS)
+  : Base(std::move(Base)), Tokenizer(Tokenizer), FS(std::move(FS)) {
+assert(this->Base != nullptr);
+assert(this->Tokenizer != nullptr);
+assert(this->FS != nullptr);
+  }
+
+  std::vector getAllFiles() const override {
+return Base->getAllFiles();
+  }
+
+  std::vector
+  getCompileCommands(StringRef FilePath) const override {
+return expand(Base->getCompileCommands(FilePath));
+  }
+
+  std::vector getAllCompileCommands() const override {
+return expand(Base->getAllCompileCommands());
+  }
+
+private:
+  std::vector expand(std::vector Cmds) const {
+for (auto &Cmd : Cmds) {
+  // FIXME: we should rather propagate the current directory into
+  // ExpandResponseFiles as well in addition to FS and someone can take a
+  // look at it later on.
+  if (std::error_code EC = FS->setCurrentWorkingDirectory(Cmd.Directory)) {
+llvm::consumeError(llvm::errorCodeToError(EC));
+continue;
+  }
+  bool SeenRSPFile = false;
+  llvm::SmallVector Argv;
+  Argv.reserve(Cmd.CommandLine.size());
+  for (auto &Arg : Cmd.CommandLine) {
+Argv.push_back(Arg.c_str());
+SeenRSPFile |= Arg.front() == '@';
+  }
+  if (!SeenRSPFile)
+ 

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread James Henderson via Phabricator via cfe-commits
jhenderson added inline comments.



Comment at: llvm/lib/Support/CommandLine.cpp:1148
+  llvm::ErrorOr RHS = FS.status(RFile.File);
+  if (!LHS || !RHS) {
+return false;

kadircet wrote:
> again you need to `consumeError`s before returning. I would first get `LHS`, 
> consume and bail out if it was an error, then do the same for `RHS` and only 
> after that return `equivalent`.
Could you add a TODO comment here and at the other `consumeError()` call to say 
that the error should be propagated up the stack, please?



Comment at: llvm/lib/Support/CommandLine.cpp:1054
+  if (!CurrDirOrErr) {
+llvm::consumeError(llvm::errorCodeToError(CurrDirOrErr.getError()));
 return false;

I'd ultimately like to see the public interface return 
llvm::Expected/llvm::Error so that a potentially useful error with information 
isn't just thrown away. However, I agree that that's probably a separate 
change. On the other hand, it should be simple to return it here, since this is 
only used locally, for consumption in `ExpandResponseFiles` below. Could you 
make that change, please?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D70804: [Frontend] Allow OpenMP offloading to aarch64

2019-11-28 Thread Bryan Chan via Phabricator via cfe-commits
bryanpkc created this revision.
bryanpkc added reviewers: pawosm01, gtbercea.
Herald added subscribers: cfe-commits, guansong, kristof.beyls.
Herald added a reviewer: jdoerfert.
Herald added a project: clang.

D30644  added OpenMP offloading to AArch64 
targets, then D32035  changed the
frontend to throw an error when offloading is requested for an unsupported
target architecture. However the latter did not include AArch64 in the list
of supported architectures, causing the following unit tests to fail:

  libomptarget :: api/omp_get_num_devices.c
  libomptarget :: mapping/pr38704.c
  libomptarget :: offloading/offloading_success.c
  libomptarget :: offloading/offloading_success.cpp


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70804

Files:
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3070,7 +3070,8 @@
   llvm::Triple TT(A->getValue(i));
 
   if (TT.getArch() == llvm::Triple::UnknownArch ||
-  !(TT.getArch() == llvm::Triple::ppc ||
+  !(TT.getArch() == llvm::Triple::aarch64 ||
+TT.getArch() == llvm::Triple::ppc ||
 TT.getArch() == llvm::Triple::ppc64 ||
 TT.getArch() == llvm::Triple::ppc64le ||
 TT.getArch() == llvm::Triple::nvptx ||


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3070,7 +3070,8 @@
   llvm::Triple TT(A->getValue(i));
 
   if (TT.getArch() == llvm::Triple::UnknownArch ||
-  !(TT.getArch() == llvm::Triple::ppc ||
+  !(TT.getArch() == llvm::Triple::aarch64 ||
+TT.getArch() == llvm::Triple::ppc ||
 TT.getArch() == llvm::Triple::ppc64 ||
 TT.getArch() == llvm::Triple::ppc64le ||
 TT.getArch() == llvm::Triple::nvptx ||
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70779: AArch64: add support for newer Apple CPUs

2019-11-28 Thread Tim Northover via Phabricator via cfe-commits
t.p.northover marked an inline comment as done.
t.p.northover added a comment.

Thanks Florian. I'll wait as you suggest.




Comment at: clang/lib/Driver/ToolChains/Arch/AArch64.cpp:143
 MtuneLowerCase = llvm::sys::getHostCPUName();
-  if (MtuneLowerCase == "cyclone") {
+  if (MtuneLowerCase == "cyclone" || MtuneLowerCase.find("apple") == 0) {
 Features.push_back("+zcm");

fhahn wrote:
> It might be slightly more obvious to use MtuneLowerCAse.StartsWith("apple")
I'd have preferred to, but unfortnately it's a `std::string` so doesn't have 
that function.


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

https://reviews.llvm.org/D70779



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


[PATCH] D70779: AArch64: add support for newer Apple CPUs

2019-11-28 Thread Kristof Beyls via Phabricator via cfe-commits
kristof.beyls added inline comments.



Comment at: clang/lib/Driver/ToolChains/Arch/AArch64.cpp:143
 MtuneLowerCase = llvm::sys::getHostCPUName();
-  if (MtuneLowerCase == "cyclone") {
+  if (MtuneLowerCase == "cyclone" || MtuneLowerCase.find("apple") == 0) {
 Features.push_back("+zcm");

t.p.northover wrote:
> fhahn wrote:
> > It might be slightly more obvious to use MtuneLowerCAse.StartsWith("apple")
> I'd have preferred to, but unfortnately it's a `std::string` so doesn't have 
> that function.
At least not until C++20... 
https://en.cppreference.com/w/cpp/string/basic_string/starts_with


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

https://reviews.llvm.org/D70779



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


[PATCH] D70805: [analyzer] SValHasDescendant: Determine whether the SVal has an SVal descendant

2019-11-28 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso created this revision.
Charusso added a reviewer: NoQ.
Charusso added a project: clang.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.
Charusso added a parent revision: D70411: [analyzer] CERT: StrChecker: 31.c.

This relies on the `SValVisitor` and behaves something similar to the
Clang Tidy's `hasDescendant()`.


Repository:
  rC Clang

https://reviews.llvm.org/D70805

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValHasDescendant.h
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
  clang/test/Analysis/cert/str31-c-fp-suppression.cpp
  clang/test/Analysis/sval-has-desc.c

Index: clang/test/Analysis/sval-has-desc.c
===
--- /dev/null
+++ clang/test/Analysis/sval-has-desc.c
@@ -0,0 +1,12 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,unix,debug.ExprInspection \
+// RUN:  -verify %s
+
+#include "Inputs/system-header-simulator.h"
+
+void clang_analyzer_hasDescendant(size_t size, const char *src);
+
+void f(const char *src) {
+  size_t size = strlen(src);
+  clang_analyzer_hasDescendant(size, src); // expected-warning {{TRUE}}
+}
Index: clang/test/Analysis/cert/str31-c-fp-suppression.cpp
===
--- clang/test/Analysis/cert/str31-c-fp-suppression.cpp
+++ clang/test/Analysis/cert/str31-c-fp-suppression.cpp
@@ -71,7 +71,6 @@
   free(dest); // no-warning
 }
 
-// FIXME: Suppress that with 'SValVisitor' or something similar.
 void test_complex_size_false_positive(const char *src) {
   char *dest;
   size_t size;
@@ -80,8 +79,7 @@
   dest = (char *)malloc(size * 2 + 2);
 
   strcpy(dest, &src[13]);
-  free(dest);
-  // expected-warning@-1 {{'dest' is not null-terminated}}
+  free(dest); // no-warning
 }
 
 void test_complex_size_wrong_size(const char *src) {
@@ -93,8 +91,7 @@
   dest = (char *)malloc(size * 2);
 
   strcpy(dest, &src[13]);
-  free(dest);
-  // expected-warning@-1 {{'dest' is not null-terminated}}
+  free(dest); // no-warning
 }
 
 void test_char_by_char(const char *src, size_t size) {
Index: clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
@@ -27,6 +27,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SValHasDescendant.h"
 #include "llvm/ADT/Optional.h"
 #include 
 
@@ -216,16 +217,16 @@
   DefinedOrUnknownSVal SrcSize = getDynamicSize(State, SrcMR, SVB);
   DefinedOrUnknownSVal DestSize = getDynamicSize(State, DestMR, SVB);
 
-  // '13 * strlen(src) + 1' is fine
-  // FIXME: Use the 'SValVisitor' to catch every such constructs of the symbol.
-  if (const SymExpr *SE = DestSize.getAsSymExpr())
-for (const auto &Sym : SE->symbols())
-  if (const auto *SIE = dyn_cast(Sym))
-if (SIE->getOpcode() == BO_Add)
-  if (SIE->getRHS().isOneValue())
-if (const auto *SM = dyn_cast(SIE->getLHS()))
-  if (SM->getRegion() == SrcMR)
-return;
+  // 'strlen(src) + integer' is most likely fine.
+  // FIXME: We cannot catch every '+ integer' part at the moment so we do not
+  // check that property for now.
+  SValHasDescendant HasDescendantSrc(SrcMR);
+  if (HasDescendantSrc.Visit(DestSize))
+return;
+
+  if (const MemRegion *DestSizeR = DestSize.getAsRegion())
+if (DestSizeR == SrcMR)
+  return;
 
   // 'StringRegion' returns the size with the null-terminator.
   if (const llvm::APSInt *SrcSizeInt = SVB.getKnownValue(State, SrcSize))
Index: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -14,6 +14,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SValHasDescendant.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/ScopedPrinter.h"
 
@@ -41,6 +42,7 @@
   void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext &C) const;
   void analyzerDump(const CallExpr *CE, CheckerContext &C) const;
   void analyzerExplain(const CallExpr *CE, CheckerContext &C) const;
+  void analyzerHasDescendant(const CallExpr *CE, CheckerContext &C) const;
   void analyzerPrintState(const CallExpr *CE, CheckerContext &C) const;
   v

[PATCH] D69266: [clangd] Define out-of-line availability checks

2019-11-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 231374.
kadircet marked 2 inline comments as done.
kadircet added a comment.

- Address comments
- Bail out on templated classes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69266

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
  clang-tools-extra/clangd/unittests/TweakTesting.cpp
  clang-tools-extra/clangd/unittests/TweakTesting.h
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -1809,6 +1809,67 @@
   EXPECT_EQ(apply(Test), Expected) << Test;
 }
 
+TWEAK_TEST(DefineOutline);
+TEST_F(DefineOutlineTest, TriggersOnFunctionDecl) {
+  FileName = "Test.cpp";
+  // Not available unless in a header file.
+  EXPECT_UNAVAILABLE(R"cpp(
+[[void [[f^o^o]]() [[{
+  return;
+})cpp");
+
+  FileName = "Test.hpp";
+  // Not available unless function name or fully body is selected.
+  EXPECT_UNAVAILABLE(R"cpp(
+// Not a definition
+vo^i[[d^ ^f]]^oo();
+
+[[vo^id ]]foo[[()]] {[[
+  [[(void)(5+3);
+  return;]]
+}]])cpp");
+
+  // Available even if there are no implementation files.
+  EXPECT_AVAILABLE(R"cpp(
+[[void [[f^o^o]]() [[{
+  return;
+})cpp");
+
+  // Not available for out-of-line methods.
+  EXPECT_UNAVAILABLE(R"cpp(
+class Bar {
+  void baz();
+};
+
+[[void [[Bar::[[b^a^z() [[{
+  return;
+})cpp");
+
+  // Basic check for function body and signature.
+  EXPECT_AVAILABLE(R"cpp(
+class Bar {
+  [[void [[f^o^o]]() [[{ return; }
+};
+
+void foo();
+[[void [[f^o^o]]() [[{
+  return;
+})cpp");
+
+  // Not available on defaulted/deleted members.
+  EXPECT_UNAVAILABLE(R"cpp(
+class Foo {
+  Fo^o() = default;
+  F^oo(const Foo&) = delete;
+};)cpp");
+
+  // Not available within templated classes, as it is hard to spell class name
+  // out-of-line in such cases.
+  EXPECT_UNAVAILABLE(R"cpp(
+template  struct Foo { void fo^o(){} };
+})cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/TweakTesting.h
===
--- clang-tools-extra/clangd/unittests/TweakTesting.h
+++ clang-tools-extra/clangd/unittests/TweakTesting.h
@@ -12,6 +12,7 @@
 #include "TestTU.h"
 #include "index/Index.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
@@ -62,6 +63,8 @@
   // testcases.
   std::string Header;
 
+  llvm::StringRef FileName = "TestTU.cpp";
+
   // Extra flags passed to the compilation in apply().
   std::vector ExtraArgs;
 
Index: clang-tools-extra/clangd/unittests/TweakTesting.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTesting.cpp
+++ clang-tools-extra/clangd/unittests/TweakTesting.cpp
@@ -63,12 +63,14 @@
   cantFail(positionToOffset(A.code(), SelectionRng.end))};
 }
 
-MATCHER_P6(TweakIsAvailable, TweakID, Ctx, Header, ExtraArgs, ExtraFiles, Index,
+MATCHER_P7(TweakIsAvailable, TweakID, Ctx, Header, ExtraArgs, ExtraFiles, Index,
+   FileName,
(TweakID + (negation ? " is unavailable" : " is available")).str()) {
   std::string WrappedCode = wrap(Ctx, arg);
   Annotations Input(WrappedCode);
   auto Selection = rangeOrPoint(Input);
   TestTU TU;
+  TU.Filename = FileName;
   TU.HeaderCode = Header;
   TU.Code = Input.code();
   TU.ExtraArgs = ExtraArgs;
@@ -91,6 +93,7 @@
   auto Selection = rangeOrPoint(Input);
 
   TestTU TU;
+  TU.Filename = FileName;
   TU.HeaderCode = Header;
   TU.AdditionalFiles = std::move(ExtraFiles);
   TU.Code = Input.code();
@@ -132,7 +135,7 @@
 
 ::testing::Matcher TweakTest::isAvailable() const {
   return TweakIsAvailable(llvm::StringRef(TweakID), Context, Header, ExtraArgs,
-  ExtraFiles, Index.get());
+  ExtraFiles, Index.get(), FileName);
 }
 
 std::vector TweakTest::expandCases(llvm::StringRef MarkedCode) {
Index: clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -0,0 +1,109 @@
+//===--- DefineOutline.cpp ---*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===-

[PATCH] D70805: [analyzer] SValHasDescendant: Determine whether the SVal has an SVal descendant

2019-11-28 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso added a comment.

It suppresses stuff in `curl` like:

  char buf[4096];
  size_t linelen = strlen(line);
  char *ptr = realloc(line, linelen + strlen(buf) + 1);
  strcpy(&line[linelen], buf);



  char buffer[256];
  char *string = NULL;
  size_t buflen = strlen(buffer);
  char *ptr = realloc(string, stringlen + buflen + 1);
  string = ptr;
  strcpy(string + stringlen, buffer);



  char *enc = curl_easy_escape(NULL, postdata, (int)size);
  size_t outlen = nlen + strlen(enc) + 2;
  char *n = malloc(outlen);
  strcpy(n, enc);


Repository:
  rC Clang

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

https://reviews.llvm.org/D70805



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


[PATCH] D69266: [clangd] Define out-of-line availability checks

2019-11-28 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: pass - 60292 tests passed, 0 failed and 732 were skipped.

Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69266



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


[PATCH] D70779: AArch64: add support for newer Apple CPUs

2019-11-28 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added inline comments.



Comment at: clang/lib/Driver/ToolChains/Arch/AArch64.cpp:143
 MtuneLowerCase = llvm::sys::getHostCPUName();
-  if (MtuneLowerCase == "cyclone") {
+  if (MtuneLowerCase == "cyclone" || MtuneLowerCase.find("apple") == 0) {
 Features.push_back("+zcm");

kristof.beyls wrote:
> t.p.northover wrote:
> > fhahn wrote:
> > > It might be slightly more obvious to use 
> > > MtuneLowerCAse.StartsWith("apple")
> > I'd have preferred to, but unfortnately it's a `std::string` so doesn't 
> > have that function.
> At least not until C++20... 
> https://en.cppreference.com/w/cpp/string/basic_string/starts_with
> I'd have preferred to, but unfortnately it's a std::string so doesn't have 
> that function.

Ah yes, that's unfortunate. I somehow assumed it being a StringRef without 
expanding the context


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

https://reviews.llvm.org/D70779



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


[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231377.
lh123 added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769

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

Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -29,6 +29,7 @@
 #include "llvm/Config/config.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -37,6 +38,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -1043,14 +1045,20 @@
   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
 }
 
-static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
+static llvm::Error ExpandResponseFile(StringRef FName, StringSaver &Saver,
TokenizerCallback Tokenizer,
SmallVectorImpl &NewArgv,
-   bool MarkEOLs, bool RelativeNames) {
-  ErrorOr> MemBufOrErr =
-  MemoryBuffer::getFile(FName);
-  if (!MemBufOrErr)
-return false;
+   bool MarkEOLs, bool RelativeNames,
+   llvm::vfs::FileSystem &FS) {
+  llvm::ErrorOr CurrDirOrErr = FS.getCurrentWorkingDirectory();
+  if (!CurrDirOrErr) {
+return llvm::errorCodeToError(CurrDirOrErr.getError());
+  }
+  llvm::ErrorOr> MemBufOrErr =
+  FS.getBufferForFile(FName);
+  if (!MemBufOrErr) {
+return llvm::errorCodeToError(MemBufOrErr.getError());
+  }
   MemoryBuffer &MemBuf = *MemBufOrErr.get();
   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
 
@@ -1059,7 +1067,8 @@
   std::string UTF8Buf;
   if (hasUTF16ByteOrderMark(BufRef)) {
 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
-  return false;
+  return llvm::make_error(
+  "Could not convert UTF16 To UTF8");
 Str = StringRef(UTF8Buf);
   }
   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
@@ -1084,9 +1093,7 @@
 SmallString<128> ResponseFile;
 ResponseFile.append(1, '@');
 if (llvm::sys::path::is_relative(FName)) {
-  SmallString<128> curr_dir;
-  llvm::sys::fs::current_path(curr_dir);
-  ResponseFile.append(curr_dir.str());
+  ResponseFile.append(CurrDirOrErr.get());
 }
 llvm::sys::path::append(
 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
@@ -1095,14 +1102,14 @@
 }
   }
 
-  return true;
+  return Error::success();
 }
 
 /// Expand response files on a command line recursively using the given
 /// StringSaver and tokenization strategy.
 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
- SmallVectorImpl &Argv,
- bool MarkEOLs, bool RelativeNames) {
+ SmallVectorImpl &Argv, bool MarkEOLs,
+ bool RelativeNames, llvm::vfs::FileSystem &FS) {
   bool AllExpanded = true;
   struct ResponseFileRecord {
 const char *File;
@@ -1139,8 +1146,18 @@
 }
 
 const char *FName = Arg + 1;
-auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
-  return sys::fs::equivalent(RFile.File, FName);
+auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
+  llvm::ErrorOr LHS = FS.status(FName);
+  if (!LHS) {
+llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
+return false;
+  }
+  llvm::ErrorOr RHS = FS.status(RFile.File);
+  if (!RHS) {
+llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
+return false;
+  }
+  return LHS->equivalent(*RHS);
 };
 
 // Check for recursive response files.
@@ -1155,10 +1172,13 @@
 // Replace this response file argument with the tokenization of its
 // contents.  Nested response files are expanded in subsequent iterations.
 SmallVector ExpandedArgv;
-if (!ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
-RelativeNames)) {
+
+// TODO: The error should be propagated up the stack.
+if (llvm::Error Err = ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
+RelativeNames, FS)) {
   // We couldn't read this file, so we leave it in the argument stream and
   // move on.
+  llvm::consumeError(std::move(Err));
   AllExpanded = false;
   ++I;
   c

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: FAILURE - 
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231381.
lh123 added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769

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

Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -29,6 +29,7 @@
 #include "llvm/Config/config.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -37,6 +38,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -1043,14 +1045,20 @@
   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
 }
 
-static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
+static llvm::Error ExpandResponseFile(StringRef FName, StringSaver &Saver,
TokenizerCallback Tokenizer,
SmallVectorImpl &NewArgv,
-   bool MarkEOLs, bool RelativeNames) {
-  ErrorOr> MemBufOrErr =
-  MemoryBuffer::getFile(FName);
-  if (!MemBufOrErr)
-return false;
+   bool MarkEOLs, bool RelativeNames,
+   llvm::vfs::FileSystem &FS) {
+  llvm::ErrorOr CurrDirOrErr = FS.getCurrentWorkingDirectory();
+  if (!CurrDirOrErr) {
+return llvm::errorCodeToError(CurrDirOrErr.getError());
+  }
+  llvm::ErrorOr> MemBufOrErr =
+  FS.getBufferForFile(FName);
+  if (!MemBufOrErr) {
+return llvm::errorCodeToError(MemBufOrErr.getError());
+  }
   MemoryBuffer &MemBuf = *MemBufOrErr.get();
   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
 
@@ -1059,7 +1067,8 @@
   std::string UTF8Buf;
   if (hasUTF16ByteOrderMark(BufRef)) {
 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
-  return false;
+  return llvm::make_error(
+  "Could not convert UTF16 To UTF8");
 Str = StringRef(UTF8Buf);
   }
   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
@@ -1084,9 +1093,7 @@
 SmallString<128> ResponseFile;
 ResponseFile.append(1, '@');
 if (llvm::sys::path::is_relative(FName)) {
-  SmallString<128> curr_dir;
-  llvm::sys::fs::current_path(curr_dir);
-  ResponseFile.append(curr_dir.str());
+  ResponseFile.append(CurrDirOrErr.get());
 }
 llvm::sys::path::append(
 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
@@ -1095,14 +1102,14 @@
 }
   }
 
-  return true;
+  return Error::success();
 }
 
 /// Expand response files on a command line recursively using the given
 /// StringSaver and tokenization strategy.
 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
- SmallVectorImpl &Argv,
- bool MarkEOLs, bool RelativeNames) {
+ SmallVectorImpl &Argv, bool MarkEOLs,
+ bool RelativeNames, llvm::vfs::FileSystem &FS) {
   bool AllExpanded = true;
   struct ResponseFileRecord {
 const char *File;
@@ -1139,8 +1146,20 @@
 }
 
 const char *FName = Arg + 1;
-auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
-  return sys::fs::equivalent(RFile.File, FName);
+auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
+  llvm::ErrorOr LHS = FS.status(FName);
+  if (!LHS) {
+// TODO: The error should be propagated up the stack.
+llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
+return false;
+  }
+  llvm::ErrorOr RHS = FS.status(RFile.File);
+  if (!RHS) {
+// TODO: The error should be propagated up the stack.
+llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
+return false;
+  }
+  return LHS->equivalent(*RHS);
 };
 
 // Check for recursive response files.
@@ -1155,10 +1174,13 @@
 // Replace this response file argument with the tokenization of its
 // contents.  Nested response files are expanded in subsequent iterations.
 SmallVector ExpandedArgv;
-if (!ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
-RelativeNames)) {
+
+if (llvm::Error Err = ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
+RelativeNames, FS)) {
   // We couldn't read this file, so we leave it in the argument stream and
   // move on.
+  // TODO: The erro

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: FAILURE - 
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D69298: [clangd] Define out-of-line initial apply logic

2019-11-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 231382.
kadircet marked an inline comment as done.
kadircet added a comment.

- Address comments
- Better handling for macros and tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69298

Files:
  clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
  clang-tools-extra/clangd/unittests/TweakTesting.cpp
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -1870,6 +1870,110 @@
 })cpp");
 }
 
+TEST_F(DefineOutlineTest, FailsWithoutSource) {
+  FileName = "Test.hpp";
+  llvm::StringRef Test = "void fo^o() { return; }";
+  llvm::StringRef Expected =
+  "fail: Couldn't find a suitable implementation file.";
+  EXPECT_EQ(apply(Test), Expected);
+}
+
+TEST_F(DefineOutlineTest, ApplyTest) {
+  llvm::StringMap EditedFiles;
+  ExtraFiles["Test.cpp"] = "";
+  FileName = "Test.hpp";
+
+  struct {
+llvm::StringRef Test;
+llvm::StringRef ExpectedHeader;
+llvm::StringRef ExpectedSource;
+  } Cases[] = {
+  // Simple check
+  {
+  "void fo^o() { return; }",
+  "void foo() ;",
+  "void foo() { return; }",
+  },
+  // Templated function.
+  {
+  "template  void fo^o(T, T x) { return; }",
+  "template  void foo(T, T x) ;",
+  "template  void foo(T, T x) { return; }",
+  },
+  {
+  "template  void fo^o() { return; }",
+  "template  void foo() ;",
+  "template  void foo() { return; }",
+  },
+  // Template specialization.
+  {
+  R"cpp(
+template  void foo();
+template <> void fo^o() { return; })cpp",
+  R"cpp(
+template  void foo();
+template <> void foo() ;)cpp",
+  "template <> void foo() { return; }",
+  },
+  };
+  for (const auto &Case : Cases) {
+SCOPED_TRACE(Case.Test);
+EXPECT_EQ(apply(Case.Test, &EditedFiles), Case.ExpectedHeader);
+EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents(
+ testPath("Test.cpp"), Case.ExpectedSource)));
+  }
+}
+
+TEST_F(DefineOutlineTest, HandleMacros) {
+  llvm::StringMap EditedFiles;
+  ExtraFiles["Test.cpp"] = "";
+  FileName = "Test.hpp";
+
+  struct {
+llvm::StringRef Test;
+llvm::StringRef ExpectedHeader;
+llvm::StringRef ExpectedSource;
+  } Cases[] = {
+  {R"cpp(
+  #define BODY { return; }
+  void f^oo()BODY)cpp",
+   R"cpp(
+  #define BODY { return; }
+  void foo();)cpp",
+   "void foo()BODY"},
+
+  {R"cpp(
+  #define BODY return;
+  void f^oo(){BODY})cpp",
+   R"cpp(
+  #define BODY return;
+  void foo();)cpp",
+   "void foo(){BODY}"},
+
+  {R"cpp(
+  #define TARGET void foo()
+  [[TARGET]]{ return; })cpp",
+   R"cpp(
+  #define TARGET void foo()
+  TARGET;)cpp",
+   "TARGET{ return; }"},
+
+  {R"cpp(
+  #define TARGET foo
+  void [[TARGET]](){ return; })cpp",
+   R"cpp(
+  #define TARGET foo
+  void TARGET();)cpp",
+   "void TARGET(){ return; }"},
+  };
+  for (const auto &Case : Cases) {
+SCOPED_TRACE(Case.Test);
+EXPECT_EQ(apply(Case.Test, &EditedFiles), Case.ExpectedHeader);
+EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents(
+ testPath("Test.cpp"), Case.ExpectedSource)));
+  }
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/TweakTesting.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTesting.cpp
+++ clang-tools-extra/clangd/unittests/TweakTesting.cpp
@@ -127,7 +127,7 @@
 ADD_FAILURE() << "There were changes to additional files, but client "
  "provided a nullptr for EditedFiles.";
   else
-EditedFiles->try_emplace(It.first(), Unwrapped.str());
+EditedFiles->insert_or_assign(It.first(), Unwrapped.str());
 }
   }
   return EditedMainFile;
Index: clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -13,9 +13,17 @@
 #include "refactor/Tweak.h"
 #include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Stmt.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Driver/Types.h"
+#include "clang/Format/Format.h"
+#include "clang/T

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231384.
lh123 added a comment.

fixes no matching constructor for initialization of `llvm::StringError`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769

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

Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -29,6 +29,7 @@
 #include "llvm/Config/config.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -37,6 +38,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -1043,14 +1045,20 @@
   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
 }
 
-static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
+static llvm::Error ExpandResponseFile(StringRef FName, StringSaver &Saver,
TokenizerCallback Tokenizer,
SmallVectorImpl &NewArgv,
-   bool MarkEOLs, bool RelativeNames) {
-  ErrorOr> MemBufOrErr =
-  MemoryBuffer::getFile(FName);
-  if (!MemBufOrErr)
-return false;
+   bool MarkEOLs, bool RelativeNames,
+   llvm::vfs::FileSystem &FS) {
+  llvm::ErrorOr CurrDirOrErr = FS.getCurrentWorkingDirectory();
+  if (!CurrDirOrErr) {
+return llvm::errorCodeToError(CurrDirOrErr.getError());
+  }
+  llvm::ErrorOr> MemBufOrErr =
+  FS.getBufferForFile(FName);
+  if (!MemBufOrErr) {
+return llvm::errorCodeToError(MemBufOrErr.getError());
+  }
   MemoryBuffer &MemBuf = *MemBufOrErr.get();
   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
 
@@ -1059,7 +1067,8 @@
   std::string UTF8Buf;
   if (hasUTF16ByteOrderMark(BufRef)) {
 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
-  return false;
+  return llvm::make_error(
+  "Could not convert UTF16 To UTF8", llvm::inconvertibleErrorCode());
 Str = StringRef(UTF8Buf);
   }
   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
@@ -1084,9 +1093,7 @@
 SmallString<128> ResponseFile;
 ResponseFile.append(1, '@');
 if (llvm::sys::path::is_relative(FName)) {
-  SmallString<128> curr_dir;
-  llvm::sys::fs::current_path(curr_dir);
-  ResponseFile.append(curr_dir.str());
+  ResponseFile.append(CurrDirOrErr.get());
 }
 llvm::sys::path::append(
 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
@@ -1095,14 +1102,14 @@
 }
   }
 
-  return true;
+  return Error::success();
 }
 
 /// Expand response files on a command line recursively using the given
 /// StringSaver and tokenization strategy.
 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
- SmallVectorImpl &Argv,
- bool MarkEOLs, bool RelativeNames) {
+ SmallVectorImpl &Argv, bool MarkEOLs,
+ bool RelativeNames, llvm::vfs::FileSystem &FS) {
   bool AllExpanded = true;
   struct ResponseFileRecord {
 const char *File;
@@ -1139,8 +1146,20 @@
 }
 
 const char *FName = Arg + 1;
-auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
-  return sys::fs::equivalent(RFile.File, FName);
+auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
+  llvm::ErrorOr LHS = FS.status(FName);
+  if (!LHS) {
+// TODO: The error should be propagated up the stack.
+llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
+return false;
+  }
+  llvm::ErrorOr RHS = FS.status(RFile.File);
+  if (!RHS) {
+// TODO: The error should be propagated up the stack.
+llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
+return false;
+  }
+  return LHS->equivalent(*RHS);
 };
 
 // Check for recursive response files.
@@ -1155,10 +1174,13 @@
 // Replace this response file argument with the tokenization of its
 // contents.  Nested response files are expanded in subsequent iterations.
 SmallVector ExpandedArgv;
-if (!ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
-RelativeNames)) {
+
+if (llvm::Error Err = ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
+RelativeNames, FS)) {
   // We couldn't read this file

[PATCH] D69298: [clangd] Define out-of-line initial apply logic

2019-11-28 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: FAILURE - Could not check out parent git hash 
"6a2d56e54fa4a2009787a605607b0df7fe16dd98". It was not found in the repository. 
Did you configure the "Parent Revision" in Phabricator properly? Trying to 
apply the patch to the master branch instead...

ERROR: arc patch failed with error code 1. Check build log for details.
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69298



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


[PATCH] D70807: [clangd] Prefer the left character if the character on the right of the cursor is semicolon.

2019-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

This would make go-to-def works on the cases like int A = abc^;


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70807

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -88,11 +88,8 @@
   R"cpp( // Single statement in TU.
 [[int v = [[1^00;
   )cpp",
-  // FIXME: No node found associated to the position.
   R"cpp( // Cursor at end of VarDecl.
-void func() {
-  int v = 100 + 100^;
-}
+[[int v = [[100]]^]];
   )cpp",
   // FIXME: No node found associated to the position.
   R"cpp( // Cursor in between spaces.
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -234,6 +234,7 @@
   {"void foo() { [[foo^()]]; }", "CallExpr"},
   {"void foo() { [[foo^]] (); }", "DeclRefExpr"},
   {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
+  {"int x = [[42]]^;", "IntegerLiteral"},
 
   // Ignores whitespace, comments, and semicolons in the selection.
   {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
@@ -271,7 +272,6 @@
   // FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
   // This doesn't happen now; the RAV doesn't traverse a node containing ;.
   {"int x = 42;^", nullptr},
-  {"int x = 42^;", nullptr},
 
   // Common ancestor is logically TUDecl, but we never return that.
   {"^int x; int y;^", nullptr},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -513,8 +513,8 @@
 return {Offset - 1, Offset};
   // We could choose either this byte or the previous. Usually we prefer the
   // character on the right of the cursor (or under a block cursor).
-  // But if that's whitespace, we likely want the token on the left.
-  if (isWhitespace(Buf[Offset]) && !isWhitespace(Buf[Offset - 1]))
+  // But if that's whitespace/semicolon, we likely want the token on the left.
+  if (isWhitespace(Buf[Offset]) || Buf[Offset] == ';')
 return {Offset - 1, Offset};
   return {Offset, Offset + 1};
 }


Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -88,11 +88,8 @@
   R"cpp( // Single statement in TU.
 [[int v = [[1^00;
   )cpp",
-  // FIXME: No node found associated to the position.
   R"cpp( // Cursor at end of VarDecl.
-void func() {
-  int v = 100 + 100^;
-}
+[[int v = [[100]]^]];
   )cpp",
   // FIXME: No node found associated to the position.
   R"cpp( // Cursor in between spaces.
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -234,6 +234,7 @@
   {"void foo() { [[foo^()]]; }", "CallExpr"},
   {"void foo() { [[foo^]] (); }", "DeclRefExpr"},
   {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
+  {"int x = [[42]]^;", "IntegerLiteral"},
 
   // Ignores whitespace, comments, and semicolons in the selection.
   {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
@@ -271,7 +272,6 @@
   // FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
   // This doesn't happen now; the RAV doesn't traverse a node containing ;.
   {"int x = 42;^", nullptr},
-  {"int x = 42^;", nullptr},
 
   // Common ancestor is logically TUDecl, but we never return that.
   {"^int x; int y;^", nullptr},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -513,8 +513,8 @@
 return {Offset - 1, Offset};
   // We could choose either this byte or the previous. Usually we prefer the
   // character on the right of the cursor (or under a block cursor).
-  // But if that's whitesp

[PATCH] D60455: [SYCL] Implement SYCL device code outlining

2019-11-28 Thread Alexey Bader via Phabricator via cfe-commits
bader updated this revision to Diff 231386.
bader added a comment.

Applied code review suggestions.

- Split the patch into two parts. This patch contains only Sema part and LLVM 
IR generation part will be added separately. Updated commit message.
- Replace `can't` with `cannot`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60455

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/SemaSYCL/device-attributes-on-non-sycl.cpp
  clang/test/SemaSYCL/device-attributes.cpp

Index: clang/test/SemaSYCL/device-attributes.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/device-attributes.cpp
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fsycl-is-device -verify %s
+
+[[clang::sycl_kernel]] int gv2 = 0; // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+__attribute__((sycl_kernel)) int gv3 = 0; // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+
+__attribute__((sycl_kernel(1))) void foo(); // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+[[clang::sycl_kernel(1)]] void foo2(); // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+
+// Only function templates
+__attribute__((sycl_kernel)) void foo(); // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+[[clang::sycl_kernel]] void foo1(); // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+
+// At least two template parameters
+template 
+__attribute__((sycl_kernel)) void foo(T P); // expected-warning {{'sycl_kernel' attribute only applies to a function template with at least two template parameters}}
+template 
+[[clang::sycl_kernel]] void foo1(T P); // expected-warning {{'sycl_kernel' attribute only applies to a function template with at least two template parameters}}
+
+// First two template parameters cannot be non-type template parameters
+template 
+__attribute__((sycl_kernel)) void foo(T P); // expected-warning {{template parameter of a function template with the 'sycl_kernel' attribute cannot be a non-type template parameter}}
+template 
+[[clang::sycl_kernel]] void foo1(T P); // expected-warning {{template parameter of a function template with the 'sycl_kernel' attribute cannot be a non-type template parameter}}
+
+// Must return void
+template 
+__attribute__((sycl_kernel)) int foo(T P); // expected-warning {{function template with 'sycl_kernel' attribute must have a 'void' return type}}
+template 
+[[clang::sycl_kernel]] int foo1(T P); // expected-warning {{function template with 'sycl_kernel' attribute must have a 'void' return type}}
+
+// Must take at least one argument
+template 
+__attribute__((sycl_kernel)) void foo(); // expected-warning {{function template with 'sycl_kernel' attribute must have a single parameter}}
+template 
+[[clang::sycl_kernel]] void foo1(T t, A a); // expected-warning {{function template with 'sycl_kernel' attribute must have a single parameter}}
+
+// No diagnostics
+template 
+__attribute__((sycl_kernel)) void foo(T P);
+template 
+[[clang::sycl_kernel]] void foo1(T P);
Index: clang/test/SemaSYCL/device-attributes-on-non-sycl.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/device-attributes-on-non-sycl.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fsycl-is-device -verify %s
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -x c++ %s
+
+#ifndef __SYCL_DEVICE_ONLY__
+// expected-warning@+7 {{'sycl_kernel' attribute ignored}}
+// expected-warning@+8 {{'sycl_kernel' attribute ignored}}
+#else
+// expected-no-diagnostics
+#endif
+
+template 
+__attribute__((sycl_kernel)) void foo(T P);
+template 
+[[clang::sycl_kernel]] void foo1(T P);
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -6412,6 +6412,45 @@
   D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
 }
 
+static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  // The 'sycl_kernel' attribute applies only to functions.
+  const auto *FD = cast(D);
+  const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
+  assert(FT && "Function template is expected");
+
+  // Function template must have at least two template parameters.
+  const TemplateParameterList *TL = FT->getTemplateParameters();
+  if (TL->size() < 2) {
+S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
+return;
+  }
+
+  // Template parameters must be typenames.
+  for (unsigned I = 0; I < 2; ++I) {
+const NamedDecl *TParam = TL->getParam(I

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

LGTM, please make sure you've clang-formatted the changes though




Comment at: llvm/lib/Support/CommandLine.cpp:1054
+  llvm::ErrorOr CurrDirOrErr = FS.getCurrentWorkingDirectory();
+  if (!CurrDirOrErr) {
+return llvm::errorCodeToError(CurrDirOrErr.getError());

nit: no need for braces



Comment at: llvm/lib/Support/CommandLine.cpp:1059
+  FS.getBufferForFile(FName);
+  if (!MemBufOrErr) {
+return llvm::errorCodeToError(MemBufOrErr.getError());

nit: no need for braces



Comment at: llvm/lib/Support/CommandLine.cpp:1178
+
+if (llvm::Error Err = ExpandResponseFile(FName, Saver, Tokenizer, 
ExpandedArgv, MarkEOLs,
+RelativeNames, FS)) {

clang-format ?



Comment at: llvm/lib/Support/CommandLine.cpp:1070
 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
-  return false;
+  return llvm::make_error(
+  "Could not convert UTF16 To UTF8", llvm::inconvertibleErrorCode());

nit: you can make use of `llvm::createStringError` instead


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread James Henderson via Phabricator via cfe-commits
jhenderson added inline comments.



Comment at: llvm/lib/Support/CommandLine.cpp:1071
+  return llvm::make_error(
+  "Could not convert UTF16 To UTF8", llvm::inconvertibleErrorCode());
 Str = StringRef(UTF8Buf);

Not sure, but you might want to use `illegal_byte_sequence` here instead of 
`llvm::inconvertibleErrorCode()`.



Comment at: llvm/lib/Support/CommandLine.cpp:1178
+
+if (llvm::Error Err = ExpandResponseFile(FName, Saver, Tokenizer, 
ExpandedArgv, MarkEOLs,
+RelativeNames, FS)) {

clang-format please


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D70808: [mips] Check that features required by built-ins are enabled

2019-11-28 Thread Simon Atanasyan via Phabricator via cfe-commits
atanasyan created this revision.
atanasyan added a reviewer: Petar.Avramovic.
Herald added subscribers: jrtc27, arichardson, sdardis.
Herald added a project: clang.

Now Clang does not check that features required by built-in functions are 
enabled. That causes errors in the backend reported in PR44018.

This patch fixes this bug by checking that required features are enabled.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70808

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Basic/Targets/Mips.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-mips-args.c
  clang/test/CodeGen/builtins-mips.c
  clang/test/Sema/builtins-mips-features.c

Index: clang/test/Sema/builtins-mips-features.c
===
--- /dev/null
+++ clang/test/Sema/builtins-mips-features.c
@@ -0,0 +1,37 @@
+// REQUIRES: mips-registered-target
+// RUN: %clang_cc1 -triple mips64 -fsyntax-only -verify %s
+
+typedef signed char v4i8 __attribute__ ((vector_size(4)));
+typedef signed char v4q7 __attribute__ ((vector_size(4)));
+typedef signed char v16i8 __attribute__((vector_size(16), aligned(16)));
+typedef unsigned char v16u8 __attribute__((vector_size(16), aligned(16)));
+
+void dsp() {
+  v4i8 a;
+  void* p;
+
+  // expected-error@+1 {{this builtin requires 'dsp' ASE, please use -mdsp}}
+  __builtin_mips_addu_qb(a, a);
+  // expected-error@+1 {{this builtin requires 'dsp' ASE, please use -mdsp}}
+  __builtin_mips_lwx(p, 32);
+}
+
+void dspr2() {
+  v4i8 a;
+  v4q7 b;
+
+  // expected-error@+1 {{this builtin requires 'dsp r2' ASE, please use -mdspr2}}
+  __builtin_mips_absq_s_qb(b);
+  // expected-error@+1 {{this builtin requires 'dsp r2' ASE, please use -mdspr2}}
+  __builtin_mips_subuh_r_qb(a, a);
+}
+
+void msa() {
+  v16i8 a;
+  v16u8 b;
+
+  // expected-error@+1 {{this builtin requires 'msa' ASE, please use -mmsa}}
+  __builtin_msa_add_a_b(a, a);
+  // expected-error@+1 {{this builtin requires 'msa' ASE, please use -mmsa}}
+  __builtin_msa_xori_b(b, 5);
+}
Index: clang/test/CodeGen/builtins-mips.c
===
--- clang/test/CodeGen/builtins-mips.c
+++ clang/test/CodeGen/builtins-mips.c
@@ -1,5 +1,6 @@
 // REQUIRES: mips-registered-target
-// RUN: %clang_cc1 -triple mips-unknown-linux-gnu -emit-llvm %s -o - \
+// RUN: %clang_cc1 -triple mips-unknown-linux-gnu -emit-llvm %s \
+// RUN:-target-feature +dspr2 -o - \
 // RUN:   | FileCheck %s
 
 typedef int q31;
Index: clang/test/CodeGen/builtins-mips-args.c
===
--- clang/test/CodeGen/builtins-mips-args.c
+++ clang/test/CodeGen/builtins-mips-args.c
@@ -1,5 +1,6 @@
 // REQUIRES: mips-registered-target
-// RUN: %clang_cc1 -triple mips-unknown-linux-gnu -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple mips-unknown-linux-gnu -target-feature +dspr2 \
+// RUN:-fsyntax-only -verify %s
 
 void foo() {
   // MIPS DSP Rev 1
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -3051,8 +3051,37 @@
  CheckHexagonBuiltinArgument(BuiltinID, TheCall);
 }
 
+bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
+  return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
+ CheckMipsBuiltinArgument(BuiltinID, TheCall);
+}
+
+bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
+  const TargetInfo &TI = Context.getTargetInfo();
 
-// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
+  if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_mips_lwx) {
+if (!TI.hasFeature("dsp"))
+  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
+  }
+
+  if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
+if (!TI.hasFeature("dspr2"))
+  return Diag(TheCall->getBeginLoc(),
+  diag::err_mips_builtin_requires_dspr2);
+  }
+
+  if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_msa_xori_b) {
+if (!TI.hasFeature("msa"))
+  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
+  }
+
+  return false;
+}
+
+// CheckMipsBuiltinArgument - Checks the constant value passed to the
 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
 // ordering for DSP is unspecified. MSA is ordered by the data format used
 // by the underlying instruction i.e., df/m, df/n and then by size.
@@ -3061,7 +3090,7 @@
 //definitions from include/clang/Basic/BuiltinsMips.def.
 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
 //be too.
-bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, 

[PATCH] D70807: [clangd] Prefer the left character if the character on the right of the cursor is semicolon.

2019-11-28 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: pass - 60338 tests passed, 0 failed and 732 were skipped.

Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70807



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


[PATCH] D70809: [clangd] Tweak the no-index error message for rename, NFC.

2019-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ilya-biryukov.
Herald added subscribers: usaxena95, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

The current error message doesn't fit well for cross-file rename.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70809

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp


Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -186,7 +186,7 @@
 case ReasonToReject::NoSymbolFound:
   return "there is no symbol at the given location";
 case ReasonToReject::NoIndexProvided:
-  return "symbol may be used in other files (no index available)";
+  return "no index provided";
 case ReasonToReject::UsedOutsideFile:
   return "the symbol is used outside main file";
 case ReasonToReject::NonIndexable:


Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -186,7 +186,7 @@
 case ReasonToReject::NoSymbolFound:
   return "there is no symbol at the given location";
 case ReasonToReject::NoIndexProvided:
-  return "symbol may be used in other files (no index available)";
+  return "no index provided";
 case ReasonToReject::UsedOutsideFile:
   return "the symbol is used outside main file";
 case ReasonToReject::NonIndexable:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70222: [clangd] Add support for .rsp files in compile_commands.json

2019-11-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

mostly LG, a few last nits.




Comment at: clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp:51
+  // FIXME: we should rather propagate the current directory into
+  // ExpandResponseFiles as well in addition to FS and someone can take a
+  // look at it later on.

nit: drop `and someone can take a look at it later on.`



Comment at: clang/unittests/Tooling/CompilationDatabaseTest.cpp:865
+  void SetUp() override {
+FS = new llvm::vfs::InMemoryFileSystem;
+ASSERT_TRUE(addFile(path(StringRef("rsp1.rsp")), "-Dflag"));

make this part of the constructor instead of having a SetUp



Comment at: clang/unittests/Tooling/CompilationDatabaseTest.cpp:866
+FS = new llvm::vfs::InMemoryFileSystem;
+ASSERT_TRUE(addFile(path(StringRef("rsp1.rsp")), "-Dflag"));
+  }

move this to the test



Comment at: clang/unittests/Tooling/CompilationDatabaseTest.cpp:870
+  bool addFile(StringRef File, StringRef Context) {
+return FS->addFile(File, 0, llvm::MemoryBuffer::getMemBufferCopy(Context));
+  }

nit: I would rather keep ASSERT_TRUE in here



Comment at: clang/unittests/Tooling/CompilationDatabaseTest.cpp:877
+   ->getCompileCommands(path(F));
+if (Results.empty()) {
+  return "none";

nit: no need for braces


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70222



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


[PATCH] D70535: [clangd] Define out-of-line qualify return value

2019-11-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 231391.
kadircet added a comment.

- Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70535

Files:
  clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -1974,6 +1974,56 @@
   }
 }
 
+TEST_F(DefineOutlineTest, QualifyReturnValue) {
+  FileName = "Test.hpp";
+  ExtraFiles["Test.cpp"] = "";
+
+  struct {
+llvm::StringRef Test;
+llvm::StringRef ExpectedHeader;
+llvm::StringRef ExpectedSource;
+  } Cases[] = {
+  {R"cpp(
+namespace a { class Foo; }
+using namespace a;
+Foo fo^o() { return; })cpp",
+   R"cpp(
+namespace a { class Foo; }
+using namespace a;
+Foo foo() ;)cpp",
+   "a::Foo foo() { return; }"},
+  {R"cpp(
+namespace a {
+  class Foo {
+class Bar {};
+Bar fo^o() { return {}; }
+  }
+})cpp",
+   R"cpp(
+namespace a {
+  class Foo {
+class Bar {};
+Bar foo() ;
+  }
+})cpp",
+   "a::Foo::Bar foo() { return {}; }\n"},
+  {R"cpp(
+class Foo;
+Foo fo^o() { return; })cpp",
+   R"cpp(
+class Foo;
+Foo foo() ;)cpp",
+   "Foo foo() { return; }"},
+  };
+  llvm::StringMap EditedFiles;
+  for (auto &Case : Cases) {
+apply(Case.Test, &EditedFiles);
+EXPECT_EQ(apply(Case.Test, &EditedFiles), Case.ExpectedHeader);
+EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents(
+ testPath("Test.cpp"), Case.ExpectedSource)));
+  }
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -6,13 +6,17 @@
 //
 //===--===//
 
+#include "AST.h"
+#include "FindTarget.h"
 #include "HeaderSourceSwitch.h"
+#include "Logger.h"
 #include "Path.h"
 #include "Selection.h"
 #include "SourceCode.h"
 #include "refactor/Tweak.h"
 #include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/DeclBase.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Stmt.h"
 #include "clang/Basic/SourceLocation.h"
@@ -20,10 +24,13 @@
 #include "clang/Driver/Types.h"
 #include "clang/Format/Format.h"
 #include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/Error.h"
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -57,31 +64,127 @@
   return getCorrespondingHeaderOrSource(FileName, Sel.AST, Sel.Index);
 }
 
+// Synthesize a DeclContext for TargetNS from CurContext.
+llvm::Optional
+synthesizeContextForNS(llvm::StringRef TargetNS,
+   const DeclContext *CurContext) {
+  assert(TargetNS.empty() || TargetNS.endswith("::"));
+  // Skip any non-namespace contexts, e.g. TagDecls, functions/methods.
+  CurContext = CurContext->getEnclosingNamespaceContext();
+  if (TargetNS.empty()) {
+// If TargetNS is empty, it means global ns, which is translation unit.
+while (!CurContext->isTranslationUnit())
+  CurContext = CurContext->getParent();
+  } else {
+// Otherwise we need to drop any trailing namespaces from CurContext until
+// we reach TargetNS.
+std::string TargetContextNS =
+CurContext->isNamespace()
+? llvm::cast(CurContext)->getQualifiedNameAsString()
+: "";
+TargetContextNS.append("::");
+
+llvm::StringRef CurrentContextNS(TargetContextNS);
+// If TargetNS is not a prefix of CurrentContext, there's no way to reach
+// it.
+if (!CurrentContextNS.startswith(TargetNS))
+  return llvm::None;
+
+while (CurrentContextNS != TargetNS) {
+  CurContext = CurContext->getParent();
+  // These colons always exists since TargetNS is a prefix of
+  // CurrentContextNS, it ends with "::" and they are not equal.
+  CurrentContextNS = CurrentContextNS.take_front(
+  CurrentContextNS.drop_back(2).rfind("::") + 2);
+}
+  }
+  return CurContext;
+}
+
 // Creates a modified version of function definition that can be inserted at a
 // different location. Contains both function signature and body.
-llvm::Optional getFunctionSourceCode(const FunctionDecl *FD) {
+llvm::Expected
+getFunctionSourceCode(const FunctionDecl *FD, llvm:

[PATCH] D70807: [clangd] Prefer the left character if the character on the right of the cursor is semicolon.

2019-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/Selection.cpp:517
+  // But if that's whitespace/semicolon, we likely want the token on the left.
+  if (isWhitespace(Buf[Offset]) || Buf[Offset] == ';')
 return {Offset - 1, Offset};

Would you mind preserving the prev-character check?
I don't know how to observe it in tests, but when debugging SelectionTree (e.g. 
`for (;;)`) it's nice to have the internal state be what you expect.

I'd suggest extracting a lambda IsIgnoredChar or so to keep the condition 
simple.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70807



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


[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231390.
lh123 marked 6 inline comments as done.
lh123 added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769

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

Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -29,6 +29,7 @@
 #include "llvm/Config/config.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -37,6 +38,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -1043,14 +1045,18 @@
   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
 }
 
-static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
+static llvm::Error ExpandResponseFile(StringRef FName, StringSaver &Saver,
TokenizerCallback Tokenizer,
SmallVectorImpl &NewArgv,
-   bool MarkEOLs, bool RelativeNames) {
-  ErrorOr> MemBufOrErr =
-  MemoryBuffer::getFile(FName);
+   bool MarkEOLs, bool RelativeNames,
+   llvm::vfs::FileSystem &FS) {
+  llvm::ErrorOr CurrDirOrErr = FS.getCurrentWorkingDirectory();
+  if (!CurrDirOrErr)
+return llvm::errorCodeToError(CurrDirOrErr.getError());
+  llvm::ErrorOr> MemBufOrErr =
+  FS.getBufferForFile(FName);
   if (!MemBufOrErr)
-return false;
+return llvm::errorCodeToError(MemBufOrErr.getError());
   MemoryBuffer &MemBuf = *MemBufOrErr.get();
   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
 
@@ -1059,7 +1065,9 @@
   std::string UTF8Buf;
   if (hasUTF16ByteOrderMark(BufRef)) {
 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
-  return false;
+  return llvm::createStringError(
+  std::make_error_code(std::errc::illegal_byte_sequence),
+  "Could not convert UTF16 To UTF8");
 Str = StringRef(UTF8Buf);
   }
   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
@@ -1084,9 +1092,7 @@
 SmallString<128> ResponseFile;
 ResponseFile.append(1, '@');
 if (llvm::sys::path::is_relative(FName)) {
-  SmallString<128> curr_dir;
-  llvm::sys::fs::current_path(curr_dir);
-  ResponseFile.append(curr_dir.str());
+  ResponseFile.append(CurrDirOrErr.get());
 }
 llvm::sys::path::append(
 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
@@ -1095,14 +1101,14 @@
 }
   }
 
-  return true;
+  return Error::success();
 }
 
 /// Expand response files on a command line recursively using the given
 /// StringSaver and tokenization strategy.
 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
- SmallVectorImpl &Argv,
- bool MarkEOLs, bool RelativeNames) {
+ SmallVectorImpl &Argv, bool MarkEOLs,
+ bool RelativeNames, llvm::vfs::FileSystem &FS) {
   bool AllExpanded = true;
   struct ResponseFileRecord {
 const char *File;
@@ -1139,8 +1145,20 @@
 }
 
 const char *FName = Arg + 1;
-auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
-  return sys::fs::equivalent(RFile.File, FName);
+auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
+  llvm::ErrorOr LHS = FS.status(FName);
+  if (!LHS) {
+// TODO: The error should be propagated up the stack.
+llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
+return false;
+  }
+  llvm::ErrorOr RHS = FS.status(RFile.File);
+  if (!RHS) {
+// TODO: The error should be propagated up the stack.
+llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
+return false;
+  }
+  return LHS->equivalent(*RHS);
 };
 
 // Check for recursive response files.
@@ -1155,10 +1173,13 @@
 // Replace this response file argument with the tokenization of its
 // contents.  Nested response files are expanded in subsequent iterations.
 SmallVector ExpandedArgv;
-if (!ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
-RelativeNames)) {
+if (llvm::Error Err =
+ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
+   RelativeNames, FS)) {
   // We couldn't read thi

[PATCH] D70222: [clangd] Add support for .rsp files in compile_commands.json

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231393.
lh123 marked 5 inline comments as done.
lh123 added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70222

Files:
  clang/include/clang/Tooling/CompilationDatabase.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
  clang/lib/Tooling/JSONCompilationDatabase.cpp
  clang/unittests/Tooling/CompilationDatabaseTest.cpp

Index: clang/unittests/Tooling/CompilationDatabaseTest.cpp
===
--- clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -859,5 +859,35 @@
 "clang++ --driver-mode=g++ bar.cpp -D bar.cpp");
 }
 
+class ExpandResponseFilesTest : public MemDBTest {
+public:
+  ExpandResponseFilesTest() : FS(new llvm::vfs::InMemoryFileSystem) {}
+
+protected:
+  void addFile(StringRef File, StringRef Content) {
+ASSERT_TRUE(
+FS->addFile(File, 0, llvm::MemoryBuffer::getMemBufferCopy(Content)));
+  }
+
+  std::string getCommand(llvm::StringRef F) {
+auto Results = expandResponseFiles(std::make_unique(Entries), FS)
+   ->getCompileCommands(path(F));
+if (Results.empty())
+  return "none";
+return llvm::join(Results[0].CommandLine, " ");
+  }
+
+  llvm::IntrusiveRefCntPtr FS;
+};
+
+TEST_F(ExpandResponseFilesTest, ExpandResponseFiles) {
+  addFile(path(StringRef("rsp1.rsp")), "-Dflag");
+
+  add("foo.cpp", "clang", "@rsp1.rsp");
+  add("bar.cpp", "clang", "-Dflag");
+  EXPECT_EQ(getCommand("foo.cpp"), "clang foo.cpp -D foo.cpp -Dflag");
+  EXPECT_EQ(getCommand("bar.cpp"), "clang bar.cpp -D bar.cpp -Dflag");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: clang/lib/Tooling/JSONCompilationDatabase.cpp
===
--- clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ clang/lib/Tooling/JSONCompilationDatabase.cpp
@@ -168,7 +168,9 @@
 auto Base = JSONCompilationDatabase::loadFromFile(
 JSONDatabasePath, ErrorMessage, JSONCommandLineSyntax::AutoDetect);
 return Base ? inferTargetAndDriverMode(
-  inferMissingCompileCommands(std::move(Base)))
+  inferMissingCompileCommands(expandResponseFiles(
+  std::move(Base),
+  llvm::vfs::createPhysicalFileSystem().release(
 : nullptr;
   }
 };
Index: clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
===
--- /dev/null
+++ clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
@@ -0,0 +1,92 @@
+//===- ExpandResponseFileCompilationDataBase.cpp --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/CompilationDatabase.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ConvertUTF.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/StringSaver.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+class ExpandResponseFilesDatabase : public CompilationDatabase {
+public:
+  ExpandResponseFilesDatabase(
+  std::unique_ptr Base,
+  llvm::cl::TokenizerCallback Tokenizer,
+  llvm::IntrusiveRefCntPtr FS)
+  : Base(std::move(Base)), Tokenizer(Tokenizer), FS(std::move(FS)) {
+assert(this->Base != nullptr);
+assert(this->Tokenizer != nullptr);
+assert(this->FS != nullptr);
+  }
+
+  std::vector getAllFiles() const override {
+return Base->getAllFiles();
+  }
+
+  std::vector
+  getCompileCommands(StringRef FilePath) const override {
+return expand(Base->getCompileCommands(FilePath));
+  }
+
+  std::vector getAllCompileCommands() const override {
+return expand(Base->getAllCompileCommands());
+  }
+
+private:
+  std::vector expand(std::vector Cmds) const {
+for (auto &Cmd : Cmds) {
+  // FIXME: we should rather propagate the current directory into
+  // ExpandResponseFiles as well in addition to FS.
+  if (std::error_code EC = FS->setCurrentWorkingDirectory(Cmd.Directory)) {
+llvm::consumeError(llvm::errorCodeToError(EC));
+continue;
+  }
+  bool SeenRSPFile = false;
+  llvm::SmallVector Argv;
+  Argv.reserve(Cmd.CommandLine.size());
+  for (auto &Arg : Cmd.CommandLine) {
+Argv.push_back(Arg.c_str());
+SeenRSPFile |= Arg.front() == '@';
+  }
+  if (!SeenRSPFile)
+continue;
+  llvm::BumpPtrAllocator

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread James Henderson via Phabricator via cfe-commits
jhenderson added inline comments.



Comment at: llvm/lib/Support/CommandLine.cpp:1069
+  return llvm::createStringError(
+  std::make_error_code(std::errc::illegal_byte_sequence),
+  "Could not convert UTF16 To UTF8");

`std::make_error_code(std::errc::illegal_byte_sequence)` -> 
`errc::illegal_byte_sequence`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 updated this revision to Diff 231395.
lh123 marked an inline comment as done.
lh123 added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769

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

Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -29,6 +29,7 @@
 #include "llvm/Config/config.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -37,6 +38,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -1043,14 +1045,18 @@
   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
 }
 
-static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
+static llvm::Error ExpandResponseFile(StringRef FName, StringSaver &Saver,
TokenizerCallback Tokenizer,
SmallVectorImpl &NewArgv,
-   bool MarkEOLs, bool RelativeNames) {
-  ErrorOr> MemBufOrErr =
-  MemoryBuffer::getFile(FName);
+   bool MarkEOLs, bool RelativeNames,
+   llvm::vfs::FileSystem &FS) {
+  llvm::ErrorOr CurrDirOrErr = FS.getCurrentWorkingDirectory();
+  if (!CurrDirOrErr)
+return llvm::errorCodeToError(CurrDirOrErr.getError());
+  llvm::ErrorOr> MemBufOrErr =
+  FS.getBufferForFile(FName);
   if (!MemBufOrErr)
-return false;
+return llvm::errorCodeToError(MemBufOrErr.getError());
   MemoryBuffer &MemBuf = *MemBufOrErr.get();
   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
 
@@ -1059,7 +1065,8 @@
   std::string UTF8Buf;
   if (hasUTF16ByteOrderMark(BufRef)) {
 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
-  return false;
+  return llvm::createStringError(std::errc::illegal_byte_sequence,
+ "Could not convert UTF16 To UTF8");
 Str = StringRef(UTF8Buf);
   }
   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
@@ -1084,9 +1091,7 @@
 SmallString<128> ResponseFile;
 ResponseFile.append(1, '@');
 if (llvm::sys::path::is_relative(FName)) {
-  SmallString<128> curr_dir;
-  llvm::sys::fs::current_path(curr_dir);
-  ResponseFile.append(curr_dir.str());
+  ResponseFile.append(CurrDirOrErr.get());
 }
 llvm::sys::path::append(
 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
@@ -1095,14 +1100,14 @@
 }
   }
 
-  return true;
+  return Error::success();
 }
 
 /// Expand response files on a command line recursively using the given
 /// StringSaver and tokenization strategy.
 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
- SmallVectorImpl &Argv,
- bool MarkEOLs, bool RelativeNames) {
+ SmallVectorImpl &Argv, bool MarkEOLs,
+ bool RelativeNames, llvm::vfs::FileSystem &FS) {
   bool AllExpanded = true;
   struct ResponseFileRecord {
 const char *File;
@@ -1139,8 +1144,20 @@
 }
 
 const char *FName = Arg + 1;
-auto IsEquivalent = [FName](const ResponseFileRecord &RFile) {
-  return sys::fs::equivalent(RFile.File, FName);
+auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
+  llvm::ErrorOr LHS = FS.status(FName);
+  if (!LHS) {
+// TODO: The error should be propagated up the stack.
+llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
+return false;
+  }
+  llvm::ErrorOr RHS = FS.status(RFile.File);
+  if (!RHS) {
+// TODO: The error should be propagated up the stack.
+llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
+return false;
+  }
+  return LHS->equivalent(*RHS);
 };
 
 // Check for recursive response files.
@@ -1155,10 +1172,13 @@
 // Replace this response file argument with the tokenization of its
 // contents.  Nested response files are expanded in subsequent iterations.
 SmallVector ExpandedArgv;
-if (!ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
-RelativeNames)) {
+if (llvm::Error Err =
+ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
+   RelativeNames, FS)) {
   // We couldn't read this file,

[PATCH] D60455: [SYCL] Add sycl_kernel attribute for accelerated code outlining

2019-11-28 Thread Alexey Bader via Phabricator via cfe-commits
bader updated this revision to Diff 231396.
bader added a comment.

Fixed typo in the commit message: complier -> compiler.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60455

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/SemaSYCL/device-attributes-on-non-sycl.cpp
  clang/test/SemaSYCL/device-attributes.cpp

Index: clang/test/SemaSYCL/device-attributes.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/device-attributes.cpp
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fsycl-is-device -verify %s
+
+[[clang::sycl_kernel]] int gv2 = 0; // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+__attribute__((sycl_kernel)) int gv3 = 0; // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+
+__attribute__((sycl_kernel(1))) void foo(); // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+[[clang::sycl_kernel(1)]] void foo2(); // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+
+// Only function templates
+__attribute__((sycl_kernel)) void foo(); // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+[[clang::sycl_kernel]] void foo1(); // expected-warning {{'sycl_kernel' attribute only applies to function templates}}
+
+// At least two template parameters
+template 
+__attribute__((sycl_kernel)) void foo(T P); // expected-warning {{'sycl_kernel' attribute only applies to a function template with at least two template parameters}}
+template 
+[[clang::sycl_kernel]] void foo1(T P); // expected-warning {{'sycl_kernel' attribute only applies to a function template with at least two template parameters}}
+
+// First two template parameters cannot be non-type template parameters
+template 
+__attribute__((sycl_kernel)) void foo(T P); // expected-warning {{template parameter of a function template with the 'sycl_kernel' attribute cannot be a non-type template parameter}}
+template 
+[[clang::sycl_kernel]] void foo1(T P); // expected-warning {{template parameter of a function template with the 'sycl_kernel' attribute cannot be a non-type template parameter}}
+
+// Must return void
+template 
+__attribute__((sycl_kernel)) int foo(T P); // expected-warning {{function template with 'sycl_kernel' attribute must have a 'void' return type}}
+template 
+[[clang::sycl_kernel]] int foo1(T P); // expected-warning {{function template with 'sycl_kernel' attribute must have a 'void' return type}}
+
+// Must take at least one argument
+template 
+__attribute__((sycl_kernel)) void foo(); // expected-warning {{function template with 'sycl_kernel' attribute must have a single parameter}}
+template 
+[[clang::sycl_kernel]] void foo1(T t, A a); // expected-warning {{function template with 'sycl_kernel' attribute must have a single parameter}}
+
+// No diagnostics
+template 
+__attribute__((sycl_kernel)) void foo(T P);
+template 
+[[clang::sycl_kernel]] void foo1(T P);
Index: clang/test/SemaSYCL/device-attributes-on-non-sycl.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/device-attributes-on-non-sycl.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fsycl-is-device -verify %s
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -x c++ %s
+
+#ifndef __SYCL_DEVICE_ONLY__
+// expected-warning@+7 {{'sycl_kernel' attribute ignored}}
+// expected-warning@+8 {{'sycl_kernel' attribute ignored}}
+#else
+// expected-no-diagnostics
+#endif
+
+template 
+__attribute__((sycl_kernel)) void foo(T P);
+template 
+[[clang::sycl_kernel]] void foo1(T P);
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -6412,6 +6412,45 @@
   D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
 }
 
+static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  // The 'sycl_kernel' attribute applies only to functions.
+  const auto *FD = cast(D);
+  const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
+  assert(FT && "Function template is expected");
+
+  // Function template must have at least two template parameters.
+  const TemplateParameterList *TL = FT->getTemplateParameters();
+  if (TL->size() < 2) {
+S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
+return;
+  }
+
+  // Template parameters must be typenames.
+  for (unsigned I = 0; I < 2; ++I) {
+const NamedDecl *TParam = TL->getParam(I);
+if (isa(TParam)) {
+  S.Diag(FT->getLocation(),
+ diag::warn_sycl_kernel_invalid_template_param_type);
+  return;
+}
+  }
+
+  

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread James Henderson via Phabricator via cfe-commits
jhenderson added inline comments.



Comment at: llvm/lib/Support/CommandLine.cpp:1069
+  return llvm::createStringError(
+  std::make_error_code(std::errc::illegal_byte_sequence),
+  "Could not convert UTF16 To UTF8");

jhenderson wrote:
> `std::make_error_code(std::errc::illegal_byte_sequence)` -> 
> `errc::illegal_byte_sequence`
LLVM has its own errc error_code set. Please use that, i.e. delete the `std::` 
(note that I didn't add `std::` in my previous comment).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D60455: [SYCL] Add sycl_kernel attribute for accelerated code outlining

2019-11-28 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia resigned from this revision.
Anastasia added a comment.
This revision is now accepted and ready to land.

Sorry, I don't have capacity currently to review this and I don't want to be 
blocking it either.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60455



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


[PATCH] D70723: [clangd] Store index::SymbolKind in HoverInfo

2019-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/Hover.cpp:363
   HI.Name = Macro.Name;
-  HI.Kind = indexSymbolKindToSymbolKind(
-  index::getSymbolInfoForMacro(*Macro.Info).Kind);
+  HI.Kind = index::getSymbolInfoForMacro(*Macro.Info).Kind;
   // FIXME: Populate documentation

just Kind = Macro seems clearer...



Comment at: clang-tools-extra/clangd/unittests/HoverTests.cpp:473
  HI.Definition = "static constexpr int result = a + b";
- HI.Kind = SymbolKind::Property;
+ HI.Kind = index::SymbolKind::StaticProperty;
  HI.Type = "const int";

(FWIW, both the old and the new value here seem suspect - this isn't a property)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70723



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


[PATCH] D60455: [SYCL] Add sycl_kernel attribute for accelerated code outlining

2019-11-28 Thread Alexey Bader via Phabricator via cfe-commits
bader added a comment.

In D60455#1762804 , @Anastasia wrote:

> Sorry, I don't have capacity currently to review this and I don't want to be 
> blocking it either.


@Anastasia, thanks for finding time for reviewing previous revisions of the 
patch. I really appreciate your comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60455



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


[PATCH] D70809: [clangd] Tweak the no-index error message for rename, NFC.

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

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70809



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


[PATCH] D70811: [clangd] Don't perform rename when the refs result from index is incomplete.

2019-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ilya-biryukov.
Herald added subscribers: usaxena95, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Also do an early return if the number of affected files > limit to save
some unnecessary FileURI computations.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70811

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -621,6 +621,34 @@
   UnorderedElementsAre(
   Pair(Eq(BarPath), Eq(expectedResult(BarCode, NewName))),
   Pair(Eq(MainFilePath), Eq(expectedResult(MainCode, NewName);
+
+  // Run rename on a pagination index which couldn't return all refs in one
+  // request, we reject rename on this case.
+  class PaginationIndex : public SymbolIndex {
+bool refs(const RefsRequest &Req,
+  llvm::function_ref Callback) const override {
+  return true; // has more references
+}
+
+bool fuzzyFind(
+const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+  return false;
+}
+void
+lookup(const LookupRequest &Req,
+   llvm::function_ref Callback) const override {}
+
+void relations(const RelationsRequest &Req,
+   llvm::function_ref
+   Callback) const override {}
+size_t estimateMemoryUsage() const override { return 0; }
+  } PIndex;
+  Results = rename({MainCode.point(), NewName, AST, MainFilePath, &PIndex,
+/*CrossFile=*/true, GetDirtyBuffer});
+  EXPECT_FALSE(Results);
+  EXPECT_THAT(llvm::toString(Results.takeError()),
+  testing::HasSubstr("too many occurrences"));
 }
 
 TEST(CrossFileRenameTests, CrossFileOnLocalSymbol) {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -281,20 +281,37 @@
 
 // Return all rename occurrences (per the index) outside of the main file,
 // grouped by the absolute file path.
-llvm::StringMap>
+llvm::Expected>>
 findOccurrencesOutsideFile(const NamedDecl &RenameDecl,
llvm::StringRef MainFile, const SymbolIndex &Index) {
   RefsRequest RQuest;
   RQuest.IDs.insert(*getSymbolID(&RenameDecl));
 
-  // Absolute file path => rename ocurrences in that file.
+  // Absolute file path => rename occurrences in that file.
   llvm::StringMap> AffectedFiles;
-  Index.refs(RQuest, [&](const Ref &R) {
+  // FIXME: make the limit customizable.
+  static constexpr size_t MaxLimitFiles = 50;
+  bool HasMore = Index.refs(RQuest, [&](const Ref &R) {
+if (AffectedFiles.size() > MaxLimitFiles)
+  return;
 if (auto RefFilePath = filePath(R.Location, /*HintFilePath=*/MainFile)) {
   if (*RefFilePath != MainFile)
 AffectedFiles[*RefFilePath].push_back(toRange(R.Location));
 }
   });
+
+  if (AffectedFiles.size() > MaxLimitFiles)
+return llvm::make_error(
+llvm::formatv("The number of affected files exceeds the max limit {0}",
+  MaxLimitFiles),
+llvm::inconvertibleErrorCode());
+  if (HasMore) {
+return llvm::make_error(
+llvm::formatv("The symbol {0} has too many occurrences",
+  RenameDecl.getQualifiedNameAsString()),
+llvm::inconvertibleErrorCode());
+  }
+
   return AffectedFiles;
 }
 
@@ -321,17 +338,10 @@
 llvm::function_ref(PathRef)> GetFileContent) {
   auto AffectedFiles =
   findOccurrencesOutsideFile(RenameDecl, MainFilePath, Index);
-  // FIXME: make the limit customizable.
-  static constexpr size_t MaxLimitFiles = 50;
-  if (AffectedFiles.size() >= MaxLimitFiles)
-return llvm::make_error(
-llvm::formatv(
-"The number of affected files exceeds the max limit {0}: {1}",
-MaxLimitFiles, AffectedFiles.size()),
-llvm::inconvertibleErrorCode());
-
+  if (!AffectedFiles)
+return AffectedFiles.takeError();
   FileEdits Results;
-  for (auto &FileAndOccurrences : AffectedFiles) {
+  for (auto &FileAndOccurrences : *AffectedFiles) {
 llvm::StringRef FilePath = FileAndOccurrences.first();
 
 auto AffectedFileCode = GetFileContent(FilePath);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D69948: [Checkers] Added support for freopen to StreamChecker.

2019-11-28 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:201
+std::tie(StateRetNotNull, StateRetNull) =
+CM.assumeDual(StateStreamNull, RetVal);
+if (StateRetNull) {

balazske wrote:
> NoQ wrote:
> > Mmm, wait, this doesn't look right to me. You cannot deduce from the 
> > presence of `freopen()` in the code that the argument may be null, so the 
> > split over the argument is not well-justified.
> > 
> > The right thing to do here will be to produce a "Schrödinger file 
> > descriptor" that's both `Opened` and `OpenFailed` until we observe the 
> > return value to be constrained to null or non-null later during analysis 
> > (cf. D32449), otherwise conservatively assume that the open succeeded when 
> > queried for the first time (because that's how non-paranoid code under 
> > analysis will behave).
> > 
> > Or you could drop the failed path immediately if the argument isn't known 
> > to be zero. That'll drop the coverage slightly but won't cause anything bad 
> > to happen.
> > 
> > 
> Where does this comment belong? I got this in the email:
> ```
> Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:201
> +std::tie(StateRetNotNull, StateRetNull) =
> +CM.assumeDual(StateStreamNull, RetVal);
> +if (StateRetNull) {
> ```
> Is the problem with the null-check of argument of freopen? Why is this 
> different than the other calls where `checkNullStream` is used? 
> Or is the problem with the case of NULL return value from `freopen` (in this 
> case the argument was non-null, for the null case we assume program crash)? 
> In this case we really do not know what happened with the file descriptor 
> argument (but the value of it is not changed), so the code assumes now that 
> is will be OpenFailed. This is not accurate always (it may remain open or 
> become closed). We could have another state split here (for these cases)?
The argument is checked against `NULL`, becuase it must not be `NULL`. That is 
the "checker" part. The return value is split like in the existing code for 
modeling `fopen()`. I do not see anything wrong here.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:206
+  StateRetNotNull->set(StreamSym, StreamState::getOpened());
+  C.addTransition(StateRetNotNull);
+}

I think it would be better to rearrange these lines to exactly match 
`evalFopen()`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69948



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


[clang-tools-extra] 08cce03 - [clangd] Tweak the no-index error message for rename, NFC.

2019-11-28 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2019-11-28T13:03:28+01:00
New Revision: 08cce03a6d959c899e07398603c85168a96f549c

URL: 
https://github.com/llvm/llvm-project/commit/08cce03a6d959c899e07398603c85168a96f549c
DIFF: 
https://github.com/llvm/llvm-project/commit/08cce03a6d959c899e07398603c85168a96f549c.diff

LOG: [clangd] Tweak the no-index error message for rename, NFC.

Summary: The current error message doesn't fit well for cross-file rename.

Reviewers: ilya-biryukov

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/Rename.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index ab121d434c9c..f775539cb63d 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -186,7 +186,7 @@ llvm::Error makeError(ReasonToReject Reason) {
 case ReasonToReject::NoSymbolFound:
   return "there is no symbol at the given location";
 case ReasonToReject::NoIndexProvided:
-  return "symbol may be used in other files (no index available)";
+  return "no index provided";
 case ReasonToReject::UsedOutsideFile:
   return "the symbol is used outside main file";
 case ReasonToReject::NonIndexable:



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


[PATCH] D70809: [clangd] Tweak the no-index error message for rename, NFC.

2019-11-28 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG08cce03a6d95: [clangd] Tweak the no-index error message for 
rename, NFC. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70809

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp


Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -186,7 +186,7 @@
 case ReasonToReject::NoSymbolFound:
   return "there is no symbol at the given location";
 case ReasonToReject::NoIndexProvided:
-  return "symbol may be used in other files (no index available)";
+  return "no index provided";
 case ReasonToReject::UsedOutsideFile:
   return "the symbol is used outside main file";
 case ReasonToReject::NonIndexable:


Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -186,7 +186,7 @@
 case ReasonToReject::NoSymbolFound:
   return "there is no symbol at the given location";
 case ReasonToReject::NoIndexProvided:
-  return "symbol may be used in other files (no index available)";
+  return "no index provided";
 case ReasonToReject::UsedOutsideFile:
   return "the symbol is used outside main file";
 case ReasonToReject::NonIndexable:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread liu hui via Phabricator via cfe-commits
lh123 marked an inline comment as done.
lh123 added inline comments.



Comment at: llvm/lib/Support/CommandLine.cpp:1069
+  return llvm::createStringError(
+  std::make_error_code(std::errc::illegal_byte_sequence),
+  "Could not convert UTF16 To UTF8");

jhenderson wrote:
> jhenderson wrote:
> > `std::make_error_code(std::errc::illegal_byte_sequence)` -> 
> > `errc::illegal_byte_sequence`
> LLVM has its own errc error_code set. Please use that, i.e. delete the 
> `std::` (note that I didn't add `std::` in my previous comment).
I think we should use `std::errc::illegal_byte_sequence`, because it's sigature 
is:
 ```
template 
inline Error createStringError(std::errc EC, char const *Fmt, const Ts &... 
Vals)
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D70807: [clangd] Prefer the left character if the character on the right of the cursor is semicolon.

2019-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 231404.
hokein marked an inline comment as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70807

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -88,11 +88,8 @@
   R"cpp( // Single statement in TU.
 [[int v = [[1^00;
   )cpp",
-  // FIXME: No node found associated to the position.
   R"cpp( // Cursor at end of VarDecl.
-void func() {
-  int v = 100 + 100^;
-}
+[[int v = [[100]]^]];
   )cpp",
   // FIXME: No node found associated to the position.
   R"cpp( // Cursor in between spaces.
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -234,6 +234,7 @@
   {"void foo() { [[foo^()]]; }", "CallExpr"},
   {"void foo() { [[foo^]] (); }", "DeclRefExpr"},
   {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
+  {"int x = [[42]]^;", "IntegerLiteral"},
 
   // Ignores whitespace, comments, and semicolons in the selection.
   {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
@@ -271,7 +272,6 @@
   // FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
   // This doesn't happen now; the RAV doesn't traverse a node containing ;.
   {"int x = 42;^", nullptr},
-  {"int x = 42^;", nullptr},
 
   // Common ancestor is logically TUDecl, but we never return that.
   {"^int x; int y;^", nullptr},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -513,8 +513,11 @@
 return {Offset - 1, Offset};
   // We could choose either this byte or the previous. Usually we prefer the
   // character on the right of the cursor (or under a block cursor).
-  // But if that's whitespace, we likely want the token on the left.
-  if (isWhitespace(Buf[Offset]) && !isWhitespace(Buf[Offset - 1]))
+  // But if that's whitespace/semicolon, we likely want the token on the left.
+  auto IsIgnoredChar = [](char C) {
+return isWhitespace(C) || C == ';';
+  };
+  if (IsIgnoredChar(Buf[Offset]) && !IsIgnoredChar(Buf[Offset - 1]))
 return {Offset - 1, Offset};
   return {Offset, Offset + 1};
 }


Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -88,11 +88,8 @@
   R"cpp( // Single statement in TU.
 [[int v = [[1^00;
   )cpp",
-  // FIXME: No node found associated to the position.
   R"cpp( // Cursor at end of VarDecl.
-void func() {
-  int v = 100 + 100^;
-}
+[[int v = [[100]]^]];
   )cpp",
   // FIXME: No node found associated to the position.
   R"cpp( // Cursor in between spaces.
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -234,6 +234,7 @@
   {"void foo() { [[foo^()]]; }", "CallExpr"},
   {"void foo() { [[foo^]] (); }", "DeclRefExpr"},
   {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
+  {"int x = [[42]]^;", "IntegerLiteral"},
 
   // Ignores whitespace, comments, and semicolons in the selection.
   {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
@@ -271,7 +272,6 @@
   // FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
   // This doesn't happen now; the RAV doesn't traverse a node containing ;.
   {"int x = 42;^", nullptr},
-  {"int x = 42^;", nullptr},
 
   // Common ancestor is logically TUDecl, but we never return that.
   {"^int x; int y;^", nullptr},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -513,8 +513,11 @@
 return {Offset - 1, Offset};
   // We could choose either this byte or the previous. Usually we prefer the
   // character on the right of the cursor (or under a 

[clang-tools-extra] 2330cee - [clangd] Prefer the left character if the character on the right of the cursor is semicolon.

2019-11-28 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2019-11-28T13:15:10+01:00
New Revision: 2330cee82f0aa06e8063189fe7a68db3e51f3054

URL: 
https://github.com/llvm/llvm-project/commit/2330cee82f0aa06e8063189fe7a68db3e51f3054
DIFF: 
https://github.com/llvm/llvm-project/commit/2330cee82f0aa06e8063189fe7a68db3e51f3054.diff

LOG: [clangd] Prefer the left character if the character on the right of the 
cursor is semicolon.

Summary: This would make go-to-def works on the cases like int A = abc^;

Reviewers: sammccall

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp
clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index c91cd24e2f25..5b29b916b33c 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -513,8 +513,9 @@ static std::pair pointBounds(unsigned 
Offset, FileID FID,
 return {Offset - 1, Offset};
   // We could choose either this byte or the previous. Usually we prefer the
   // character on the right of the cursor (or under a block cursor).
-  // But if that's whitespace, we likely want the token on the left.
-  if (isWhitespace(Buf[Offset]) && !isWhitespace(Buf[Offset - 1]))
+  // But if that's whitespace/semicolon, we likely want the token on the left.
+  auto IsIgnoredChar = [](char C) { return isWhitespace(C) || C == ';'; };
+  if (IsIgnoredChar(Buf[Offset]) && !IsIgnoredChar(Buf[Offset - 1]))
 return {Offset - 1, Offset};
   return {Offset, Offset + 1};
 }

diff  --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 2803aaaca1c5..6f4ccd88b978 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -234,6 +234,7 @@ TEST(SelectionTest, CommonAncestor) {
   {"void foo() { [[foo^()]]; }", "CallExpr"},
   {"void foo() { [[foo^]] (); }", "DeclRefExpr"},
   {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
+  {"int x = [[42]]^;", "IntegerLiteral"},
 
   // Ignores whitespace, comments, and semicolons in the selection.
   {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
@@ -271,7 +272,6 @@ TEST(SelectionTest, CommonAncestor) {
   // FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
   // This doesn't happen now; the RAV doesn't traverse a node containing ;.
   {"int x = 42;^", nullptr},
-  {"int x = 42^;", nullptr},
 
   // Common ancestor is logically TUDecl, but we never return that.
   {"^int x; int y;^", nullptr},

diff  --git a/clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
index b9ca0273a823..f518fea67292 100644
--- a/clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -88,11 +88,8 @@ TEST(SemanticSelection, All) {
   R"cpp( // Single statement in TU.
 [[int v = [[1^00;
   )cpp",
-  // FIXME: No node found associated to the position.
   R"cpp( // Cursor at end of VarDecl.
-void func() {
-  int v = 100 + 100^;
-}
+[[int v = [[100]]^]];
   )cpp",
   // FIXME: No node found associated to the position.
   R"cpp( // Cursor in between spaces.



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


[PATCH] D70811: [clangd] Don't perform rename when the refs result from index is incomplete.

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

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70811



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


[PATCH] D70807: [clangd] Prefer the left character if the character on the right of the cursor is semicolon.

2019-11-28 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2330cee82f0a: [clangd] Prefer the left character if the 
character on the right of the cursor… (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D70807?vs=231404&id=231405#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70807

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -88,11 +88,8 @@
   R"cpp( // Single statement in TU.
 [[int v = [[1^00;
   )cpp",
-  // FIXME: No node found associated to the position.
   R"cpp( // Cursor at end of VarDecl.
-void func() {
-  int v = 100 + 100^;
-}
+[[int v = [[100]]^]];
   )cpp",
   // FIXME: No node found associated to the position.
   R"cpp( // Cursor in between spaces.
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -234,6 +234,7 @@
   {"void foo() { [[foo^()]]; }", "CallExpr"},
   {"void foo() { [[foo^]] (); }", "DeclRefExpr"},
   {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
+  {"int x = [[42]]^;", "IntegerLiteral"},
 
   // Ignores whitespace, comments, and semicolons in the selection.
   {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
@@ -271,7 +272,6 @@
   // FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
   // This doesn't happen now; the RAV doesn't traverse a node containing ;.
   {"int x = 42;^", nullptr},
-  {"int x = 42^;", nullptr},
 
   // Common ancestor is logically TUDecl, but we never return that.
   {"^int x; int y;^", nullptr},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -513,8 +513,9 @@
 return {Offset - 1, Offset};
   // We could choose either this byte or the previous. Usually we prefer the
   // character on the right of the cursor (or under a block cursor).
-  // But if that's whitespace, we likely want the token on the left.
-  if (isWhitespace(Buf[Offset]) && !isWhitespace(Buf[Offset - 1]))
+  // But if that's whitespace/semicolon, we likely want the token on the left.
+  auto IsIgnoredChar = [](char C) { return isWhitespace(C) || C == ';'; };
+  if (IsIgnoredChar(Buf[Offset]) && !IsIgnoredChar(Buf[Offset - 1]))
 return {Offset - 1, Offset};
   return {Offset, Offset + 1};
 }


Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -88,11 +88,8 @@
   R"cpp( // Single statement in TU.
 [[int v = [[1^00;
   )cpp",
-  // FIXME: No node found associated to the position.
   R"cpp( // Cursor at end of VarDecl.
-void func() {
-  int v = 100 + 100^;
-}
+[[int v = [[100]]^]];
   )cpp",
   // FIXME: No node found associated to the position.
   R"cpp( // Cursor in between spaces.
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -234,6 +234,7 @@
   {"void foo() { [[foo^()]]; }", "CallExpr"},
   {"void foo() { [[foo^]] (); }", "DeclRefExpr"},
   {"int bar; void foo() [[{ foo (); }]]^", "CompoundStmt"},
+  {"int x = [[42]]^;", "IntegerLiteral"},
 
   // Ignores whitespace, comments, and semicolons in the selection.
   {"void foo() { [[foo^()]]; /*comment*/^}", "CallExpr"},
@@ -271,7 +272,6 @@
   // FIXME: Ideally we'd get a declstmt or the VarDecl itself here.
   // This doesn't happen now; the RAV doesn't traverse a node containing ;.
   {"int x = 42;^", nullptr},
-  {"int x = 42^;", nullptr},
 
   // Common ancestor is logically TUDecl, but we never return that.
   {"^int x; int y;^", nullptr},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -513,8 +513,9 @@
 return {

[PATCH] D70769: [Support] add vfs support for ExpandResponseFiles

2019-11-28 Thread James Henderson via Phabricator via cfe-commits
jhenderson added inline comments.



Comment at: llvm/lib/Support/CommandLine.cpp:1069
+  return llvm::createStringError(
+  std::make_error_code(std::errc::illegal_byte_sequence),
+  "Could not convert UTF16 To UTF8");

lh123 wrote:
> jhenderson wrote:
> > jhenderson wrote:
> > > `std::make_error_code(std::errc::illegal_byte_sequence)` -> 
> > > `errc::illegal_byte_sequence`
> > LLVM has its own errc error_code set. Please use that, i.e. delete the 
> > `std::` (note that I didn't add `std::` in my previous comment).
> I think we should use `std::errc::illegal_byte_sequence`, because it's 
> sigature is:
>  ```
> template 
> inline Error createStringError(std::errc EC, char const *Fmt, const Ts &... 
> Vals)
> ```
I'm not sure if that's a mistake in the function interface or not, and it looks 
like our usage is very inconsistent, but the comments in Errc.h imply that we 
really should use llvm::errc values and not std::errc, or there may be problems.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70769



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


[PATCH] D69938: [OpenCL] Use __generic addr space when generating internal representation of lambda

2019-11-28 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia updated this revision to Diff 231409.
Anastasia added a comment.

Switched to using `getAddrSpaceQualType` in the entire code base.


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

https://reviews.llvm.org/D69938

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaOpenCLCXX/address-space-lambda.cl

Index: clang/test/SemaOpenCLCXX/address-space-lambda.cl
===
--- /dev/null
+++ clang/test/SemaOpenCLCXX/address-space-lambda.cl
@@ -0,0 +1,25 @@
+//RUN: %clang_cc1 %s -cl-std=clc++ -pedantic -ast-dump -verify | FileCheck %s
+
+//CHECK: CXXMethodDecl {{.*}} constexpr operator() 'int (int) const __generic'
+auto glambda = [](auto a) { return a; };
+
+__kernel void foo() {
+  int i;
+//CHECK: CXXMethodDecl {{.*}} constexpr operator() 'void () const __generic'
+  auto  llambda = [&]() {i++;};
+  llambda();
+  glambda(1);
+  // Test lambda with default parameters
+//CHECK: CXXMethodDecl {{.*}} constexpr operator() 'void () const __generic'
+  [&] {i++;} ();
+  __constant auto err = [&]() {}; //expected-note-re{{candidate function not viable: address space mismatch in 'this' argument ('__constant (lambda at {{.*}})'), parameter type must be 'const __generic (lambda at {{.*}})'}}
+  err();  //expected-error-re{{no matching function for call to object of type '__constant (lambda at {{.*}})'}}
+  // FIXME: There is very limited addr space functionality
+  // we can test when taking lambda type from the object.
+  // The limitation is due to addr spaces being added to all
+  // objects in OpenCL. Once we add metaprogramming utility
+  // for removing address spaces from a type we can enhance
+  // testing here.
+  (*(__constant decltype(llambda) *)nullptr)(); //expected-error{{multiple address spaces specified for type}}
+  (*(decltype(llambda) *)nullptr)();
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -4916,7 +4916,9 @@
   .getScopeRep()
   ->getKind() == NestedNameSpecifier::TypeSpec) ||
  state.getDeclarator().getContext() ==
- DeclaratorContext::MemberContext;
+ DeclaratorContext::MemberContext ||
+ state.getDeclarator().getContext() ==
+ DeclaratorContext::LambdaExprContext;
 };
 
 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
@@ -4935,7 +4937,8 @@
   // If a class member function's address space is not set, set it to
   // __generic.
   LangAS AS =
-  (ASIdx == LangAS::Default ? LangAS::opencl_generic : ASIdx);
+  (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
+: ASIdx);
   EPI.TypeQuals.addAddressSpace(AS);
 }
 T = Context.getFunctionType(T, ParamTys, EPI);
Index: clang/lib/Sema/SemaLambda.cpp
===
--- clang/lib/Sema/SemaLambda.cpp
+++ clang/lib/Sema/SemaLambda.cpp
@@ -887,6 +887,10 @@
 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
 EPI.HasTrailingReturn = true;
 EPI.TypeQuals.addConst();
+LangAS AS = getDefaultCXXMethodAddrSpace();
+if (AS != LangAS::Default)
+  EPI.TypeQuals.addAddressSpace(AS);
+
 // C++1y [expr.prim.lambda]:
 //   The lambda return type is 'auto', which is replaced by the
 //   trailing-return type if provided and/or deduced from 'return'
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -11129,10 +11129,9 @@
   // Build an exception specification pointing back at this constructor.
   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
 
-  if (getLangOpts().OpenCLCPlusPlus) {
-// OpenCL: Implicitly defaulted special member are of the generic address
-// space.
-EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
+  LangAS AS = getDefaultCXXMethodAddrSpace();
+  if (AS != LangAS::Default) {
+EPI.TypeQuals.addAddressSpace(AS);
   }
 
   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
@@ -12036,8 +12035,9 @@
 return nullptr;
 
   QualType ArgType = Context.getTypeDeclType(ClassDecl);
-  if (Context.getLangOpts().OpenCLCPlusPlus)
-ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
+  LangAS AS = getDefaultCXXMethodAddrSpace();
+  if (AS != LangAS::Default)
+ArgType = Context.getAddrSpaceQualType(ArgType, AS);
   QualType RetType = Context.getLValueReferenceType(ArgType);
   bool Const = ClassDecl->implicitCopyAssignm

[clang-tools-extra] 3c3aca2 - [clangd] Don't perform rename when the refs result from index is incomplete.

2019-11-28 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2019-11-28T13:56:19+01:00
New Revision: 3c3aca245e67fa70b6f49b9062983fbdf120ba04

URL: 
https://github.com/llvm/llvm-project/commit/3c3aca245e67fa70b6f49b9062983fbdf120ba04
DIFF: 
https://github.com/llvm/llvm-project/commit/3c3aca245e67fa70b6f49b9062983fbdf120ba04.diff

LOG: [clangd] Don't perform rename when the refs result from index is 
incomplete.

Summary:
Also do an early return if the number of affected files > limit to save
some unnecessary FileURI computations.

Reviewers: ilya-biryukov

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/Rename.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index f775539cb63d..e57bf61dc2e5 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -281,20 +281,37 @@ Range toRange(const SymbolLocation &L) {
 
 // Return all rename occurrences (per the index) outside of the main file,
 // grouped by the absolute file path.
-llvm::StringMap>
+llvm::Expected>>
 findOccurrencesOutsideFile(const NamedDecl &RenameDecl,
llvm::StringRef MainFile, const SymbolIndex &Index) 
{
   RefsRequest RQuest;
   RQuest.IDs.insert(*getSymbolID(&RenameDecl));
 
-  // Absolute file path => rename ocurrences in that file.
+  // Absolute file path => rename occurrences in that file.
   llvm::StringMap> AffectedFiles;
-  Index.refs(RQuest, [&](const Ref &R) {
+  // FIXME: make the limit customizable.
+  static constexpr size_t MaxLimitFiles = 50;
+  bool HasMore = Index.refs(RQuest, [&](const Ref &R) {
+if (AffectedFiles.size() > MaxLimitFiles)
+  return;
 if (auto RefFilePath = filePath(R.Location, /*HintFilePath=*/MainFile)) {
   if (*RefFilePath != MainFile)
 AffectedFiles[*RefFilePath].push_back(toRange(R.Location));
 }
   });
+
+  if (AffectedFiles.size() > MaxLimitFiles)
+return llvm::make_error(
+llvm::formatv("The number of affected files exceeds the max limit {0}",
+  MaxLimitFiles),
+llvm::inconvertibleErrorCode());
+  if (HasMore) {
+return llvm::make_error(
+llvm::formatv("The symbol {0} has too many occurrences",
+  RenameDecl.getQualifiedNameAsString()),
+llvm::inconvertibleErrorCode());
+  }
+
   return AffectedFiles;
 }
 
@@ -321,17 +338,10 @@ llvm::Expected renameOutsideFile(
 llvm::function_ref(PathRef)> GetFileContent) {
   auto AffectedFiles =
   findOccurrencesOutsideFile(RenameDecl, MainFilePath, Index);
-  // FIXME: make the limit customizable.
-  static constexpr size_t MaxLimitFiles = 50;
-  if (AffectedFiles.size() >= MaxLimitFiles)
-return llvm::make_error(
-llvm::formatv(
-"The number of affected files exceeds the max limit {0}: {1}",
-MaxLimitFiles, AffectedFiles.size()),
-llvm::inconvertibleErrorCode());
-
+  if (!AffectedFiles)
+return AffectedFiles.takeError();
   FileEdits Results;
-  for (auto &FileAndOccurrences : AffectedFiles) {
+  for (auto &FileAndOccurrences : *AffectedFiles) {
 llvm::StringRef FilePath = FileAndOccurrences.first();
 
 auto AffectedFileCode = GetFileContent(FilePath);

diff  --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index 47aca380f3e9..89efb32a2bb5 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -621,6 +621,34 @@ TEST(RenameTests, CrossFile) {
   UnorderedElementsAre(
   Pair(Eq(BarPath), Eq(expectedResult(BarCode, NewName))),
   Pair(Eq(MainFilePath), Eq(expectedResult(MainCode, NewName);
+
+  // Run rename on a pagination index which couldn't return all refs in one
+  // request, we reject rename on this case.
+  class PaginationIndex : public SymbolIndex {
+bool refs(const RefsRequest &Req,
+  llvm::function_ref Callback) const override {
+  return true; // has more references
+}
+
+bool fuzzyFind(
+const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+  return false;
+}
+void
+lookup(const LookupRequest &Req,
+   llvm::function_ref Callback) const override {}
+
+void relations(const RelationsRequest &Req,
+   llvm::function_ref
+   Callback) const override {}
+size_t estimateMemoryUsage() const override { return 0; }
+  } PIndex;
+  Results = rename({MainCode.point(), NewName, AST, MainFilePath, &PIndex,
+/*CrossFile=*/true, GetDirtyBuffer});
+  EXPECT_FALSE(Results);
+

[PATCH] D70811: [clangd] Don't perform rename when the refs result from index is incomplete.

2019-11-28 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3c3aca245e67: [clangd] Don't perform rename when the 
refs result from index is incomplete. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70811

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -621,6 +621,34 @@
   UnorderedElementsAre(
   Pair(Eq(BarPath), Eq(expectedResult(BarCode, NewName))),
   Pair(Eq(MainFilePath), Eq(expectedResult(MainCode, NewName);
+
+  // Run rename on a pagination index which couldn't return all refs in one
+  // request, we reject rename on this case.
+  class PaginationIndex : public SymbolIndex {
+bool refs(const RefsRequest &Req,
+  llvm::function_ref Callback) const override {
+  return true; // has more references
+}
+
+bool fuzzyFind(
+const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+  return false;
+}
+void
+lookup(const LookupRequest &Req,
+   llvm::function_ref Callback) const override {}
+
+void relations(const RelationsRequest &Req,
+   llvm::function_ref
+   Callback) const override {}
+size_t estimateMemoryUsage() const override { return 0; }
+  } PIndex;
+  Results = rename({MainCode.point(), NewName, AST, MainFilePath, &PIndex,
+/*CrossFile=*/true, GetDirtyBuffer});
+  EXPECT_FALSE(Results);
+  EXPECT_THAT(llvm::toString(Results.takeError()),
+  testing::HasSubstr("too many occurrences"));
 }
 
 TEST(CrossFileRenameTests, CrossFileOnLocalSymbol) {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -281,20 +281,37 @@
 
 // Return all rename occurrences (per the index) outside of the main file,
 // grouped by the absolute file path.
-llvm::StringMap>
+llvm::Expected>>
 findOccurrencesOutsideFile(const NamedDecl &RenameDecl,
llvm::StringRef MainFile, const SymbolIndex &Index) {
   RefsRequest RQuest;
   RQuest.IDs.insert(*getSymbolID(&RenameDecl));
 
-  // Absolute file path => rename ocurrences in that file.
+  // Absolute file path => rename occurrences in that file.
   llvm::StringMap> AffectedFiles;
-  Index.refs(RQuest, [&](const Ref &R) {
+  // FIXME: make the limit customizable.
+  static constexpr size_t MaxLimitFiles = 50;
+  bool HasMore = Index.refs(RQuest, [&](const Ref &R) {
+if (AffectedFiles.size() > MaxLimitFiles)
+  return;
 if (auto RefFilePath = filePath(R.Location, /*HintFilePath=*/MainFile)) {
   if (*RefFilePath != MainFile)
 AffectedFiles[*RefFilePath].push_back(toRange(R.Location));
 }
   });
+
+  if (AffectedFiles.size() > MaxLimitFiles)
+return llvm::make_error(
+llvm::formatv("The number of affected files exceeds the max limit {0}",
+  MaxLimitFiles),
+llvm::inconvertibleErrorCode());
+  if (HasMore) {
+return llvm::make_error(
+llvm::formatv("The symbol {0} has too many occurrences",
+  RenameDecl.getQualifiedNameAsString()),
+llvm::inconvertibleErrorCode());
+  }
+
   return AffectedFiles;
 }
 
@@ -321,17 +338,10 @@
 llvm::function_ref(PathRef)> GetFileContent) {
   auto AffectedFiles =
   findOccurrencesOutsideFile(RenameDecl, MainFilePath, Index);
-  // FIXME: make the limit customizable.
-  static constexpr size_t MaxLimitFiles = 50;
-  if (AffectedFiles.size() >= MaxLimitFiles)
-return llvm::make_error(
-llvm::formatv(
-"The number of affected files exceeds the max limit {0}: {1}",
-MaxLimitFiles, AffectedFiles.size()),
-llvm::inconvertibleErrorCode());
-
+  if (!AffectedFiles)
+return AffectedFiles.takeError();
   FileEdits Results;
-  for (auto &FileAndOccurrences : AffectedFiles) {
+  for (auto &FileAndOccurrences : *AffectedFiles) {
 llvm::StringRef FilePath = FileAndOccurrences.first();
 
 auto AffectedFileCode = GetFileContent(FilePath);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 6623788 - [include-fixer] Python 3 support for clang-include-fixer.py

2019-11-28 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2019-11-28T14:22:21+01:00
New Revision: 66237889a79f728fffc96394740b975774de26bf

URL: 
https://github.com/llvm/llvm-project/commit/66237889a79f728fffc96394740b975774de26bf
DIFF: 
https://github.com/llvm/llvm-project/commit/66237889a79f728fffc96394740b975774de26bf.diff

LOG: [include-fixer] Python 3 support for clang-include-fixer.py

Patch by Yannick Brehon!

Added: 


Modified: 
clang-tools-extra/clang-include-fixer/tool/clang-include-fixer.py

Removed: 




diff  --git a/clang-tools-extra/clang-include-fixer/tool/clang-include-fixer.py 
b/clang-tools-extra/clang-include-fixer/tool/clang-include-fixer.py
index df05101e4fd8..fcdd5a0b60ee 100644
--- a/clang-tools-extra/clang-include-fixer/tool/clang-include-fixer.py
+++ b/clang-tools-extra/clang-include-fixer/tool/clang-include-fixer.py
@@ -17,6 +17,7 @@
 # It operates on the current, potentially unsaved buffer and does not create
 # or save any files. To revert a fix, just undo.
 
+from __future__ import print_function
 import argparse
 import 
diff lib
 import json
@@ -79,7 +80,7 @@ def GetUserSelection(message, headers, 
maximum_suggested_headers):
 except Exception:
   # Show a new prompt on invalid option instead of aborting so that users
   # don't need to wait for another clang-include-fixer run.
-  print >> sys.stderr, "Invalid option:", res
+  print("Invalid option: {}".format(res), file=sys.stderr)
   return GetUserSelection(message, headers, maximum_suggested_headers)
   return headers[idx - 1]
 
@@ -95,7 +96,7 @@ def execute(command, text):
   p = subprocess.Popen(command,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE, startupinfo=startupinfo)
-  return p.communicate(input=text)
+  return p.communicate(input=text.encode('utf-8'))
 
 
 def InsertHeaderToVimBuffer(header, text):
@@ -159,7 +160,7 @@ def main():
   if query_mode:
 symbol = get_symbol_under_cursor()
 if len(symbol) == 0:
-  print "Skip querying empty symbol."
+  print("Skip querying empty symbol.")
   return
 command = [binary, "-stdin", "-query-symbol="+get_symbol_under_cursor(),
"-db=" + args.db, "-input=" + args.input,
@@ -170,13 +171,14 @@ def main():
"-input=" + args.input, vim.current.buffer.name]
   stdout, stderr = execute(command, text)
   if stderr:
-print >> sys.stderr, "Error while running clang-include-fixer: " + stderr
+print("Error while running clang-include-fixer: {}".format(stderr),
+  file=sys.stderr)
 return
 
   include_fixer_context = json.loads(stdout)
   query_symbol_infos = include_fixer_context["QuerySymbolInfos"]
   if not query_symbol_infos:
-print "The file is fine, no need to add a header."
+print("The file is fine, no need to add a header.")
 return
   symbol = query_symbol_infos[0]["RawIdentifier"]
   # The header_infos is already sorted by clang-include-fixer.
@@ -192,7 +194,7 @@ def main():
   unique_headers.append(header)
 
   if not unique_headers:
-print "Couldn't find a header for {0}.".format(symbol)
+print("Couldn't find a header for {0}.".format(symbol))
 return
 
   try:
@@ -207,9 +209,9 @@ def main():
 include_fixer_context["HeaderInfos"] = inserted_header_infos
 
 InsertHeaderToVimBuffer(include_fixer_context, text)
-print "Added #include {0} for {1}.".format(selected, symbol)
+print("Added #include {0} for {1}.".format(selected, symbol))
   except Exception as error:
-print >> sys.stderr, error.message
+print(error.message, file=sys.stderr)
   return
 
 



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


[PATCH] D70818: [Analyzer] Model STL Algoirthms to improve the iterator checkers

2019-11-28 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware created this revision.
baloghadamsoftware added reviewers: NoQ, Szelethus.
baloghadamsoftware added a project: clang.
Herald added subscribers: Charusso, donat.nagy, mikhail.ramalho, a.sidorin, 
rnkovacs, szepet, xazax.hun, whisperity, mgorny.
baloghadamsoftware added a parent revision: D70320: [Analyzer] [NFC] Iterator 
Checkers - Separate iterator modeling and the actual checkers.

STL Algorithms are usually implemented in a tricky for performance reasons 
which is too complicated for the analyzer. Furthermore inlining them is costly. 
Instead of inlining we should model their behavior according to the 
specifications.

This patch is the first step towards STL Algorithm modeling. It models all the 
`find()`-like functions in a simple way: the result is either found or not. In 
the future it can be extended to only return success if container modeling is 
also extended in a way the it keeps track of trivial insertions and deletions.


Repository:
  rC Clang

https://reviews.llvm.org/D70818

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.h
  clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/STLAlgorithmModeling.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/stl-algorithm-modeling.cpp

Index: clang/test/Analysis/stl-algorithm-modeling.cpp
===
--- /dev/null
+++ clang/test/Analysis/stl-algorithm-modeling.cpp
@@ -0,0 +1,481 @@
+// RUN: %clang_analyze_cc1 -std=c++17 -analyzer-checker=core,cplusplus,alpha.cplusplus.IteratorModeling,debug.DebugIteratorModeling,optin.cplusplus.STLAlgorithmModeling,debug.ExprInspection -analyzer-config aggressive-binary-operation-simplification=true %s -verify
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+void clang_analyzer_eval(bool);
+
+template 
+long clang_analyzer_iterator_position(const Iterator&);
+
+template  Iter return_any_iterator(const Iter &It);
+
+void test_find1(std::vector V, int n) {
+  const auto i1 = return_any_iterator(V.begin());
+  const auto i2 = return_any_iterator(V.begin());
+
+  const auto i3 = std::find(i1, i2, n);
+
+  clang_analyzer_eval(i3 == i2); // expected-warning{{TRUE}} expected-warning{{FALSE}}
+
+  if (i3 != i2) {
+clang_analyzer_eval(clang_analyzer_iterator_position(i3) <
+clang_analyzer_iterator_position(i2)); // expected-warning@-1{{TRUE}}
+clang_analyzer_eval(clang_analyzer_iterator_position(i3) >=
+clang_analyzer_iterator_position(i2)); // expected-warning@-1{{FALSE}}
+  }
+}
+
+void test_find2(std::vector V, int n) {
+  const auto i1 = return_any_iterator(V.begin());
+  const auto i2 = return_any_iterator(V.begin());
+
+  const auto i3 = std::find(std::execution::sequenced_policy(), i1, i2, n);
+
+  clang_analyzer_eval(i3 == i2); // expected-warning{{TRUE}} expected-warning{{FALSE}}
+
+  if (i3 != i2) {
+clang_analyzer_eval(clang_analyzer_iterator_position(i3) <
+clang_analyzer_iterator_position(i2)); // expected-warning@-1{{TRUE}}
+clang_analyzer_eval(clang_analyzer_iterator_position(i3) >=
+clang_analyzer_iterator_position(i2)); // expected-warning@-1{{FALSE}}
+  }
+}
+
+bool odd(int i) { return i % 2; }
+
+void test_find_if1(std::vector V) {
+  const auto i1 = return_any_iterator(V.begin());
+  const auto i2 = return_any_iterator(V.begin());
+
+  const auto i3 = std::find_if(i1, i2, odd);
+
+  clang_analyzer_eval(i3 == i2); // expected-warning{{TRUE}} expected-warning{{FALSE}}
+
+  if (i3 != i2) {
+clang_analyzer_eval(clang_analyzer_iterator_position(i3) <
+clang_analyzer_iterator_position(i2)); // expected-warning@-1{{TRUE}}
+clang_analyzer_eval(clang_analyzer_iterator_position(i3) >=
+clang_analyzer_iterator_position(i2)); // expected-warning@-1{{FALSE}}
+  }
+}
+
+void test_find_if2(std::vector V) {
+  const auto i1 = return_any_iterator(V.begin());
+  const auto i2 = return_any_iterator(V.begin());
+
+  const auto i3 = std::find_if(std::execution::sequenced_policy(), i1, i2, odd);
+
+  clang_analyzer_eval(i3 == i2); // expected-warning{{TRUE}} expected-warning{{FALSE}}
+
+  if (i3 != i2) {
+clang_analyzer_eval(clang_analyzer_iterator_position(i3) <
+clang_analyzer_iterator_position(i2)); // expected-warning@-1{{TRUE}}
+clang_analyzer_eval(clang_analyzer_iterator_position(i3) >=
+clang_analyzer_iterator_position(i2)); // expected-warning@-1{{FALSE}}
+  }
+}
+
+void test_find_if_not1(std::vector V) {
+  const auto i1 = return_any_iterator(V.begin());
+  const auto i2 = return_any_iterator(V.begin());
+
+  const auto i3 = std::find_if_not(i1, i2, odd);
+
+  clang_analyzer_eval(i3 == i2);

[PATCH] D70819: [ASTImporter] Support functions with placeholder return types ...

2019-11-28 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: balazske, a_sidorin.
Herald added subscribers: cfe-commits, teemperor, gamesh411, Szelethus, dkrupp, 
rnkovacs.
Herald added a reviewer: a.sidorin.
Herald added a reviewer: shafik.
Herald added a project: clang.

Support functions with placeholder return types even in cases when the type is
declared in the body of the function.
Example: auto f() { struct X{}; return X(); }


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70819

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

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -10,9 +10,11 @@
 //
 //===--===//
 
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "llvm/ADT/StringMap.h"
 
 #include "clang/AST/DeclContextInternals.h"
+#include "gtest/gtest.h"
 
 #include "ASTImporterFixtures.h"
 #include "MatchVerifier.h"
@@ -5599,6 +5601,113 @@
 2u);
 }
 
+struct ImportAutoFunctions : ASTImporterOptionSpecificTestBase {};
+
+TEST_P(ImportAutoFunctions, ReturnWithTypedefDeclaredInside) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  auto X = [](long l){
+using int_type = long;
+auto dur = 13;
+return static_cast(dur);
+  };
+  )",
+  Lang_CXX14, "input0.cc");
+  CXXMethodDecl *From =
+  FirstDeclMatcher().match(FromTU, cxxMethodDecl());
+
+  // Explicitly set the return type of the lambda's operator() to the TypeAlias.
+  // Normally the return type would be the built-in 'long' type. However, there
+  // are cases when Clang does not use the canonical type and the TypeAlias is
+  // used. I could not create such an AST from regular source code, it requires
+  // some special state in the preprocessor. I've found such an AST when Clang
+  // parsed libcxx/src/filesystem/directory_iterator.cpp, but could not reduce
+  // that with creduce, because after preprocessing, the AST no longer
+  // contained the TypeAlias as a return type of the lambda.
+  ASTContext &Ctx = From->getASTContext();
+  TypeAliasDecl *FromTA =
+  FirstDeclMatcher().match(FromTU, typeAliasDecl());
+  QualType TT = Ctx.getTypedefType(FromTA);
+  const FunctionProtoType *FPT = cast(From->getType());
+  QualType NewFunType =
+  Ctx.getFunctionType(TT, FPT->getParamTypes(), FPT->getExtProtoInfo());
+  From->setType(NewFunType);
+
+  CXXMethodDecl *To = Import(From, Lang_CXX14);
+  EXPECT_TRUE(To);
+  EXPECT_TRUE(isa(To->getReturnType()));
+}
+
+TEST_P(ImportAutoFunctions, ReturnWithStructDeclaredInside) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  auto foo() {
+struct X {};
+return X();
+  }
+  )",
+  Lang_CXX14, "input0.cc");
+  FunctionDecl *From =
+  FirstDeclMatcher().match(FromTU, functionDecl());
+
+  FunctionDecl *To = Import(From, Lang_CXX14);
+  EXPECT_TRUE(To);
+  EXPECT_TRUE(isa(To->getReturnType()));
+}
+
+TEST_P(ImportAutoFunctions, ReturnWithStructDeclaredInside2) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  auto foo() {
+struct X {};
+return X();
+  }
+  )",
+  Lang_CXX14, "input0.cc");
+  FunctionDecl *From =
+  FirstDeclMatcher().match(FromTU, functionDecl());
+
+  // This time import the type directly.
+  QualType ToT = ImportType(From->getType(), From, Lang_CXX14);
+  const FunctionProtoType *FPT = cast(ToT);
+  EXPECT_TRUE(isa(FPT->getReturnType()));
+}
+
+TEST_P(ImportAutoFunctions, ReturnWithTypedefToStructDeclaredInside) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  auto foo() {
+struct X {};
+using Y = X;
+return Y();
+  }
+  )",
+  Lang_CXX14, "input0.cc");
+  FunctionDecl *From =
+  FirstDeclMatcher().match(FromTU, functionDecl());
+
+  FunctionDecl *To = Import(From, Lang_CXX14);
+  EXPECT_TRUE(To);
+  EXPECT_TRUE(isa(To->getReturnType()));
+}
+
+TEST_P(ImportAutoFunctions, ReturnWithStructDeclaredNestedInside) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  auto foo() {
+struct X { struct Y{}; };
+return X::Y();
+  }
+  )",
+  Lang_CXX14, "input0.cc");
+  FunctionDecl *From =
+  FirstDeclMatcher().match(FromTU, functionDecl());
+
+  FunctionDecl *To = Import(From, Lang_CXX14);
+  EXPECT_TRUE(To);
+  EXPECT_TRUE(isa(To->getReturnType()));
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, ASTImporterLookupTableTest,
 DefaultTestValuesForRunOptions, );
 
@@ -5626,6 +5735,9 @@
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportFunctions,
 DefaultTestValuesForRunOptions, );
 
+INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportAutoFunctions,
+DefaultTestValuesForRunOptions, );
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportFunctionTemplates,
   

[PATCH] D70439: [Analyzer][Docs][NFC] Add CodeChecker to the command line tools

2019-11-28 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

@Szelethus, Kristof thanks for the review.
@NoQ Ping. I'd like to have an approve from somebody who is outside the 
CodeChecker/E/// gang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70439



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


[PATCH] D70808: [mips] Check that features required by built-ins are enabled

2019-11-28 Thread Petar Avramovic via Phabricator via cfe-commits
Petar.Avramovic accepted this revision.
Petar.Avramovic added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70808



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


[PATCH] D70302: [CodeGen] Fix clang crash on aggregate initialization of array of labels

2019-11-28 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

Fix looks good post commit, but we should enhance the test.




Comment at: clang/test/CodeGen/label-array-aggregate-init.c:1
+// RUN: %clang -cc1 -emit-llvm %s -o /dev/null
+

It's best practice to filecheck for something, even if this used to crash.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70302



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


[PATCH] D70605: [OpenCL] Fix address space for implicit conversion (PR43145)

2019-11-28 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh updated this revision to Diff 231426.
svenvh added a comment.

Address comment from @rjmccall to preserve original `ToType` pointer type.


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

https://reviews.llvm.org/D70605

Files:
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/CodeGenOpenCLCXX/addrspace-derived-base.cl


Index: clang/test/CodeGenOpenCLCXX/addrspace-derived-base.cl
===
--- clang/test/CodeGenOpenCLCXX/addrspace-derived-base.cl
+++ clang/test/CodeGenOpenCLCXX/addrspace-derived-base.cl
@@ -69,3 +69,14 @@
   // CHECK: bitcast i8 addrspace(4)* %add.ptr1 to %class.B2 addrspace(4)*
   // CHECK: call {{.*}} @_ZNU3AS42B26getRefEv
 }
+
+// Implicit conversion of derived to base.
+
+void functionWithBaseArgPtr(class B2 *b) {}
+void functionWithBaseArgRef(class B2 &b) {}
+
+void pr43145_4() {
+  Derived d;
+  functionWithBaseArgPtr(&d);
+  functionWithBaseArgRef(d);
+}
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -4095,9 +4095,26 @@
 << From->getSourceRange();
 }
 
+// Defer address space conversion to the third conversion.
+QualType FromPteeType = From->getType()->getPointeeType();
+QualType ToPteeType = ToType->getPointeeType();
+QualType NewToType = ToType;
+if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
+FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
+  NewToType = Context.removeAddrSpaceQualType(ToPteeType);
+  NewToType = Context.getAddrSpaceQualType(NewToType,
+   FromPteeType.getAddressSpace());
+  if (ToType->isObjCObjectPointerType())
+NewToType = Context.getObjCObjectPointerType(NewToType);
+  else if (ToType->isBlockPointerType())
+NewToType = Context.getBlockPointerType(NewToType);
+  else
+NewToType = Context.getPointerType(NewToType);
+}
+
 CastKind Kind;
 CXXCastPath BasePath;
-if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
+if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
   return ExprError();
 
 // Make sure we extend blocks if necessary.
@@ -4108,8 +4125,8 @@
   From = E.get();
 }
 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
-  CheckObjCConversion(SourceRange(), ToType, From, CCK);
-From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
+  CheckObjCConversion(SourceRange(), NewToType, From, CCK);
+From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK)
  .get();
 break;
   }


Index: clang/test/CodeGenOpenCLCXX/addrspace-derived-base.cl
===
--- clang/test/CodeGenOpenCLCXX/addrspace-derived-base.cl
+++ clang/test/CodeGenOpenCLCXX/addrspace-derived-base.cl
@@ -69,3 +69,14 @@
   // CHECK: bitcast i8 addrspace(4)* %add.ptr1 to %class.B2 addrspace(4)*
   // CHECK: call {{.*}} @_ZNU3AS42B26getRefEv
 }
+
+// Implicit conversion of derived to base.
+
+void functionWithBaseArgPtr(class B2 *b) {}
+void functionWithBaseArgRef(class B2 &b) {}
+
+void pr43145_4() {
+  Derived d;
+  functionWithBaseArgPtr(&d);
+  functionWithBaseArgRef(d);
+}
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -4095,9 +4095,26 @@
 << From->getSourceRange();
 }
 
+// Defer address space conversion to the third conversion.
+QualType FromPteeType = From->getType()->getPointeeType();
+QualType ToPteeType = ToType->getPointeeType();
+QualType NewToType = ToType;
+if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
+FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
+  NewToType = Context.removeAddrSpaceQualType(ToPteeType);
+  NewToType = Context.getAddrSpaceQualType(NewToType,
+   FromPteeType.getAddressSpace());
+  if (ToType->isObjCObjectPointerType())
+NewToType = Context.getObjCObjectPointerType(NewToType);
+  else if (ToType->isBlockPointerType())
+NewToType = Context.getBlockPointerType(NewToType);
+  else
+NewToType = Context.getPointerType(NewToType);
+}
+
 CastKind Kind;
 CXXCastPath BasePath;
-if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
+if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
   return ExprError();
 
 // Make sure we extend blocks if necessary.
@@ -4108,8 +4125,8 @@
   From = E.get();
 }
 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
-  CheckObjCConversion(SourceRange(), ToType, From, CCK);
-From = ImpCastExprToType(From, ToType, Ki

[PATCH] D70823: [clang-tidy] Adding cert-pos34-c check

2019-11-28 Thread Zurab Tsinadze via Phabricator via cfe-commits
zukatsinadze created this revision.
zukatsinadze added reviewers: aaron.ballman, alexfh, hokein, Charusso.
zukatsinadze added projects: clang-tools-extra, clang.
Herald added subscribers: cfe-commits, mgehre, xazax.hun, mgorny.

According to
https://wiki.sei.cmu.edu/confluence/display/c/POS34-C.+Do+not+call+putenv%28%29+with+a+pointer+to+an+automatic+variable+as+the+argument
cert-pos34-c check is created. The check warns if `putenv` function is 
called with automatic storage variable as an argument.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D70823

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/clang-tidy/cert/CMakeLists.txt
  clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.cpp
  clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-pos34-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/cert-pos34-c.cpp

Index: clang-tools-extra/test/clang-tidy/cert-pos34-c.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/cert-pos34-c.cpp
@@ -0,0 +1,64 @@
+// RUN: %check_clang_tidy %s cert-pos34-c %t
+#include 
+#include 
+
+namespace test_auto_var_used_bad {
+
+int func1(const char *var) {
+  char env[1024];
+  /*
+  Do Something
+  */
+  return putenv(env);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: 'putenv' function should not be called with auto variables [cert-pos34-c]
+}
+
+int func2(char* a){
+  return putenv(a);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: 'putenv' function should not be called with auto variables [cert-pos34-c]
+}
+
+
+void func3(char* a){
+  putenv(a);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'putenv' function should not be called with auto variables [cert-pos34-c]
+}
+
+} // namespace test_auto_var_used_bad
+
+namespace test_auto_var_used_good {
+
+int func4(const char *var) {
+  static char env[1024];
+  /*
+  Do Something
+  */
+  return putenv(env); // no-warning: env is static.
+}
+
+// example from cert
+int func5(const char *var) {
+  static char *oldenv;
+  const char *env_format = "TEST=%s";
+  const size_t len = strlen(var) + strlen(env_format);
+  char *env = (char *) malloc(len);
+  if (env == NULL) {
+return -1;
+  }
+  if (putenv(env) != 0) { // no-warning: env was dynamically allocated.
+free(env);
+return -1;
+  }
+  if (oldenv != NULL) {
+free(oldenv); /* avoid memory leak */
+  }
+  oldenv = env;
+  return 0;
+}
+
+extern char* testExt;
+int func6(){
+  return putenv(testExt); // no-warning: extern storage class.
+}
+
+} // namespace test_auto_var_used_good
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -102,6 +102,7 @@
cert-msc51-cpp
cert-oop11-cpp (redirects to performance-move-constructor-init) 
cert-oop54-cpp (redirects to bugprone-unhandled-self-assignment) 
+   cert-pos34-c
cppcoreguidelines-avoid-c-arrays (redirects to modernize-avoid-c-arrays) 
cppcoreguidelines-avoid-goto
cppcoreguidelines-avoid-magic-numbers (redirects to readability-magic-numbers) 
Index: clang-tools-extra/docs/clang-tidy/checks/cert-pos34-c.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cert-pos34-c.rst
@@ -0,0 +1,25 @@
+.. title:: clang-tidy - cert-pos34-c
+
+cert-pos34-c
+=
+
+Finds calls of ``putenv`` function with automatic variable as the argument.
+
+.. code-block:: c
+
+  #include 
+
+  int func(const char *var) {
+char env[1024];
+int retval = snprintf(env, sizeof(env),"TEST=%s", var);
+if (retval < 0 || (size_t)retval >= sizeof(env)) {
+/* Handle error */
+}
+ 
+return putenv(env); // putenv function should not be called with auto variables
+  }
+
+
+This check corresponds to the CERT Standard rule 
+`POS34-C. Do not call putenv() with a pointer to an automatic variable as the argument.
+`_.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -194,6 +194,11 @@
   against self-assignment either by checking self-assignment explicitly or
   using the copy-and-swap or the copy-and-move method.
 
+- New :doc:`cert-pos34-c
+  ` check.
+
+  Finds calls of 'putenv' function with automatic variable as the argument.
+
 - New :doc:`fuchsia-default-arguments-calls
   ` check.
 
Index: clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.h

[PATCH] D70820: [OpenMP][test] Fix test on MIPS-based buildbots

2019-11-28 Thread Miloš Stojanović via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGed864745c97e: [OpenMP][test] Fix test on MIPS-based 
buildbots (authored by mstojanovic).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70820

Files:
  clang/test/OpenMP/parallel_codegen.cpp


Index: clang/test/OpenMP/parallel_codegen.cpp
===
--- clang/test/OpenMP/parallel_codegen.cpp
+++ clang/test/OpenMP/parallel_codegen.cpp
@@ -109,7 +109,7 @@
 // CHECK-DEBUG-NEXT:  ret i32 0
 // CHECK-DEBUG-NEXT:  }
 
-// CHECK:   define internal {{.*}}void [[OMP_OUTLINED]](i32* noalias 
%.global_tid., i32* noalias %.bound_tid., i8*** dereferenceable({{4|8}}) %argc, 
i{{64|32}} %{{.+}})
+// CHECK:   define internal {{.*}}void [[OMP_OUTLINED]](i32* noalias 
%.global_tid., i32* noalias %.bound_tid., i8*** dereferenceable({{4|8}}) %argc, 
i{{64|32}}{{.*}} %{{.+}})
 // CHECK:   store i8*** %argc, i8 [[ARGC_PTR_ADDR:%.+]],
 // CHECK:   [[ARGC_REF:%.+]] = load i8***, i8 [[ARGC_PTR_ADDR]]
 // CHECK:   [[ARGC:%.+]] = load i8**, i8*** [[ARGC_REF]]


Index: clang/test/OpenMP/parallel_codegen.cpp
===
--- clang/test/OpenMP/parallel_codegen.cpp
+++ clang/test/OpenMP/parallel_codegen.cpp
@@ -109,7 +109,7 @@
 // CHECK-DEBUG-NEXT:  ret i32 0
 // CHECK-DEBUG-NEXT:  }
 
-// CHECK:   define internal {{.*}}void [[OMP_OUTLINED]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i8*** dereferenceable({{4|8}}) %argc, i{{64|32}} %{{.+}})
+// CHECK:   define internal {{.*}}void [[OMP_OUTLINED]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i8*** dereferenceable({{4|8}}) %argc, i{{64|32}}{{.*}} %{{.+}})
 // CHECK:   store i8*** %argc, i8 [[ARGC_PTR_ADDR:%.+]],
 // CHECK:   [[ARGC_REF:%.+]] = load i8***, i8 [[ARGC_PTR_ADDR]]
 // CHECK:   [[ARGC:%.+]] = load i8**, i8*** [[ARGC_REF]]
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D69948: [Checkers] Added support for freopen to StreamChecker.

2019-11-28 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/test/Analysis/stream.c:160
+} else {
+  // Open failed, f1 points now to an invalid stream but this condition is 
currently not checked.
+  rewind(f1);

This comment is confusing for me. Maybe there are typos here?
Isn't the 'freopen' failed? `fopen` was successful and it's return value was 
checked in line 153.
`f1` seems to be ok here (still associated with "foo.c"), only `f2` is bad, as 
we see in line 162.

Or `f1` is already closed here, even though it could not open the new file?


> If a new filename is specified, the function first attempts to close any file 
> already associated with stream (third parameter) and disassociates it. Then, 
> independently of whether that stream was successfuly closed or not, freopen 
> opens the file specified by filename and associates it with the stream just 
> as fopen would do using the specified mode.

https://stackoverflow.com/questions/20908740/check-the-return-value-of-freopen-in-c



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69948



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


[PATCH] D70828: [clangd] Correct the file path in Edit::replacements when generating the rename edit.

2019-11-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ilya-biryukov.
Herald added subscribers: usaxena95, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

The file path was set to the file content previously, and it isn't
covered by normal clangd & unittest code path (as we only uses the
offset, length, replacement text).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70828

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/refactor/Rename.h
  clang-tools-extra/clangd/unittests/RenameTests.cpp


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -669,14 +669,16 @@
 TEST(CrossFileRenameTests, BuildRenameEdits) {
   Annotations Code("[[😂]]");
   auto LSPRange = Code.range();
-  auto Edit = buildRenameEdit(Code.code(), {LSPRange}, "abc");
+  llvm::StringRef FilePath = "/test/TestTU.cpp";
+  auto Edit = buildRenameEdit(FilePath, Code.code(), {LSPRange}, "abc");
   ASSERT_TRUE(bool(Edit)) << Edit.takeError();
   ASSERT_EQ(1UL, Edit->Replacements.size());
+  EXPECT_EQ(FilePath, Edit->Replacements.begin()->getFilePath());
   EXPECT_EQ(4UL, Edit->Replacements.begin()->getLength());
 
   // Test invalid range.
   LSPRange.end = {10, 0}; // out of range
-  Edit = buildRenameEdit(Code.code(), {LSPRange}, "abc");
+  Edit = buildRenameEdit(FilePath, Code.code(), {LSPRange}, "abc");
   EXPECT_FALSE(Edit);
   EXPECT_THAT(llvm::toString(Edit.takeError()),
   testing::HasSubstr("fail to convert"));
@@ -687,7 +689,7 @@
   [[range]]
   [[range]]
   )cpp");
-  Edit = buildRenameEdit(T.code(), T.ranges(), "abc");
+  Edit = buildRenameEdit(FilePath, T.code(), T.ranges(), "abc");
   ASSERT_TRUE(bool(Edit)) << Edit.takeError();
   EXPECT_EQ(applyEdits(FileEdits{{T.code(), std::move(*Edit)}}).front().second,
 expectedResult(Code, expectedResult(T, "abc")));
Index: clang-tools-extra/clangd/refactor/Rename.h
===
--- clang-tools-extra/clangd/refactor/Rename.h
+++ clang-tools-extra/clangd/refactor/Rename.h
@@ -50,7 +50,8 @@
 /// Generates rename edits that replaces all given occurrences with the
 /// NewName.
 /// Exposed for testing only.
-llvm::Expected buildRenameEdit(llvm::StringRef InitialCode,
+llvm::Expected buildRenameEdit(llvm::StringRef AbsFilePath,
+ llvm::StringRef InitialCode,
  std::vector Occurrences,
  llvm::StringRef NewName);
 
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -349,8 +349,9 @@
   elog("Fail to read file content: {0}", AffectedFileCode.takeError());
   continue;
 }
-auto RenameEdit = buildRenameEdit(
-*AffectedFileCode, std::move(FileAndOccurrences.second), NewName);
+auto RenameEdit =
+buildRenameEdit(FilePath, *AffectedFileCode,
+std::move(FileAndOccurrences.second), NewName);
 if (!RenameEdit) {
   return llvm::make_error(
   llvm::formatv("fail to build rename edit for file {0}: {1}", 
FilePath,
@@ -451,7 +452,8 @@
   return Results;
 }
 
-llvm::Expected buildRenameEdit(llvm::StringRef InitialCode,
+llvm::Expected buildRenameEdit(llvm::StringRef AbsFilePath,
+ llvm::StringRef InitialCode,
  std::vector Occurrences,
  llvm::StringRef NewName) {
   llvm::sort(Occurrences);
@@ -491,7 +493,7 @@
   for (const auto &R : OccurrencesOffsets) {
 auto ByteLength = R.second - R.first;
 if (auto Err = RenameEdit.add(
-tooling::Replacement(InitialCode, R.first, ByteLength, NewName)))
+tooling::Replacement(AbsFilePath, R.first, ByteLength, NewName)))
   return std::move(Err);
   }
   return Edit(InitialCode, std::move(RenameEdit));


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -669,14 +669,16 @@
 TEST(CrossFileRenameTests, BuildRenameEdits) {
   Annotations Code("[[😂]]");
   auto LSPRange = Code.range();
-  auto Edit = buildRenameEdit(Code.code(), {LSPRange}, "abc");
+  llvm::StringRef FilePath = "/test/TestTU.cpp";
+  auto Edit = buildRenameEdit(FilePath, Code.code(), {LSPRange}, "abc");
   ASSERT_TRUE(bool(Edit)) << Edit.takeError();
   ASSERT_EQ(1UL, Edit->Replacements.size());
+  EXPECT_EQ(FilePath, Edit->Replacements.begin()->getFilePath());
   EXPECT_EQ(4UL, Edit->Re

[PATCH] D70320: [Analyzer] [NFC] Iterator Checkers - Separate iterator modeling and the actual checkers

2019-11-28 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware marked 2 inline comments as done.
baloghadamsoftware added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:1308-1318
+ProgramStateRef removeIteratorPosition(ProgramStateRef State, const SVal &Val) 
{
   if (auto Reg = Val.getAsRegion()) {
 Reg = Reg->getMostDerivedObjectRegion();
-return State->get(Reg);
+return State->remove(Reg);
   } else if (const auto Sym = Val.getAsSymbol()) {
-return State->get(Sym);
+return State->remove(Sym);
   } else if (const auto LCVal = Val.getAs()) {

baloghadamsoftware wrote:
> Charusso wrote:
> > baloghadamsoftware wrote:
> > > NoQ wrote:
> > > > Maybe move this function to `Iterator.cpp` as well, and then move the 
> > > > definitions for iterator maps from `Iterator.h` to `Iterator.cpp`, 
> > > > which will allow you to use the usual `REGISTER_MAP_WITH_PROGRAMSTATE` 
> > > > macros, and additionally guarantee that all access to the maps goes 
> > > > through the accessor methods that you provide?
> > > Hmm, I was trying hard to use these macros but failed so I reverted to 
> > > the manual solution. I will retry now.
> > Here is a how-to: https://reviews.llvm.org/D69726
> > 
> > You need to add the fully qualified names to the register macro because of 
> > the global scope. I hope it helps.
> OK, I checked it now. If we want to put the maps into `Iterator.cpp` then we 
> also have to move a couple of functions there which are only used by the 
> modeling part: the internals of `checkDeadSymbols()` and `checkLiveSymbols()` 
> must go there, although no other checker should use them. Also 
> `processIteratorPositions()` iterates over these maps, thus it must also go 
> there. Should I do it? Generally I like the current solution better, only 
> functions used by multiple checker classes are in the library.
> 
> On the other hand I do not see why I should move `assumeNoOverflow()` to 
> `Iterator.cpp`? This function is only used by the modeling part, and does not 
> refer to the maps. You mean that we should ensure this constraint whenever 
> setting the position for any iterator? This would mean that we should 
> decompose every symblic expression and (re)assume this range on the symbolic 
> part. Or we should replace `setPosition()` by at least two different 
> functions (e.g. `setAdvancedPosition()` and `setConjuredPosition()`) but this 
> means a total reqriting of the modeling.
> 
> I plan some refactoring but this first patch is meant to be a single 
> separation of code.
@Charusso It does not help because the macros put the maps into a local 
namespace. If it is in a header, it means separate maps for every checker and 
the modeling which of course does not work.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:1308-1318
+ProgramStateRef removeIteratorPosition(ProgramStateRef State, const SVal &Val) 
{
   if (auto Reg = Val.getAsRegion()) {
 Reg = Reg->getMostDerivedObjectRegion();
-return State->get(Reg);
+return State->remove(Reg);
   } else if (const auto Sym = Val.getAsSymbol()) {
-return State->get(Sym);
+return State->remove(Sym);
   } else if (const auto LCVal = Val.getAs()) {

baloghadamsoftware wrote:
> baloghadamsoftware wrote:
> > Charusso wrote:
> > > baloghadamsoftware wrote:
> > > > NoQ wrote:
> > > > > Maybe move this function to `Iterator.cpp` as well, and then move the 
> > > > > definitions for iterator maps from `Iterator.h` to `Iterator.cpp`, 
> > > > > which will allow you to use the usual 
> > > > > `REGISTER_MAP_WITH_PROGRAMSTATE` macros, and additionally guarantee 
> > > > > that all access to the maps goes through the accessor methods that 
> > > > > you provide?
> > > > Hmm, I was trying hard to use these macros but failed so I reverted to 
> > > > the manual solution. I will retry now.
> > > Here is a how-to: https://reviews.llvm.org/D69726
> > > 
> > > You need to add the fully qualified names to the register macro because 
> > > of the global scope. I hope it helps.
> > OK, I checked it now. If we want to put the maps into `Iterator.cpp` then 
> > we also have to move a couple of functions there which are only used by the 
> > modeling part: the internals of `checkDeadSymbols()` and 
> > `checkLiveSymbols()` must go there, although no other checker should use 
> > them. Also `processIteratorPositions()` iterates over these maps, thus it 
> > must also go there. Should I do it? Generally I like the current solution 
> > better, only functions used by multiple checker classes are in the library.
> > 
> > On the other hand I do not see why I should move `assumeNoOverflow()` to 
> > `Iterator.cpp`? This function is only used by the modeling part, and does 
> > not refer to the maps. You mean that we should ensure this constraint 
> > whenever setting the position for any iterator? This would mean that we 
> > should decompose every symblic expression and (re)ass

[PATCH] D70244: [Analyzer] Iterator Checkers: Replace `UnknownVal` in comparison result by a conjured value

2019-11-28 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

@NoQ, @Szelethus What about this patch? It is an essential bugfix.


Repository:
  rC Clang

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

https://reviews.llvm.org/D70244



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


[PATCH] D68682: format::cleanupAroundReplacements removes whole line when Removals leave previously non-blank line blank

2019-11-28 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: clang/include/clang/Basic/CharInfo.h:94
+LLVM_READONLY inline bool isWhitespace(llvm::StringRef S) {
+  for (StringRef::const_iterator I = S.begin(), E = S.end(); I != E; ++I) {
+if (!isWhitespace(*I))

I'd suggest to avoid overloading here. A name like `isWhitespaceOnly` would be 
less ambiguous.

As for implementation, it can be less verbose:
```
for (char C : S)
  if (!isWhitespace(*I))
return false;
return true;
```
or just
```
return llvm::all_of(S, isWhitespace);
```



Comment at: clang/lib/AST/CommentParser.cpp:19
 
-static inline bool isWhitespace(llvm::StringRef S) {
+// Consider moving this useful function to a more general utility location.
+bool isWhitespace(llvm::StringRef S) {

poelmanc wrote:
> kadircet wrote:
> > poelmanc wrote:
> > > gribozavr2 wrote:
> > > > clang/include/clang/Basic/CharInfo.h ?
> > > Done. I renamed it to `isWhitespaceStringRef` to avoid making it an 
> > > overload of the existing `isWhitespace(unsigned char)`, which causes 
> > > ambiguous overload errors at QueryParser.cpp:42 & CommentSema.cpp:237.
> > > 
> > > We could alternatively keep this as an `isWhitespace` overload and 
> > > instead change those two lines to use a `static_cast > > char)>(&clang::isWhitespace)` or precede them with a line like:
> > > ```
> > > bool (*isWhitespaceOverload)(unsigned char) = &clang::isWhitespace;
> > > ```
> > ah that's unfortunate, I believe it makes sense to have this as an overload 
> > though.
> > 
> > Could you instead make the predicate explicit by putting
> > ```[](char c) { return clang::isWhitespace(c); }```
> > instead of just `clang::isWhitespace` in those call sites?
> Excellent! Better than the two ideas I thought of. Thanks!
I'd like to draw your attention that `isWhitespace(StringRef)` is somewhat 
ambiguous. What exactly does it check? That the string is exactly one 
whitespace character? That it contains a whitespace? That it's only contains 
whitespace? Maybe `isWhitespaceOnly`? See also the comment in CharInfo.h.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D68682



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


[PATCH] D70638: [Diagnostic] add a warning which warns about misleading indentation

2019-11-28 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 reopened this revision.
xbolva00 added a subscriber: tstellar.
xbolva00 added a comment.
This revision is now accepted and ready to land.

@tstellar reverted this change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70638



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


[PATCH] D70829: [ARM][MVE][Intrinsics] Add VMINQ/VMAXQ/VMINNMQ/VMAXNMQ intrinsics.

2019-11-28 Thread Mark Murray via Phabricator via cfe-commits
MarkMurrayARM created this revision.
Herald added subscribers: llvm-commits, cfe-commits, dmgreen, hiraditya, 
kristof.beyls.
Herald added projects: clang, LLVM.

Add VMINQ/VMAXQ/VMINNMQ/VMAXNMQ intrinsics and their predicated versions. Add 
unit tests.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70829

Files:
  clang/include/clang/Basic/arm_mve.td
  clang/include/clang/Basic/arm_mve_defs.td
  clang/test/CodeGen/arm-mve-intrinsics/vmaxnmq.c
  clang/test/CodeGen/arm-mve-intrinsics/vmaxq.c
  clang/test/CodeGen/arm-mve-intrinsics/vminnmq.c
  clang/test/CodeGen/arm-mve-intrinsics/vminq.c
  llvm/include/llvm/IR/IntrinsicsARM.td
  llvm/lib/Target/ARM/ARMInstrMVE.td
  llvm/test/CodeGen/Thumb2/mve-intrinsics/vmaxnmq.ll
  llvm/test/CodeGen/Thumb2/mve-intrinsics/vmaxq.ll
  llvm/test/CodeGen/Thumb2/mve-intrinsics/vminnmq.ll
  llvm/test/CodeGen/Thumb2/mve-intrinsics/vminq.ll

Index: llvm/test/CodeGen/Thumb2/mve-intrinsics/vminq.ll
===
--- /dev/null
+++ llvm/test/CodeGen/Thumb2/mve-intrinsics/vminq.ll
@@ -0,0 +1,89 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mtriple=thumbv8.1m.main -mattr=+mve.fp -verify-machineinstrs -o - %s | FileCheck %s
+
+define dso_local arm_aapcs_vfpcc <16 x i8> @test_vminq_u8(<16 x i8> %a, <16 x i8> %b) local_unnamed_addr #0 {
+; CHECK-LABEL: test_vminq_u8:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmin.u8 q0, q0, q1
+; CHECK-NEXT:bx lr
+entry:
+  %0 = icmp ugt <16 x i8> %a, %b
+  %1 = select <16 x i1> %0, <16 x i8> %b, <16 x i8> %a
+  ret <16 x i8> %1
+}
+
+define dso_local arm_aapcs_vfpcc <8 x i16> @test_vminq_s16(<8 x i16> %a, <8 x i16> %b) local_unnamed_addr #0 {
+; CHECK-LABEL: test_vminq_s16:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmin.s16 q0, q0, q1
+; CHECK-NEXT:bx lr
+entry:
+  %0 = icmp sgt <8 x i16> %a, %b
+  %1 = select <8 x i1> %0, <8 x i16> %b, <8 x i16> %a
+  ret <8 x i16> %1
+}
+
+define dso_local arm_aapcs_vfpcc <4 x i32> @test_vminq_u32(<4 x i32> %a, <4 x i32> %b) local_unnamed_addr #0 {
+; CHECK-LABEL: test_vminq_u32:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmin.u32 q0, q0, q1
+; CHECK-NEXT:bx lr
+entry:
+  %0 = icmp ugt <4 x i32> %a, %b
+  %1 = select <4 x i1> %0, <4 x i32> %b, <4 x i32> %a
+  ret <4 x i32> %1
+}
+
+define dso_local arm_aapcs_vfpcc <16 x i8> @test_vminq_m_s8(<16 x i8> %inactive, <16 x i8> %a, <16 x i8> %b, i16 zeroext %p) local_unnamed_addr #1 {
+; CHECK-LABEL: test_vminq_m_s8:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmsr p0, r0
+; CHECK-NEXT:vpst
+; CHECK-NEXT:vmint.s8 q0, q1, q2
+; CHECK-NEXT:bx lr
+entry:
+  %0 = zext i16 %p to i32
+  %1 = tail call <16 x i1> @llvm.arm.mve.pred.i2v.v16i1(i32 %0)
+  %2 = tail call <16 x i8> @llvm.arm.mve.min.predicated.v16i8.v16i1(<16 x i8> %a, <16 x i8> %b, <16 x i1> %1, <16 x i8> %inactive)
+  ret <16 x i8> %2
+}
+
+declare <16 x i1> @llvm.arm.mve.pred.i2v.v16i1(i32) #2
+
+declare <16 x i8> @llvm.arm.mve.min.predicated.v16i8.v16i1(<16 x i8>, <16 x i8>, <16 x i1>, <16 x i8>) #2
+
+define dso_local arm_aapcs_vfpcc <8 x i16> @test_vminq_m_u16(<8 x i16> %inactive, <8 x i16> %a, <8 x i16> %b, i16 zeroext %p) local_unnamed_addr #1 {
+; CHECK-LABEL: test_vminq_m_u16:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmsr p0, r0
+; CHECK-NEXT:vpst
+; CHECK-NEXT:vmint.s16 q0, q1, q2
+; CHECK-NEXT:bx lr
+entry:
+  %0 = zext i16 %p to i32
+  %1 = tail call <8 x i1> @llvm.arm.mve.pred.i2v.v8i1(i32 %0)
+  %2 = tail call <8 x i16> @llvm.arm.mve.min.predicated.v8i16.v8i1(<8 x i16> %a, <8 x i16> %b, <8 x i1> %1, <8 x i16> %inactive)
+  ret <8 x i16> %2
+}
+
+declare <8 x i1> @llvm.arm.mve.pred.i2v.v8i1(i32) #2
+
+declare <8 x i16> @llvm.arm.mve.min.predicated.v8i16.v8i1(<8 x i16>, <8 x i16>, <8 x i1>, <8 x i16>) #2
+
+define dso_local arm_aapcs_vfpcc <4 x i32> @test_vminq_m_s32(<4 x i32> %inactive, <4 x i32> %a, <4 x i32> %b, i16 zeroext %p) local_unnamed_addr #1 {
+; CHECK-LABEL: test_vminq_m_s32:
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vmsr p0, r0
+; CHECK-NEXT:vpst
+; CHECK-NEXT:vmint.s32 q0, q1, q2
+; CHECK-NEXT:bx lr
+entry:
+  %0 = zext i16 %p to i32
+  %1 = tail call <4 x i1> @llvm.arm.mve.pred.i2v.v4i1(i32 %0)
+  %2 = tail call <4 x i32> @llvm.arm.mve.min.predicated.v4i32.v4i1(<4 x i32> %a, <4 x i32> %b, <4 x i1> %1, <4 x i32> %inactive)
+  ret <4 x i32> %2
+}
+
+declare <4 x i1> @llvm.arm.mve.pred.i2v.v4i1(i32) #2
+
+declare <4 x i32> @llvm.arm.mve.min.predicated.v4i32.v4i1(<4 x i32>, <4 x i32>, <4 x i1>, <4 x i32>) #2
Index: llvm/test/CodeGen/Thumb2/mve-intrinsics/vminnmq.ll
===
--- /dev/null
+++ llvm/test/CodeGen/Thumb2/mve-intrinsics/vminnmq.ll
@@ -0,0 +1,62 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mtriple=thumbv8.1m.main -mattr=+mve.fp -verify-machineinstrs -o - %s 

[PATCH] D61446: Generalize the pass registration mechanism used by Polly to any third-party tool

2019-11-28 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

@Alouest thanks for the reproducer. I confirm your issue, and also confirm that 
if you pass `-fexperimental-new-pass-manager -O1` to clang (i.e. use the new 
pass manager) it works fine. As far as I can tell, the segfault happens because 
`RegisterPass` also register the pass to the FunctionPassManager. Can you 
confirm it's orthogonal to that patch, i.e. it's a legacy PM issue ?

Basically runModule is called with a Function as first parameter and it's 
obviously a bad idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61446



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


[PATCH] D70823: [clang-tidy] Adding cert-pos34-c check

2019-11-28 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:200
+
+  Finds calls of 'putenv' function with automatic variable as the argument.
+

Please use double back-ticks to highlight putenv.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D70823



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


[PATCH] D70828: [clangd] Correct the file path in Edit::replacements when generating the rename edit.

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

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70828



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


[PATCH] D70823: [clang-tidy] Adding cert-pos34-c check

2019-11-28 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso added inline comments.



Comment at: clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.cpp:28
+  unless(hasDescendant(callExpr(callee(functionDecl(hasAnyName(
+  "::alloc", "::malloc", "::realloc", "::calloc")))
+  .bind("func"),

`alloc` -> `alloca`



Comment at: clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.cpp:34
+void PutenvWithAutoCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *MatchedDecl = Result.Nodes.getNodeAs("func");
+

It is not a `Decl`, but a `CallExpr`, maybe use `PutenvCall`?



Comment at: clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.h:19
+/// Finds calls of putenv function with automatic variable as the argument.
+
+///

Extra space.



Comment at: clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.h:36
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CERT_PUTENV_WITH_AUTO_H
\ No newline at end of file


No new-line.



Comment at: clang-tools-extra/test/clang-tidy/cert-pos34-c.cpp:59
+
+extern char* testExt;
+int func6(){

`clang-format`?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D70823



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


[PATCH] D70829: [ARM][MVE][Intrinsics] Add VMINQ/VMAXQ/VMINNMQ/VMAXNMQ intrinsics.

2019-11-28 Thread Dave Green via Phabricator via cfe-commits
dmgreen added inline comments.



Comment at: llvm/test/CodeGen/Thumb2/mve-intrinsics/vmaxnmq.ll:7
+; CHECK:   @ %bb.0: @ %entry
+; CHECK-NEXT:vcmp.f16 ge, q0, q1
+; CHECK-NEXT:vpsel q0, q0, q1

You may want to use llvm.minnum directly (providing the semantics are indeed 
equivalent). Otherwise it will need fastmath to fuse these together, which 
isn't the same as the original intrinsic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70829



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


[PATCH] D70804: [Frontend] Allow OpenMP offloading to aarch64

2019-11-28 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70804



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


[PATCH] D61446: Generalize the pass registration mechanism used by Polly to any third-party tool

2019-11-28 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

@Meinersbur I have a strange symbol issue when activating the GPu part: 
https://github.com/serge-sans-paille/llvm-project/pull/2/checks?check_run_id=324901896#step:5:4888
Any hint?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61446



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


[PATCH] D70799: [OpenMP] Lower taskyield using OpenMP IR Builder

2019-11-28 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a subscriber: fghanim.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LGTM.

@fghanim started a spreadsheet to coordinate our work:

https://docs.google.com/spreadsheets/d/1FvHPuSkGbl4mQZRAwCIndvQx9dQboffiD-xD0oqxgU0/edit?usp=sharing

Feel free to add directives there that you plan to work on.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70799



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


[PATCH] D70832: [clangd] Log cc1 args at verbose level.

2019-11-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kbobyrev.
Herald added subscribers: cfe-commits, usaxena95, kadircet, arphaman, jkorous, 
MaskRay, javed.absar, ilya-biryukov.
Herald added a project: clang.

This will help debugging driver issues.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70832

Files:
  clang-tools-extra/clangd/Compiler.cpp
  clang-tools-extra/clangd/Compiler.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang/include/clang/Frontend/Utils.h
  clang/lib/Frontend/CreateInvocationFromCommandLine.cpp

Index: clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
===
--- clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -26,7 +26,8 @@
 
 std::unique_ptr clang::createInvocationFromCommandLine(
 ArrayRef ArgList, IntrusiveRefCntPtr Diags,
-IntrusiveRefCntPtr VFS, bool ShouldRecoverOnErorrs) {
+IntrusiveRefCntPtr VFS, bool ShouldRecoverOnErorrs,
+std::vector *CC1Args) {
   if (!Diags.get()) {
 // No diagnostics engine was provided, so create our own diagnostics object
 // with the default options.
@@ -89,6 +90,8 @@
   }
 
   const ArgStringList &CCArgs = Cmd.getArguments();
+  if (CC1Args)
+*CC1Args = {CCArgs.begin(), CCArgs.end()};
   auto CI = std::make_unique();
   if (!CompilerInvocation::CreateFromArgs(*CI, CCArgs, *Diags) &&
   !ShouldRecoverOnErorrs)
Index: clang/include/clang/Frontend/Utils.h
===
--- clang/include/clang/Frontend/Utils.h
+++ clang/include/clang/Frontend/Utils.h
@@ -217,14 +217,18 @@
 /// non-null (and possibly incorrect) CompilerInvocation if any errors were
 /// encountered. When this flag is false, always return null on errors.
 ///
-/// \return A CompilerInvocation, or 0 if none was built for the given
+/// \param CC1Args - if non-null, will be populated with the args to cc1
+/// expanded from \p Args. May be set even if nullptr is returned.
+///
+/// \return A CompilerInvocation, or nullptr if none was built for the given
 /// argument vector.
 std::unique_ptr createInvocationFromCommandLine(
 ArrayRef Args,
 IntrusiveRefCntPtr Diags =
 IntrusiveRefCntPtr(),
 IntrusiveRefCntPtr VFS = nullptr,
-bool ShouldRecoverOnErrors = false);
+bool ShouldRecoverOnErrors = false,
+std::vector *CC1Args = nullptr);
 
 /// Return the value of the last argument as an integer, or a default. If Diags
 /// is non-null, emits an error if the argument is given, but non-integral.
Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -407,8 +407,12 @@
 llvm::join(Inputs.CompileCommand.CommandLine, " "));
 // Rebuild the preamble and the AST.
 StoreDiags CompilerInvocationDiagConsumer;
+std::vector CC1Args;
 std::unique_ptr Invocation =
 buildCompilerInvocation(Inputs, CompilerInvocationDiagConsumer);
+// Log cc1 args even (especially!) if creating invocation failed.
+if (!CC1Args.empty())
+  vlog("cc1 args: {0}", llvm::join(CC1Args, " "));
 std::vector CompilerInvocationDiags =
 CompilerInvocationDiagConsumer.take();
 if (!Invocation) {
Index: clang-tools-extra/clangd/Compiler.h
===
--- clang-tools-extra/clangd/Compiler.h
+++ clang-tools-extra/clangd/Compiler.h
@@ -68,7 +68,8 @@
 std::unique_ptr prepareCompilerInstance(
 std::unique_ptr, const PrecompiledPreamble *,
 std::unique_ptr MainFile,
-IntrusiveRefCntPtr, DiagnosticConsumer &);
+IntrusiveRefCntPtr, DiagnosticConsumer &,
+std::vector *CC1Args = nullptr);
 
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/Compiler.cpp
===
--- clang-tools-extra/clangd/Compiler.cpp
+++ clang-tools-extra/clangd/Compiler.cpp
@@ -42,7 +42,8 @@
 
 std::unique_ptr
 buildCompilerInvocation(const ParseInputs &Inputs,
-clang::DiagnosticConsumer &D) {
+clang::DiagnosticConsumer &D,
+std::vector *CC1Args) {
   std::vector ArgStrs;
   for (const auto &S : Inputs.CompileCommand.CommandLine)
 ArgStrs.push_back(S.c_str());
@@ -57,7 +58,7 @@
   CompilerInstance::createDiagnostics(new DiagnosticOptions, &D, false);
   std::unique_ptr CI = createInvocationFromCommandLine(
   ArgStrs, CommandLineDiagsEngine, Inputs.FS,
-  /*ShouldRecoverOnErrors=*/true);
+  /*ShouldRecoverOnErrors=*/true, CC1Args);
   if (!CI)
 return nullptr;
   // createInvocationFromCommandLine sets DisableFree.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cg

[PATCH] D70804: [Frontend] Allow OpenMP offloading to aarch64

2019-11-28 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev requested changes to this revision.
ABataev added a comment.
This revision now requires changes to proceed.

Tests are required


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70804



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


[PATCH] D69922: [OpenMP] Use the OpenMP-IR-Builder

2019-11-28 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert marked 3 inline comments as done.
jdoerfert added a comment.

In D69922#1742392 , @ABataev wrote:

> In D69922#1741659 , @jdoerfert wrote:
>
> > Use IRBuilder for cancel barriers
>
>
> In general, it would better to implement cancellation barriers in the 
> separate patch.  Same for OpenMPIrBuilder.


Why would you think that splitting these closely related concepts would be 
beneficial?

In D69922#1751827 , @kiranchandramohan 
wrote:

> Thanks @jdoerfert for working on this.
>
> Sorry for being late to the party. I am trying to implement one trivial 
> directive (Flush) and one slightly more involved (not decided).
>
> I applied D69853 , D69785 
> , D69922  
> to my local build and found that D69922  is 
> referring to OpenMPIRBuilder.h in llvm/Frontend whereas in D69785 
>  it was introduced in 
> llvm/Transforms/Utils/OpenMPIRBuilder.h


The conversation (on the llvm-dev list) seems to have settled on 
`{include/llvm,lib}/frontend/OpenMP/`. I will move the files around once we 
finally settle these reviews that haven't moved (more than 2 comments at a 
time).
As you can see, I have a huge backlog here and that is really hard to modify. 
You have a problem now as you depend on these. @hfinkel mentioned it in his 
email to the llvm-dev (about review etiquette), we need to
minimize iterations in reviews and actually review patches not only a few lines 
every time.




Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:3492
+  CGF.createBasicBlock(".cancel.exit", IP.getBlock()->getParent());
+  OMPBuilder->setCancellationBlock(ExitBB);
+  CGF.Builder.SetInsertPoint(ExitBB);

ABataev wrote:
> Maybe, instead of saving the state, pass the pointer to the cancel block as a 
> parameter to the `CreateBarrier` function?
All of this goes away in D70258, as it should. The frontend when creating a 
barrier does not need to know if it is cancelable and if so, where the cancel 
block is.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69922



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


[PATCH] D70832: [clangd] Log cc1 args at verbose level.

2019-11-28 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: FAILURE - 
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70832



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


[PATCH] D69785: [OpenMP] Introduce the OpenMP-IR-Builder

2019-11-28 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert marked an inline comment as done.
jdoerfert added a comment.

In D69785#1762438 , @JonChesterfield 
wrote:

> I'd very much like this to land soon. It's the prereq for a lot of other 
> patches and the code looks good.
>
> It's tricky to test the infra before the users are landed so the unit test is 
> particularly appreciated.


I'm confused. Was this a review? I'm waiting for a decision here so we can move 
on and improve on this instead of me modifying it inp-lace two comments at a 
time.




Comment at: llvm/include/llvm/Frontend/OpenMPKinds.def:165
+
+__OMP_RTL(__kmpc_barrier, false, Void, IdentPtr, Int32)
+__OMP_RTL(__kmpc_cancel_barrier, false, Int32, IdentPtr, Int32)

rogfer01 wrote:
> As we migrate, we will end with a significant number of interfaces here.
> 
> @jdoerfert what do you think about adding a comment with their C prototype 
> before each one like we do in `clang/lib/CodeGen/CGOpenMPRuntime.cpp`?
> 
> Something like this
> 
> ```lang=cpp
> // void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
> __OMP_RTL(__kmpc_barrier, false, Void, IdentPtr, Int32)
> // kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
> // global_tid)
> __OMP_RTL(__kmpc_cancel_barrier, false, Int32, IdentPtr, Int32)
> ...
> ```
I'm fine with this but I doubt it'll help much (compared to the lines we have 
that show name and types).

If you want this to happen you should create a patch do add comments for the 
ones we have here, and others can way in. If there is agreement to apply it, we 
will do so and continue that tradition from then on. Does that sound good?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69785



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


[PATCH] D69938: [OpenCL] Use __generic addr space when generating internal representation of lambda

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

Thanks, that looks great.


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

https://reviews.llvm.org/D69938



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


[PATCH] D69785: [OpenMP] Introduce the OpenMP-IR-Builder

2019-11-28 Thread Roger Ferrer Ibanez via Phabricator via cfe-commits
rogfer01 added inline comments.



Comment at: llvm/include/llvm/Frontend/OpenMPKinds.def:165
+
+__OMP_RTL(__kmpc_barrier, false, Void, IdentPtr, Int32)
+__OMP_RTL(__kmpc_cancel_barrier, false, Int32, IdentPtr, Int32)

jdoerfert wrote:
> rogfer01 wrote:
> > As we migrate, we will end with a significant number of interfaces here.
> > 
> > @jdoerfert what do you think about adding a comment with their C prototype 
> > before each one like we do in `clang/lib/CodeGen/CGOpenMPRuntime.cpp`?
> > 
> > Something like this
> > 
> > ```lang=cpp
> > // void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
> > __OMP_RTL(__kmpc_barrier, false, Void, IdentPtr, Int32)
> > // kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
> > // global_tid)
> > __OMP_RTL(__kmpc_cancel_barrier, false, Int32, IdentPtr, Int32)
> > ...
> > ```
> I'm fine with this but I doubt it'll help much (compared to the lines we have 
> that show name and types).
> 
> If you want this to happen you should create a patch do add comments for the 
> ones we have here, and others can way in. If there is agreement to apply it, 
> we will do so and continue that tradition from then on. Does that sound good?
Sounds reasonable to me. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69785



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


[PATCH] D66035: [WebAssembly] WIP: Add support for reference types

2019-11-28 Thread Valentin Churavy via Phabricator via cfe-commits
vchuravy updated this revision to Diff 231460.
vchuravy added a comment.

support old DL modules


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66035

Files:
  llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp


Index: llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
@@ -102,16 +102,45 @@
   return *RM;
 }
 
+static bool HasReferenceTypes(StringRef FS) {
+  bool ReferenceTypes = false;
+  SmallVector Features;
+
+  FS.split(Features, ',', -1, false /* KeepEmpty */);
+  for (auto &Feature : Features) {
+if (Feature == "reference-types" || Feature == "+reference-types")
+  ReferenceTypes = true;
+if (Feature == "-reference-types")
+  ReferenceTypes = false;
+  }
+
+  return ReferenceTypes;
+}
+
+static std::string computeDataLayout(const Triple &TT, StringRef FS) {
+  std::string Ret = "e-m:e";
+
+  if (TT.isArch64Bit()) {
+Ret += "-p:64:64";
+  } else {
+Ret += "-p:32:32";
+  }
+
+  Ret += "-i64:64-n32:64-S128";
+
+  if (HasReferenceTypes(FS)) {
+Ret += "-ni:256"; // anyref
+  }
+  return Ret;
+}
+
 /// Create an WebAssembly architecture model.
 ///
 WebAssemblyTargetMachine::WebAssemblyTargetMachine(
 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
 const TargetOptions &Options, Optional RM,
 Optional CM, CodeGenOpt::Level OL, bool JIT)
-: LLVMTargetMachine(T,
-TT.isArch64Bit()
-? "e-m:e-p:64:64-i64:64-n32:64-S128-ni:256"
-: "e-m:e-p:32:32-i64:64-n32:64-S128-ni:256",
+: LLVMTargetMachine(T, computeDataLayout(TT, FS),
 TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),
 getEffectiveCodeModel(CM, CodeModel::Large), OL),
   TLOF(new WebAssemblyTargetObjectFile()) {


Index: llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
@@ -102,16 +102,45 @@
   return *RM;
 }
 
+static bool HasReferenceTypes(StringRef FS) {
+  bool ReferenceTypes = false;
+  SmallVector Features;
+
+  FS.split(Features, ',', -1, false /* KeepEmpty */);
+  for (auto &Feature : Features) {
+if (Feature == "reference-types" || Feature == "+reference-types")
+  ReferenceTypes = true;
+if (Feature == "-reference-types")
+  ReferenceTypes = false;
+  }
+
+  return ReferenceTypes;
+}
+
+static std::string computeDataLayout(const Triple &TT, StringRef FS) {
+  std::string Ret = "e-m:e";
+
+  if (TT.isArch64Bit()) {
+Ret += "-p:64:64";
+  } else {
+Ret += "-p:32:32";
+  }
+
+  Ret += "-i64:64-n32:64-S128";
+
+  if (HasReferenceTypes(FS)) {
+Ret += "-ni:256"; // anyref
+  }
+  return Ret;
+}
+
 /// Create an WebAssembly architecture model.
 ///
 WebAssemblyTargetMachine::WebAssemblyTargetMachine(
 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
 const TargetOptions &Options, Optional RM,
 Optional CM, CodeGenOpt::Level OL, bool JIT)
-: LLVMTargetMachine(T,
-TT.isArch64Bit()
-? "e-m:e-p:64:64-i64:64-n32:64-S128-ni:256"
-: "e-m:e-p:32:32-i64:64-n32:64-S128-ni:256",
+: LLVMTargetMachine(T, computeDataLayout(TT, FS),
 TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),
 getEffectiveCodeModel(CM, CodeModel::Large), OL),
   TLOF(new WebAssemblyTargetObjectFile()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66035: [WebAssembly] WIP: Add support for reference types

2019-11-28 Thread Valentin Churavy via Phabricator via cfe-commits
vchuravy marked an inline comment as done.
vchuravy added inline comments.



Comment at: llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp:113
+TT.isArch64Bit() ? 
"e-m:e-p:64:64-i64:64-n32:64-S128-ni:1"
+ : 
"e-m:e-p:32:32-i64:64-n32:64-S128-ni:1",
 TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),

vchuravy wrote:
> aheejin wrote:
> > Is this gonna support existing .ll files with the previous data layout?
> I don't see why it shouldn't without activating `-mattr=+reference-types` new 
> .ll files won't compile,
> but old one should.
I see what you meant know after building emscripten/binaryen with these 
changes, I made the DL changes depending on the feature flag.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66035



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


[PATCH] D66035: [WebAssembly] WIP: Add support for reference types

2019-11-28 Thread Valentin Churavy via Phabricator via cfe-commits
vchuravy updated this revision to Diff 231462.
vchuravy added a comment.

restore previous changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66035

Files:
  clang/lib/Basic/Targets/WebAssembly.h
  lld/wasm/WriterUtils.cpp
  llvm/include/llvm/BinaryFormat/Wasm.h
  llvm/include/llvm/BinaryFormat/WasmRelocs.def
  llvm/include/llvm/CodeGen/TargetLowering.h
  llvm/include/llvm/CodeGen/ValueTypes.td
  llvm/include/llvm/MC/MCExpr.h
  llvm/include/llvm/MC/MCSymbolWasm.h
  llvm/include/llvm/Object/Wasm.h
  llvm/include/llvm/Support/MachineValueType.h
  llvm/lib/BinaryFormat/Wasm.cpp
  llvm/lib/CodeGen/CodeGenPrepare.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/ValueTypes.cpp
  llvm/lib/MC/MCExpr.cpp
  llvm/lib/MC/WasmObjectWriter.cpp
  llvm/lib/Object/WasmObjectFile.cpp
  llvm/lib/ObjectYAML/WasmEmitter.cpp
  llvm/lib/ObjectYAML/WasmYAML.cpp
  llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmParser.cpp
  llvm/lib/Target/WebAssembly/Disassembler/WebAssemblyDisassembler.cpp
  llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyInstPrinter.cpp
  llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCCodeEmitter.cpp
  llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.cpp
  llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyMCTargetDesc.h
  llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyWasmObjectWriter.cpp
  llvm/lib/Target/WebAssembly/WebAssembly.h
  llvm/lib/Target/WebAssembly/WebAssembly.td
  llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyExplicitLocals.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h
  llvm/lib/Target/WebAssembly/WebAssemblyInstrCall.td
  llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyInstrInfo.td
  llvm/lib/Target/WebAssembly/WebAssemblyInstrTable.td
  llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyPeephole.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyRegisterInfo.td
  llvm/lib/Target/WebAssembly/WebAssemblySubtarget.h
  llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
  llvm/test/CodeGen/WebAssembly/anyref.ll
  llvm/test/CodeGen/WebAssembly/reg-argument.mir
  llvm/test/CodeGen/WebAssembly/reg-copy.mir
  llvm/utils/TableGen/CodeGenTarget.cpp

Index: llvm/utils/TableGen/CodeGenTarget.cpp
===
--- llvm/utils/TableGen/CodeGenTarget.cpp
+++ llvm/utils/TableGen/CodeGenTarget.cpp
@@ -196,6 +196,7 @@
   case MVT::iPTRAny:  return "MVT::iPTRAny";
   case MVT::Untyped:  return "MVT::Untyped";
   case MVT::exnref:   return "MVT::exnref";
+  case MVT::anyref:   return "MVT::anyref";
   default: llvm_unreachable("ILLEGAL VALUE TYPE!");
   }
 }
Index: llvm/test/CodeGen/WebAssembly/reg-copy.mir
===
--- llvm/test/CodeGen/WebAssembly/reg-copy.mir
+++ llvm/test/CodeGen/WebAssembly/reg-copy.mir
@@ -66,3 +66,14 @@
 %0:exnref = COPY %1:exnref
 RETURN implicit-def $arguments
 ...
+---
+name: copy_anyref
+# CHECK-LABEL: copy_anyref
+body: |
+  ; CHECK-LABEL: bb.0
+  ; CHECK-NEXT: %0:anyref = COPY_ANYREF %1:anyref
+  ; CHECK-NEXT: RETURN
+  bb.0:
+%0:anyref = COPY %1:anyref
+RETURN implicit-def $arguments
+...
Index: llvm/test/CodeGen/WebAssembly/reg-argument.mir
===
--- llvm/test/CodeGen/WebAssembly/reg-argument.mir
+++ llvm/test/CodeGen/WebAssembly/reg-argument.mir
@@ -57,3 +57,14 @@
 %1:exnref = ARGUMENT_exnref 0, implicit $arguments
 RETURN implicit-def $arguments
 ...
+---
+name: argument_anyref
+# CHECK-LABEL: argument_anyref
+body: |
+  ; CHECK-LABEL: bb.0:
+  ; CHECK-NEXT: %1:anyref = ARGUMENT_anyref 0
+  bb.0:
+%0:i32 = CONST_I32 0, implicit-def $arguments
+%1:anyref = ARGUMENT_anyref 0, implicit $arguments
+RETURN implicit-def $arguments
+...
Index: llvm/test/CodeGen/WebAssembly/anyref.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/anyref.ll
@@ -0,0 +1,29 @@
+; RUN: llc < %s -asm-verbose=false -disable-wasm-fallthrough-return-opt -wasm-disable-explicit-locals -wasm-keep-registers -mattr=+reference-types | FileCheck %s
+
+target datalayout = "e-m:e-p:32:32-i64:64-n32:64-S128"
+target triple = "wasm32-unknown-unknown"
+
+declare i8 addrspace(256)* @test(i8 addrspace(256)*) 
+
+
+; CHECK-LABEL: call_test:
+; CHECK: .functype   call_test (anyref) -> (anyref)
+define i8 addrspace(256)* @call_test(i8 addrspace(256)*) {
+; CHECK: anyref.call $push0=, test, $0
+  %a = call i8 addrspace(256)* @test(i8 addrspace(256)* %0) 
+  ret i8 addrspace(256)* %a
+}
+
+; TODO: nullref?
+; define i8 addrspace(256)* @

[PATCH] D70605: [OpenCL] Fix address space for implicit conversion (PR43145)

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

Thanks, LGTM.


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

https://reviews.llvm.org/D70605



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


[PATCH] D70823: [clang-tidy] Adding cert-pos34-c check

2019-11-28 Thread Zurab Tsinadze via Phabricator via cfe-commits
zukatsinadze marked 5 inline comments as done.
zukatsinadze added inline comments.



Comment at: clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.cpp:28
+  unless(hasDescendant(callExpr(callee(functionDecl(hasAnyName(
+  "::alloc", "::malloc", "::realloc", "::calloc")))
+  .bind("func"),

Charusso wrote:
> `alloc` -> `alloca`
I think ``alloca`` allocates memory on stack, so thats why I didn't include it 
here.


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

https://reviews.llvm.org/D70823



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


[PATCH] D70823: [clang-tidy] Adding cert-pos34-c check

2019-11-28 Thread Zurab Tsinadze via Phabricator via cfe-commits
zukatsinadze updated this revision to Diff 231465.
zukatsinadze added a comment.

changes after review.


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

https://reviews.llvm.org/D70823

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/clang-tidy/cert/CMakeLists.txt
  clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.cpp
  clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-pos34-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/cert-pos34-c.cpp

Index: clang-tools-extra/test/clang-tidy/cert-pos34-c.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/cert-pos34-c.cpp
@@ -0,0 +1,63 @@
+// RUN: %check_clang_tidy %s cert-pos34-c %t
+#include 
+#include 
+
+namespace test_auto_var_used_bad {
+
+int func1(const char *var) {
+  char env[1024];
+  /*
+  Do Something
+  */
+  return putenv(env);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: 'putenv' function should not be called with auto variables [cert-pos34-c]
+}
+
+int func2(char *a) {
+  return putenv(a);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: 'putenv' function should not be called with auto variables [cert-pos34-c]
+}
+
+void func3(char *a) {
+  putenv(a);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'putenv' function should not be called with auto variables [cert-pos34-c]
+}
+
+} // namespace test_auto_var_used_bad
+
+namespace test_auto_var_used_good {
+
+int func4(const char *var) {
+  static char env[1024];
+  /*
+  Do Something
+  */
+  return putenv(env); // no-warning: env is static.
+}
+
+// example from cert
+int func5(const char *var) {
+  static char *oldenv;
+  const char *env_format = "TEST=%s";
+  const size_t len = strlen(var) + strlen(env_format);
+  char *env = (char *)malloc(len);
+  if (env == NULL) {
+return -1;
+  }
+  if (putenv(env) != 0) { // no-warning: env was dynamically allocated.
+free(env);
+return -1;
+  }
+  if (oldenv != NULL) {
+free(oldenv); /* avoid memory leak */
+  }
+  oldenv = env;
+  return 0;
+}
+
+extern char *testExt;
+int func6() {
+  return putenv(testExt); // no-warning: extern storage class.
+}
+
+} // namespace test_auto_var_used_good
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -102,6 +102,7 @@
cert-msc51-cpp
cert-oop11-cpp (redirects to performance-move-constructor-init) 
cert-oop54-cpp (redirects to bugprone-unhandled-self-assignment) 
+   cert-pos34-c
cppcoreguidelines-avoid-c-arrays (redirects to modernize-avoid-c-arrays) 
cppcoreguidelines-avoid-goto
cppcoreguidelines-avoid-magic-numbers (redirects to readability-magic-numbers) 
Index: clang-tools-extra/docs/clang-tidy/checks/cert-pos34-c.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cert-pos34-c.rst
@@ -0,0 +1,25 @@
+.. title:: clang-tidy - cert-pos34-c
+
+cert-pos34-c
+=
+
+Finds calls of ``putenv`` function with automatic variable as the argument.
+
+.. code-block:: c
+
+  #include 
+
+  int func(const char *var) {
+char env[1024];
+int retval = snprintf(env, sizeof(env),"TEST=%s", var);
+if (retval < 0 || (size_t)retval >= sizeof(env)) {
+/* Handle error */
+}
+ 
+return putenv(env); // putenv function should not be called with auto variables
+  }
+
+
+This check corresponds to the CERT Standard rule 
+`POS34-C. Do not call putenv() with a pointer to an automatic variable as the argument.
+`_.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -194,6 +194,11 @@
   against self-assignment either by checking self-assignment explicitly or
   using the copy-and-swap or the copy-and-move method.
 
+- New :doc:`cert-pos34-c
+  ` check.
+
+  Finds calls of ``putenv`` function with automatic variable as the argument.
+
 - New :doc:`fuchsia-default-arguments-calls
   ` check.
 
Index: clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/cert/PutenvWithAutoCheck.h
@@ -0,0 +1,34 @@
+//===--- PutenvWithAutoCheck.h - clang-tidy -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Ident

[clang] f4d32ae - [mips] Check that features required by built-ins are enabled

2019-11-28 Thread Simon Atanasyan via cfe-commits

Author: Simon Atanasyan
Date: 2019-11-29T00:23:00+03:00
New Revision: f4d32ae75bf515f443a2c99dce5c882f460c82bd

URL: 
https://github.com/llvm/llvm-project/commit/f4d32ae75bf515f443a2c99dce5c882f460c82bd
DIFF: 
https://github.com/llvm/llvm-project/commit/f4d32ae75bf515f443a2c99dce5c882f460c82bd.diff

LOG: [mips] Check that features required by built-ins are enabled

Now Clang does not check that features required by built-in functions
are enabled. That causes errors in the backend reported in PR44018.

This patch fixes this bug by checking that required features
are enabled.

This should fix PR44018.

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

Added: 
clang/test/Sema/builtins-mips-features.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Basic/Targets/Mips.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/builtins-mips-args.c
clang/test/CodeGen/builtins-mips.c

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 746320fa526b..c30f65d94581 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8742,6 +8742,12 @@ def err_32_bit_builtin_64_bit_tgt : Error<
   "this builtin is only available on 32-bit targets">;
 def err_builtin_x64_aarch64_only : Error<
   "this builtin is only available on x86-64 and aarch64 targets">;
+def err_mips_builtin_requires_dsp : Error<
+  "this builtin requires 'dsp' ASE, please use -mdsp">;
+def err_mips_builtin_requires_dspr2 : Error<
+  "this builtin requires 'dsp r2' ASE, please use -mdspr2">;
+def err_mips_builtin_requires_msa : Error<
+  "this builtin requires 'msa' ASE, please use -mmsa">;
 def err_ppc_builtin_only_on_pwr7 : Error<
   "this builtin is only valid on POWER7 or later CPUs">;
 def err_x86_builtin_invalid_rounding : Error<

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index ac5a4953e00d..59e8f3439669 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11282,6 +11282,8 @@ class Sema final {
   bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
+  bool CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
+  bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr 
*TheCall);

diff  --git a/clang/lib/Basic/Targets/Mips.cpp 
b/clang/lib/Basic/Targets/Mips.cpp
index b9ab80df6194..ead5e91f7c8f 100644
--- a/clang/lib/Basic/Targets/Mips.cpp
+++ b/clang/lib/Basic/Targets/Mips.cpp
@@ -213,7 +213,10 @@ void MipsTargetInfo::getTargetDefines(const LangOptions 
&Opts,
 bool MipsTargetInfo::hasFeature(StringRef Feature) const {
   return llvm::StringSwitch(Feature)
   .Case("mips", true)
+  .Case("dsp", DspRev >= DSP1)
+  .Case("dspr2", DspRev >= DSP2)
   .Case("fp64", FPMode == FP64)
+  .Case("msa", HasMSA)
   .Default(false);
 }
 

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index c19badf80137..adefca7fe4e7 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -3051,8 +3051,37 @@ bool Sema::CheckHexagonBuiltinFunctionCall(unsigned 
BuiltinID,
  CheckHexagonBuiltinArgument(BuiltinID, TheCall);
 }
 
+bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) 
{
+  return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
+ CheckMipsBuiltinArgument(BuiltinID, TheCall);
+}
+
+bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
+  const TargetInfo &TI = Context.getTargetInfo();
 
-// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
+  if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_mips_lwx) {
+if (!TI.hasFeature("dsp"))
+  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
+  }
+
+  if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
+if (!TI.hasFeature("dspr2"))
+  return Diag(TheCall->getBeginLoc(),
+  diag::err_mips_builtin_requires_dspr2);
+  }
+
+  if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_msa_xori_b) {
+if (!TI.hasFeature("msa"))
+  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
+  }
+
+  return false;
+}
+
+// CheckMipsBuiltinArgument - Checks the constant value passed to the

[PATCH] D70808: [mips] Check that features required by built-ins are enabled

2019-11-28 Thread Simon Atanasyan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf4d32ae75bf5: [mips] Check that features required by 
built-ins are enabled (authored by atanasyan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70808

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Basic/Targets/Mips.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-mips-args.c
  clang/test/CodeGen/builtins-mips.c
  clang/test/Sema/builtins-mips-features.c

Index: clang/test/Sema/builtins-mips-features.c
===
--- /dev/null
+++ clang/test/Sema/builtins-mips-features.c
@@ -0,0 +1,37 @@
+// REQUIRES: mips-registered-target
+// RUN: %clang_cc1 -triple mips64 -fsyntax-only -verify %s
+
+typedef signed char v4i8 __attribute__ ((vector_size(4)));
+typedef signed char v4q7 __attribute__ ((vector_size(4)));
+typedef signed char v16i8 __attribute__((vector_size(16), aligned(16)));
+typedef unsigned char v16u8 __attribute__((vector_size(16), aligned(16)));
+
+void dsp() {
+  v4i8 a;
+  void* p;
+
+  // expected-error@+1 {{this builtin requires 'dsp' ASE, please use -mdsp}}
+  __builtin_mips_addu_qb(a, a);
+  // expected-error@+1 {{this builtin requires 'dsp' ASE, please use -mdsp}}
+  __builtin_mips_lwx(p, 32);
+}
+
+void dspr2() {
+  v4i8 a;
+  v4q7 b;
+
+  // expected-error@+1 {{this builtin requires 'dsp r2' ASE, please use -mdspr2}}
+  __builtin_mips_absq_s_qb(b);
+  // expected-error@+1 {{this builtin requires 'dsp r2' ASE, please use -mdspr2}}
+  __builtin_mips_subuh_r_qb(a, a);
+}
+
+void msa() {
+  v16i8 a;
+  v16u8 b;
+
+  // expected-error@+1 {{this builtin requires 'msa' ASE, please use -mmsa}}
+  __builtin_msa_add_a_b(a, a);
+  // expected-error@+1 {{this builtin requires 'msa' ASE, please use -mmsa}}
+  __builtin_msa_xori_b(b, 5);
+}
Index: clang/test/CodeGen/builtins-mips.c
===
--- clang/test/CodeGen/builtins-mips.c
+++ clang/test/CodeGen/builtins-mips.c
@@ -1,5 +1,6 @@
 // REQUIRES: mips-registered-target
-// RUN: %clang_cc1 -triple mips-unknown-linux-gnu -emit-llvm %s -o - \
+// RUN: %clang_cc1 -triple mips-unknown-linux-gnu -emit-llvm %s \
+// RUN:-target-feature +dspr2 -o - \
 // RUN:   | FileCheck %s
 
 typedef int q31;
Index: clang/test/CodeGen/builtins-mips-args.c
===
--- clang/test/CodeGen/builtins-mips-args.c
+++ clang/test/CodeGen/builtins-mips-args.c
@@ -1,5 +1,6 @@
 // REQUIRES: mips-registered-target
-// RUN: %clang_cc1 -triple mips-unknown-linux-gnu -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple mips-unknown-linux-gnu -target-feature +dspr2 \
+// RUN:-fsyntax-only -verify %s
 
 void foo() {
   // MIPS DSP Rev 1
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -3051,8 +3051,37 @@
  CheckHexagonBuiltinArgument(BuiltinID, TheCall);
 }
 
+bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
+  return CheckMipsBuiltinCpu(BuiltinID, TheCall) ||
+ CheckMipsBuiltinArgument(BuiltinID, TheCall);
+}
+
+bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
+  const TargetInfo &TI = Context.getTargetInfo();
 
-// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
+  if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_mips_lwx) {
+if (!TI.hasFeature("dsp"))
+  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
+  }
+
+  if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
+if (!TI.hasFeature("dspr2"))
+  return Diag(TheCall->getBeginLoc(),
+  diag::err_mips_builtin_requires_dspr2);
+  }
+
+  if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
+  BuiltinID <= Mips::BI__builtin_msa_xori_b) {
+if (!TI.hasFeature("msa"))
+  return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
+  }
+
+  return false;
+}
+
+// CheckMipsBuiltinArgument - Checks the constant value passed to the
 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
 // ordering for DSP is unspecified. MSA is ordered by the data format used
 // by the underlying instruction i.e., df/m, df/n and then by size.
@@ -3061,7 +3090,7 @@
 //definitions from include/clang/Basic/BuiltinsMips.def.
 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
 //be too.
-bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
+bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
   unsigned i = 0, l =

[clang] 1abd4c9 - [Clang] Bypass distro detection on non-Linux hosts

2019-11-28 Thread Alexandre Ganea via cfe-commits

Author: Alexandre Ganea
Date: 2019-11-28T17:02:06-05:00
New Revision: 1abd4c94d7575e4cd288e0024c1ec79f17b048a9

URL: 
https://github.com/llvm/llvm-project/commit/1abd4c94d7575e4cd288e0024c1ec79f17b048a9
DIFF: 
https://github.com/llvm/llvm-project/commit/1abd4c94d7575e4cd288e0024c1ec79f17b048a9.diff

LOG: [Clang] Bypass distro detection on non-Linux hosts

Skip distro detection when we're not running on Linux, or when the target 
triple is not Linux. This saves a few OS calls for each invocation of clang.exe.

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

Added: 


Modified: 
clang/include/clang/Driver/Distro.h
clang/lib/Driver/Distro.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Cuda.cpp
clang/lib/Driver/ToolChains/Linux.cpp
clang/unittests/Driver/DistroTest.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Distro.h 
b/clang/include/clang/Driver/Distro.h
index da8f819dee96..d382cf77a8b2 100644
--- a/clang/include/clang/Driver/Distro.h
+++ b/clang/include/clang/Driver/Distro.h
@@ -9,6 +9,7 @@
 #ifndef LLVM_CLANG_DRIVER_DISTRO_H
 #define LLVM_CLANG_DRIVER_DISTRO_H
 
+#include "llvm/ADT/Triple.h"
 #include "llvm/Support/VirtualFileSystem.h"
 
 namespace clang {
@@ -84,7 +85,7 @@ class Distro {
   Distro(DistroType D) : DistroVal(D) {}
 
   /// Detects the distribution using specified VFS.
-  explicit Distro(llvm::vfs::FileSystem &VFS);
+  explicit Distro(llvm::vfs::FileSystem &VFS, const llvm::Triple 
&TargetOrHost);
 
   bool operator==(const Distro &Other) const {
 return DistroVal == Other.DistroVal;

diff  --git a/clang/lib/Driver/Distro.cpp b/clang/lib/Driver/Distro.cpp
index 92e04108a7e2..06707fefc9d0 100644
--- a/clang/lib/Driver/Distro.cpp
+++ b/clang/lib/Driver/Distro.cpp
@@ -13,11 +13,28 @@
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/ADT/Triple.h"
 
 using namespace clang::driver;
 using namespace clang;
 
-static Distro::DistroType DetectDistro(llvm::vfs::FileSystem &VFS) {
+static Distro::DistroType DetectDistro(llvm::vfs::FileSystem &VFS,
+   const llvm::Triple &TargetOrHost) {
+  // If we don't target Linux, no need to check the distro. This saves a few
+  // OS calls.
+  if (!TargetOrHost.isOSLinux())
+return Distro::UnknownDistro;
+
+  // If the host is not running Linux, and we're backed by a real file system,
+  // no need to check the distro. This is the case where someone is
+  // cross-compiling from BSD or Windows to Linux, and it would be meaningless
+  // to try to figure out the "distro" of the non-Linux host.
+  IntrusiveRefCntPtr RealFS =
+  llvm::vfs::getRealFileSystem();
+  llvm::Triple HostTriple(llvm::sys::getProcessTriple());
+  if (!HostTriple.isOSLinux() && &VFS == RealFS.get())
+return Distro::UnknownDistro;
+
   llvm::ErrorOr> File =
   VFS.getBufferForFile("/etc/lsb-release");
   if (File) {
@@ -149,4 +166,5 @@ static Distro::DistroType 
DetectDistro(llvm::vfs::FileSystem &VFS) {
   return Distro::UnknownDistro;
 }
 
-Distro::Distro(llvm::vfs::FileSystem &VFS) : DistroVal(DetectDistro(VFS)) {}
+Distro::Distro(llvm::vfs::FileSystem &VFS, const llvm::Triple &TargetOrHost)
+: DistroVal(DetectDistro(VFS, TargetOrHost)) {}

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 26d13c714670..03a6de812047 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5619,7 +5619,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 TC.getTriple().isOSBinFormatCOFF()) &&
   !TC.getTriple().isPS4() &&
   !TC.getTriple().isOSNetBSD() &&
-  !Distro(D.getVFS()).IsGentoo() &&
+  !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
   !TC.getTriple().isAndroid() &&
TC.useIntegratedAs()))
 CmdArgs.push_back("-faddrsig");

diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 8c704a3078ad..02871d2ce411 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -115,7 +115,8 @@ CudaInstallationDetector::CudaInstallationDetector(
 for (const char *Ver : Versions)
   Candidates.emplace_back(D.SysRoot + "/usr/local/cuda-" + Ver);
 
-if (Distro(D.getVFS()).IsDebian() || Distro(D.getVFS()).IsUbuntu())
+Distro Dist(D.getVFS(), llvm::Triple(llvm::sys::getProcessTriple()));
+if (Dist.IsDebian() || Dist.IsUbuntu())
   // Special case for Debian to have nvidia-cuda-toolkit work
   // out of the box. More info on http://bugs.debian.org/882505
   Candidates.emplace_back(D.SysRoot + "/usr/lib/cuda");

diff  --git a/clang/lib/Driver/ToolChains/Linux.cpp 
b/clang

[PATCH] D70467: [Distro] Bypass distro detection on non-Linux hosts

2019-11-28 Thread Alexandre Ganea via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
aganea marked an inline comment as done.
Closed by commit rG1abd4c94d757: [Clang] Bypass distro detection on non-Linux 
hosts (authored by aganea).

Changed prior to commit:
  https://reviews.llvm.org/D70467?vs=230525&id=231468#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70467

Files:
  clang/include/clang/Driver/Distro.h
  clang/lib/Driver/Distro.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/unittests/Driver/DistroTest.cpp

Index: clang/unittests/Driver/DistroTest.cpp
===
--- clang/unittests/Driver/DistroTest.cpp
+++ clang/unittests/Driver/DistroTest.cpp
@@ -44,7 +44,7 @@
"SUPPORT_URL=\"http://help.ubuntu.com/\"\n";
"BUG_REPORT_URL=\"http://bugs.launchpad.net/ubuntu/\"\n";));
 
-  Distro UbuntuTrusty{UbuntuTrustyFileSystem};
+  Distro UbuntuTrusty{UbuntuTrustyFileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::UbuntuTrusty), UbuntuTrusty);
   ASSERT_TRUE(UbuntuTrusty.IsUbuntu());
   ASSERT_FALSE(UbuntuTrusty.IsRedhat());
@@ -52,6 +52,9 @@
   ASSERT_FALSE(UbuntuTrusty.IsDebian());
   ASSERT_FALSE(UbuntuTrusty.IsGentoo());
 
+  Distro UbuntuTrusty2{UbuntuTrustyFileSystem, llvm::Triple("unknown-pc-windows")};
+  ASSERT_EQ(Distro(Distro::UnknownDistro), UbuntuTrusty2);
+
   llvm::vfs::InMemoryFileSystem UbuntuYakketyFileSystem;
   UbuntuYakketyFileSystem.addFile("/etc/debian_version", 0,
   llvm::MemoryBuffer::getMemBuffer("stretch/sid\n"));
@@ -74,7 +77,7 @@
"VERSION_CODENAME=yakkety\n"
"UBUNTU_CODENAME=yakkety\n"));
 
-  Distro UbuntuYakkety{UbuntuYakketyFileSystem};
+  Distro UbuntuYakkety{UbuntuYakketyFileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::UbuntuYakkety), UbuntuYakkety);
   ASSERT_TRUE(UbuntuYakkety.IsUbuntu());
   ASSERT_FALSE(UbuntuYakkety.IsRedhat());
@@ -109,7 +112,7 @@
"REDHAT_SUPPORT_PRODUCT=\"Fedora\"\n"
"REDHAT_SUPPORT_PRODUCT_VERSION=25\n"
"PRIVACY_POLICY_URL=https://fedoraproject.org/wiki/Legal:PrivacyPolicy\n";));
-  Distro Fedora25{Fedora25FileSystem};
+  Distro Fedora25{Fedora25FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::Fedora), Fedora25);
   ASSERT_FALSE(Fedora25.IsUbuntu());
   ASSERT_TRUE(Fedora25.IsRedhat());
@@ -146,7 +149,7 @@
"REDHAT_SUPPORT_PRODUCT=\"centos\"\n"
"REDHAT_SUPPORT_PRODUCT_VERSION=\"7\"\n"));
 
-  Distro CentOS7{CentOS7FileSystem};
+  Distro CentOS7{CentOS7FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::RHEL7), CentOS7);
   ASSERT_FALSE(CentOS7.IsUbuntu());
   ASSERT_TRUE(CentOS7.IsRedhat());
@@ -174,7 +177,7 @@
"HOME_URL=\"https://opensuse.org/\"\n";
"ID_LIKE=\"suse\"\n"));
 
-  Distro OpenSUSELeap421{OpenSUSELeap421FileSystem};
+  Distro OpenSUSELeap421{OpenSUSELeap421FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::OpenSUSE), OpenSUSELeap421);
   ASSERT_FALSE(OpenSUSELeap421.IsUbuntu());
   ASSERT_FALSE(OpenSUSELeap421.IsRedhat());
@@ -200,7 +203,7 @@
"HOME_URL=\"https://opensuse.org/\"\n";
"ID_LIKE=\"suse\"\n"));
 
-  Distro OpenSUSE132{OpenSUSE132FileSystem};
+  Distro OpenSUSE132{OpenSUSE132FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::OpenSUSE), OpenSUSE132);
   ASSERT_FALSE(OpenSUSE132.IsUbuntu());
   ASSERT_FALSE(OpenSUSE132.IsRedhat());
@@ -217,7 +220,7 @@
   llvm::MemoryBuffer::getMemBuffer("LSB_VERSION=\"core-2.0-noarch:core-3.0-noarch:core-2.0-x86_64:core-3.0-x86_64\"\n"));
 
   // SLES10 is unsupported and therefore evaluates to unknown
-  Distro SLES10{SLES10FileSystem};
+  Distro SLES10{SLES10FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::UnknownDistro), SLES10);
   ASSERT_FALSE(SLES10.IsUbuntu());
   ASSERT_FALSE(SLES10.IsRedhat());
@@ -240,7 +243,7 @@
"SUPPORT_URL=\"http://www.debian.org/support\"\n";
"BUG_REPORT_URL=\"https://bugs.debian.org/\"\n";));
 
-  Distro DebianJessie{DebianJessieFileSystem};
+  Distro DebianJessie{DebianJessieFileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::DebianJessie), DebianJessie);
   ASSERT_FALSE(DebianJessie.IsUbuntu());
   ASSERT_FALSE(DebianJessie.IsRedhat());
@@ -259,7 +262,7 @@
   

[PATCH] D70579: [coroutines][PR41909] Generalize fix from D62550

2019-11-28 Thread JunMa via Phabricator via cfe-commits
junparser added a comment.

This also fix same ice when build cppcoro with current trunk. FYI


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70579



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


[PATCH] D70836: [analysis] Fix value tracking for pointers to qualified types

2019-11-28 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers created this revision.
vabridgers added reviewers: dcoughlin, dergachev.a.
vabridgers added a project: clang.
Herald added a subscriber: cfe-commits.

This change fixes part 1 described by Artem in the Bugzilla report 43364. The 
comparison done was on a canonical, but should have been done on an unqualified 
type. Without using the unqualified type, the type comparison in this specific 
case is for "const Type * const" against "Type * const", which for the purposes 
of static analysis can be done not considering the Type's const qualifier. This 
is best done using a nonqualified type comparison.
Test cases were added to cover this change.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70836

Files:
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/test/Analysis/uninit-val-const-likeness.c


Index: clang/test/Analysis/uninit-val-const-likeness.c
===
--- /dev/null
+++ clang/test/Analysis/uninit-val-const-likeness.c
@@ -0,0 +1,56 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core %s -verify 
+// expected-no-diagnostics
+
+#define SIZE 2
+
+typedef struct {
+  int noOfSymbols;
+} Params;
+
+static void create(const Params * const params, int fooList[]) {
+  int tmpList[SIZE] = {0};
+  for (int i = 0; i < params->noOfSymbols; i++)
+fooList[i] = tmpList[i];
+}
+
+int work(Params * const params) {
+  int fooList[SIZE];
+  create(params, fooList);
+  int sum = 0;
+  for (int i = 0; i < params->noOfSymbols; i++)
+sum += fooList[i];
+  return sum;
+}
+
+static void create2(const Params * const * pparams, int fooList[]) {
+  const Params * params = *pparams;
+  int tmpList[SIZE] = {0};
+  for (int i = 0; i < params->noOfSymbols; i++)
+fooList[i] = tmpList[i];
+}
+
+int work2(const Params * const params) {
+  int fooList[SIZE];
+  create2(¶ms, fooList);
+  int sum = 0;
+  for (int i = 0; i < params->noOfSymbols; i++)
+sum += fooList[i];
+  return sum;
+}
+
+static void create3(Params * const * pparams, int fooList[]) {
+  const Params * params = *pparams;
+  int tmpList[SIZE] = {0};
+  for (int i = 0; i < params->noOfSymbols; i++)
+fooList[i] = tmpList[i];
+}
+
+int work3(const Params * const params) {
+  int fooList[SIZE];
+  Params *const *ptr = (Params *const*)¶ms;
+  create3(ptr, fooList);
+  int sum = 0;
+  for (int i = 0; i < params->noOfSymbols; i++)
+sum += fooList[i];
+  return sum;
+}
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -393,6 +393,11 @@
   return UnknownVal();
 }
 
+static bool hasSameUnqualifiedPointeeType(QualType ty1, QualType ty2) {
+  return ty1->getPointeeType().getTypePtr() == 
+ty2->getPointeeType().getTypePtr();
+}
+
 /// CastRetrievedVal - Used by subclasses of StoreManager to implement
 ///  implicit casts that arise from loads from regions that are reinterpreted
 ///  as another region.
@@ -421,10 +426,11 @@
   // FIXME: We really need a single good function to perform casts for us
   // correctly every time we need it.
   if (castTy->isPointerType() && !castTy->isVoidPointerType())
-if (const auto *SR = dyn_cast_or_null(V.getAsRegion()))
-  if (SR->getSymbol()->getType().getCanonicalType() !=
-  castTy.getCanonicalType())
-return loc::MemRegionVal(castRegion(SR, castTy));
+if (const auto *SR = dyn_cast_or_null(V.getAsRegion())) {
+  QualType sr = SR->getSymbol()->getType(); 
+  if (!hasSameUnqualifiedPointeeType(sr, castTy))
+  return loc::MemRegionVal(castRegion(SR, castTy));
+}
 
   return svalBuilder.dispatchCast(V, castTy);
 }


Index: clang/test/Analysis/uninit-val-const-likeness.c
===
--- /dev/null
+++ clang/test/Analysis/uninit-val-const-likeness.c
@@ -0,0 +1,56 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core %s -verify 
+// expected-no-diagnostics
+
+#define SIZE 2
+
+typedef struct {
+  int noOfSymbols;
+} Params;
+
+static void create(const Params * const params, int fooList[]) {
+  int tmpList[SIZE] = {0};
+  for (int i = 0; i < params->noOfSymbols; i++)
+fooList[i] = tmpList[i];
+}
+
+int work(Params * const params) {
+  int fooList[SIZE];
+  create(params, fooList);
+  int sum = 0;
+  for (int i = 0; i < params->noOfSymbols; i++)
+sum += fooList[i];
+  return sum;
+}
+
+static void create2(const Params * const * pparams, int fooList[]) {
+  const Params * params = *pparams;
+  int tmpList[SIZE] = {0};
+  for (int i = 0; i < params->noOfSymbols; i++)
+fooList[i] = tmpList[i];
+}
+
+int work2(const Params * const params) {
+  int fooList[SIZE];
+  create2(¶ms, fooList);
+  int sum = 0;
+  for (int i = 0; i < params->noOfSymbols; i++)
+sum += fooList[i];
+  return sum;
+}
+
+static void create3(Params * const * pparams, int fooList[]) {
+  const Params * params 

[PATCH] D70804: [Frontend] Allow OpenMP offloading to aarch64

2019-11-28 Thread Bryan Chan via Phabricator via cfe-commits
bryanpkc added a comment.

In D70804#1763289 , @ABataev wrote:

> Tests are required


The tests for this were added in D30644 , but 
they are currently failing on AArch64 due to D32035 
. This patch allows those tests to pass again. 
What further testing should I add?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70804



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


[PATCH] D70838: [clang][IFS] Ignoring -Xlinker/-Xclang arguments in InterfaceStubs pass for now.

2019-11-28 Thread Puyan Lotfi via Phabricator via cfe-commits
plotfi created this revision.
plotfi added reviewers: compnerd, cishida.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.

I intend to add something like -Xifs, but for now if an InputArg is not a 
filename then I want to skip it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70838

Files:
  clang/lib/Driver/ToolChains/InterfaceStubs.cpp
  clang/test/InterfaceStubs/XlinkerInputArgs.cpp


Index: clang/test/InterfaceStubs/XlinkerInputArgs.cpp
===
--- /dev/null
+++ clang/test/InterfaceStubs/XlinkerInputArgs.cpp
@@ -0,0 +1,3 @@
+// RUN: %clang -### -Xlinker -Bsymbolic -emit-interface-stubs 2>&1 | FileCheck 
%s
+// CHECK: Bsymbolic
+// CHECK-NOT: Bsymbolic
Index: clang/lib/Driver/ToolChains/InterfaceStubs.cpp
===
--- clang/lib/Driver/ToolChains/InterfaceStubs.cpp
+++ clang/lib/Driver/ToolChains/InterfaceStubs.cpp
@@ -46,6 +46,8 @@
   // Here we append the input files. If the input files are object files, then
   // we look for .ifs files present in the same location as the object files.
   for (const auto &Input : Inputs) {
+if (!Input.isFilename())
+  continue;
 SmallString<128> InputFilename(Input.getFilename());
 if (Input.getType() == types::TY_Object)
   llvm::sys::path::replace_extension(InputFilename, ".ifs");


Index: clang/test/InterfaceStubs/XlinkerInputArgs.cpp
===
--- /dev/null
+++ clang/test/InterfaceStubs/XlinkerInputArgs.cpp
@@ -0,0 +1,3 @@
+// RUN: %clang -### -Xlinker -Bsymbolic -emit-interface-stubs 2>&1 | FileCheck %s
+// CHECK: Bsymbolic
+// CHECK-NOT: Bsymbolic
Index: clang/lib/Driver/ToolChains/InterfaceStubs.cpp
===
--- clang/lib/Driver/ToolChains/InterfaceStubs.cpp
+++ clang/lib/Driver/ToolChains/InterfaceStubs.cpp
@@ -46,6 +46,8 @@
   // Here we append the input files. If the input files are object files, then
   // we look for .ifs files present in the same location as the object files.
   for (const auto &Input : Inputs) {
+if (!Input.isFilename())
+  continue;
 SmallString<128> InputFilename(Input.getFilename());
 if (Input.getType() == types::TY_Object)
   llvm::sys::path::replace_extension(InputFilename, ".ifs");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70839: [clang][IFS] Claiming -emit-merged-ifs in clang driver when -c is used.

2019-11-28 Thread Puyan Lotfi via Phabricator via cfe-commits
plotfi created this revision.
plotfi added a reviewer: compnerd.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Sometimes it is difficult to tell when you want your compile flags to be 
invoked with -emit-interface-stubs -c or with -emit-interface-stubs 
-emit-merged-ifs. On -Werror builds -emit-interface-stubs -emit-merged-ifs -c 
causes build errors. I think for now we can claim -emit-merged-ifs.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70839

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/InterfaceStubs/warnings.c


Index: clang/test/InterfaceStubs/warnings.c
===
--- /dev/null
+++ clang/test/InterfaceStubs/warnings.c
@@ -0,0 +1,3 @@
+// RUN: %clang -emit-interface-stubs -emit-merged-ifs -c %s -o - 2>&1 | 
FileCheck %s
+// CHECK-NOT: warning: argument unused during compilation: '-emit-merged-ifs'
+int main() {}
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -3501,6 +3501,11 @@
   if (Args.hasArg(options::OPT_emit_interface_stubs)) {
 llvm::SmallVector PhaseList;
 if (Args.hasArg(options::OPT_c)) {
+  // Claim -emit-merged-ifs if we aren't going to invoke llvm-ifs.
+  // The intention of -emit-merged-ifs is to force llvm-ifs to generate 
text
+  // instead of a ifso. Perhaps this should be inverted.
+  if (Args.hasArg(options::OPT_emit_merged_ifs))
+Args.ClaimAllArgs(options::OPT_emit_merged_ifs);
   llvm::SmallVector 
CompilePhaseList;
   types::getCompilationPhases(types::TY_IFS_CPP, CompilePhaseList);
   llvm::copy_if(CompilePhaseList, std::back_inserter(PhaseList),


Index: clang/test/InterfaceStubs/warnings.c
===
--- /dev/null
+++ clang/test/InterfaceStubs/warnings.c
@@ -0,0 +1,3 @@
+// RUN: %clang -emit-interface-stubs -emit-merged-ifs -c %s -o - 2>&1 | FileCheck %s
+// CHECK-NOT: warning: argument unused during compilation: '-emit-merged-ifs'
+int main() {}
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -3501,6 +3501,11 @@
   if (Args.hasArg(options::OPT_emit_interface_stubs)) {
 llvm::SmallVector PhaseList;
 if (Args.hasArg(options::OPT_c)) {
+  // Claim -emit-merged-ifs if we aren't going to invoke llvm-ifs.
+  // The intention of -emit-merged-ifs is to force llvm-ifs to generate text
+  // instead of a ifso. Perhaps this should be inverted.
+  if (Args.hasArg(options::OPT_emit_merged_ifs))
+Args.ClaimAllArgs(options::OPT_emit_merged_ifs);
   llvm::SmallVector CompilePhaseList;
   types::getCompilationPhases(types::TY_IFS_CPP, CompilePhaseList);
   llvm::copy_if(CompilePhaseList, std::back_inserter(PhaseList),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >