[PATCH] D42642: [CUDA] Detect installation in PATH

2018-01-31 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld updated this revision to Diff 132103.
Hahnfeld marked 3 inline comments as done.
Hahnfeld added a comment.

Add some `sysroot` arguments to new test to make sure it doesn't accidentally 
find CUDA installations in the system.


https://reviews.llvm.org/D42642

Files:
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Cuda.cpp
  test/Driver/Inputs/CUDA-nolibdevice/usr/local/cuda/bin/ptxas
  test/Driver/Inputs/CUDA-symlinks/opt/cuda/bin/ptxas
  test/Driver/Inputs/CUDA-symlinks/opt/cuda/include/.keep
  test/Driver/Inputs/CUDA-symlinks/opt/cuda/lib/.keep
  
test/Driver/Inputs/CUDA-symlinks/opt/cuda/nvvm/libdevice/libdevice.compute_30.10.bc
  
test/Driver/Inputs/CUDA-symlinks/opt/cuda/nvvm/libdevice/libdevice.compute_35.10.bc
  test/Driver/Inputs/CUDA-symlinks/usr/bin/ptxas
  test/Driver/Inputs/CUDA/usr/local/cuda/bin/ptxas
  test/Driver/cuda-detect-path.cu
  test/Driver/cuda-detect.cu
  test/Driver/cuda-not-found.cu
  test/Driver/cuda-version-check.cu

Index: test/Driver/cuda-version-check.cu
===
--- test/Driver/cuda-version-check.cu
+++ test/Driver/cuda-version-check.cu
@@ -2,50 +2,50 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: nvptx-registered-target
 
-// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_20 --sysroot=%S/Inputs/CUDA 2>&1 %s | \
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_20 --cuda-path=%S/Inputs/CUDA/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=OK
-// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_20 --sysroot=%S/Inputs/CUDA_80 2>&1 %s | \
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_20 --cuda-path=%S/Inputs/CUDA_80/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=OK
-// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --sysroot=%S/Inputs/CUDA_80 2>&1 %s | \
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA_80/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=OK
 
 // The installation at Inputs/CUDA is CUDA 7.0, which doesn't support sm_60.
-// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --sysroot=%S/Inputs/CUDA 2>&1 %s | \
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=ERR_SM60
 
 // This should only complain about sm_60, not sm_35.
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-gpu-arch=sm_35 \
-// RUN:--sysroot=%S/Inputs/CUDA 2>&1 %s | \
+// RUN:--cuda-path=%S/Inputs/CUDA/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=ERR_SM60 --check-prefix=OK_SM35
 
 // We should get two errors here, one for sm_60 and one for sm_61.
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-gpu-arch=sm_61 \
-// RUN:--sysroot=%S/Inputs/CUDA 2>&1 %s | \
+// RUN:--cuda-path=%S/Inputs/CUDA/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=ERR_SM60 --check-prefix=ERR_SM61
 
 // We should still get an error if we pass -nocudainc, because this compilation
 // would invoke ptxas, and we do a version check on that, too.
-// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 -nocudainc --sysroot=%S/Inputs/CUDA 2>&1 %s | \
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 -nocudainc --cuda-path=%S/Inputs/CUDA/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=ERR_SM60
 
 // If with -nocudainc and -E, we don't touch the CUDA install, so we
 // shouldn't get an error.
 // RUN: %clang --target=x86_64-linux -v -### -E --cuda-device-only --cuda-gpu-arch=sm_60 -nocudainc \
-// RUN:--sysroot=%S/Inputs/CUDA 2>&1 %s | \
+// RUN:--cuda-path=%S/Inputs/CUDA/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=OK
 
 // --no-cuda-version-check should suppress all of these errors.
-// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --sysroot=%S/Inputs/CUDA 2>&1 \
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA/usr/local/cuda 2>&1 \
 // RUN:--no-cuda-version-check %s | \
 // RUN:FileCheck %s --check-prefix=OK
 
 // We need to make sure the version check is done only for the device toolchain,
 // therefore we should not get an error in host-only mode. We use the -S here
 // to avoid the error being produced in case by the assembler tool, which does
 // the same check.
-// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-host-only --sysroot=%S/Inputs/CUDA -S 2>&1 %s | \
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-host-only --cuda-path=%S/Inputs/CUDA/usr/local/cuda -S 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=OK
-// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-device-only --sysroot=%S/Inputs/CUDA -S 2>&1 %s | \
+/

r323848 - [CUDA] Detect installation in PATH

2018-01-31 Thread Jonas Hahnfeld via cfe-commits
Author: hahnfeld
Date: Wed Jan 31 00:26:51 2018
New Revision: 323848

URL: http://llvm.org/viewvc/llvm-project?rev=323848&view=rev
Log:
[CUDA] Detect installation in PATH

If the CUDA toolkit is not installed to its default locations
in /usr/local/cuda, the user is forced to specify --cuda-path.
This is tedious and the driver can be smarter if well-known tools
(like ptxas) can already be found in the PATH environment variable.

Add option --cuda-path-ignore-env if the user wants to ignore
set environment variables. Also use it in the tests to make sure
the driver always finds the same CUDA installation, regardless
of the user's environment.

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

Added:
cfe/trunk/test/Driver/Inputs/CUDA-nolibdevice/usr/local/cuda/bin/ptxas   
(with props)
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/bin/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/bin/ptxas   (with props)
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/include/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/include/.keep
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/lib/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/lib/.keep
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/nvvm/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/nvvm/libdevice/

cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/nvvm/libdevice/libdevice.compute_30.10.bc

cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/nvvm/libdevice/libdevice.compute_35.10.bc
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/usr/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/usr/bin/
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/usr/bin/ptxas   (with props)
cfe/trunk/test/Driver/Inputs/CUDA/usr/local/cuda/bin/ptxas   (with props)
cfe/trunk/test/Driver/cuda-detect-path.cu
Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Driver/ToolChains/Cuda.cpp
cfe/trunk/test/Driver/cuda-detect.cu
cfe/trunk/test/Driver/cuda-not-found.cu
cfe/trunk/test/Driver/cuda-version-check.cu

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=323848&r1=323847&r2=323848&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Wed Jan 31 00:26:51 2018
@@ -556,6 +556,8 @@ def no_cuda_version_check : Flag<["--"],
 def no_cuda_noopt_device_debug : Flag<["--"], "no-cuda-noopt-device-debug">;
 def cuda_path_EQ : Joined<["--"], "cuda-path=">, Group,
   HelpText<"CUDA installation path">;
+def cuda_path_ignore_env : Joined<["--"], "cuda-path-ignore-env">, 
Group,
+  HelpText<"Ignore environment variables to detect CUDA installation">;
 def ptxas_path_EQ : Joined<["--"], "ptxas-path=">, Group,
   HelpText<"Path to ptxas (used for compiling CUDA code)">;
 def fcuda_flush_denormals_to_zero : Flag<["-"], 
"fcuda-flush-denormals-to-zero">,

Modified: cfe/trunk/lib/Driver/ToolChains/Cuda.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Cuda.cpp?rev=323848&r1=323847&r2=323848&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Cuda.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Cuda.cpp Wed Jan 31 00:26:51 2018
@@ -8,18 +8,20 @@
 
//===--===//
 
 #include "Cuda.h"
-#include "InputInfo.h"
 #include "CommonArgs.h"
+#include "InputInfo.h"
 #include "clang/Basic/Cuda.h"
-#include "clang/Config/config.h"
 #include "clang/Basic/VirtualFileSystem.h"
-#include "clang/Driver/Distro.h"
+#include "clang/Config/config.h"
 #include "clang/Driver/Compilation.h"
+#include "clang/Driver/Distro.h"
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
 #include "llvm/Option/ArgList.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Program.h"
 #include 
 
 using namespace clang::driver;
@@ -61,42 +63,75 @@ CudaInstallationDetector::CudaInstallati
 const Driver &D, const llvm::Triple &HostTriple,
 const llvm::opt::ArgList &Args)
 : D(D) {
-  SmallVector CudaPathCandidates;
+  struct Candidate {
+std::string Path;
+bool StrictChecking;
+
+Candidate(std::string Path, bool StrictChecking = false)
+: Path(Path), StrictChecking(StrictChecking) {}
+  };
+  SmallVector Candidates;
 
   // In decreasing order so we prefer newer versions to older versions.
   std::initializer_list Versions = {"8.0", "7.5", "7.0"};
 
   if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) {
-CudaPathCandidates.push_back(
-  

[PATCH] D42642: [CUDA] Detect installation in PATH

2018-01-31 Thread Jonas Hahnfeld via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323848: [CUDA] Detect installation in PATH (authored by 
Hahnfeld, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42642?vs=132103&id=132104#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42642

Files:
  cfe/trunk/include/clang/Driver/Options.td
  cfe/trunk/lib/Driver/ToolChains/Cuda.cpp
  cfe/trunk/test/Driver/Inputs/CUDA-nolibdevice/usr/local/cuda/bin/ptxas
  cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/bin/ptxas
  cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/include/.keep
  cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/lib/.keep
  
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/nvvm/libdevice/libdevice.compute_30.10.bc
  
cfe/trunk/test/Driver/Inputs/CUDA-symlinks/opt/cuda/nvvm/libdevice/libdevice.compute_35.10.bc
  cfe/trunk/test/Driver/Inputs/CUDA-symlinks/usr/bin/ptxas
  cfe/trunk/test/Driver/Inputs/CUDA/usr/local/cuda/bin/ptxas
  cfe/trunk/test/Driver/cuda-detect-path.cu
  cfe/trunk/test/Driver/cuda-detect.cu
  cfe/trunk/test/Driver/cuda-not-found.cu
  cfe/trunk/test/Driver/cuda-version-check.cu

Index: cfe/trunk/include/clang/Driver/Options.td
===
--- cfe/trunk/include/clang/Driver/Options.td
+++ cfe/trunk/include/clang/Driver/Options.td
@@ -556,6 +556,8 @@
 def no_cuda_noopt_device_debug : Flag<["--"], "no-cuda-noopt-device-debug">;
 def cuda_path_EQ : Joined<["--"], "cuda-path=">, Group,
   HelpText<"CUDA installation path">;
+def cuda_path_ignore_env : Joined<["--"], "cuda-path-ignore-env">, Group,
+  HelpText<"Ignore environment variables to detect CUDA installation">;
 def ptxas_path_EQ : Joined<["--"], "ptxas-path=">, Group,
   HelpText<"Path to ptxas (used for compiling CUDA code)">;
 def fcuda_flush_denormals_to_zero : Flag<["-"], "fcuda-flush-denormals-to-zero">,
Index: cfe/trunk/test/Driver/Inputs/CUDA-symlinks/usr/bin/ptxas
===
--- cfe/trunk/test/Driver/Inputs/CUDA-symlinks/usr/bin/ptxas
+++ cfe/trunk/test/Driver/Inputs/CUDA-symlinks/usr/bin/ptxas
@@ -0,0 +1 @@
+link ../../opt/cuda/bin/ptxas
\ No newline at end of file
Index: cfe/trunk/test/Driver/cuda-detect-path.cu
===
--- cfe/trunk/test/Driver/cuda-detect-path.cu
+++ cfe/trunk/test/Driver/cuda-detect-path.cu
@@ -0,0 +1,83 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+// This tests uses the PATH environment variable.
+// REQUIRES: !system-windows
+
+// RUN: env PATH=%S/Inputs/CUDA/usr/local/cuda/bin \
+// RUN:%clang -v --target=i386-unknown-linux --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s
+// RUN: env PATH=%S/Inputs/CUDA/usr/local/cuda/bin \
+// RUN:%clang -v --target=i386-apple-macosx --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s
+// RUN: env PATH=%S/Inputs/CUDA/usr/local/cuda/bin \
+// RUN:%clang -v --target=x86_64-unknown-linux --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s
+// RUN: env PATH=%S/Inputs/CUDA/usr/local/cuda/bin \
+// RUN:%clang -v --target=x86_64-apple-macosx --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s
+
+
+// Check that we follow ptxas binaries that are symlinks.
+// RUN: env PATH=%S/Inputs/CUDA-symlinks/usr/bin \
+// RUN:%clang -v --target=i386-unknown-linux --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s --check-prefix SYMLINKS
+// RUN: env PATH=%S/Inputs/CUDA-symlinks/usr/bin \
+// RUN:%clang -v --target=i386-apple-macosx --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s --check-prefix SYMLINKS
+// RUN: env PATH=%S/Inputs/CUDA-symlinks/usr/bin \
+// RUN:%clang -v --target=x86_64-unknown-linux --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s --check-prefix SYMLINKS
+// RUN: env PATH=%S/Inputs/CUDA-symlinks/usr/bin \
+// RUN:%clang -v --target=x86_64-apple-macosx --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s --check-prefix SYMLINKS
+
+
+// We only take a CUDA installation from PATH if it contains libdevice.
+// RUN: env PATH=%S/Inputs/CUDA-nolibdevice/usr/local/cuda/bin \
+// RUN:%clang -v --target=i386-unknown-linux --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s --check-prefix NOCUDA
+// RUN: env PATH=%S/Inputs/CUDA-nolibdevice/usr/local/cuda/bin \
+// RUN:%clang -v --target=i386-apple-macosx --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s --check-prefix NOCUDA
+// RUN: env PATH=%S/Inputs/CUDA-nolibdevice/usr/local/cuda/bin \
+// RUN:%clang -v --target=x86_64-unknown-linux --sysroot=%S/no-cuda-there \
+// RUN:2>&1 | FileCheck %s --check-prefix NOCUDA
+// RUN: env PATH=%S/Inputs/CUDA-nolibdevice/usr/local/cuda/bin \
+// RUN:%clang -v --target=x86_64-apple-macosx --sysroot=%S/no-cuda-there \
+// R

[PATCH] D42573: [wip] The new threading implementation

2018-01-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 132105.
ilya-biryukov added a comment.

- An initial version of thread-per-file approach.

This is by no means a final version, we should definitely move things between 
files, do some renames, etc. before landing the final version.
Some things are not used anymore (e.g. ThreadPool), but are still in the patch, 
we'll need to remove them too.

The new version does not drop updates that are immidieately followed by other 
updates, this seems like an oversight and should be fixed too.
Please take a look at the overall design and let me know what you think. Feel 
free to add suggestions on how we can improve things, too!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.h
  clangd/ClangdUnitStore.cpp
  clangd/ClangdUnitStore.h
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  clangd/Threading.cpp
  clangd/Threading.h
  clangd/threading/Cancellation.cpp
  clangd/threading/Cancellation.h
  clangd/threading/RequestQueue.cpp
  clangd/threading/RequestQueue.h

Index: clangd/threading/RequestQueue.h
===
--- /dev/null
+++ clangd/threading/RequestQueue.h
@@ -0,0 +1,50 @@
+//===--- RequestQueue.h -*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===-===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_THREADING_REQUESTQUEUE_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_THREADING_REQUESTQUEUE_H
+
+#include "Function.h"
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+/// A thread-safe request queue managed by ThreadPool. This is an implementation
+/// detail, see QueueHandle and ThreadPool for user-facing APIs.
+class RequestQueue {
+public:
+  RequestQueue(std::condition_variable &Condition);
+
+  void addToFront(UniqueFunction Req);
+  void addToBack(UniqueFunction Req);
+
+  llvm::Optional> pop();
+
+  bool needsProcessing() const;
+
+  bool isScheduledForRemoval() const;
+  void setScheduledForRemoval();
+
+  void startProcessing();
+  void stopProcessing();
+
+private:
+  std::condition_variable &Condition;
+  mutable std::mutex Mutex;
+  bool IsProcessing;
+  bool IsScheduledForRemoval;
+  std::deque> Requests;
+};
+
+} // namespace clangd
+} // namespace clang
+#endif
Index: clangd/threading/RequestQueue.cpp
===
--- /dev/null
+++ clangd/threading/RequestQueue.cpp
@@ -0,0 +1,78 @@
+//===--- RequestQueue.cpp ---*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===-===//
+#include "RequestQueue.h"
+
+namespace clang {
+namespace clangd {
+
+RequestQueue::RequestQueue(std::condition_variable &Condition)
+: Condition(Condition), IsProcessing(false), IsScheduledForRemoval(false) {}
+
+void RequestQueue::addToFront(UniqueFunction Req) {
+  std::unique_lock Lock(Mutex);
+  Requests.emplace_front(std::move(Req));
+
+  Lock.unlock();
+  Condition.notify_one();
+}
+
+void RequestQueue::addToBack(UniqueFunction Req) {
+  std::unique_lock Lock(Mutex);
+  Requests.emplace_back(std::move(Req));
+
+  Lock.unlock();
+  Condition.notify_one();
+}
+
+llvm::Optional> RequestQueue::pop() {
+  std::unique_lock Lock(Mutex);
+  if (Requests.empty())
+return llvm::None;
+
+  UniqueFunction Result = std::move(Requests.front());
+  Requests.pop_front();
+  return Result;
+}
+
+bool RequestQueue::needsProcessing() const {
+  std::unique_lock Lock(Mutex);
+  if (IsProcessing)
+return false;
+  return !Requests.empty() || IsScheduledForRemoval;
+}
+
+bool RequestQueue::isScheduledForRemoval() const {
+  std::unique_lock Lock(Mutex);
+  return IsScheduledForRemoval;
+}
+
+void RequestQueue::setScheduledForRemoval() {
+  std::unique_lock Lock(Mutex);
+  assert(!IsScheduledForRemoval);
+  IsScheduledForRemoval = true;
+}
+
+void RequestQueue::startProcessing() {
+  std::unique_lock Lock(Mutex);
+  assert(!IsProcessing);
+  assert(!Requests.empty() || IsScheduledForRemoval);
+  IsProcessing = true;
+}
+
+void RequestQueue::stopProcessing() {
+  std::unique_lock Lock(Mutex);
+  assert(IsProcessing);
+  IsProcessing = false;
+
+  Lock.unlock();
+  Condition.notify_one();
+}
+
+} // namespace clangd
+} // namespace clang
Index: clangd/threading/Cancellation.h
===
--- /dev/null
+++ clangd/threading/Cancellation.h
@@ -0,0 +1,44 @@
+//===--- Cancellation.h -*- C++-*-==

[PATCH] D42174: [clangd] Refactored threading in ClangdServer

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

Addressed last review comments:

- Rename blockingRead to blockingRun
- Added a comment to ThreadPool's destructor


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42174

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnitStore.h
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  clangd/Threading.cpp
  clangd/Threading.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/TUSchedulerTests.cpp

Index: unittests/clangd/TUSchedulerTests.cpp
===
--- /dev/null
+++ unittests/clangd/TUSchedulerTests.cpp
@@ -0,0 +1,176 @@
+//===-- TUSchedulerTests.cpp *- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "TUScheduler.h"
+#include "TestFS.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+using ::testing::Pair;
+using ::testing::Pointee;
+
+void ignoreUpdate(Context, llvm::Optional>) {}
+void ignoreError(llvm::Error Err) {
+  handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
+}
+
+class TUSchedulerTests : public ::testing::Test {
+protected:
+  ParseInputs getInputs(PathRef File, std::string Contents) {
+return ParseInputs{*CDB.getCompileCommand(File), buildTestFS(Files),
+   std::move(Contents)};
+  }
+
+  void changeFile(PathRef File, std::string Contents) {
+Files[File] = Contents;
+  }
+
+private:
+  llvm::StringMap Files;
+  MockCompilationDatabase CDB;
+};
+
+TEST_F(TUSchedulerTests, MissingFiles) {
+  TUScheduler S(getDefaultAsyncThreadsCount(),
+/*StorePreamblesInMemory=*/true,
+/*ASTParsedCallback=*/nullptr);
+
+  auto Added = getVirtualTestFilePath("added.cpp");
+  changeFile(Added, "");
+
+  auto Missing = getVirtualTestFilePath("missing.cpp");
+  changeFile(Missing, "");
+
+  S.update(Context::empty(), Added, getInputs(Added, ""), ignoreUpdate);
+
+  // Assert each operation for missing file is an error (even if it's available
+  // in VFS).
+  S.runWithAST(Missing, [&](llvm::Expected AST) {
+ASSERT_FALSE(bool(AST));
+ignoreError(AST.takeError());
+  });
+  S.runWithPreamble(Missing, [&](llvm::Expected Preamble) {
+ASSERT_FALSE(bool(Preamble));
+ignoreError(Preamble.takeError());
+  });
+  S.remove(Missing, [&](llvm::Error Err) {
+EXPECT_TRUE(bool(Err));
+ignoreError(std::move(Err));
+  });
+
+  // Assert there aren't any errors for added file.
+  S.runWithAST(
+  Added, [&](llvm::Expected AST) { EXPECT_TRUE(bool(AST)); });
+  S.runWithPreamble(Added, [&](llvm::Expected Preamble) {
+EXPECT_TRUE(bool(Preamble));
+  });
+  S.remove(Added, [&](llvm::Error Err) { EXPECT_FALSE(bool(Err)); });
+
+  // Assert that all operations fail after removing the file.
+  S.runWithAST(Added, [&](llvm::Expected AST) {
+ASSERT_FALSE(bool(AST));
+ignoreError(AST.takeError());
+  });
+  S.runWithPreamble(Added, [&](llvm::Expected Preamble) {
+ASSERT_FALSE(bool(Preamble));
+ignoreError(Preamble.takeError());
+  });
+  S.remove(Added, [&](llvm::Error Err) {
+EXPECT_TRUE(bool(Err));
+ignoreError(std::move(Err));
+  });
+}
+
+TEST_F(TUSchedulerTests, ManyUpdates) {
+  const int FilesCount = 3;
+  const int UpdatesPerFile = 10;
+
+  std::mutex Mut;
+  int TotalASTReads = 0;
+  int TotalPreambleReads = 0;
+  int TotalUpdates = 0;
+
+  // Run TUScheduler and collect some stats.
+  {
+TUScheduler S(getDefaultAsyncThreadsCount(),
+  /*StorePreamblesInMemory=*/true,
+  /*ASTParsedCallback=*/nullptr);
+
+std::vector Files;
+for (int I = 0; I < FilesCount; ++I) {
+  Files.push_back(
+  getVirtualTestFilePath("foo" + std::to_string(I) + ".cpp").str());
+  changeFile(Files.back(), "");
+}
+
+llvm::StringRef Contents1 = R"cpp(int a;)cpp";
+llvm::StringRef Contents2 = R"cpp(int main() { return 1; })cpp";
+llvm::StringRef Contents3 =
+R"cpp(int a; int b; int sum() { return a + b; })cpp";
+
+llvm::StringRef AllContents[] = {Contents1, Contents2, Contents3};
+const int AllContentsSize = 3;
+
+for (int FileI = 0; FileI < FilesCount; ++FileI) {
+  for (int UpdateI = 0; UpdateI < UpdatesPerFile; ++UpdateI) {
+auto Contents = AllContents[(FileI + UpdateI) % AllContentsSize];
+
+auto File = Files[FileI];
+auto Inputs = getInputs(File, Contents.str());
+static Key> FileAndUpdateKey;
+auto Ctx = Context::empty().derive(FileAndUpdateKey,
+   std

[PATCH] D42174: [clangd] Refactored threading in ClangdServer

2018-01-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/TUScheduler.h:23
+/// synchronously).
+unsigned getDefaultAsyncThreadsCount();
+

sammccall wrote:
> just use llvm::hardware_concurrency()?
It can return 0, which will cause clangd to run synchronously. This function is 
only called when someone wants to have at least one worker thread for async 
processing.

We can change it if you want, but I'd rather leave it as is in this patch.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42174



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


[clang-tools-extra] r323851 - [clangd] Refactored threading in ClangdServer

2018-01-31 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Jan 31 00:51:16 2018
New Revision: 323851

URL: http://llvm.org/viewvc/llvm-project?rev=323851&view=rev
Log:
[clangd] Refactored threading in ClangdServer

Summary:
We now provide an abstraction of Scheduler that abstracts threading
and resource management in ClangdServer.
No changes to behavior are intended with an exception of changed error
messages.
This patch is preliminary work to allow a revamped threading
implementation that will move the threading code out of CppFile.

Reviewers: sammccall, bkramer, jkorous-apple

Reviewed By: sammccall

Subscribers: hokein, mgorny, hintonda, ioeric, jkorous-apple, cfe-commits, 
klimek

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

Added:
clang-tools-extra/trunk/clangd/TUScheduler.cpp
clang-tools-extra/trunk/clangd/TUScheduler.h
clang-tools-extra/trunk/clangd/Threading.cpp
clang-tools-extra/trunk/clangd/Threading.h
clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/ClangdUnitStore.h
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=323851&r1=323850&r2=323851&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Wed Jan 31 00:51:16 2018
@@ -21,7 +21,9 @@ add_clang_library(clangDaemon
   Protocol.cpp
   ProtocolHandlers.cpp
   SourceCode.cpp
+  Threading.cpp
   Trace.cpp
+  TUScheduler.cpp
   URI.cpp
   XRefs.cpp
   index/FileIndex.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=323851&r1=323850&r2=323851&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Wed Jan 31 00:51:16 2018
@@ -22,8 +22,6 @@
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/FormatProviders.h"
-#include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
@@ -33,6 +31,30 @@ using namespace clang::clangd;
 
 namespace {
 
+// Issues an async read of AST and waits for results.
+template 
+Ret blockingRunWithAST(TUScheduler &S, PathRef File, Func &&F) {
+  std::packaged_task)> Task(
+  std::forward(F));
+  auto Future = Task.get_future();
+  S.runWithAST(File, std::move(Task));
+  return Future.get();
+}
+
+// Issues an async read of preamble and waits for results.
+template 
+Ret blockingRunWithPreamble(TUScheduler &S, PathRef File, Func &&F) {
+  std::packaged_task)> Task(
+  std::forward(F));
+  auto Future = Task.get_future();
+  S.runWithPreamble(File, std::move(Task));
+  return Future.get();
+}
+
+void ignoreError(llvm::Error Err) {
+  handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
+}
+
 std::string getStandardResourceDir() {
   static int Dummy; // Just an address in this process.
   return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
@@ -67,70 +89,6 @@ RealFileSystemProvider::getTaggedFileSys
   return make_tagged(vfs::getRealFileSystem(), VFSTag());
 }
 
-unsigned clangd::getDefaultAsyncThreadsCount() {
-  unsigned HardwareConcurrency = std::thread::hardware_concurrency();
-  // C++ standard says that hardware_concurrency()
-  // may return 0, fallback to 1 worker thread in
-  // that case.
-  if (HardwareConcurrency == 0)
-return 1;
-  return HardwareConcurrency;
-}
-
-ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
-: RunSynchronously(AsyncThreadsCount == 0) {
-  if (RunSynchronously) {
-// Don't start the worker thread if we're running synchronously
-return;
-  }
-
-  Workers.reserve(AsyncThreadsCount);
-  for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
-Workers.push_back(std::thread([this, I]() {
-  llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
-  while (true) {
-UniqueFunction Request;
-
-// Pick request from the queue
-{
-  std::unique_lock Lock(Mutex);
-  // Wait for more requests.
-  RequestCV.wait(Lock,
- [this] { return !RequestQueue.empty() || Done; });
-  if (Done)
-return;
-
-  assert(!RequestQueue.empty() && "RequestQueue was empty");
-
-  // We process requests starting from the front of the queue. Users of
-  // ClangdScheduler have a way to prioritise their requests by putting
-  // them to the 

[PATCH] D42174: [clangd] Refactored threading in ClangdServer

2018-01-31 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323851: [clangd] Refactored threading in ClangdServer 
(authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42174

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

Index: clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
@@ -0,0 +1,176 @@
+//===-- TUSchedulerTests.cpp *- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "TUScheduler.h"
+#include "TestFS.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+using ::testing::Pair;
+using ::testing::Pointee;
+
+void ignoreUpdate(Context, llvm::Optional>) {}
+void ignoreError(llvm::Error Err) {
+  handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
+}
+
+class TUSchedulerTests : public ::testing::Test {
+protected:
+  ParseInputs getInputs(PathRef File, std::string Contents) {
+return ParseInputs{*CDB.getCompileCommand(File), buildTestFS(Files),
+   std::move(Contents)};
+  }
+
+  void changeFile(PathRef File, std::string Contents) {
+Files[File] = Contents;
+  }
+
+private:
+  llvm::StringMap Files;
+  MockCompilationDatabase CDB;
+};
+
+TEST_F(TUSchedulerTests, MissingFiles) {
+  TUScheduler S(getDefaultAsyncThreadsCount(),
+/*StorePreamblesInMemory=*/true,
+/*ASTParsedCallback=*/nullptr);
+
+  auto Added = getVirtualTestFilePath("added.cpp");
+  changeFile(Added, "");
+
+  auto Missing = getVirtualTestFilePath("missing.cpp");
+  changeFile(Missing, "");
+
+  S.update(Context::empty(), Added, getInputs(Added, ""), ignoreUpdate);
+
+  // Assert each operation for missing file is an error (even if it's available
+  // in VFS).
+  S.runWithAST(Missing, [&](llvm::Expected AST) {
+ASSERT_FALSE(bool(AST));
+ignoreError(AST.takeError());
+  });
+  S.runWithPreamble(Missing, [&](llvm::Expected Preamble) {
+ASSERT_FALSE(bool(Preamble));
+ignoreError(Preamble.takeError());
+  });
+  S.remove(Missing, [&](llvm::Error Err) {
+EXPECT_TRUE(bool(Err));
+ignoreError(std::move(Err));
+  });
+
+  // Assert there aren't any errors for added file.
+  S.runWithAST(
+  Added, [&](llvm::Expected AST) { EXPECT_TRUE(bool(AST)); });
+  S.runWithPreamble(Added, [&](llvm::Expected Preamble) {
+EXPECT_TRUE(bool(Preamble));
+  });
+  S.remove(Added, [&](llvm::Error Err) { EXPECT_FALSE(bool(Err)); });
+
+  // Assert that all operations fail after removing the file.
+  S.runWithAST(Added, [&](llvm::Expected AST) {
+ASSERT_FALSE(bool(AST));
+ignoreError(AST.takeError());
+  });
+  S.runWithPreamble(Added, [&](llvm::Expected Preamble) {
+ASSERT_FALSE(bool(Preamble));
+ignoreError(Preamble.takeError());
+  });
+  S.remove(Added, [&](llvm::Error Err) {
+EXPECT_TRUE(bool(Err));
+ignoreError(std::move(Err));
+  });
+}
+
+TEST_F(TUSchedulerTests, ManyUpdates) {
+  const int FilesCount = 3;
+  const int UpdatesPerFile = 10;
+
+  std::mutex Mut;
+  int TotalASTReads = 0;
+  int TotalPreambleReads = 0;
+  int TotalUpdates = 0;
+
+  // Run TUScheduler and collect some stats.
+  {
+TUScheduler S(getDefaultAsyncThreadsCount(),
+  /*StorePreamblesInMemory=*/true,
+  /*ASTParsedCallback=*/nullptr);
+
+std::vector Files;
+for (int I = 0; I < FilesCount; ++I) {
+  Files.push_back(
+  getVirtualTestFilePath("foo" + std::to_string(I) + ".cpp").str());
+  changeFile(Files.back(), "");
+}
+
+llvm::StringRef Contents1 = R"cpp(int a;)cpp";
+llvm::StringRef Contents2 = R"cpp(int main() { return 1; })cpp";
+llvm::StringRef Contents3 =
+R"cpp(int a; int b; int sum() { return a + b; })cpp";
+
+llvm::StringRef AllContents[] = {Contents1, Contents2, Contents3};
+const int AllContentsSize = 3;
+
+for (int FileI = 0; FileI < FilesCount; ++FileI) {
+  for (int UpdateI = 0; UpdateI < UpdatesPerFile; ++UpdateI) {
+a

[PATCH] D42708: [clang-format] Set BinPackObjCProtocolList to Never for google style

2018-01-31 Thread Jacek Olesiak via Phabricator via cfe-commits
jolesiak added inline comments.



Comment at: lib/Format/Format.cpp:765
 GoogleStyle.ColumnLimit = 100;
+GoogleStyle.BinPackObjCProtocolList = FormatStyle::BPS_Never;
   }

If I understand correctly this is meant to be ObjC-specific flag. I feel like 
this should be put in general config (next to 
GoogleStyle.ObjcSpaceAfterProperty and GoogleStyle.ObjCSpaceBeforeProtocolList; 
~50 lines above).
To me putting it inside 'if' check means different value is used for ObjC than 
for other languages (what isn't the case here, as this flag shouldn't be used 
in formatting other languages code). 


Repository:
  rC Clang

https://reviews.llvm.org/D42708



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


[PATCH] D41102: Setup clang-doc frontend framework

2018-01-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Really sorry about the delay in getting to this.
At a high level, I'm most concerned about:

- the monolithic in-memory intermediate format, which seems to put hard limits 
on performance and scalability
- having high-level documentation and clear APIs
- having multiple intermediate formats




Comment at: test/Tooling/clang-doc-basic.cpp:3
+// RUN: mkdir %t
+// RUN: echo '[{"directory":"%t","command":"clang++ -c 
%t/test.cpp","file":"%t/test.cpp"}]' | sed -e 's/\\/\//g' > 
%t/compile_commands.json
+// RUN: cp "%s" "%t/test.cpp"

nit: you can also just write compile_flags.txt, which in this case would be 
empty



Comment at: test/Tooling/clang-doc-basic.cpp:22
+ // CHECK: ---
+ // CHECK: Qualified Name:  ''
+ // CHECK: Name:''

what is this? The TU? The global namespace?
What's the value in emitting it?



Comment at: tools/clang-doc/ClangDoc.h:1
+//===-- ClangDoc.cpp - ClangDoc -*- C++ 
-*-===//
+//

This needs some high-level documentation: what does the clang-doc library do, 
what's the main user (clang-doc command-line tool), what are the major moving 
parts.

I don't personally have a strong opinion on how this is split between this 
header / the implementation / a documentation page for the tool itself, but 
we'll probably need *something* for each of those.

(I think it's OK to defer the user-facing documentation to another patch, but 
we should do it before the tool becomes widely publicized or included in an 
llvm release)



Comment at: tools/clang-doc/ClangDoc.h:27
+
+// A Context which contains extra options which are used in ClangMoveTool.
+struct ClangDocContext {

what's clangmovetool?



Comment at: tools/clang-doc/ClangDoc.h:27
+
+// A Context which contains extra options which are used in ClangMoveTool.
+struct ClangDocContext {

sammccall wrote:
> what's clangmovetool?
nit: this sounds more like "options" than a context to me, though there's only 
one member to go on :-)



Comment at: tools/clang-doc/ClangDoc.h:29
+struct ClangDocContext {
+  // Which format in which to emit representation.
+  OutFormat EmitFormat;

Is this the intermediate representation referred to in the design doc, or the 
final output format?

If the former, why two formats rather than picking one?
YAML is nice for being usable by out-of-tree tools (though not as nice as 
JSON). But it seems like providing YAML as a trivial backend format would fit 
well?
Bitcode is presumably more space-efficient - if this is significant in practice 
it seems like a better choice.



Comment at: tools/clang-doc/ClangDoc.h:33
+
+class ClangDocVisitor : public RecursiveASTVisitor {
+public:

This API makes essentially everything public. Is that the intent?

It seems like `ClangDocVisitor` is a detail, and the operation you want to 
expose is "extract doc from this AST into this reporter" or maybe "create an 
AST consumer that feeds this reporter".

It would be useful to have an API to extract documentation from individual AST 
nodes (e.g. a Decl). But I'd be nervous about trying to use the classes exposed 
here to do that. If it's efficiently possible, it'd be nice to expose a 
function.
(one use case for this is clangd)



Comment at: tools/clang-doc/ClangDoc.h:39
+
+  bool VisitTagDecl(const TagDecl *D);
+  bool VisitNamespaceDecl(const NamespaceDecl *D);

`override` where applicable



Comment at: tools/clang-doc/ClangDoc.h:80
+
+class ClangDocActionFactory : public tooling::FrontendActionFactory {
+public:

this class can definitely be hidden in the c++ file, behind a 
newClangDocActionFactory() func
(actually I think newFrontendActionFactory in Tooling.h could be extended to 
cover this, but not 100% sure)



Comment at: tools/clang-doc/ClangDocReporter.cpp:1
+//===-- ClangDocReporter.cpp - ClangDoc Reporter *- C++ 
-*-===//
+//

It looks like the plan for merging data across sources is to hold all 
information in one in-memory structure and incrementally add to it as you get 
information from TUs.
(This should be documented somewhere!)

This seems somewhat hostile to parallel processing: you're going to need to 
synchronize access to the structs owned by the ClangDocReporter if you want to 
gather from multiple TUs at once. Moreover, documenting large codebases using 
multiple machines in parallel seems very difficult.
And obviously it assumes you can fit the generated documentation for the 
codebase in memory, which would be nice to avoid.

Have you considered a mapreduce-like architecture, where the mapper gets AST 
callbacks and spits out data, and the reducer is responsible for assembling all 
the data together?

We don't

[PATCH] D42639: [clang-move] Clever on handling header file which includes itself.

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



Comment at: clang-move/ClangMove.cpp:708
+// Find old.h includes "old.h".
+if (AbsoluteOldHeader == AbsoluteOldHeader) {
+  OldHeaderIncludeRangeInHeader = IncludeFilenameRange;

ioeric wrote:
> This check is always true?
Oops, good catch, should be AbsoluteIncludeHeader.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42639



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


[PATCH] D42639: [clang-move] Clever on handling header file which includes itself.

2018-01-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 132111.
hokein marked an inline comment as done.
hokein added a comment.

address review comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42639

Files:
  clang-move/ClangMove.cpp
  clang-move/ClangMove.h
  unittests/clang-move/ClangMoveTests.cpp

Index: unittests/clang-move/ClangMoveTests.cpp
===
--- unittests/clang-move/ClangMoveTests.cpp
+++ unittests/clang-move/ClangMoveTests.cpp
@@ -293,6 +293,32 @@
   EXPECT_EQ(0u, Results.size());
 }
 
+TEST(ClangMove, HeaderIncludeSelf) {
+  move::MoveDefinitionSpec Spec;
+  Spec.Names = {std::string("Foo")};
+  Spec.OldHeader = "foo.h";
+  Spec.OldCC = "foo.cc";
+  Spec.NewHeader = "new_foo.h";
+  Spec.NewCC = "new_foo.cc";
+
+  const char TestHeader[] = "#ifndef FOO_H\n"
+"#define FOO_H\n"
+"#include \"foo.h\"\n"
+"class Foo {};\n"
+"#endif\n";
+  const char TestCode[] = "#include \"foo.h\"";
+  const char ExpectedNewHeader[] = "#ifndef FOO_H\n"
+   "#define FOO_H\n"
+   "#include \"new_foo.h\"\n"
+   "class Foo {};\n"
+   "#endif\n";
+  const char ExpectedNewCC[] = "#include \"new_foo.h\"";
+  auto Results = runClangMoveOnCode(Spec, TestHeader, TestCode);
+  EXPECT_EQ("", Results[Spec.OldHeader]);
+  EXPECT_EQ(ExpectedNewHeader, Results[Spec.NewHeader]);
+  EXPECT_EQ(ExpectedNewCC, Results[Spec.NewCC]);
+}
+
 TEST(ClangMove, MoveAll) {
   std::vector TestHeaders = {
 "class A {\npublic:\n  int f();\n};",
Index: clang-move/ClangMove.h
===
--- clang-move/ClangMove.h
+++ clang-move/ClangMove.h
@@ -176,7 +176,11 @@
   /// The source range for the written file name in #include (i.e. "old.h" for
   /// #include "old.h") in old.cc,  including the enclosing quotes or angle
   /// brackets.
-  clang::CharSourceRange OldHeaderIncludeRange;
+  clang::CharSourceRange OldHeaderIncludeRangeInCC;
+  /// The source range for the written file name in #include (i.e. "old.h" for
+  /// #include "old.h") in old.h,  including the enclosing quotes or angle
+  /// brackets.
+  clang::CharSourceRange OldHeaderIncludeRangeInHeader;
   /// Mapping from FilePath to FileID, which can be used in post processes like
   /// cleanup around replacements.
   llvm::StringMap FilePathToFileID;
Index: clang-move/ClangMove.cpp
===
--- clang-move/ClangMove.cpp
+++ clang-move/ClangMove.cpp
@@ -694,22 +694,28 @@
 const SourceManager &SM) {
   SmallVector HeaderWithSearchPath;
   llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
-  std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
-  if (AbsoluteOldHeader ==
+  std::string AbsoluteIncludeHeader =
   MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
-   HeaderWithSearchPath.size( {
-OldHeaderIncludeRange = IncludeFilenameRange;
-return;
-  }
-
+   HeaderWithSearchPath.size()));
   std::string IncludeLine =
   IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
: ("#include \"" + IncludeHeader + "\"\n").str();
 
+  std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
   std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
   if (AbsoluteOldHeader == AbsoluteCurrentFile) {
+// Find old.h includes "old.h".
+if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
+  OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
+  return;
+}
 HeaderIncludes.push_back(IncludeLine);
   } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
+// Find old.cc includes "old.h".
+if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
+  OldHeaderIncludeRangeInCC = IncludeFilenameRange;
+  return;
+}
 CCIncludes.push_back(IncludeLine);
   }
 }
@@ -857,13 +863,18 @@
   if (!NewFile.empty()) {
 auto AllCode = clang::tooling::Replacements(
 clang::tooling::Replacement(NewFile, 0, 0, Code));
-// If we are moving from old.cc, an extra step is required: excluding
-// the #include of "old.h", instead, we replace it with #include of "new.h".
-if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
-  AllCode = AllCode.merge(
-  clang::tooling::Replacements(clang::tooling::Replacement(
-  SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
-}
+auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) {
+  AllCode = AllCode.merge(clang::tooling::Replacements(
+  clang::tooling::

[PATCH] D41720: [clang-tidy] Add a -show-color flag.

2018-01-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: clang-tidy/ClangTidyOptions.h:93
+  /// \brief Show color diagnostics.
+  llvm::Optional ShowColor;
+

itessier wrote:
> alexfh wrote:
> > This doesn't belong to ClangTidyOptions. It's specific to the CLI, but CLI 
> > is not the only frontend for clang-tidy.
> Since we have to propagate the value to the ErrorReporter, how about adding a 
> bool param to the ErrorReporter ctor? We could add a setter instead, but that 
> would require moving a diag printer call out of the ctor since it uses the 
> DiagOpts instance.
> 
> The colour logic would then be moved into either clangTidyMain or 
> handleErrors.
A bool parameter in ErrorReporter ctor seems good.


https://reviews.llvm.org/D41720



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


[PATCH] D42464: add prefix with '_' support for property name. Corresponding apple dev doc: https://developer.apple.com/library/content/qa/qa1908/_index.html

2018-01-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:115
+
+bool prefixedPropertyNameMatches(const llvm::StringRef &PropertyName,
+ const std::vector &Acronyms) {

benhamilton wrote:
> Wizard wrote:
> > hokein wrote:
> > > Wizard wrote:
> > > > hokein wrote:
> > > > > no need to pass const reference of `llvm::StringRef`. `StringRef` is 
> > > > > cheap.
> > > > The original property name I directly get from ast is a const. If I 
> > > > remove the const here, I will have to make a copy of the property name 
> > > > before calling this.
> > > > I prefer keep this const to save that copy :-)
> > > Why? `MatchedDecl->getName()` returns `llvm::StringRef`. As the name 
> > > indicates, StringRef is a const reference of String, using StringRef is 
> > > sufficient.
> > > 
> > > The same to ArrayRef. So the function is like `bool 
> > > prefixedPropertyNameMatches(llvm::StringRef PropertyName, 
> > > llvm::ArrayRef Acronyms)`.
> > > 
> > > 
> > If I remove the const in the method, compiler will have error of "candidate 
> > function not viable: expects an l-value for 1st argument". I believe it 
> > cannot accept a const reference as arg if the definition is var.
> I think hokein@ is saying you should change:
> 
>   const llvm::StringRef &
> 
> to:
> 
>   llvm::StringRef
> 
> Note removing both `const` and `&`, not just removing `const`. This is 
> because there is no need to pass these by reference, they are already a 
> reference.
> 
> Same with `const llvm::ArrayRef &`, it should just be `llvm::ArrayRef`.
Yeah, this is what I mean, thanks for the clarifying.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:151
+  hasCategoryPropertyPrefix(MatchedDecl->getName())) {
+const auto *CategoryDecl = (const ObjCCategoryDecl *)(DeclContext);
+if (!prefixedPropertyNameMatches(MatchedDecl->getName(), SpecialAcronyms) 
||

Wizard wrote:
> benhamilton wrote:
> > Wizard wrote:
> > > hokein wrote:
> > > > Wizard wrote:
> > > > > hokein wrote:
> > > > > > Consider using `const auto* CategoryDecl = 
> > > > > > dyn_cast(DeclContext)`, we can get rid of this 
> > > > > > cast, and `NodeKind` variable.
> > > > > Tried that before but I encountered 2 issues:
> > > > > 1. 'clang::DeclContext' is not polymorphic
> > > > > 2. cannot use dynamic_cast with -fno-rtti
> > > > > which are preventing me from using dynamic_cast
> > > > Sorry, I mean `llvm::dyn_cast` here, it should work.
> > > It is not working either. It says "error: static_cast from 'clang::Decl 
> > > *' to 'const clang::ObjCCategoryDecl *const *' is not allowed" though I 
> > > have no idea why it is regarded as a static cast.
> > > I am using it like this:
> > > const auto *CategoryDecl = llvm::dyn_cast > > *>(DeclContext);
> > You definitely don't want to use a C-style cast. My guess is adding const 
> > is not part of what dyn_cast<> does, so you can probably remove that from 
> > the dyn_cast<>. (You can of course assign to a const pointer if you want.)
> > 
> Finally figured out that I cannot put pointer type in dyn_cast<>. It needs to 
> be "llvm::dyn_cast(DeclContext)" even though DeclContext is 
> a pointer. I have to say it is weird in C++...
Yeah, llvm::dyn_cast doesn't need to specify the pointer, sorry for my 
beginning comment...


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42464



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


[PATCH] D41720: [clang-tidy] Add a -show-color flag.

2018-01-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: test/clang-tidy/show-color.cpp:7
+  int *value = 0;
+  // CHECK-COLOR: [[BOLD:.\[1m]]{{.*}}[[@LINE+2]]:10: 
[[RESET:.\[0m]][[MAGENTA:.\[0;1;35m]]warning: [[RESET]][[BOLD]]Dereference of 
null pointer (loaded from variable 'value') 
[clang-analyzer-core.NullDereference][[RESET]]
+  // CHECK-NO-COLOR: [[@LINE+1]]:10: warning: Dereference of null pointer 
(loaded from variable 'value') [clang-analyzer-core.NullDereference]

nit: I'd prefer to depend on the wording and format of static analyzer warnings 
only where necessary.  Static analyzer is in a different repository and when it 
changes, it's a bit more difficult for folks to detect failures in clang-tidy. 
Here we could use any native clang-tidy check instead.


https://reviews.llvm.org/D41720



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


[clang-tools-extra] r323859 - [clangd] Attempt to fix compilation breakage with MSVC.

2018-01-31 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Jan 31 01:50:21 2018
New Revision: 323859

URL: http://llvm.org/viewvc/llvm-project?rev=323859&view=rev
Log:
[clangd] Attempt to fix compilation breakage with MSVC.

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

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=323859&r1=323858&r2=323859&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Wed Jan 31 01:50:21 2018
@@ -34,21 +34,25 @@ namespace {
 // Issues an async read of AST and waits for results.
 template 
 Ret blockingRunWithAST(TUScheduler &S, PathRef File, Func &&F) {
-  std::packaged_task)> Task(
+  // Using Optional to workaround MSVC bug. It requires future<> arguments to
+  // have default ctor.
+  std::packaged_task(llvm::Expected)> Task(
   std::forward(F));
   auto Future = Task.get_future();
   S.runWithAST(File, std::move(Task));
-  return Future.get();
+  return *Future.get();
 }
 
 // Issues an async read of preamble and waits for results.
 template 
 Ret blockingRunWithPreamble(TUScheduler &S, PathRef File, Func &&F) {
-  std::packaged_task)> Task(
-  std::forward(F));
+  // Using Optional to workaround MSVC bug. It requires future<> arguments to
+  // have default ctor.
+  std::packaged_task(llvm::Expected)>
+  Task(std::forward(F));
   auto Future = Task.get_future();
   S.runWithPreamble(File, std::move(Task));
-  return Future.get();
+  return *Future.get();
 }
 
 void ignoreError(llvm::Error Err) {


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


r323860 - [clang-format] Adds space around braces in text protos

2018-01-31 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Jan 31 02:14:10 2018
New Revision: 323860

URL: http://llvm.org/viewvc/llvm-project?rev=323860&view=rev
Log:
[clang-format] Adds space around braces in text protos

Summary:
This patch modifies the text proto Google style to add spaces around braces.

I investigated using something different than Cpp11BracedListStyle, but it 
turns out it's what we want and also the java and js styles also depend on that.

Reviewers: djasper

Reviewed By: djasper

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTestProto.cpp
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=323860&r1=323859&r2=323860&view=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Jan 31 02:14:10 2018
@@ -750,6 +750,7 @@ FormatStyle getGoogleStyle(FormatStyle::
   } else if (Language == FormatStyle::LK_Proto) {
 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
 GoogleStyle.SpacesInContainerLiterals = false;
+GoogleStyle.Cpp11BracedListStyle = false;
   } else if (Language == FormatStyle::LK_ObjC) {
 GoogleStyle.ColumnLimit = 100;
   }

Modified: cfe/trunk/unittests/Format/FormatTestProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestProto.cpp?rev=323860&r1=323859&r2=323860&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestProto.cpp Wed Jan 31 02:14:10 2018
@@ -97,7 +97,7 @@ TEST_F(FormatTestProto, FormatsEnums) {
"  TYPE_B = 2;\n"
"};");
   verifyFormat("enum Type {\n"
-   "  UNKNOWN = 0 [(some_options) = {a: aa, b: bb}];\n"
+   "  UNKNOWN = 0 [(some_options) = { a: aa, b: bb }];\n"
"};");
   verifyFormat("enum Type {\n"
"  UNKNOWN = 0 [(some_options) = {\n"
@@ -121,7 +121,7 @@ TEST_F(FormatTestProto, MessageFieldAttr
   verifyFormat("optional LongMessageType long_proto_field = 1\n"
"[default = REALLY_REALLY_LONG_CONSTANT_VALUE];");
   verifyFormat("repeated double value = 1\n"
-   "[(aaa.a) = {a: }];");
+   "[(aaa.a) = { a:  }];");
   verifyFormat("repeated double value = 1 [(aaa.a) = {\n"
"  : AA,\n"
"  : BB\n"
@@ -183,27 +183,27 @@ TEST_F(FormatTestProto, FormatsOptions)
"  field_a: OK\n"
"  field_b: \"OK\"\n"
"  field_c: \"OK\"\n"
-   "  msg_field: {field_d: 123}\n"
+   "  msg_field: { field_d: 123 }\n"
"};");
   verifyFormat("option (MyProto.options) = {\n"
"  field_a: OK\n"
"  field_b: \"OK\"\n"
"  field_c: \"OK\"\n"
-   "  msg_field: {field_d: 123 field_e: OK}\n"
+   "  msg_field: { field_d: 123 field_e: OK }\n"
"};");
   verifyFormat("option (MyProto.options) = {\n"
"  field_a: OK  // Comment\n"
"  field_b: \"OK\"\n"
"  field_c: \"OK\"\n"
-   "  msg_field: {field_d: 123}\n"
+   "  msg_field: { field_d: 123 }\n"
"};");
   verifyFormat("option (MyProto.options) = {\n"
"  field_c: \"OK\"\n"
-   "  msg_field {field_d: 123}\n"
+   "  msg_field { field_d: 123 }\n"
"};");
   verifyFormat("option (MyProto.options) = {\n"
"  field_a: OK\n"
-   "  field_b {field_c: OK}\n"
+   "  field_b { field_c: OK }\n"
"  field_d: OKOKOK\n"
"  field_e: OK\n"
"}");
@@ -247,7 +247,7 @@ TEST_F(FormatTestProto, FormatsOptions)
 
   verifyFormat("option (MyProto.options) = <\n"
"  field_a: \"OK\"\n"
-   "  msg_field: {field_b: OK}\n"
+   "  msg_field: { field_b: OK }\n"
"  field_g: OK\n"
"  field_g: OK\n"
"  field_g: OK\n"
@@ -359,7 +359,7 @@ TEST_F(FormatTestProto, FormatsOptions)
 
   verifyFormat("option (MyProto.options) = <\n"
"  data1 \n"
-   "  data2 {key2: value2}\n"
+   "  data2 { key2: value2 }\n"
">;");
 
   verifyFormat("option (MyProto.options) = <\n"
@@ -372,7 +372,7 @@ TEST_F(FormatTestProto, FormatsOptions)
"  app_id: 'com.javax.swing.salsa.

[PATCH] D42685: [clang-format] Adds space around braces in text protos

2018-01-31 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323860: [clang-format] Adds space around braces in text 
protos (authored by krasimir, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42685?vs=131947&id=132117#toc

Repository:
  rC Clang

https://reviews.llvm.org/D42685

Files:
  lib/Format/Format.cpp
  unittests/Format/FormatTestProto.cpp
  unittests/Format/FormatTestRawStrings.cpp
  unittests/Format/FormatTestTextProto.cpp

Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -750,6 +750,7 @@
   } else if (Language == FormatStyle::LK_Proto) {
 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
 GoogleStyle.SpacesInContainerLiterals = false;
+GoogleStyle.Cpp11BracedListStyle = false;
   } else if (Language == FormatStyle::LK_ObjC) {
 GoogleStyle.ColumnLimit = 100;
   }
Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -49,9 +49,9 @@
 TEST_F(FormatTestTextProto, SupportsMessageFields) {
   verifyFormat("msg_field: {}");
 
-  verifyFormat("msg_field: {field_a: A}");
+  verifyFormat("msg_field: { field_a: A }");
 
-  verifyFormat("msg_field: {field_a: \"OK\" field_b: 123}");
+  verifyFormat("msg_field: { field_a: \"OK\" field_b: 123 }");
 
   verifyFormat("msg_field: {\n"
"  field_a: 1\n"
@@ -63,9 +63,9 @@
 
   verifyFormat("msg_field {}");
 
-  verifyFormat("msg_field {field_a: A}");
+  verifyFormat("msg_field { field_a: A }");
 
-  verifyFormat("msg_field {field_a: \"OK\" field_b: 123}");
+  verifyFormat("msg_field { field_a: \"OK\" field_b: 123 }");
 
   verifyFormat("msg_field {\n"
"  field_a: 1\n"
@@ -78,11 +78,11 @@
"  field_h: 1234.567e-89\n"
"}");
 
-  verifyFormat("msg_field: {msg_field {field_a: 1}}");
+  verifyFormat("msg_field: { msg_field { field_a: 1 } }");
 
   verifyFormat("id: \"ala.bala\"\n"
-   "item {type: ITEM_A rank: 1 score: 90.0}\n"
-   "item {type: ITEM_B rank: 2 score: 70.5}\n"
+   "item { type: ITEM_A rank: 1 score: 90.0 }\n"
+   "item { type: ITEM_B rank: 2 score: 70.5 }\n"
"item {\n"
"  type: ITEM_A\n"
"  rank: 3\n"
@@ -102,24 +102,24 @@
   verifyFormat("field_a: OK\n"
"field_b: \"OK\"\n"
"field_c: \"OK\"\n"
-   "msg_field: {field_d: 123}\n"
+   "msg_field: { field_d: 123 }\n"
"field_e: OK\n"
"field_f: OK");
 
   verifyFormat("field_a: OK\n"
"field_b: \"OK\"\n"
"field_c: \"OK\"\n"
-   "msg_field: {field_d: 123 field_e: OK}");
+   "msg_field: { field_d: 123 field_e: OK }");
 
   verifyFormat("a: {\n"
"  field_a: OK\n"
-   "  field_b {field_c: OK}\n"
+   "  field_b { field_c: OK }\n"
"  field_d: OKOKOK\n"
"  field_e: OK\n"
"}");
 
   verifyFormat("field_a: OK,\n"
-   "field_b {field_c: OK},\n"
+   "field_b { field_c: OK },\n"
"field_d: OKOKOK,\n"
"field_e: OK");
 }
@@ -150,10 +150,10 @@
   verifyFormat("msg_field: >>");
   verifyFormat("msg_field ");
   verifyFormat("msg_field , field_c: OK>");
-  verifyFormat("msg_field >");
+  verifyFormat("msg_field >");
   verifyFormat("msg_field: ");
   verifyFormat("msg_field: , field_c: OK>");
-  verifyFormat("msg_field: >");
+  verifyFormat("msg_field: >");
   verifyFormat("field_a: \"OK\", msg_field: , field_c: {}");
   verifyFormat("field_a , msg_field: , field_c <>");
   verifyFormat("field_a  msg_field:  field_c <>");
@@ -200,7 +200,7 @@
 
   verifyFormat("msg_field: <\n"
"  field_a: \"OK\"\n"
-   "  msg_field: {field_b: OK}\n"
+   "  msg_field: { field_b: OK }\n"
"  field_g: OK\n"
"  field_g: OK\n"
"  field_g: OK\n"
@@ -226,7 +226,7 @@
"  field_b2: ok,\n"
"  field_b3: <\n"
"field_x {}  // Comment\n"
-   "field_y: {field_z: 1}\n"
+   "field_y: { field_z: 1 }\n"
"field_w: ok\n"
"  >\n"
"  field {\n"
@@ -258,7 +258,7 @@
   verifyFormat("app_id: 'com.javax.swing.salsa.latino'\n"
"head_id: 1\n"
"data \n"
-   "data {key: value}");
+   "data { key: value }");
 
   verifyFormat("app {\n"
"  app_id: 'com.javax.swing.salsa.latino'\n"
@@ -274,24 +274,24 @@
 
   verifyFormat("app_id: 'com.javax.swing.salsa.latino'\n"
"headheadheadheadheadhead_id: 1\n

[PATCH] D42727: [clang-format] Adds space around angle brackets in text protos

2018-01-31 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.
krasimir added a reviewer: djasper.
Herald added subscribers: cfe-commits, klimek.

This patch adds spaces around angle brackets in text proto Google style.
Previously these were detected as template openers and closers, which happened
to have the expected effect. Now we detect them as scope openers and closers
similarly to the way braces are handled in this context.


Repository:
  rC Clang

https://reviews.llvm.org/D42727

Files:
  lib/Format/ContinuationIndenter.cpp
  lib/Format/FormatToken.h
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestRawStrings.cpp
  unittests/Format/FormatTestTextProto.cpp

Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -143,21 +143,21 @@
   // Single-line tests
   verifyFormat("msg_field <>");
   verifyFormat("msg_field: <>");
-  verifyFormat("msg_field ");
-  verifyFormat("msg_field: ");
-  verifyFormat("msg_field >");
-  verifyFormat("msg_field >>");
-  verifyFormat("msg_field: >>");
-  verifyFormat("msg_field ");
-  verifyFormat("msg_field , field_c: OK>");
-  verifyFormat("msg_field >");
-  verifyFormat("msg_field: ");
-  verifyFormat("msg_field: , field_c: OK>");
-  verifyFormat("msg_field: >");
-  verifyFormat("field_a: \"OK\", msg_field: , field_c: {}");
-  verifyFormat("field_a , msg_field: , field_c <>");
-  verifyFormat("field_a  msg_field:  field_c <>");
-  verifyFormat("field >, field <>> field: ");
+  verifyFormat("msg_field < field_a: OK >");
+  verifyFormat("msg_field: < field_a: 123 >");
+  verifyFormat("msg_field < field_a <> >");
+  verifyFormat("msg_field < field_a < field_b <> > >");
+  verifyFormat("msg_field: < field_a < field_b: <> > >");
+  verifyFormat("msg_field < field_a: OK, field_b: \"OK\" >");
+  verifyFormat("msg_field < field_a: OK field_b: <>, field_c: OK >");
+  verifyFormat("msg_field < field_a { field_b: 1 }, field_c: < f_d: 2 > >");
+  verifyFormat("msg_field: < field_a: OK, field_b: \"OK\" >");
+  verifyFormat("msg_field: < field_a: OK field_b: <>, field_c: OK >");
+  verifyFormat("msg_field: < field_a { field_b: 1 }, field_c: < fd_d: 2 > >");
+  verifyFormat("field_a: \"OK\", msg_field: < field_b: 123 >, field_c: {}");
+  verifyFormat("field_a < field_b: 1 >, msg_fid: < fiel_b: 123 >, field_c <>");
+  verifyFormat("field_a < field_b: 1 > msg_fied: < field_b: 123 > field_c <>");
+  verifyFormat("field < field < field: <> >, field <> > field: < field: 1 >");
 
   // Multiple lines tests
   verifyFormat("msg_field <\n"
@@ -170,31 +170,31 @@
 
   verifyFormat("msg_field: <>\n"
"field_c: \"OK\",\n"
-   "msg_field: \n"
+   "msg_field: < field_d: 123 >\n"
"field_e: OK\n"
-   "msg_field: ");
+   "msg_field: < field_d: 12 >");
 
   verifyFormat("field_a: OK,\n"
-   "field_b ,\n"
-   "field_d: <12.5>,\n"
+   "field_b < field_c: OK >,\n"
+   "field_d: < 12.5 >,\n"
"field_e: OK");
 
   verifyFormat("field_a: OK\n"
-   "field_b \n"
-   "field_d: <12.5>\n"
+   "field_b < field_c: OK >\n"
+   "field_d: < 12.5 >\n"
"field_e: OKOKOK");
 
   verifyFormat("msg_field <\n"
"  field_a: OK,\n"
-   "  field_b ,\n"
-   "  field_d: <12.5>,\n"
+   "  field_b < field_c: OK >,\n"
+   "  field_d: < 12.5 >,\n"
"  field_e: OK\n"
">");
 
   verifyFormat("msg_field <\n"
-   "  field_a: ,\n"
-   "  field_b ,\n"
-   "  field_d: <12.5>,\n"
+   "  field_a: < field: OK >,\n"
+   "  field_b < field_c: OK >,\n"
+   "  field_d: < 12.5 >,\n"
"  field_e: OK,\n"
">");
 
@@ -208,19 +208,19 @@
 
   verifyFormat("field_a {\n"
"  field_d: ok\n"
-   "  field_b: \n"
+   "  field_b: < field_c: 1 >\n"
"  field_d: ok\n"
"  field_d: ok\n"
"}");
 
   verifyFormat("field_a: {\n"
"  field_d: ok\n"
-   "  field_b: \n"
+   "  field_b: < field_c: 1 >\n"
"  field_d: ok\n"
"  field_d: ok\n"
"}");
 
-  verifyFormat("field_a: >\n"
+  verifyFormat("field_a: < f1: 1, f2: <> >\n"
"field_b <\n"
"  field_b1: <>\n"
"  field_b2: ok,\n"
@@ -231,63 +231,63 @@
"  >\n"
"  field {\n"
"field_x <>  // Comment\n"
-   "field_y: \n"
+   "field_y: < field_z: 1 >\n"
"field_w: ok\n"
"msg_field: <\n"
"  field: <>\n"
-   "  field: \n"
-  

[PATCH] D42727: [clang-format] Adds space around angle brackets in text protos

2018-01-31 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 132121.
krasimir added a comment.

- Remove braces around single statement


Repository:
  rC Clang

https://reviews.llvm.org/D42727

Files:
  lib/Format/ContinuationIndenter.cpp
  lib/Format/FormatToken.h
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestRawStrings.cpp
  unittests/Format/FormatTestTextProto.cpp

Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -143,21 +143,21 @@
   // Single-line tests
   verifyFormat("msg_field <>");
   verifyFormat("msg_field: <>");
-  verifyFormat("msg_field ");
-  verifyFormat("msg_field: ");
-  verifyFormat("msg_field >");
-  verifyFormat("msg_field >>");
-  verifyFormat("msg_field: >>");
-  verifyFormat("msg_field ");
-  verifyFormat("msg_field , field_c: OK>");
-  verifyFormat("msg_field >");
-  verifyFormat("msg_field: ");
-  verifyFormat("msg_field: , field_c: OK>");
-  verifyFormat("msg_field: >");
-  verifyFormat("field_a: \"OK\", msg_field: , field_c: {}");
-  verifyFormat("field_a , msg_field: , field_c <>");
-  verifyFormat("field_a  msg_field:  field_c <>");
-  verifyFormat("field >, field <>> field: ");
+  verifyFormat("msg_field < field_a: OK >");
+  verifyFormat("msg_field: < field_a: 123 >");
+  verifyFormat("msg_field < field_a <> >");
+  verifyFormat("msg_field < field_a < field_b <> > >");
+  verifyFormat("msg_field: < field_a < field_b: <> > >");
+  verifyFormat("msg_field < field_a: OK, field_b: \"OK\" >");
+  verifyFormat("msg_field < field_a: OK field_b: <>, field_c: OK >");
+  verifyFormat("msg_field < field_a { field_b: 1 }, field_c: < f_d: 2 > >");
+  verifyFormat("msg_field: < field_a: OK, field_b: \"OK\" >");
+  verifyFormat("msg_field: < field_a: OK field_b: <>, field_c: OK >");
+  verifyFormat("msg_field: < field_a { field_b: 1 }, field_c: < fd_d: 2 > >");
+  verifyFormat("field_a: \"OK\", msg_field: < field_b: 123 >, field_c: {}");
+  verifyFormat("field_a < field_b: 1 >, msg_fid: < fiel_b: 123 >, field_c <>");
+  verifyFormat("field_a < field_b: 1 > msg_fied: < field_b: 123 > field_c <>");
+  verifyFormat("field < field < field: <> >, field <> > field: < field: 1 >");
 
   // Multiple lines tests
   verifyFormat("msg_field <\n"
@@ -170,31 +170,31 @@
 
   verifyFormat("msg_field: <>\n"
"field_c: \"OK\",\n"
-   "msg_field: \n"
+   "msg_field: < field_d: 123 >\n"
"field_e: OK\n"
-   "msg_field: ");
+   "msg_field: < field_d: 12 >");
 
   verifyFormat("field_a: OK,\n"
-   "field_b ,\n"
-   "field_d: <12.5>,\n"
+   "field_b < field_c: OK >,\n"
+   "field_d: < 12.5 >,\n"
"field_e: OK");
 
   verifyFormat("field_a: OK\n"
-   "field_b \n"
-   "field_d: <12.5>\n"
+   "field_b < field_c: OK >\n"
+   "field_d: < 12.5 >\n"
"field_e: OKOKOK");
 
   verifyFormat("msg_field <\n"
"  field_a: OK,\n"
-   "  field_b ,\n"
-   "  field_d: <12.5>,\n"
+   "  field_b < field_c: OK >,\n"
+   "  field_d: < 12.5 >,\n"
"  field_e: OK\n"
">");
 
   verifyFormat("msg_field <\n"
-   "  field_a: ,\n"
-   "  field_b ,\n"
-   "  field_d: <12.5>,\n"
+   "  field_a: < field: OK >,\n"
+   "  field_b < field_c: OK >,\n"
+   "  field_d: < 12.5 >,\n"
"  field_e: OK,\n"
">");
 
@@ -208,19 +208,19 @@
 
   verifyFormat("field_a {\n"
"  field_d: ok\n"
-   "  field_b: \n"
+   "  field_b: < field_c: 1 >\n"
"  field_d: ok\n"
"  field_d: ok\n"
"}");
 
   verifyFormat("field_a: {\n"
"  field_d: ok\n"
-   "  field_b: \n"
+   "  field_b: < field_c: 1 >\n"
"  field_d: ok\n"
"  field_d: ok\n"
"}");
 
-  verifyFormat("field_a: >\n"
+  verifyFormat("field_a: < f1: 1, f2: <> >\n"
"field_b <\n"
"  field_b1: <>\n"
"  field_b2: ok,\n"
@@ -231,63 +231,63 @@
"  >\n"
"  field {\n"
"field_x <>  // Comment\n"
-   "field_y: \n"
+   "field_y: < field_z: 1 >\n"
"field_w: ok\n"
"msg_field: <\n"
"  field: <>\n"
-   "  field: \n"
-   "  field: \n"
-   "  field: \n"
-   "  field: \n"
+   "  field: < field: 1 >\n"
+   "  field: < field: 2 >\n"
+   "  field: < field: 3 >\n"
+   "  field: < field: 4 >\n"
 

[PATCH] D42575: [clangd] Better handling symbols defined in macros.

2018-01-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 132122.
hokein marked 4 inline comments as done.
hokein added a comment.

- address review comments.
- add tests for indexing main files
- use SourceLocation.printToString


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42575

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "Annotations.h"
 #include "index/SymbolCollector.h"
 #include "index/SymbolYAML.h"
 #include "clang/Basic/FileManager.h"
@@ -44,11 +45,22 @@
   return arg.CompletionSnippetInsertText == S;
 }
 MATCHER_P(QName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
+MATCHER_P(LocationOffsets, Offsets, "") {
+  // Offset range in SymbolLocation is [start, end] while in Clangd is [start,
+  // end).
+  return arg.CanonicalDeclaration.StartOffset == Offsets.first &&
+  arg.CanonicalDeclaration.EndOffset == Offsets.second - 1;
+}
+MATCHER_P(FilePath, P, "") {
+  return arg.CanonicalDeclaration.FilePath.contains(P);
+}
 
 namespace clang {
 namespace clangd {
 
 namespace {
+const char TestHeaderName[] = "symbols.h";
+const char TestFileName[] = "symbol.cc";
 class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
 public:
   SymbolIndexActionFactory(SymbolCollector::Options COpts)
@@ -77,21 +89,20 @@
 llvm::IntrusiveRefCntPtr Files(
 new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
-const std::string FileName = "symbol.cc";
-const std::string HeaderName = "symbols.h";
 auto Factory = llvm::make_unique(CollectorOpts);
 
 tooling::ToolInvocation Invocation(
-{"symbol_collector", "-fsyntax-only", "-std=c++11", FileName},
+{"symbol_collector", "-fsyntax-only", "-std=c++11", TestFileName},
 Factory->create(), Files.get(),
 std::make_shared());
 
-InMemoryFileSystem->addFile(HeaderName, 0,
+InMemoryFileSystem->addFile(TestHeaderName, 0,
 llvm::MemoryBuffer::getMemBuffer(HeaderCode));
 
-std::string Content = "#include\"" + std::string(HeaderName) + "\"";
-Content += "\n" + MainCode.str();
-InMemoryFileSystem->addFile(FileName, 0,
+std::string Content = MainCode;
+if (!HeaderCode.empty())
+  Content = "#include\"" + std::string(TestHeaderName) + "\"\n" + Content;
+InMemoryFileSystem->addFile(TestFileName, 0,
 llvm::MemoryBuffer::getMemBuffer(Content));
 Invocation.run();
 Symbols = Factory->Collector->takeSymbols();
@@ -196,6 +207,57 @@
   UnorderedElementsAre(QName("Foo")));
 }
 
+TEST_F(SymbolCollectorTest, SymbolFormedFromMacro) {
+  CollectorOpts.IndexMainFiles = false;
+
+  Annotations Header(R"(
+#define FF(name) \
+  class name##_Test {};
+
+$expansion[[FF(abc)]];
+
+#define FF2() \
+  $spelling[[class Test {}]];
+
+FF2();
+  )");
+
+  runSymbolCollector(Header.code(), /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("abc_Test"),
+LocationOffsets(Header.offsetRange("expansion")),
+FilePath(TestHeaderName)),
+  AllOf(QName("Test"),
+LocationOffsets(Header.offsetRange("spelling")),
+FilePath(TestHeaderName;
+}
+
+TEST_F(SymbolCollectorTest, SymbolFormedFromMacroInMainFile) {
+  CollectorOpts.IndexMainFiles = true;
+
+  Annotations Header(R"(
+#define FF(name) \
+  class name##_Test {};
+
+$expansion[[FF(abc)]];
+
+#define FF2() \
+  $spelling[[class Test {}]];
+
+FF2();
+  )");
+  runSymbolCollector(/*Header=*/"", Header.code());
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("abc_Test"),
+LocationOffsets(Header.offsetRange("expansion")),
+FilePath(TestFileName)),
+  AllOf(QName("Test"),
+LocationOffsets(Header.offsetRange("spelling")),
+FilePath(TestFileName;
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) {
   CollectorOpts.IndexMainFiles = false;
   const std::string Header = R"(
Index: unittests/clangd/Annotations.h
===
--- unittests/clangd/Annotations.h
+++ unittests/clangd/Annotations.h
@@ -58,6 +58,10 @@
   // Returns the location of all ranges marked by [[ ]] (or $name[[ ]]).
   std::vector ranges(llvm::StringRef Name = "") const;
 
+  // The same to `range` method, but returns range in offsets [sta

[PATCH] D42575: [clangd] Better handling symbols defined in macros.

2018-01-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 132123.
hokein added a comment.

Update test.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42575

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "Annotations.h"
 #include "index/SymbolCollector.h"
 #include "index/SymbolYAML.h"
 #include "clang/Basic/FileManager.h"
@@ -44,11 +45,22 @@
   return arg.CompletionSnippetInsertText == S;
 }
 MATCHER_P(QName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
+MATCHER_P(LocationOffsets, Offsets, "") {
+  // Offset range in SymbolLocation is [start, end] while in Clangd is [start,
+  // end).
+  return arg.CanonicalDeclaration.StartOffset == Offsets.first &&
+  arg.CanonicalDeclaration.EndOffset == Offsets.second - 1;
+}
+MATCHER_P(FilePath, P, "") {
+  return arg.CanonicalDeclaration.FilePath.contains(P);
+}
 
 namespace clang {
 namespace clangd {
 
 namespace {
+const char TestHeaderName[] = "symbols.h";
+const char TestFileName[] = "symbol.cc";
 class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
 public:
   SymbolIndexActionFactory(SymbolCollector::Options COpts)
@@ -77,21 +89,20 @@
 llvm::IntrusiveRefCntPtr Files(
 new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
-const std::string FileName = "symbol.cc";
-const std::string HeaderName = "symbols.h";
 auto Factory = llvm::make_unique(CollectorOpts);
 
 tooling::ToolInvocation Invocation(
-{"symbol_collector", "-fsyntax-only", "-std=c++11", FileName},
+{"symbol_collector", "-fsyntax-only", "-std=c++11", TestFileName},
 Factory->create(), Files.get(),
 std::make_shared());
 
-InMemoryFileSystem->addFile(HeaderName, 0,
+InMemoryFileSystem->addFile(TestHeaderName, 0,
 llvm::MemoryBuffer::getMemBuffer(HeaderCode));
 
-std::string Content = "#include\"" + std::string(HeaderName) + "\"";
-Content += "\n" + MainCode.str();
-InMemoryFileSystem->addFile(FileName, 0,
+std::string Content = MainCode;
+if (!HeaderCode.empty())
+  Content = "#include\"" + std::string(TestHeaderName) + "\"\n" + Content;
+InMemoryFileSystem->addFile(TestFileName, 0,
 llvm::MemoryBuffer::getMemBuffer(Content));
 Invocation.run();
 Symbols = Factory->Collector->takeSymbols();
@@ -196,6 +207,57 @@
   UnorderedElementsAre(QName("Foo")));
 }
 
+TEST_F(SymbolCollectorTest, SymbolFormedFromMacro) {
+  CollectorOpts.IndexMainFiles = false;
+
+  Annotations Header(R"(
+#define FF(name) \
+  class name##_Test {};
+
+$expansion[[FF(abc)]];
+
+#define FF2() \
+  $spelling[[class Test {}]];
+
+FF2();
+  )");
+
+  runSymbolCollector(Header.code(), /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("abc_Test"),
+LocationOffsets(Header.offsetRange("expansion")),
+FilePath(TestHeaderName)),
+  AllOf(QName("Test"),
+LocationOffsets(Header.offsetRange("spelling")),
+FilePath(TestHeaderName;
+}
+
+TEST_F(SymbolCollectorTest, SymbolFormedFromMacroInMainFile) {
+  CollectorOpts.IndexMainFiles = true;
+
+  Annotations Main(R"(
+#define FF(name) \
+  class name##_Test {};
+
+$expansion[[FF(abc)]];
+
+#define FF2() \
+  $spelling[[class Test {}]];
+
+FF2();
+  )");
+  runSymbolCollector(/*Header=*/"", Main.code());
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("abc_Test"),
+LocationOffsets(Main.offsetRange("expansion")),
+FilePath(TestFileName)),
+  AllOf(QName("Test"),
+LocationOffsets(Main.offsetRange("spelling")),
+FilePath(TestFileName;
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) {
   CollectorOpts.IndexMainFiles = false;
   const std::string Header = R"(
Index: unittests/clangd/Annotations.h
===
--- unittests/clangd/Annotations.h
+++ unittests/clangd/Annotations.h
@@ -58,6 +58,10 @@
   // Returns the location of all ranges marked by [[ ]] (or $name[[ ]]).
   std::vector ranges(llvm::StringRef Name = "") const;
 
+  // The same to `range` method, but returns range in offsets [start, end).
+  std::pair
+  offsetRange(llvm::StringRef Name = "") const;
+
 private:
   std::string Code;
   llvm::StringMap> Points;
I

[PATCH] D42575: [clangd] Better handling symbols defined in macros.

2018-01-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:108
 
+std::string PrintableLoc(SourceLocation Loc, SourceManager &SM) {
+  if (Loc.isInvalid())

ioeric wrote:
> `PrintLoc`? `PrintableLoc` sounds like a checker for whether a location is 
> printable.
`SourceLocation` has provided `printToString` API already, we don't need to 
reinvent the wheel now.



Comment at: clangd/index/SymbolCollector.cpp:127
+// location instead.
+if (llvm::StringRef(PrintableLoc(Loc, SM)).startswith(" To reduce some code, consider
> 
> ```
> Loc, Start, End = spelling locs;
> if (D->getLocation().isMacroID() && llvm::StringRef(PrintableLoc(Loc, 
> SM)).startswith("   Loc, Start, End = expension locs;
> }
> // Generate SymbolLocation with Loc, Start, End
> ```
> 
> Also, I think you could use `getLocStart` in place of `getLocation`?
There is no much duplicated code among the cases here (only one line of 
generating the SymbolLocation). I prefer to the current way -- it shows the 
logic a bit clearer, and also saves the cost of `getSpellingLoc` for the macro 
case.



Comment at: unittests/clangd/Annotations.h:63
+  std::pair
+  offsetRange(llvm::StringRef Name = "") const;
+

ioeric wrote:
> This doesn't seem to be necessary? I think you could use the `range` method 
> above and convert it to offsets in the test matcher.
I think this is a useful method (probably be used in the future). Putting it to 
test matcher, we have to pass `Code` parameter to the matcher 
(`LocationOffset(range, Header.code())`) everywhere. Annotation seems to be the 
best place.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42575



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


[PATCH] D42729: clang-format: Fix formatting of function blocks followed by semicolon

2018-01-31 Thread Francois Ferrand via Phabricator via cfe-commits
Typz created this revision.
Typz added reviewers: krasimir, djasper, klimek.

In some case, the heuristic used to identify the type of blocks (in
UnwrappedLineParser) mistakens a Block for a BracedInit, when the
TokenAnnotator eventually finds (correclty) that this is a function
declaration.

This happens with empty function blocks followed by a semicolon.

This causes for exemple the following code to be mistakenly formatted:

  void abort(){};

instead of:

  void abort() {};


Repository:
  rC Clang

https://reviews.llvm.org/D42729

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11386,6 +11386,15 @@
"};");
 }
 
+TEST_F(FormatTest, MunchSemicolonAfterFunction) {
+  verifyFormat("void foo() { int i; };");
+  verifyFormat("void foo() {\n"
+   "  int i;\n"
+   "  int j;\n"
+   "};");
+  verifyFormat("void foo() {};");
+}
+
 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
   TwoIndent.ContinuationIndentWidth = 2;
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -1783,9 +1783,12 @@
 }
 
 // This function heuristically determines whether 'Current' starts the name of a
-// function declaration.
-static bool isFunctionDeclarationName(const FormatToken &Current,
-  const AnnotatedLine &Line) {
+// function declaration, and returns the first token of parameters list in that
+// case.
+// @return The token which opens the parameters list (e.g. the opening
+// parenthesis), or nullptr if this is not a function declaration.
+static const FormatToken *getFunctionParameterList(const FormatToken &Current,
+   const AnnotatedLine &Line) {
   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
 for (; Next; Next = Next->Next) {
   if (Next->is(TT_OverloadedOperatorLParen))
@@ -1809,58 +1812,58 @@
   const FormatToken *Next = Current.Next;
   if (Current.is(tok::kw_operator)) {
 if (Current.Previous && Current.Previous->is(tok::coloncolon))
-  return false;
+  return nullptr;
 Next = skipOperatorName(Next);
   } else {
 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
-  return false;
+  return nullptr;
 for (; Next; Next = Next->Next) {
   if (Next->is(TT_TemplateOpener)) {
 Next = Next->MatchingParen;
   } else if (Next->is(tok::coloncolon)) {
 Next = Next->Next;
 if (!Next)
-  return false;
+  return nullptr;
 if (Next->is(tok::kw_operator)) {
   Next = skipOperatorName(Next->Next);
   break;
 }
 if (!Next->is(tok::identifier))
-  return false;
+  return nullptr;
   } else if (Next->is(tok::l_paren)) {
 break;
   } else {
-return false;
+return nullptr;
   }
 }
   }
 
   // Check whether parameter list can belong to a function declaration.
   if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
-return false;
+return nullptr;
   // If the lines ends with "{", this is likely an function definition.
   if (Line.Last->is(tok::l_brace))
-return true;
+return Next;
   if (Next->Next == Next->MatchingParen)
-return true; // Empty parentheses.
+return Next; // Empty parentheses.
   // If there is an &/&& after the r_paren, this is likely a function.
   if (Next->MatchingParen->Next &&
   Next->MatchingParen->Next->is(TT_PointerOrReference))
-return true;
+return Next;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
 if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
   Tok = Tok->MatchingParen;
   continue;
 }
 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
-  return true;
+  return Next;
 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
 Tok->Tok.isLiteral())
-  return false;
+  return nullptr;
   }
-  return false;
+  return nullptr;
 }
 
 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
@@ -1899,8 +1902,14 @@
   FormatToken *Current = Line.First->Next;
   bool InFunctionDecl = Line.MightBeFunctionDecl;
   while (Current) {
-if (isFunctionDeclarationName(*Current, Line))
+if (const FormatToken *Tok = getFunctionParameterList(*Current, Line)) {
   Current->Type = TT_FunctionDeclarationName;
+
+  // Fix block kind, if it was mistakenly identified as a BracedInit
+  Fo

[PATCH] D42729: clang-format: Fix formatting of function body followed by semicolon

2018-01-31 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 132130.
Typz added a comment.

update commit message


Repository:
  rC Clang

https://reviews.llvm.org/D42729

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11386,6 +11386,15 @@
"};");
 }
 
+TEST_F(FormatTest, MunchSemicolonAfterFunction) {
+  verifyFormat("void foo() { int i; };");
+  verifyFormat("void foo() {\n"
+   "  int i;\n"
+   "  int j;\n"
+   "};");
+  verifyFormat("void foo() {};");
+}
+
 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
   TwoIndent.ContinuationIndentWidth = 2;
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -1783,9 +1783,12 @@
 }
 
 // This function heuristically determines whether 'Current' starts the name of a
-// function declaration.
-static bool isFunctionDeclarationName(const FormatToken &Current,
-  const AnnotatedLine &Line) {
+// function declaration, and returns the first token of parameters list in that
+// case.
+// @return The token which opens the parameters list (e.g. the opening
+// parenthesis), or nullptr if this is not a function declaration.
+static const FormatToken *getFunctionParameterList(const FormatToken &Current,
+   const AnnotatedLine &Line) {
   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
 for (; Next; Next = Next->Next) {
   if (Next->is(TT_OverloadedOperatorLParen))
@@ -1809,58 +1812,58 @@
   const FormatToken *Next = Current.Next;
   if (Current.is(tok::kw_operator)) {
 if (Current.Previous && Current.Previous->is(tok::coloncolon))
-  return false;
+  return nullptr;
 Next = skipOperatorName(Next);
   } else {
 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
-  return false;
+  return nullptr;
 for (; Next; Next = Next->Next) {
   if (Next->is(TT_TemplateOpener)) {
 Next = Next->MatchingParen;
   } else if (Next->is(tok::coloncolon)) {
 Next = Next->Next;
 if (!Next)
-  return false;
+  return nullptr;
 if (Next->is(tok::kw_operator)) {
   Next = skipOperatorName(Next->Next);
   break;
 }
 if (!Next->is(tok::identifier))
-  return false;
+  return nullptr;
   } else if (Next->is(tok::l_paren)) {
 break;
   } else {
-return false;
+return nullptr;
   }
 }
   }
 
   // Check whether parameter list can belong to a function declaration.
   if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
-return false;
+return nullptr;
   // If the lines ends with "{", this is likely an function definition.
   if (Line.Last->is(tok::l_brace))
-return true;
+return Next;
   if (Next->Next == Next->MatchingParen)
-return true; // Empty parentheses.
+return Next; // Empty parentheses.
   // If there is an &/&& after the r_paren, this is likely a function.
   if (Next->MatchingParen->Next &&
   Next->MatchingParen->Next->is(TT_PointerOrReference))
-return true;
+return Next;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
 if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
   Tok = Tok->MatchingParen;
   continue;
 }
 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
-  return true;
+  return Next;
 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
 Tok->Tok.isLiteral())
-  return false;
+  return nullptr;
   }
-  return false;
+  return nullptr;
 }
 
 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
@@ -1899,8 +1902,14 @@
   FormatToken *Current = Line.First->Next;
   bool InFunctionDecl = Line.MightBeFunctionDecl;
   while (Current) {
-if (isFunctionDeclarationName(*Current, Line))
+if (const FormatToken *Tok = getFunctionParameterList(*Current, Line)) {
   Current->Type = TT_FunctionDeclarationName;
+
+  // Fix block kind, if it was mistakenly identified as a BracedInit
+  FormatToken *Next = Tok->MatchingParen->Next;
+  if (Next && Next->is(tok::l_brace) && Next->BlockKind == BK_BracedInit)
+  Next->BlockKind = BK_Block;
+}
 if (Current->is(TT_LineComment)) {
   if (Current->Previous->BlockKind == BK_BracedInit &&
   Current->Previous->opensScope())
___
cfe-commits mailing list
cfe-commi

[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from functional.h which are deprecated and removed in C++17

2018-01-31 Thread Jens Massberg via Phabricator via cfe-commits
massberg created this revision.
massberg added a reviewer: alexfh.
Herald added subscribers: cfe-commits, hintonda, mgorny.

In C++17 several classes, types and functions from functional.h are no longer 
available.
In this change we add first clang-tidy checks for occurrences of

- std::unary_function
- std::binary_function
- std::ptr_fun
- std::mem_fun

As there are several more deprecated types in functional.h, this check will be 
extended in the future.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42730

Files:
  clang-tidy/modernize/AvoidFunctionalCheck.cpp
  clang-tidy/modernize/AvoidFunctionalCheck.h
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-avoid-functional.rst
  test/clang-tidy/modernize-avoid-functional.cpp

Index: test/clang-tidy/modernize-avoid-functional.cpp
===
--- test/clang-tidy/modernize-avoid-functional.cpp
+++ test/clang-tidy/modernize-avoid-functional.cpp
@@ -0,0 +1,53 @@
+// RUN: %check_clang_tidy %s modernize-avoid-functional %t
+
+namespace std {
+
+template 
+class binary_function {};
+
+template 
+class unary_function {};
+
+template 
+class pointer_to_unary_function : public std::unary_function {}; // NOLINT
+
+template 
+pointer_to_unary_function ptr_fun(Result (*f)(Arg)) {
+  pointer_to_unary_function Nothing;
+  return Nothing;
+}
+
+template 
+class mem_fun_t {};
+
+template 
+mem_fun_t mem_fun(Res (T::*f)()) {}
+
+} // namespace std
+
+// CHECK-MESSAGES: [[@LINE+1]]:25: warning: 'binary_function' is deprecated and removed from C++17 [modernize-avoid-functional]
+class BinaryTestClass : public std::binary_function {
+ public:
+  BinaryTestClass();
+};
+
+// CHECK-MESSAGES: [[@LINE+1]]:24: warning: 'unary_function' is deprecated and removed from C++17 [modernize-avoid-functional]
+class UnaryTestClass : public std::unary_function {
+ public:
+  UnaryTestClass();
+};
+
+int simple_func(int x) { return x + 1; };
+
+class TestClass {
+ public:
+  int test() { return 1; }
+};
+
+void foo(void) {
+// CHECK-MESSAGES: [[@LINE+1]]:3: warning: 'std::ptr_fun' is deprecated and removed from C++17 [modernize-avoid-functional]
+  std::ptr_fun(simple_func);
+
+// CHECK-MESSAGES: [[@LINE+1]]:3: warning: 'std::mem_fun' is deprecated and removed from C++17 [modernize-avoid-functional]
+  std::mem_fun(&TestClass::test);
+}
Index: docs/clang-tidy/checks/modernize-avoid-functional.rst
===
--- docs/clang-tidy/checks/modernize-avoid-functional.rst
+++ docs/clang-tidy/checks/modernize-avoid-functional.rst
@@ -0,0 +1,14 @@
+.. title:: clang-tidy - modernize-avoid-functional
+
+modernize-avoid-functional
+==
+
+In C++17 several classes, types and functions from functional.h are no longer
+available.
+In particular, this check warns if one of the following deprecated objects is
+used:
+
+-  std::unary_function
+-  std::binary_function
+-  std::ptr_fun
+-  std::mem_fun
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -154,6 +154,7 @@
misc-unused-raii
misc-unused-using-decls
modernize-avoid-bind
+   modernize-avoid-functional
modernize-deprecated-headers
modernize-loop-convert
modernize-make-shared
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -57,6 +57,12 @@
 Improvements to clang-tidy
 --
 
+- New `modernize-avoid-functional
+  `_ check
+
+  Warns if types, classes and functions from functional.h which are deprecated
+  and removed in C++17 are used.
+
 - The 'misc-incorrect-roundings' check was renamed to `bugprone-incorrect-roundings
   `_
 
Index: clang-tidy/modernize/ModernizeTidyModule.cpp
===
--- clang-tidy/modernize/ModernizeTidyModule.cpp
+++ clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "AvoidBindCheck.h"
+#include "AvoidFunctionalCheck.h"
 #include "DeprecatedHeadersCheck.h"
 #include "LoopConvertCheck.h"
 #include "MakeSharedCheck.h"
@@ -45,6 +46,8 @@
 public:
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
 CheckFactories.registerCheck("modernize-avoid-bind");
+CheckFactories.registerCheck(
+"modernize-avoid-functional");
 CheckFactories.registerCheck(
 "modernize-deprecated-headers");
 CheckFactories.registerCheck("modernize-lo

[PATCH] D42639: [clang-move] Clever on handling header file which includes itself.

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

lg


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42639



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


[clang-tools-extra] r323863 - [clangd] Second attempt to fix MSVC compilation breakage.

2018-01-31 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Jan 31 03:26:43 2018
New Revision: 323863

URL: http://llvm.org/viewvc/llvm-project?rev=323863&view=rev
Log:
[clangd] Second attempt to fix MSVC compilation breakage.

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

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=323863&r1=323862&r2=323863&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Wed Jan 31 03:26:43 2018
@@ -34,25 +34,31 @@ namespace {
 // Issues an async read of AST and waits for results.
 template 
 Ret blockingRunWithAST(TUScheduler &S, PathRef File, Func &&F) {
-  // Using Optional to workaround MSVC bug. It requires future<> arguments to
-  // have default ctor.
-  std::packaged_task(llvm::Expected)> Task(
-  std::forward(F));
+  // Using shared_ptr to workaround MSVC bug. It requires future<> arguments to
+  // have default and copy ctor.
+  auto SharedPtrFunc = [&](llvm::Expected Arg) {
+return std::make_shared(F(std::move(Arg)));
+  };
+  std::packaged_task(llvm::Expected)> Task(
+  SharedPtrFunc);
   auto Future = Task.get_future();
   S.runWithAST(File, std::move(Task));
-  return *Future.get();
+  return std::move(*Future.get());
 }
 
 // Issues an async read of preamble and waits for results.
 template 
 Ret blockingRunWithPreamble(TUScheduler &S, PathRef File, Func &&F) {
-  // Using Optional to workaround MSVC bug. It requires future<> arguments to
-  // have default ctor.
-  std::packaged_task(llvm::Expected)>
-  Task(std::forward(F));
+  // Using shared_ptr to workaround MSVC bug. It requires future<> arguments to
+  // have default and copy ctor.
+  auto SharedPtrFunc = [&](llvm::Expected Arg) {
+return std::make_shared(F(std::move(Arg)));
+  };
+  std::packaged_task(llvm::Expected)>
+  Task(SharedPtrFunc);
   auto Future = Task.get_future();
   S.runWithPreamble(File, std::move(Task));
-  return *Future.get();
+  return std::move(*Future.get());
 }
 
 void ignoreError(llvm::Error Err) {


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


[PATCH] D42575: [clangd] Better handling symbols defined in macros.

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

lg




Comment at: clangd/index/SymbolCollector.cpp:127
+// location instead.
+if (llvm::StringRef(PrintableLoc(Loc, SM)).startswith(" ioeric wrote:
> > To reduce some code, consider
> > 
> > ```
> > Loc, Start, End = spelling locs;
> > if (D->getLocation().isMacroID() && llvm::StringRef(PrintableLoc(Loc, 
> > SM)).startswith(" >   Loc, Start, End = expension locs;
> > }
> > // Generate SymbolLocation with Loc, Start, End
> > ```
> > 
> > Also, I think you could use `getLocStart` in place of `getLocation`?
> There is no much duplicated code among the cases here (only one line of 
> generating the SymbolLocation). I prefer to the current way -- it shows the 
> logic a bit clearer, and also saves the cost of `getSpellingLoc` for the 
> macro case.
I still think there is value in reducing the duplicates. For example, when the 
interface of `makeAbsolutePath` or `SymbolLocation` changes, we would only need 
to modify one place rather than two. 

I wouldn't worry about the cost of `getSpellingLoc` for the macro case since it 
is a cheap operation for a rare case anyway...



Comment at: unittests/clangd/Annotations.h:63
+  std::pair
+  offsetRange(llvm::StringRef Name = "") const;
+

hokein wrote:
> ioeric wrote:
> > This doesn't seem to be necessary? I think you could use the `range` method 
> > above and convert it to offsets in the test matcher.
> I think this is a useful method (probably be used in the future). Putting it 
> to test matcher, we have to pass `Code` parameter to the matcher 
> (`LocationOffset(range, Header.code())`) everywhere. Annotation seems to be 
> the best place.
I see. Didn't realize code is needed.



Comment at: unittests/clangd/SymbolCollectorTests.cpp:240
+  Annotations Main(R"(
+#define FF(name) \
+  class name##_Test {};

Maybe put this in the header file to make the test more meaningful?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42575



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


[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from functional.h which are deprecated and removed in C++17

2018-01-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

Thank you for this new check! A few minor comments (mostly style issues).




Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:37
+void AvoidFunctionalCheck::check(const MatchFinder::MatchResult &Result) {
+  if (const auto* const un_or_binary_derived =
+  Result.Nodes.getNodeAs("un_or_binary_derived")) {

Please use llvm naming conventions for locals (CamelCase).



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:38
+  if (const auto* const un_or_binary_derived =
+  Result.Nodes.getNodeAs("un_or_binary_derived")) {
+auto* decl = clang::cast(un_or_binary_derived);

`clang::` is not needed here (the code is inside namespace clang).



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:39
+  Result.Nodes.getNodeAs("un_or_binary_derived")) {
+auto* decl = clang::cast(un_or_binary_derived);
+for (clang::CXXBaseSpecifier base : decl->bases()) {

`const auto *`



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:42
+  clang::QualType base_type = base.getType();
+  auto clang_decl = base_type->getAsCXXRecordDecl();
+  if (!clang_decl) {

`const auto *`



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:52
+  }
+  diag(base.getLocStart(), "%0 is deprecated and removed from C++17")
+  << clang_decl;

Maybe expand a bit more: "deprecated in C++11 and removed in C++17" (or "from 
C++17", whichever sounds better in English)?



Comment at: docs/ReleaseNotes.rst:63
+
+  Warns if types, classes and functions from functional.h which are deprecated
+  and removed in C++17 are used.

".h" is an anachronism, I'd write "from the `` header" or something 
like that. Same in other places.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42730



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


[PATCH] D42517: [clangd] Pass Context implicitly using TLS.

2018-01-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/Context.h:77
+  /// See WithContext and WithContextValue for how to do this safely.
+  static Context ¤t();
 

Maybe we could return `const Context&` here and have a separate `setCurrent()` 
method for replacing the current context?
Most of the clients shouldn't mutate the contexts anyway, and finding the few 
that do seems easier if there's a separate method for that.



Comment at: clangd/Context.h:201
+  WithContext &operator=(const WithContext &) = delete;
+  WithContext(WithContext &&) = default; // Allow return-by-value.
+  WithContext &operator=(WithContext &&) = delete;

Where do we use it? Can't we make move ctor deleted too?



Comment at: clangd/JSONRPCDispatcher.h:60
+/// Current context must derive from JSONRPCDispatcher::Handler.
+void reply(json::Expr &&Result);
+/// Sends an error response to the client, and logs it.

`reply`'s signature is scary now.
Should we change it to accept something request-specific that can be found in 
the `Context` by the clients? WDYT? 

PS we could change it after the patch lands, just wanted to get your opinion on 
this



Comment at: clangd/Threading.cpp:37
   // addToFront).
-  Request = std::move(RequestQueue.front());
+  Request = std::move(RequestQueue.front().first);
+  Ctx = std::move(RequestQueue.front().second);

Maybe replace with `std::tie(Request, Ctx) = std::move(RequestQueue.front())`?



Comment at: clangd/Trace.cpp:131
+return Context::current().clone();
+  WithContextValue WithArgs{std::unique_ptr(Args)};
+  return T->beginSpan(Name, Args);

Maybe use parentheses instead of braces for initialization?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517



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


[PATCH] D42682: [clang-tidy] Add misc-io-functions-misused checker

2018-01-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh requested changes to this revision.
alexfh added inline comments.
This revision now requires changes to proceed.



Comment at: clang-tidy/misc/IoFunctionsMisusedCheck.cpp:33
+  has(cxxMemberCallExpr(
+  on(hasType(namedDecl(matchesName("istream",
+  callee(cxxMethodDecl(hasName("get")).bind("Decl"),

`matchesName` can be pretty expensive and should generally be avoided. What set 
of types should be matched here? Can they all be listed here (using hasAnyName)?



Comment at: clang-tidy/misc/IoFunctionsMisusedCheck.cpp:43-46
+  const auto *FuncDeclInStd =
+  Result.Nodes.getNodeAs("FuncDeclInStd");
+  const auto *FuncDeclInGlobal =
+  Result.Nodes.getNodeAs("FuncDeclInGlobal");

It looks like the code doesn't need to distinguish between these two. They can 
be bound to the same ID then.



Comment at: clang-tidy/misc/IoFunctionsMisusedCheck.h:19
+
+/// This checker warns for cases when the return value of certain standard
+/// iostream C functions (fgetwc, getwc, getwchar, istream::get()) return int

s/checker/check/



Comment at: docs/clang-tidy/checks/misc-io-functions-misused.rst:26-27
+   char c;
+c = is.get();   // Warning about incorrectly stored int value
+c = ownnamespace::get() // Won't warn
+   

The formatting is off.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42682



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


r323864 - Fix typo. NFC

2018-01-31 Thread Jonathan Roelofs via cfe-commits
Author: jroelofs
Date: Wed Jan 31 04:06:15 2018
New Revision: 323864

URL: http://llvm.org/viewvc/llvm-project?rev=323864&view=rev
Log:
Fix typo. NFC

Modified:
cfe/trunk/www/analyzer/scan-build.html

Modified: cfe/trunk/www/analyzer/scan-build.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/www/analyzer/scan-build.html?rev=323864&r1=323863&r2=323864&view=diff
==
--- cfe/trunk/www/analyzer/scan-build.html (original)
+++ cfe/trunk/www/analyzer/scan-build.html Wed Jan 31 04:06:15 2018
@@ -248,7 +248,7 @@ you will probably need to run config
 
 
 $ scan-build ./configure
-$ scan-build --keepk-cc make
+$ scan-build --keep-cc make
 
 
 The reason configure also needs to be run through


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


[PATCH] D42170: Fixit for 'typedef' instead of 'typename' typo

2018-01-31 Thread Jan Korous via Phabricator via cfe-commits
jkorous-apple updated this revision to Diff 132135.
jkorous-apple added a comment.

Tried to make test more readable.


https://reviews.llvm.org/D42170

Files:
  FixIt/fixit-typedef-instead-of-typename-typo.cpp
  Parse/ParseTemplate.cpp
  clang/Basic/DiagnosticParseKinds.td


Index: FixIt/fixit-typedef-instead-of-typename-typo.cpp
===
--- /dev/null
+++ FixIt/fixit-typedef-instead-of-typename-typo.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -verify %s
+
+template  struct Foo {
+  // expected-error@-1 {{expected template parameter}} expected-note@-1 {{did 
you mean to use 'typename'?}}
+
+  // Check that we are speculatively (with fixit applied) trying to parse the 
rest.
+
+  // Should not produce error about type since parsing speculatively with 
fixit applied.
+  B member;
+
+  a // expected-error {{unknown type name 'a'}} // expected-error@+1 
{{expected member name or ';' after declaration specifiers}}
+};
+
+
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | 
FileCheck %s
+// CHECK: fix-it:{{.*}}:{3:23-3:30}:"typename"
Index: Parse/ParseTemplate.cpp
===
--- Parse/ParseTemplate.cpp
+++ Parse/ParseTemplate.cpp
@@ -488,6 +488,20 @@
   if (Tok.is(tok::kw_template))
 return ParseTemplateTemplateParameter(Depth, Position);
 
+  // Is there just a typo in the input code? ('typedef' instead of 'typename')
+  if (Tok.is(tok::kw_typedef)) {
+Diag(Tok.getLocation(), diag::err_expected_template_parameter);
+
+Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
+<< FixItHint::CreateReplacement(CharSourceRange::getCharRange(
+Tok.getLocation(), 
Tok.getEndLoc()),
+"typename");
+
+Tok.setKind(tok::kw_typename);
+
+return ParseTypeParameter(Depth, Position);
+  }
+
   // If it's none of the above, then it must be a parameter declaration.
   // NOTE: This will pick up errors in the closure of the template parameter
   // list (e.g., template < ; Check here to implement >> style closures.
Index: clang/Basic/DiagnosticParseKinds.td
===
--- clang/Basic/DiagnosticParseKinds.td
+++ clang/Basic/DiagnosticParseKinds.td
@@ -1162,6 +1162,9 @@
 
 def err_objc_type_args_after_protocols : Error<
   "protocol qualifiers must precede type arguments">;
+
+def note_meant_to_use_typename : Note<
+  "did you mean to use 'typename'?">;
 }
 
 let CategoryName = "Coroutines Issue" in {


Index: FixIt/fixit-typedef-instead-of-typename-typo.cpp
===
--- /dev/null
+++ FixIt/fixit-typedef-instead-of-typename-typo.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -verify %s
+
+template  struct Foo {
+  // expected-error@-1 {{expected template parameter}} expected-note@-1 {{did you mean to use 'typename'?}}
+
+  // Check that we are speculatively (with fixit applied) trying to parse the rest.
+
+  // Should not produce error about type since parsing speculatively with fixit applied.
+  B member;
+
+  a // expected-error {{unknown type name 'a'}} // expected-error@+1 {{expected member name or ';' after declaration specifiers}}
+};
+
+
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
+// CHECK: fix-it:{{.*}}:{3:23-3:30}:"typename"
Index: Parse/ParseTemplate.cpp
===
--- Parse/ParseTemplate.cpp
+++ Parse/ParseTemplate.cpp
@@ -488,6 +488,20 @@
   if (Tok.is(tok::kw_template))
 return ParseTemplateTemplateParameter(Depth, Position);
 
+  // Is there just a typo in the input code? ('typedef' instead of 'typename')
+  if (Tok.is(tok::kw_typedef)) {
+Diag(Tok.getLocation(), diag::err_expected_template_parameter);
+
+Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
+<< FixItHint::CreateReplacement(CharSourceRange::getCharRange(
+Tok.getLocation(), Tok.getEndLoc()),
+"typename");
+
+Tok.setKind(tok::kw_typename);
+
+return ParseTypeParameter(Depth, Position);
+  }
+
   // If it's none of the above, then it must be a parameter declaration.
   // NOTE: This will pick up errors in the closure of the template parameter
   // list (e.g., template < ; Check here to implement >> style closures.
Index: clang/Basic/DiagnosticParseKinds.td
===
--- clang/Basic/DiagnosticParseKinds.td
+++ clang/Basic/DiagnosticParseKinds.td
@@ -1162,6 +1162,9 @@
 
 def err_objc_type_args_after_protocols : Error<
   "protocol qualifiers must precede type arguments">;
+
+def note_meant_to_use_typename : Note<
+  "did you mean to 

[clang-tools-extra] r323865 - [clang-move] Clever on handling header file which includes itself.

2018-01-31 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Jan 31 04:12:29 2018
New Revision: 323865

URL: http://llvm.org/viewvc/llvm-project?rev=323865&view=rev
Log:
[clang-move] Clever on handling header file which includes itself.

Summary:
Previously, we assume only old.cc includes "old.h", which would
introduce incorrect fixes for the cases where old.h also includes `#include 
"old.h"`

Although it should not be occurred in real projects, clang-move should handle 
this.

Old.h:

```
class Foo {};
```

after moving to a new old.h:

```
class Foo {};
```

Reviewers: ioeric

Reviewed By: ioeric

Subscribers: cfe-commits, klimek

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

Modified:
clang-tools-extra/trunk/clang-move/ClangMove.cpp
clang-tools-extra/trunk/clang-move/ClangMove.h
clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp

Modified: clang-tools-extra/trunk/clang-move/ClangMove.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-move/ClangMove.cpp?rev=323865&r1=323864&r2=323865&view=diff
==
--- clang-tools-extra/trunk/clang-move/ClangMove.cpp (original)
+++ clang-tools-extra/trunk/clang-move/ClangMove.cpp Wed Jan 31 04:12:29 2018
@@ -694,22 +694,28 @@ void ClangMoveTool::addIncludes(llvm::St
 const SourceManager &SM) {
   SmallVector HeaderWithSearchPath;
   llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
-  std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
-  if (AbsoluteOldHeader ==
+  std::string AbsoluteIncludeHeader =
   MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
-   HeaderWithSearchPath.size( {
-OldHeaderIncludeRange = IncludeFilenameRange;
-return;
-  }
-
+   HeaderWithSearchPath.size()));
   std::string IncludeLine =
   IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
: ("#include \"" + IncludeHeader + "\"\n").str();
 
+  std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
   std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
   if (AbsoluteOldHeader == AbsoluteCurrentFile) {
+// Find old.h includes "old.h".
+if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
+  OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
+  return;
+}
 HeaderIncludes.push_back(IncludeLine);
   } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
+// Find old.cc includes "old.h".
+if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
+  OldHeaderIncludeRangeInCC = IncludeFilenameRange;
+  return;
+}
 CCIncludes.push_back(IncludeLine);
   }
 }
@@ -857,13 +863,18 @@ void ClangMoveTool::moveAll(SourceManage
   if (!NewFile.empty()) {
 auto AllCode = clang::tooling::Replacements(
 clang::tooling::Replacement(NewFile, 0, 0, Code));
-// If we are moving from old.cc, an extra step is required: excluding
-// the #include of "old.h", instead, we replace it with #include of 
"new.h".
-if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
-  AllCode = AllCode.merge(
-  clang::tooling::Replacements(clang::tooling::Replacement(
-  SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + 
'"')));
-}
+auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) 
{
+  AllCode = AllCode.merge(clang::tooling::Replacements(
+  clang::tooling::Replacement(SM, OldHeaderIncludeRange,
+  '"' + Context->Spec.NewHeader + '"')));
+};
+// Fix the case where old.h/old.cc includes "old.h", we replace the
+// `#include "old.h"` with `#include "new.h"`.
+if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
+  ReplaceOldInclude(OldHeaderIncludeRangeInCC);
+else if (Context->Spec.NewHeader == NewFile &&
+ OldHeaderIncludeRangeInHeader.isValid())
+  ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
 Context->FileToReplacements[NewFile] = std::move(AllCode);
   }
 }

Modified: clang-tools-extra/trunk/clang-move/ClangMove.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-move/ClangMove.h?rev=323865&r1=323864&r2=323865&view=diff
==
--- clang-tools-extra/trunk/clang-move/ClangMove.h (original)
+++ clang-tools-extra/trunk/clang-move/ClangMove.h Wed Jan 31 04:12:29 2018
@@ -176,7 +176,11 @@ private:
   /// The source range for the written file name in #include (i.e. "old.h" for
   /// #include "old.h") in old.cc,  including the enclosing quotes or angle
   /// brackets.
-  clang::CharSourceRange OldHeaderIncludeRange;
+  clang::CharSourceRange OldHeaderIncludeRangeInCC;
+  /// The source range for the written file name in #includ

[PATCH] D42170: Fixit for 'typedef' instead of 'typename' typo

2018-01-31 Thread Jan Korous via Phabricator via cfe-commits
jkorous-apple added a comment.

Thanks for your patience with me still learning lit/filecheck. What do you 
think about the test now? I totally agree that this is subjective matter but I 
appreciate your feedback.


https://reviews.llvm.org/D42170



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


[PATCH] D42639: [clang-move] Clever on handling header file which includes itself.

2018-01-31 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE323865: [clang-move] Clever on handling header file which 
includes itself. (authored by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42639?vs=132111&id=132136#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42639

Files:
  clang-move/ClangMove.cpp
  clang-move/ClangMove.h
  unittests/clang-move/ClangMoveTests.cpp

Index: unittests/clang-move/ClangMoveTests.cpp
===
--- unittests/clang-move/ClangMoveTests.cpp
+++ unittests/clang-move/ClangMoveTests.cpp
@@ -293,6 +293,32 @@
   EXPECT_EQ(0u, Results.size());
 }
 
+TEST(ClangMove, HeaderIncludeSelf) {
+  move::MoveDefinitionSpec Spec;
+  Spec.Names = {std::string("Foo")};
+  Spec.OldHeader = "foo.h";
+  Spec.OldCC = "foo.cc";
+  Spec.NewHeader = "new_foo.h";
+  Spec.NewCC = "new_foo.cc";
+
+  const char TestHeader[] = "#ifndef FOO_H\n"
+"#define FOO_H\n"
+"#include \"foo.h\"\n"
+"class Foo {};\n"
+"#endif\n";
+  const char TestCode[] = "#include \"foo.h\"";
+  const char ExpectedNewHeader[] = "#ifndef FOO_H\n"
+   "#define FOO_H\n"
+   "#include \"new_foo.h\"\n"
+   "class Foo {};\n"
+   "#endif\n";
+  const char ExpectedNewCC[] = "#include \"new_foo.h\"";
+  auto Results = runClangMoveOnCode(Spec, TestHeader, TestCode);
+  EXPECT_EQ("", Results[Spec.OldHeader]);
+  EXPECT_EQ(ExpectedNewHeader, Results[Spec.NewHeader]);
+  EXPECT_EQ(ExpectedNewCC, Results[Spec.NewCC]);
+}
+
 TEST(ClangMove, MoveAll) {
   std::vector TestHeaders = {
 "class A {\npublic:\n  int f();\n};",
Index: clang-move/ClangMove.h
===
--- clang-move/ClangMove.h
+++ clang-move/ClangMove.h
@@ -176,7 +176,11 @@
   /// The source range for the written file name in #include (i.e. "old.h" for
   /// #include "old.h") in old.cc,  including the enclosing quotes or angle
   /// brackets.
-  clang::CharSourceRange OldHeaderIncludeRange;
+  clang::CharSourceRange OldHeaderIncludeRangeInCC;
+  /// The source range for the written file name in #include (i.e. "old.h" for
+  /// #include "old.h") in old.h,  including the enclosing quotes or angle
+  /// brackets.
+  clang::CharSourceRange OldHeaderIncludeRangeInHeader;
   /// Mapping from FilePath to FileID, which can be used in post processes like
   /// cleanup around replacements.
   llvm::StringMap FilePathToFileID;
Index: clang-move/ClangMove.cpp
===
--- clang-move/ClangMove.cpp
+++ clang-move/ClangMove.cpp
@@ -694,22 +694,28 @@
 const SourceManager &SM) {
   SmallVector HeaderWithSearchPath;
   llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
-  std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
-  if (AbsoluteOldHeader ==
+  std::string AbsoluteIncludeHeader =
   MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
-   HeaderWithSearchPath.size( {
-OldHeaderIncludeRange = IncludeFilenameRange;
-return;
-  }
-
+   HeaderWithSearchPath.size()));
   std::string IncludeLine =
   IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
: ("#include \"" + IncludeHeader + "\"\n").str();
 
+  std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
   std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
   if (AbsoluteOldHeader == AbsoluteCurrentFile) {
+// Find old.h includes "old.h".
+if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
+  OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
+  return;
+}
 HeaderIncludes.push_back(IncludeLine);
   } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
+// Find old.cc includes "old.h".
+if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
+  OldHeaderIncludeRangeInCC = IncludeFilenameRange;
+  return;
+}
 CCIncludes.push_back(IncludeLine);
   }
 }
@@ -857,13 +863,18 @@
   if (!NewFile.empty()) {
 auto AllCode = clang::tooling::Replacements(
 clang::tooling::Replacement(NewFile, 0, 0, Code));
-// If we are moving from old.cc, an extra step is required: excluding
-// the #include of "old.h", instead, we replace it with #include of "new.h".
-if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
-  AllCode = AllCode.merge(
-  clang::tooling::Replacements(clang::tooling::Replacement(
-  SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
-}
+auto Repla

[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Jens Massberg via Phabricator via cfe-commits
massberg updated this revision to Diff 132137.
massberg retitled this revision from "Add clang-tidy check for use of 
types/classes/functions from functional.h which are deprecated and removed in 
C++17" to "Add clang-tidy check for use of types/classes/functions from 
 header which are deprecated and removed in C++17".
massberg edited the summary of this revision.
massberg added a comment.

Implemented all suggestions from the reviewer.


https://reviews.llvm.org/D42730

Files:
  clang-tidy/modernize/AvoidFunctionalCheck.cpp
  clang-tidy/modernize/AvoidFunctionalCheck.h
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-avoid-functional.rst
  test/clang-tidy/modernize-avoid-functional.cpp

Index: test/clang-tidy/modernize-avoid-functional.cpp
===
--- test/clang-tidy/modernize-avoid-functional.cpp
+++ test/clang-tidy/modernize-avoid-functional.cpp
@@ -0,0 +1,53 @@
+// RUN: %check_clang_tidy %s modernize-avoid-functional %t
+
+namespace std {
+
+template 
+class binary_function {};
+
+template 
+class unary_function {};
+
+template 
+class pointer_to_unary_function : public std::unary_function {}; // NOLINT
+
+template 
+pointer_to_unary_function ptr_fun(Result (*f)(Arg)) {
+  pointer_to_unary_function Nothing;
+  return Nothing;
+}
+
+template 
+class mem_fun_t {};
+
+template 
+mem_fun_t mem_fun(Res (T::*f)()) {}
+
+} // namespace std
+
+// CHECK-MESSAGES: [[@LINE+1]]:25: warning: 'binary_function' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class BinaryTestClass : public std::binary_function {
+ public:
+  BinaryTestClass();
+};
+
+// CHECK-MESSAGES: [[@LINE+1]]:24: warning: 'unary_function' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class UnaryTestClass : public std::unary_function {
+ public:
+  UnaryTestClass();
+};
+
+int simpleFunc(int X) { return X + 1; };
+
+class TestClass {
+ public:
+  int test() { return 1; }
+};
+
+void foo(void) {
+// CHECK-MESSAGES: [[@LINE+1]]:3: warning: 'std::ptr_fun' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+  std::ptr_fun(simpleFunc);
+
+// CHECK-MESSAGES: [[@LINE+1]]:3: warning: 'std::mem_fun' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+  std::mem_fun(&TestClass::test);
+}
Index: docs/clang-tidy/checks/modernize-avoid-functional.rst
===
--- docs/clang-tidy/checks/modernize-avoid-functional.rst
+++ docs/clang-tidy/checks/modernize-avoid-functional.rst
@@ -0,0 +1,13 @@
+.. title:: clang-tidy - modernize-avoid-functional
+
+modernize-avoid-functional
+==
+
+In C++17 several classes, types and functions from  header are no longer available.
+In particular, this check warns if one of the following deprecated objects is
+used:
+
+-  std::unary_function
+-  std::binary_function
+-  std::ptr_fun
+-  std::mem_fun
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -154,6 +154,7 @@
misc-unused-raii
misc-unused-using-decls
modernize-avoid-bind
+   modernize-avoid-functional
modernize-deprecated-headers
modernize-loop-convert
modernize-make-shared
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -57,6 +57,12 @@
 Improvements to clang-tidy
 --
 
+- New `modernize-avoid-functional
+  `_ check
+
+  Warns if types, classes and functions from  header which are
+  deprecated in C++11 and removed in C++17 are used.
+
 - The 'misc-incorrect-roundings' check was renamed to `bugprone-incorrect-roundings
   `_
 
Index: clang-tidy/modernize/ModernizeTidyModule.cpp
===
--- clang-tidy/modernize/ModernizeTidyModule.cpp
+++ clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "AvoidBindCheck.h"
+#include "AvoidFunctionalCheck.h"
 #include "DeprecatedHeadersCheck.h"
 #include "LoopConvertCheck.h"
 #include "MakeSharedCheck.h"
@@ -45,6 +46,8 @@
 public:
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
 CheckFactories.registerCheck("modernize-avoid-bind");
+CheckFactories.registerCheck(
+"modernize-avoid-functional");
 CheckFactories.registerCheck(
 "modernize-deprecated-headers");
 CheckFactories.registerCheck("modernize-loop-convert");
Index: clang-tidy/m

[PATCH] D42729: clang-format: Fix formatting of function body followed by semicolon

2018-01-31 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added inline comments.



Comment at: lib/Format/TokenAnnotator.cpp:1911
+  if (Next && Next->is(tok::l_brace) && Next->BlockKind == BK_BracedInit)
+  Next->BlockKind = BK_Block;
+}

this may actually not be enough in all cases: to completely match the 
'standard' behavior we should be able to "split" the UnwrappedLine at both 
opening and ending brace, in this case.


Repository:
  rC Clang

https://reviews.llvm.org/D42729



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


[PATCH] D41698: [DebugInfo] Enable debug information for C99 VLA types

2018-01-31 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: lib/CodeGen/CGDecl.cpp:990
+  D.getLocation(), D.getLocation(), &NameIdent, QT,
+  getContext().CreateTypeSourceInfo(QT), SC_Auto);
+

aprantl wrote:
> sdesmalen wrote:
> > aprantl wrote:
> > > I think it does, but can you assert me that this generates the same code 
> > > with and without -g ?
> > I'm not really sure what you mean with 'generates the same code', because 
> > without -g this function is not invoked? However, this function only 
> > affects debug information, not anything else related to the actual creation 
> > of the VLA. So without -g, no 'dbg.declare()' or corresponding 
> > DILocalVariables are generated for each subexpression of each dimension.
> What I meant is that regardless of code being compile with or without -g, the 
> .text section of the resulting binary is identical.
Actually, before I commit this patch, I just realize this is not the case. At 
least not with -O0 since it creates a stackobject to store the vla-size 
subexpression, which is referenced by the dbg.declare(). We can assume this 
store/alloca to be DCE'd at optimization levels higher than O0 so it should not 
have any impact, but strictly taken the .text section will not be the same with 
and without -g at -O0.


https://reviews.llvm.org/D41698



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


[PATCH] D42517: [clangd] Pass Context implicitly using TLS.

2018-01-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 3 inline comments as done.
sammccall added a comment.

Thanks!




Comment at: clangd/Context.h:77
+  /// See WithContext and WithContextValue for how to do this safely.
+  static Context ¤t();
 

ilya-biryukov wrote:
> Maybe we could return `const Context&` here and have a separate 
> `setCurrent()` method for replacing the current context?
> Most of the clients shouldn't mutate the contexts anyway, and finding the few 
> that do seems easier if there's a separate method for that.
Done (named `swap`).

In fact the only caller is `WithContext`, which is a good sign.

It would be possible to make `swap()` private, since WithContext is in this 
file. I tend to lean against it because embedders will do explicit context 
manipulation and WithContext may not be the right primitive for them. So I've 
left the WithContext guidance as "just a comment". Could be convinced though.




Comment at: clangd/Context.h:201
+  WithContext &operator=(const WithContext &) = delete;
+  WithContext(WithContext &&) = default; // Allow return-by-value.
+  WithContext &operator=(WithContext &&) = delete;

ilya-biryukov wrote:
> Where do we use it? Can't we make move ctor deleted too?
Good catch! This was used in an old version of the patch.



Comment at: clangd/Trace.cpp:131
+return Context::current().clone();
+  WithContextValue WithArgs{std::unique_ptr(Args)};
+  return T->beginSpan(Name, Args);

ilya-biryukov wrote:
> Maybe use parentheses instead of braces for initialization?
Braces here are to avoid most-vexing-parse: with parens this is a function 
declaration.

(I'm not sure this is worth a comment, as the compiler flags it if you change 
it)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517



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


[PATCH] D42517: [clangd] Pass Context implicitly using TLS.

2018-01-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: clangd/JSONRPCDispatcher.h:60
+/// Current context must derive from JSONRPCDispatcher::Handler.
+void reply(json::Expr &&Result);
+/// Sends an error response to the client, and logs it.

ilya-biryukov wrote:
> `reply`'s signature is scary now.
> Should we change it to accept something request-specific that can be found in 
> the `Context` by the clients? WDYT? 
> 
> PS we could change it after the patch lands, just wanted to get your opinion 
> on this
Oops, missed this.
To me, the scariest part is that "reply" is a very generic name and its 
parameter is approximately "anything".

In principle your suggestion makes sense, but passing `Context::current()` 
explicitly is plain weird, and passing `Context::current().get(kRequestToken)` 
seems pretty grungy in the context.

I think I'd be more partial to either giving it a more specific name like 
`replyToLSPRequest` which hints at the current-context requirement, or actually 
making all our LSP handlers accept a `UniqueFunction>` and 
obviating the need for `reply` altogether.

Either way, I'd prefer to address this separately (partly because I'm not sure 
which is best).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517



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


[PATCH] D42517: [clangd] Pass Context implicitly using TLS.

2018-01-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

I don't see a patch corresponding to the fixed comments. `arc diff` didn't go 
through?




Comment at: clangd/Trace.cpp:131
+return Context::current().clone();
+  WithContextValue WithArgs{std::unique_ptr(Args)};
+  return T->beginSpan(Name, Args);

sammccall wrote:
> ilya-biryukov wrote:
> > Maybe use parentheses instead of braces for initialization?
> Braces here are to avoid most-vexing-parse: with parens this is a function 
> declaration.
> 
> (I'm not sure this is worth a comment, as the compiler flags it if you change 
> it)
LG. No need for a comment.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517



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


[clang-tools-extra] r323867 - [clangd] Better handling symbols defined in macros.

2018-01-31 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Jan 31 04:56:51 2018
New Revision: 323867

URL: http://llvm.org/viewvc/llvm-project?rev=323867&view=rev
Log:
[clangd] Better handling symbols defined in macros.

Summary:
For symbols defined inside macros:
 * use expansion location, if the symbol is formed via macro concatenation.
 * use spelling location, otherwise.

This will fix some symbols that have ill-format location (especial invalid 
filepath).

Reviewers: ioeric

Reviewed By: ioeric

Subscribers: klimek, ilya-biryukov, jkorous-apple, cfe-commits

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

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

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=323867&r1=323866&r2=323867&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Wed Jan 31 
04:56:51 2018
@@ -112,6 +112,37 @@ bool shouldFilterDecl(const NamedDecl *N
   return false;
 }
 
+// Return the symbol location of the given declaration `D`.
+//
+// For symbols defined inside macros:
+//   * use expansion location, if the symbol is formed via macro concatenation.
+//   * use spelling location, otherwise.
+SymbolLocation GetSymbolLocation(const NamedDecl *D, SourceManager &SM,
+ StringRef FallbackDir,
+ std::string &FilePathStorage) {
+  SymbolLocation Location;
+
+  SourceLocation Loc = SM.getSpellingLoc(D->getLocation());
+  if (D->getLocation().isMacroID()) {
+// The symbol is formed via macro concatenation, the spelling location will
+// be "", which is not interesting to us, use the expansion
+// location instead.
+if (llvm::StringRef(Loc.printToString(SM)).startswith("getLocation())),
+  FallbackDir);
+  return {FilePathStorage,
+  SM.getFileOffset(SM.getExpansionRange(D->getLocStart()).first),
+  SM.getFileOffset(SM.getExpansionRange(D->getLocEnd()).second)};
+}
+  }
+
+  FilePathStorage = makeAbsolutePath(SM, SM.getFilename(Loc), FallbackDir);
+  return {FilePathStorage,
+  SM.getFileOffset(SM.getSpellingLoc(D->getLocStart())),
+  SM.getFileOffset(SM.getSpellingLoc(D->getLocEnd()))};
+}
+
 } // namespace
 
 SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
@@ -149,17 +180,14 @@ bool SymbolCollector::handleDeclOccurenc
   return true;
 
 auto &SM = ND->getASTContext().getSourceManager();
-std::string FilePath = makeAbsolutePath(
-SM, SM.getFilename(D->getLocation()), Opts.FallbackDir);
-SymbolLocation Location = {FilePath, SM.getFileOffset(D->getLocStart()),
-   SM.getFileOffset(D->getLocEnd())};
 std::string QName = ND->getQualifiedNameAsString();
 
 Symbol S;
 S.ID = std::move(ID);
 std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
 S.SymInfo = index::getSymbolInfo(D);
-S.CanonicalDeclaration = Location;
+std::string FilePath;
+S.CanonicalDeclaration = GetSymbolLocation(ND, SM, Opts.FallbackDir, 
FilePath);
 
 // Add completion info.
 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");

Modified: clang-tools-extra/trunk/unittests/clangd/Annotations.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/Annotations.cpp?rev=323867&r1=323866&r2=323867&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/Annotations.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/Annotations.cpp Wed Jan 31 
04:56:51 2018
@@ -83,5 +83,11 @@ std::vector Annotations::ranges(l
   return {R.begin(), R.end()};
 }
 
+std::pair
+Annotations::offsetRange(llvm::StringRef Name) const {
+  auto R = range(Name);
+  return {positionToOffset(Code, R.start), positionToOffset(Code, R.end)};
+}
+
 } // namespace clangd
 } // namespace clang

Modified: clang-tools-extra/trunk/unittests/clangd/Annotations.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/Annotations.h?rev=323867&r1=323866&r2=323867&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/Annotations.h (original)
+++ clang-tools-extra/trunk/unittests/clangd/Annotations.h Wed Jan 31 04:56:51 
2018
@@ -58,6 +58,10 @@ public:
   // Returns the location of all ranges marked by [[ ]] (or $name[[ ]]).
   std::vector ranges(llvm::StringRef Name = "") const;
 
+  // The same to `range` method, b

[PATCH] D42575: [clangd] Better handling symbols defined in macros.

2018-01-31 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE323867: [clangd] Better handling symbols defined in 
macros. (authored by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42575?vs=132123&id=132143#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42575

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

Index: unittests/clangd/Annotations.h
===
--- unittests/clangd/Annotations.h
+++ unittests/clangd/Annotations.h
@@ -58,6 +58,10 @@
   // Returns the location of all ranges marked by [[ ]] (or $name[[ ]]).
   std::vector ranges(llvm::StringRef Name = "") const;
 
+  // The same to `range` method, but returns range in offsets [start, end).
+  std::pair
+  offsetRange(llvm::StringRef Name = "") const;
+
 private:
   std::string Code;
   llvm::StringMap> Points;
Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "Annotations.h"
 #include "TestFS.h"
 #include "index/SymbolCollector.h"
 #include "index/SymbolYAML.h"
@@ -46,11 +47,22 @@
 }
 MATCHER_P(QName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
 MATCHER_P(CPath, P, "") { return arg.CanonicalDeclaration.FilePath == P; }
+MATCHER_P(LocationOffsets, Offsets, "") {
+  // Offset range in SymbolLocation is [start, end] while in Clangd is [start,
+  // end).
+  return arg.CanonicalDeclaration.StartOffset == Offsets.first &&
+  arg.CanonicalDeclaration.EndOffset == Offsets.second - 1;
+}
+//MATCHER_P(FilePath, P, "") {
+  //return arg.CanonicalDeclaration.FilePath.contains(P);
+//}
 
 namespace clang {
 namespace clangd {
 
 namespace {
+const char TestHeaderName[] = "symbols.h";
+const char TestFileName[] = "symbol.cc";
 class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
 public:
   SymbolIndexActionFactory(SymbolCollector::Options COpts)
@@ -79,21 +91,20 @@
 llvm::IntrusiveRefCntPtr Files(
 new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
-const std::string FileName = "symbol.cc";
-const std::string HeaderName = "symbols.h";
 auto Factory = llvm::make_unique(CollectorOpts);
 
 tooling::ToolInvocation Invocation(
-{"symbol_collector", "-fsyntax-only", "-std=c++11", FileName},
+{"symbol_collector", "-fsyntax-only", "-std=c++11", TestFileName},
 Factory->create(), Files.get(),
 std::make_shared());
 
-InMemoryFileSystem->addFile(HeaderName, 0,
+InMemoryFileSystem->addFile(TestHeaderName, 0,
 llvm::MemoryBuffer::getMemBuffer(HeaderCode));
 
-std::string Content = "#include\"" + std::string(HeaderName) + "\"";
-Content += "\n" + MainCode.str();
-InMemoryFileSystem->addFile(FileName, 0,
+std::string Content = MainCode;
+if (!HeaderCode.empty())
+  Content = "#include\"" + std::string(TestHeaderName) + "\"\n" + Content;
+InMemoryFileSystem->addFile(TestFileName, 0,
 llvm::MemoryBuffer::getMemBuffer(Content));
 Invocation.run();
 Symbols = Factory->Collector->takeSymbols();
@@ -206,6 +217,57 @@
   UnorderedElementsAre(QName("Foo")));
 }
 
+TEST_F(SymbolCollectorTest, SymbolFormedFromMacro) {
+  CollectorOpts.IndexMainFiles = false;
+
+  Annotations Header(R"(
+#define FF(name) \
+  class name##_Test {};
+
+$expansion[[FF(abc)]];
+
+#define FF2() \
+  $spelling[[class Test {}]];
+
+FF2();
+  )");
+
+  runSymbolCollector(Header.code(), /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("abc_Test"),
+LocationOffsets(Header.offsetRange("expansion")),
+CPath(TestHeaderName)),
+  AllOf(QName("Test"),
+LocationOffsets(Header.offsetRange("spelling")),
+CPath(TestHeaderName;
+}
+
+TEST_F(SymbolCollectorTest, SymbolFormedFromMacroInMainFile) {
+  CollectorOpts.IndexMainFiles = true;
+
+  Annotations Main(R"(
+#define FF(name) \
+  class name##_Test {};
+
+$expansion[[FF(abc)]];
+
+#define FF2() \
+  $spelling[[class Test {}]];
+
+FF2();
+  )");
+  runSymbolCollector(/*Header=*/"", Main.code());
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("abc_Test"),
+LocationOffsets(Main.offsetRange("expansion")),
+CPath(TestFileName)),
+  AllOf(QName("Test"),
+LocationOffsets(Main.offsetRange("spelling")),
+  

[PATCH] D42575: [clangd] Better handling symbols defined in macros.

2018-01-31 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323867: [clangd] Better handling symbols defined in macros. 
(authored by hokein, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42575?vs=132123&id=132144#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42575

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

Index: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
@@ -112,6 +112,37 @@
   return false;
 }
 
+// Return the symbol location of the given declaration `D`.
+//
+// For symbols defined inside macros:
+//   * use expansion location, if the symbol is formed via macro concatenation.
+//   * use spelling location, otherwise.
+SymbolLocation GetSymbolLocation(const NamedDecl *D, SourceManager &SM,
+ StringRef FallbackDir,
+ std::string &FilePathStorage) {
+  SymbolLocation Location;
+
+  SourceLocation Loc = SM.getSpellingLoc(D->getLocation());
+  if (D->getLocation().isMacroID()) {
+// The symbol is formed via macro concatenation, the spelling location will
+// be "", which is not interesting to us, use the expansion
+// location instead.
+if (llvm::StringRef(Loc.printToString(SM)).startswith("getLocation())),
+  FallbackDir);
+  return {FilePathStorage,
+  SM.getFileOffset(SM.getExpansionRange(D->getLocStart()).first),
+  SM.getFileOffset(SM.getExpansionRange(D->getLocEnd()).second)};
+}
+  }
+
+  FilePathStorage = makeAbsolutePath(SM, SM.getFilename(Loc), FallbackDir);
+  return {FilePathStorage,
+  SM.getFileOffset(SM.getSpellingLoc(D->getLocStart())),
+  SM.getFileOffset(SM.getSpellingLoc(D->getLocEnd()))};
+}
+
 } // namespace
 
 SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
@@ -149,17 +180,14 @@
   return true;
 
 auto &SM = ND->getASTContext().getSourceManager();
-std::string FilePath = makeAbsolutePath(
-SM, SM.getFilename(D->getLocation()), Opts.FallbackDir);
-SymbolLocation Location = {FilePath, SM.getFileOffset(D->getLocStart()),
-   SM.getFileOffset(D->getLocEnd())};
 std::string QName = ND->getQualifiedNameAsString();
 
 Symbol S;
 S.ID = std::move(ID);
 std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
 S.SymInfo = index::getSymbolInfo(D);
-S.CanonicalDeclaration = Location;
+std::string FilePath;
+S.CanonicalDeclaration = GetSymbolLocation(ND, SM, Opts.FallbackDir, FilePath);
 
 // Add completion info.
 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Index: clang-tools-extra/trunk/unittests/clangd/Annotations.h
===
--- clang-tools-extra/trunk/unittests/clangd/Annotations.h
+++ clang-tools-extra/trunk/unittests/clangd/Annotations.h
@@ -58,6 +58,10 @@
   // Returns the location of all ranges marked by [[ ]] (or $name[[ ]]).
   std::vector ranges(llvm::StringRef Name = "") const;
 
+  // The same to `range` method, but returns range in offsets [start, end).
+  std::pair
+  offsetRange(llvm::StringRef Name = "") const;
+
 private:
   std::string Code;
   llvm::StringMap> Points;
Index: clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "Annotations.h"
 #include "TestFS.h"
 #include "index/SymbolCollector.h"
 #include "index/SymbolYAML.h"
@@ -46,11 +47,22 @@
 }
 MATCHER_P(QName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
 MATCHER_P(CPath, P, "") { return arg.CanonicalDeclaration.FilePath == P; }
+MATCHER_P(LocationOffsets, Offsets, "") {
+  // Offset range in SymbolLocation is [start, end] while in Clangd is [start,
+  // end).
+  return arg.CanonicalDeclaration.StartOffset == Offsets.first &&
+  arg.CanonicalDeclaration.EndOffset == Offsets.second - 1;
+}
+//MATCHER_P(FilePath, P, "") {
+  //return arg.CanonicalDeclaration.FilePath.contains(P);
+//}
 
 namespace clang {
 namespace clangd {
 
 namespace {
+const char TestHeaderName[] = "symbols.h";
+const char TestFileName[] = "symbol.cc";
 class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
 public:
   SymbolIndexActionFactor

[PATCH] D42517: [clangd] Pass Context implicitly using TLS.

2018-01-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/JSONRPCDispatcher.h:60
+/// Current context must derive from JSONRPCDispatcher::Handler.
+void reply(json::Expr &&Result);
+/// Sends an error response to the client, and logs it.

sammccall wrote:
> ilya-biryukov wrote:
> > `reply`'s signature is scary now.
> > Should we change it to accept something request-specific that can be found 
> > in the `Context` by the clients? WDYT? 
> > 
> > PS we could change it after the patch lands, just wanted to get your 
> > opinion on this
> Oops, missed this.
> To me, the scariest part is that "reply" is a very generic name and its 
> parameter is approximately "anything".
> 
> In principle your suggestion makes sense, but passing `Context::current()` 
> explicitly is plain weird, and passing 
> `Context::current().get(kRequestToken)` seems pretty grungy in the context.
> 
> I think I'd be more partial to either giving it a more specific name like 
> `replyToLSPRequest` which hints at the current-context requirement, or 
> actually making all our LSP handlers accept a `UniqueFunction>` 
> and obviating the need for `reply` altogether.
> 
> Either way, I'd prefer to address this separately (partly because I'm not 
> sure which is best).
Totally agree, let's address it separately.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517



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


[PATCH] D42517: [clangd] Pass Context implicitly using TLS.

2018-01-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In https://reviews.llvm.org/D42517#993131, @ilya-biryukov wrote:

> I don't see a patch corresponding to the fixed comments. `arc diff` didn't go 
> through?


Indeed, sorry. Should be up to date now.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517



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


[PATCH] D42517: [clangd] Pass Context implicitly using TLS.

2018-01-31 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 modulo two NITs.
Really excited to see this land.




Comment at: clangd/Context.cpp:32
+
+Context Context::swap(Context Replacement) {
+  std::swap(Replacement, currentContext());

Maybe call it `swapCurrent`. It's longer, but won't allow to mistake it for a 
member `swap` function. 
Since it's almost never used, having a longer name is not a big deal.



Comment at: clangd/Context.h:196
+  ~WithContext() {
+if (Restore)
+  Context::swap(std::move(*Restore));

I think it can't be `null` after move ctor is deleted.
Maybe always store a `Context` instead of `unique_ptr` and call `swap` 
unconditionally?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517



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


[PATCH] D42729: clang-format: Fix formatting of function body followed by semicolon

2018-01-31 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added a comment.

I think this case is not important enough to fix. Please tell users to just 
delete the useless semicolon.

In particular, my concern is that this makes the data-flow significantly more 
complicated. Early on in the development, we had separate token classes for the 
different states of the analysis (unwrapped line parsing, annotation, 
formatting) with const members. We had to move away from that as it didn't 
carry the costs that it had. However, this change changes the behavior from the 
BlockKind only ever being set inside the UnwrappedLineParser and being consumed 
later (e.g. in the TokenAnnotator) to a state where it is set in many places 
and setting and changing the value are inter-mingled. That makes it much harder 
to understand the invariants. E.g. how can we ensure that the incorrect 
BK_BracedInit hasn't already be consumed by something (now and in the future).


Repository:
  rC Clang

https://reviews.llvm.org/D42729



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


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

2018-01-31 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 132146.
yvvan added a comment.

Use https://reviews.llvm.org/D42474 code. Add missing parts and tests for 
errors and fixits.


https://reviews.llvm.org/D41537

Files:
  include/clang-c/Index.h
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  include/clang/Sema/Sema.h
  lib/Frontend/ASTUnit.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/CodeCompleteConsumer.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/FixIt/fixit.cpp
  test/Index/complete-arrow-dot.cpp
  test/SemaCXX/member-expr.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -170,6 +170,7 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionCorrection
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -238,6 +238,16 @@
   return cxstring::createRef(CCStr->getBriefComment());
 }
 
+enum CXCorrection
+clang_getCompletionCorrection(CXCompletionString completion_string) {
+  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
+
+  if (!CCStr)
+return CXCorrection_No;
+
+  return CCStr->getCorrection();
+}
+
 namespace {
 
 /// \brief The CXCodeCompleteResults structure we allocate internally;
@@ -644,6 +654,7 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeCorrections = options & CXCodeComplete_IncludeCorrections;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
@@ -650,7 +661,6 @@
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
 #endif
 #endif
-
   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
 
   if (cxtu::isNotUsableTU(TU)) {
@@ -691,6 +701,7 @@
   CodeCompleteOptions Opts;
   Opts.IncludeBriefComments = IncludeBriefComments;
   Opts.LoadExternal = !SkipPreamble;
+  Opts.IncludeCorrections = IncludeCorrections;
   CaptureCompletionResults Capture(Opts, *Results, &TU);
 
   // Perform completion.
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -2332,7 +2332,13 @@
 fprintf(file, "(brief comment: %s)", BriefCommentCString);
   }
   clang_disposeString(BriefComment);
-  
+
+  enum CXCorrection Corr =
+  clang_getCompletionCorrection(completion_result->CompletionString);
+  if (Corr == CXCorrection_DotToArrow)
+fprintf(file, " (requires correction: \".\" to \"->\")");
+  else if (Corr == CXCorrection_ArrowToDot)
+fprintf(file, " (requires correction: \"->\" to \".\")");
   fprintf(file, "\n");
 }
 
@@ -2431,6 +2437,8 @@
 completionOptions |= CXCodeComplete_IncludeBriefComments;
   if (getenv("CINDEXTEST_COMPLETION_SKIP_PREAMBLE"))
 completionOptions |= CXCodeComplete_SkipPreamble;
+  if (getenv("CINDEXTEST_COMPLETION_INCLUDE_CORRECTIONS"))
+completionOptions |= CXCodeComplete_IncludeCorrections;
   
   if (timing_only)
 input += strlen("-code-completion-timing=");
Index: test/SemaCXX/member-expr.cpp
===
--- test/SemaCXX/member-expr.cpp
+++ test/SemaCXX/member-expr.cpp
@@ -188,6 +188,11 @@
 return c->a;  // expected-error {{member reference type 'PR15045::Cl0' is not a pointer; did you mean to use '.'?}}
   }
 
+  int g() {
+Cl0* c;
+return c.a;  // expected-error {{member reference type 'PR15045::Cl0 *' is a pointer; did you mean to use '->'?}}
+  }
+
   struct bar {
 void func();  // expected-note {{'func' declared here}}
   };
Index: test/Index/complete-arrow-dot.cpp
===
--- test/Index/complete-arrow-dot.cpp
+++ test/Index/complete-arrow-dot.cpp
@@ -0,0 +1,54 @@
+struct X {
+  void doSomething();
+
+  int field;
+};
+
+void X::doSomething() {
+  // RUN: c-index-test -code-completion-at=%s:10:8 %s | FileCheck %s
+  // RUN: env CINDEXTEST_COMPLETION_INCLUDE_CORRECTIONS=1 c-index-test -code-completion-at=%s:10:8 %s | FileCheck -check-prefix=CHECK-WITH-CORRECTION %s
+  this.;
+}
+
+void doSomething() {
+  // RUN: c-index-test -code-completion-at=%s:17:6 %s | FileCheck -check-prefix=CHECK-ARROW-TO-DOT %s
+  // RUN: env CINDEXTEST_COMPLETION_INCLUDE_CORRECTIONS=1 c-index-test -code-completion-at=%s:17:6 %s | FileCheck -che

[clang-tools-extra] r323871 - Update header guard.

2018-01-31 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Wed Jan 31 05:31:51 2018
New Revision: 323871

URL: http://llvm.org/viewvc/llvm-project?rev=323871&view=rev
Log:
Update header guard.

Modified:
clang-tools-extra/trunk/clang-tidy/bugprone/IncorrectRoundingsCheck.h

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/IncorrectRoundingsCheck.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/IncorrectRoundingsCheck.h?rev=323871&r1=323870&r2=323871&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/IncorrectRoundingsCheck.h 
(original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/IncorrectRoundingsCheck.h Wed 
Jan 31 05:31:51 2018
@@ -7,8 +7,8 @@
 //
 
//===--===//
 
-#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCORRECTROUNDINGS_H_
-#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCORRECTROUNDINGS_H_
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTROUNDINGSCHECK_H_
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTROUNDINGSCHECK_H_
 
 #include "../ClangTidy.h"
 
@@ -36,4 +36,4 @@ public:
 } // namespace tidy
 } // namespace clang
 
-#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCORRECTROUNDINGS_H_
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_INCORRECTROUNDINGSCHECK_H_


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


[PATCH] D42517: [clangd] Pass Context implicitly using TLS.

2018-01-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: clangd/Context.h:196
+  ~WithContext() {
+if (Restore)
+  Context::swap(std::move(*Restore));

ilya-biryukov wrote:
> I think it can't be `null` after move ctor is deleted.
> Maybe always store a `Context` instead of `unique_ptr` and call `swap` 
> unconditionally?
Right! much nicer.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517



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


[PATCH] D42729: clang-format: Fix formatting of function body followed by semicolon

2018-01-31 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

There are actually other cases, e.g. with macros "containing" the semicolon:

  void abort() {
FOO()
BAR()
  };

gets reformatted to this (still wrong with this patch, but the space after the 
parenthesis is added):

  void abort(){ FOO() BAR() };

And also this one (though it may be slightly different, there is no semicolon 
here):

  void abort() {
FOO()
  }
  uint32_t bar() {}

gets reformatted to:

  void abort(){ FOO() BAR() } uint32_t bar() {}

IMO the "real" fix would be to somehow let 
`TokenAnnotator::calculateFormattingInformation` split the current 
UnwrappedLine/AnnotatedLine, so that the 'end of the line' could be unwrapped 
properly: this would also allow keeping the invariant, and just implement some 
kind of backtracking. But it may be tricky to get the state right; maybe adding 
some child lines instead of just adding the lines may be simpler?


Repository:
  rC Clang

https://reviews.llvm.org/D42729



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


[PATCH] D42729: clang-format: Fix formatting of function body followed by semicolon

2018-01-31 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

In https://reviews.llvm.org/D42729#993159, @djasper wrote:

> I think this case is not important enough to fix. Please tell users to just 
> delete the useless semicolon.


I would agree if were simple to spot: but often this may manifest itself only 
with a missing space between the function parameters and the function body, 
which can easily be overlooked...
Another option may be to create new pass which "removes" that extra semicolon: 
this way we would both fix it and get things right on next pass.

However, the issue with a function which contains only a macro and which is 
followed by another function which returns an custom type cannot so easily be 
fixed:

  void abort() {
FOO()
  }
  uint32_t bar() {}

(note that this case works fine if the body of the function contains a 
semicolon or reserved keyword, or if the next function returns a base type 
[int, void...])


Repository:
  rC Clang

https://reviews.llvm.org/D42729



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


[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:21
+void AvoidFunctionalCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  cxxRecordDecl(allOf(anyOf(isDerivedFrom("std::binary_function"),

I don't think this matcher catches other uses of these types. e.g.,
```
typedef std::binary_function awesome_sauce;
struct S : awesome_sauce {};

template 
struct S {};

template   
struct S, Ty>::value>::type> {
  typedef int value;
};
```



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:22
+  Finder->addMatcher(
+  cxxRecordDecl(allOf(anyOf(isDerivedFrom("std::binary_function"),
+isDerivedFrom("std::unary_function")),

These should all be `::std::` instead of `std::` to cover pathological code 
that puts `std` inside of another namespace.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:37
+void AvoidFunctionalCheck::check(const MatchFinder::MatchResult &Result) {
+  if (const auto* const UnaryOrBinaryDerived =
+  Result.Nodes.getNodeAs("un_or_binary_derived")) {

Formatting (here and elsewhere); you should run the patch through clang-format 
to handle this sort of thing.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:43
+  const auto *ClangDecl = BaseType->getAsCXXRecordDecl();
+  if (!ClangDecl) {
+continue;

Should elide the braces here.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:47-51
+  if (!ClangDecl->getDeclName().isIdentifier() ||
+  (ClangDecl->getName() != "unary_function" &&
+   ClangDecl->getName() != "binary_function")) {
+continue;
+  }

Shouldn't this be an `assert` instead?



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.h:19
+
+/// Check for several deprecated types and classes from  header
+///

Missing full stop at the end of the sentence.

Why should this modernize check be limited to ``? Just like we have 
a "deprecated headers" check, perhaps this should be a "deprecated APIs" check?



Comment at: docs/clang-tidy/checks/modernize-avoid-functional.rst:6
+
+In C++17 several classes, types and functions from  header are no 
longer available.
+In particular, this check warns if one of the following deprecated objects is

"In C++17, several classes, types, and functions" (commas).


https://reviews.llvm.org/D42730



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


[PATCH] D42573: [wip] The new threading implementation

2018-01-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Not a complete review, but this looks pretty good!
You probably want to read the last comment first - the gc thread is the 
threadpooliest bit of code left, and you may (or may not) want to eliminate it.




Comment at: clangd/TUScheduler.cpp:23
+return;
+  Worker = std::thread([&]() {
+while (true) {

I tend to find thread bodies more readable as a member function, up to you



Comment at: clangd/TUScheduler.cpp:220
+
+  GCThread.cleanupFile(std::move(Data->Worker));
 }

in the spirit of "just spawn a thread, and write direct code"...

can we just spawn a shared_ptr to do the work here, and replace 
GCThread with a vector>.
Then ~TUScheduler could just loop through:

  for (const auto &WeakThread : Cleanups)
if (auto SharedThread = WeakThread.lock()) // thread may have died already
  SharedThread->join();

might be simpler? You need to lock the Cleanups vector, but no fiddling with 
CVs etc.



Comment at: clangd/TUScheduler.cpp:258
+std::lock_guard BarrierLock(Barrier);
+// XXX: what if preamble got built by this time?
+// if (!Preamble)

this seems like where shared_ptr might help us out if we're willing to deal 
with it.
If we captured a shared_ptr here, then we'd want to call 
getPossiblyStalePreamble inside rather than outside the lambda.

So this would look something like:
 - FileASTThread does thread shutdown as part of destructor, and requires the 
TUScheduler to outlive it
 - TUScheduler keeps (conceptually): active files 
`StringMap>`, and shutdown handles 
`vector>`
 - removal takes the shared_ptr out of the map, transfers ownership of the 
shared_ptr to a new thread which does nothing (except destroy the shared_ptr), 
and stashes a weak_ptr to the thread as a shutdown handle, which get looped 
over in the destructor.

Is this simpler? I'm not sure. It's maybe more thematically consistent :-) and 
it solves your "preamble got built" problem.




Comment at: clangd/TUScheduler.h:37
+/// Limits the number of threads that can acquire this semaphore.
+class CountingSemaphore {
+public:

Probably belongs in Threading.h instead.

Maybe just Semaphore? If we have *two* semaphores in clangd, we've jumped the 
shark!
(Isn't a non-counting semaphore just a mutex?)




Comment at: clangd/TUScheduler.h:50
+
+class FileASTThread {
+public:

Maybe FileWorker? this has-a thread, rather than is-a



Comment at: clangd/TUScheduler.h:59
+
+  void setDone();
+

AFAICS, we require callers to setDone() before destroying, and the caller 
always does this immediately before destroying.

Why not just make the destructor do this?



Comment at: clangd/TUScheduler.h:63
+  Context Ctx, ParseInputs Inputs,
+  UniqueFunction>)>
+  OnUpdated);

do we want to move the callback to be a clangd-global thing, rather than a 
per-update thing, before this patch or later?

(And will that change be mirrored here, or will FileASTThread::update still 
take a callback?)



Comment at: clangd/TUScheduler.h:65
+  OnUpdated);
+  void enqueueRead(UniqueFunction)> Action);
+

consider mirroring the runWithAST name



Comment at: clangd/TUScheduler.h:70
+  mutable std::mutex Mutex;
+  bool Done;
+  std::condition_variable RequestsCV;

(no action required, just random thoughts)

one day we should really get the threading annotations (REQUIRES_EXCLUSIVE_LOCK 
etc macros) set up in LLVM - they're *implemented* in llvm for crying out 
loud...



Comment at: clangd/TUScheduler.h:72
+  std::condition_variable RequestsCV;
+  RequestQueue Requests;
+  std::shared_ptr File;

Having trouble seeing which parts of this are really used.
My understanding is that the ThreadPool+Queue abstraction is going away.
This means this is a deque + lock + ... a "done" state of some kind? Is more of 
it still live?

I'd probably expect the 'done' state to be redundant with the one here... If 
it's just a deque + a lock, I'd lean towards making it really thin, maybe even 
a plain struct, and putting it in this file.

But not sure of your thoughts here.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573



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


[PATCH] D42307: [OpenCL][6.0.0 Release] Release notes for OpenCL in Clang

2018-01-31 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia closed this revision.
Anastasia added a comment.

Committed in r323875 with changes as requested.


https://reviews.llvm.org/D42307



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


[PATCH] D42735: [clangd] Add a test URI scheme for lit tests to unbreak platform-specific URI failures.

2018-01-31 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added a reviewer: sammccall.
Herald added subscribers: cfe-commits, jkorous-apple, ilya-biryukov, klimek.

This should also fix the current windows buildbot breakage
(http://lab.llvm.org:8011/builders/clang-x86-windows-msvc2015/builds/9838/steps/ninja%20check%201/logs/stdio)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42735

Files:
  clangd/ClangdLSPServer.cpp
  clangd/Protocol.cpp
  test/clangd/authority-less-uri.test
  test/clangd/completion.test
  test/clangd/diagnostics.test
  test/clangd/execute-command.test
  test/clangd/extra-flags.test
  test/clangd/fixits.test
  test/clangd/formatting.test
  test/clangd/input-mirror.test
  test/clangd/protocol.test
  test/clangd/rename.test
  test/clangd/signature-help.test
  test/clangd/test-uri-posix.test
  test/clangd/test-uri-windows.test
  test/clangd/trace.test
  test/clangd/unsupported-method.test
  test/clangd/xrefs.test

Index: test/clangd/xrefs.test
===
--- test/clangd/xrefs.test
+++ test/clangd/xrefs.test
@@ -7,11 +7,11 @@
 
 Content-Length: 165
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
 
 Content-Length: 148
 
-{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":8}}}
+{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
 #  CHECK:  "id": 1,
 # CHECK-NEXT:  "jsonrpc": "2.0",
 # CHECK-NEXT:  "result": [
@@ -26,12 +26,12 @@
 # CHECK-NEXT:  "line": 0
 # CHECK-NEXT:}
 # CHECK-NEXT:  },
-# CHECK-NEXT:  "uri": "file:///{{([A-Z]:/)?}}main.cpp"
+# CHECK-NEXT:  "uri": "file://{{.*}}/{{([A-Z]:/)?}}main.cpp"
 # CHECK-NEXT:}
 # CHECK-NEXT:  ]
 Content-Length: 155
 
-{"jsonrpc":"2.0","id":1,"method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":8}}}
+{"jsonrpc":"2.0","id":1,"method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
 #  CHECK: "id": 1
 # CHECK-NEXT: "jsonrpc": "2.0",
 # CHECK-NEXT: "result": [
Index: test/clangd/unsupported-method.test
===
--- test/clangd/unsupported-method.test
+++ test/clangd/unsupported-method.test
@@ -7,7 +7,7 @@
 
 Content-Length: 143
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":""}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":""}}}
 
 Content-Length: 92
 
Index: test/clangd/trace.test
===
--- test/clangd/trace.test
+++ test/clangd/trace.test
@@ -7,16 +7,16 @@
 #
 Content-Length: 152
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///foo.c","languageId":"c","version":1,"text":"void main() {}"}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.c","languageId":"c","version":1,"text":"void main() {}"}}}
 #  CHECK: {"displayTimeUnit":"ns","traceEvents":[
 # Start opening the doc.
 #  CHECK: "name": "textDocument/didOpen"
 #  CHECK: "ph": "B"
 # Start building the preamble.
 #  CHECK: "name": "Preamble"
 #  CHECK: },
 # Finish building the preamble, with filename.
-#  CHECK: "File": "/foo.c"
+#  CHECK: "File": "{{.*}}/foo.c"
 # CHECK-NEXT: },
 # CHECK-NEXT: "ph": "E"
 # Start building the file.
Index: test/clangd/test-uri-windows.test
===
--- /dev/null
+++ test/clangd/test-uri-windows.test
@@ -0,0 +1,19 @@
+# RUN: clangd -pretty -run-synchronously < %s | FileCheck -strict-whitespace %s
+# REQUIRES: mingw32 || win32
+# It is absolutely vital that this file has CRLF line endings.
+#
+# Test authority-less URI
+Content-Length: 125
+
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+#
+Content-Length: 152
+
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.c","languageId":"c","version":1,"text":"void main() {}"}}}
+# CHECK:"uri": "file:///C:/clangd-test/foo.c"
+Content-Length: 44
+
+{"jsonrpc":"2.0","id":5,"method":"shutdown"}
+Content-Length: 33
+
+{"jsonrpc":"2.0","method":"exit"}
Index: test/clangd/test-uri-posix.test
==

[PATCH] D42736: [DebugInfo] Improvements to representation of enumeration types (PR36168)

2018-01-31 Thread Momchil Velikov via Phabricator via cfe-commits
chill created this revision.
chill added reviewers: dblaikie, keith.walker.arm.
Herald added subscribers: JDevlieghere, aprantl.

This is the `clang` counterpart to https://reviews.llvm.org/D42734

This patch:

- fixed an incorrect sign-extension of unsigned  values, when emitting debug 
info metadata for enumerators
- the enumerators metadata is created with a flag, which determines 
interpretation of the value bits (signed or unsigned)
- the enumerations metadata contains the underlying integer type and a flag, 
indicating whether this is a C++ "fixed enum"


Repository:
  rC Clang

https://reviews.llvm.org/D42736

Files:
  lib/CodeGen/CGDebugInfo.cpp
  test/CodeGen/debug-info-enum.cpp
  test/CodeGenCXX/debug-info-enum-class.cpp
  test/CodeGenCXX/debug-info-enum.cpp
  test/Modules/ModuleDebugInfo.cpp

Index: test/Modules/ModuleDebugInfo.cpp
===
--- test/Modules/ModuleDebugInfo.cpp
+++ test/Modules/ModuleDebugInfo.cpp
@@ -48,7 +48,7 @@
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type,
 // CHECK-NOT:  name:
 // CHECK-SAME: )
-// CHECK: !DIEnumerator(name: "e5", value: 5)
+// CHECK: !DIEnumerator(name: "e5", value: 5, isSigned: false)
 
 // CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "B",
 // no mangled name here yet.
Index: test/CodeGenCXX/debug-info-enum.cpp
===
--- test/CodeGenCXX/debug-info-enum.cpp
+++ test/CodeGenCXX/debug-info-enum.cpp
@@ -11,7 +11,7 @@
 // CHECK-SAME:  identifier: "_ZTSN5test11eE"
 // CHECK: [[TEST1]] = !DINamespace(name: "test1"
 // CHECK: [[TEST1_ENUMS]] = !{[[TEST1_E:![0-9]*]]}
-// CHECK: [[TEST1_E]] = !DIEnumerator(name: "E", value: 0)
+// CHECK: [[TEST1_E]] = !DIEnumerator(name: "E", value: 0, isSigned: false)
 enum e { E };
 void foo() {
   int v = E;
Index: test/CodeGenCXX/debug-info-enum-class.cpp
===
--- test/CodeGenCXX/debug-info-enum-class.cpp
+++ test/CodeGenCXX/debug-info-enum-class.cpp
@@ -15,20 +15,20 @@
 // CHECK-SAME: baseType: ![[INT:[0-9]+]]
 // CHECK-SAME: size: 32
 // CHECK-NOT:  offset:
-// CHECK-NOT:  flags:
+// CHECK-SAME: flags: DIFlagFixedEnum
 // CHECK-SAME: ){{$}}
 // CHECK: ![[INT]] = !DIBasicType(name: "int"
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "B"
 // CHECK-SAME: line: 4
 // CHECK-SAME: baseType: ![[ULONG:[0-9]+]]
 // CHECK-SAME: size: 64
 // CHECK-NOT:  offset:
-// CHECK-NOT:  flags:
+// CHECK-SAME: flags: DIFlagFixedEnum
 // CHECK-SAME: ){{$}}
 // CHECK: ![[ULONG]] = !DIBasicType(name: "long unsigned int"
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "C"
 // CHECK-SAME: line: 5
-// CHECK-NOT:  baseType:
+// CHECK-SAME: baseType: ![[ULONG:[0-9]+]]
 // CHECK-SAME: size: 32
 // CHECK-NOT:  offset:
 // CHECK-NOT:  flags:
Index: test/CodeGen/debug-info-enum.cpp
===
--- /dev/null
+++ test/CodeGen/debug-info-enum.cpp
@@ -0,0 +1,68 @@
+// RUN: %clang -target x86_64-linux -g -S -emit-llvm -o - %s | FileCheck %s
+enum class E0 : signed char {
+  A0 = -128,
+  B0 = 127,
+} x0;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E0"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "signed char", size: 8, encoding: DW_ATE_signed_char)
+// CHECK: !DIEnumerator(name: "A0", value: -128)
+// CHECK: !DIEnumerator(name: "B0", value: 127)
+
+enum class E1 : unsigned char { A1 = 255 } x1;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E1"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "unsigned char", size: 8, encoding: DW_ATE_unsigned_char)
+// CHECK: !DIEnumerator(name: "A1", value: 255, isSigned: false)
+
+enum class E2 : signed short {
+  A2 = -32768,
+  B2 = 32767,
+} x2;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E2"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "short", size: 16, encoding: DW_ATE_signed)
+// CHECK: !DIEnumerator(name: "A2", value: -32768)
+// CHECK: !DIEnumerator(name: "B2", value: 32767)
+
+enum class E3 : unsigned short { A3 = 65535 } x3;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E3"
+// CHECK-SAME: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "unsigned short", size: 16, encoding: DW_ATE_unsigned)
+// CHECK: !DIEnumerator(name: "A3", value: 65535, isSigned: false)
+
+enum class E4 : signed int { A4 = -2147483648, B4 = 2147483647 } x4;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E4"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: ![[INT:[0-9]+]] = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+/

[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Jens Massberg via Phabricator via cfe-commits
massberg updated this revision to Diff 132169.
massberg added a comment.

Addressed comments of reviewer.


https://reviews.llvm.org/D42730

Files:
  clang-tidy/modernize/AvoidFunctionalCheck.cpp
  clang-tidy/modernize/AvoidFunctionalCheck.h
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-avoid-functional.rst
  test/clang-tidy/modernize-avoid-functional.cpp

Index: test/clang-tidy/modernize-avoid-functional.cpp
===
--- test/clang-tidy/modernize-avoid-functional.cpp
+++ test/clang-tidy/modernize-avoid-functional.cpp
@@ -0,0 +1,63 @@
+// RUN: %check_clang_tidy %s modernize-avoid-functional %t
+
+namespace std {
+
+template 
+class binary_function {};
+
+template 
+class unary_function {};
+
+template 
+class pointer_to_unary_function
+: public std::unary_function {  // NOLINT
+};
+
+template 
+pointer_to_unary_function ptr_fun(Result (*f)(Arg)) {
+  pointer_to_unary_function Nothing;
+  return Nothing;
+}
+
+template 
+class mem_fun_t {};
+
+template 
+mem_fun_t mem_fun(Res (T::*f)()) {}
+
+}  // namespace std
+
+// CHECK-MESSAGES: [[@LINE+1]]:25: warning: 'binary_function' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class BinaryTestClass : public std::binary_function {
+ public:
+  BinaryTestClass();
+};
+
+// CHECK-MESSAGES: [[@LINE+1]]:24: warning: 'unary_function' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class UnaryTestClass : public std::unary_function {
+ public:
+  UnaryTestClass();
+};
+
+class TestClass {
+ public:
+  int test() { return 1; }
+};
+
+// CHECK-MESSAGES: [[@LINE+2]]:31: warning: 'unary_function' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class AnotherUnaryTestClass : public TestClass,
+  public std::unary_function {
+ public:
+  AnotherUnaryTestClass();
+};
+
+
+int simpleFunc(int X) { return X + 1; };
+
+void foo(void) {
+// CHECK-MESSAGES: [[@LINE+1]]:3: warning: 'std::ptr_fun' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+  std::ptr_fun(simpleFunc);
+
+// CHECK-MESSAGES: [[@LINE+1]]:3: warning: 'std::mem_fun' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+  std::mem_fun(&TestClass::test);
+}
Index: docs/clang-tidy/checks/modernize-avoid-functional.rst
===
--- docs/clang-tidy/checks/modernize-avoid-functional.rst
+++ docs/clang-tidy/checks/modernize-avoid-functional.rst
@@ -0,0 +1,13 @@
+.. title:: clang-tidy - modernize-avoid-functional
+
+modernize-avoid-functional
+==
+
+In C++17, several classes, types, and functions from  header are no longer available.
+In particular, this check warns if one of the following deprecated objects is
+used:
+
+-  std::unary_function
+-  std::binary_function
+-  std::ptr_fun
+-  std::mem_fun
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -154,6 +154,7 @@
misc-unused-raii
misc-unused-using-decls
modernize-avoid-bind
+   modernize-avoid-functional
modernize-deprecated-headers
modernize-loop-convert
modernize-make-shared
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -57,6 +57,12 @@
 Improvements to clang-tidy
 --
 
+- New `modernize-avoid-functional
+  `_ check
+
+  Warns if types, classes and functions from  header which are
+  deprecated in C++11 and removed in C++17 are used.
+
 - The 'misc-incorrect-roundings' check was renamed to `bugprone-incorrect-roundings
   `_
 
Index: clang-tidy/modernize/ModernizeTidyModule.cpp
===
--- clang-tidy/modernize/ModernizeTidyModule.cpp
+++ clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "AvoidBindCheck.h"
+#include "AvoidFunctionalCheck.h"
 #include "DeprecatedHeadersCheck.h"
 #include "LoopConvertCheck.h"
 #include "MakeSharedCheck.h"
@@ -45,6 +46,8 @@
 public:
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
 CheckFactories.registerCheck("modernize-avoid-bind");
+CheckFactories.registerCheck(
+"modernize-avoid-functional");
 CheckFactories.registerCheck(
 "modernize-deprecated-headers");
 CheckFactories.registerCheck("modernize-loop-convert");
Index: clang-tidy/modernize/CMakeLists.txt
===

[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Jens Massberg via Phabricator via cfe-commits
massberg marked 6 inline comments as done.
massberg added a comment.

Alex and Aaron, thanks for the comments!




Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:21
+void AvoidFunctionalCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  cxxRecordDecl(allOf(anyOf(isDerivedFrom("std::binary_function"),

aaron.ballman wrote:
> I don't think this matcher catches other uses of these types. e.g.,
> ```
> typedef std::binary_function awesome_sauce;
> struct S : awesome_sauce {};
> 
> template 
> struct S {};
> 
> template   
> struct S std::enable_if, 
> Ty>::value>::type> {
>   typedef int value;
> };
> ```
True. This matcher covers most cases in code I have looked into. I can extend 
this matcher in a follow-up change.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.cpp:47-51
+  if (!ClangDecl->getDeclName().isIdentifier() ||
+  (ClangDecl->getName() != "unary_function" &&
+   ClangDecl->getName() != "binary_function")) {
+continue;
+  }

aaron.ballman wrote:
> Shouldn't this be an `assert` instead?
Due to multiple inheritance, there might be several bases and we have to 
iterate them to find the one we are interested in.
I added an additional test case covering multiple inheritance.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.h:19
+
+/// Check for several deprecated types and classes from  header
+///

aaron.ballman wrote:
> Missing full stop at the end of the sentence.
> 
> Why should this modernize check be limited to ``? Just like we 
> have a "deprecated headers" check, perhaps this should be a "deprecated APIs" 
> check?
Added full stop.

I'm not sure if this check should be limited to  or be extended to 
a full 'deprecated API' check.
This change is just a start, several more types and classes which are removed 
from  will follow, e.g:

- std::ptr_fun, std::mem_fun, std::mem_fun_ref
- std::bind1st, std::bind2nd
- std::unary_function, std::binary_function
- std::pointer_to_unary_function, std::pointer_to_binary_function, 
std::mem_fun_t, std::mem_fun1_t, std::const_mem_fun_t, 
- std::const_mem_fun1_t, std::mem_fun_ref_t, std::mem_fun1_ref_t, 
std::const_mem_fun_ref_t, std::const_mem_fun1_ref_t
- std::binder1st, std::binder2nd

As these are a bunch of functions and types, in my eyes a check just for 
 is fine. But I'm also fine with a general 'deprecated API' check.
Alex, can you comment on this?


https://reviews.llvm.org/D42730



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


[PATCH] D41699: [OpenCL] Change sampler representation

2018-01-31 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In https://reviews.llvm.org/D41699#990894, @yaxunl wrote:

> whereas the old definition may fail to detect (not always, only for certain 
> combinations).


For this reason I think it would be good to fix this. I don't think it's good 
to report errors inconsistently

> 
> 
> 2. the new definition is less extendable. If new address mode is added, it is 
> easy for the old definition to maintain binary backward compatibility since 
> the old definition has room for new address mode. However for the new 
> definition, it is hard to maintain binary backward compatibility and a clean 
> definition at the same time. If the new bit is added at higher bits they are 
> going to be separated from the other bits for address mode.
> 
>   Probably we should seek opinions from more OpenCL platform/library 
> developers since this change could be disruptive for them.

Sure, let's hope some over developers can jump in. As for sampler modes I am 
not sure how much it is going to change in the future OpenCL versions. And as 
for binary compatibility I think this is a valid point, however it is solvable 
(by maintaining binary versions). I think we won't be able to do many 
interesting compiler refactoring tasks if we are to keep binary format 
unchanged It would be very pity to restrict us on that. Perhaps we should 
think of the solution to that overall long term.


https://reviews.llvm.org/D41699



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


[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Jens Massberg via Phabricator via cfe-commits
massberg marked 4 inline comments as done.
massberg added inline comments.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.h:19
+
+/// Check for several deprecated types and classes from  header
+///

massberg wrote:
> aaron.ballman wrote:
> > Missing full stop at the end of the sentence.
> > 
> > Why should this modernize check be limited to ``? Just like we 
> > have a "deprecated headers" check, perhaps this should be a "deprecated 
> > APIs" check?
> Added full stop.
> 
> I'm not sure if this check should be limited to  or be extended 
> to a full 'deprecated API' check.
> This change is just a start, several more types and classes which are removed 
> from  will follow, e.g:
> 
> - std::ptr_fun, std::mem_fun, std::mem_fun_ref
> - std::bind1st, std::bind2nd
> - std::unary_function, std::binary_function
> - std::pointer_to_unary_function, std::pointer_to_binary_function, 
> std::mem_fun_t, std::mem_fun1_t, std::const_mem_fun_t, 
> - std::const_mem_fun1_t, std::mem_fun_ref_t, std::mem_fun1_ref_t, 
> std::const_mem_fun_ref_t, std::const_mem_fun1_ref_t
> - std::binder1st, std::binder2nd
> 
> As these are a bunch of functions and types, in my eyes a check just for 
>  is fine. But I'm also fine with a general 'deprecated API' check.
> Alex, can you comment on this?
There are already other checks for functions which are removed in C++17 like 
modernize-replace-random-shuffle.
So I think having an separate check for functions and types removed from 
 would be OK.


https://reviews.llvm.org/D42730



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


[PATCH] D42693: [libcxx] Handle invalid escaped characters in POSIX regex

2018-01-31 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki added inline comments.



Comment at: include/regex:3465
+case '{':
+case '}':
+break;

Quuxplusone wrote:
> FWIW, I don't understand what's going on in this switch.
> Is it intentional that `'('` and `'|'` now take different paths here?
Yes. As far as I understand, only extended POSIX regular expressions support 
alternation: 
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html, so 
"\\|" should be treated as error_escape



https://reviews.llvm.org/D42693



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


[PATCH] D42573: [wip] The new threading implementation

2018-01-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/TUScheduler.cpp:220
+
+  GCThread.cleanupFile(std::move(Data->Worker));
 }

sammccall wrote:
> in the spirit of "just spawn a thread, and write direct code"...
> 
> can we just spawn a shared_ptr to do the work here, and replace 
> GCThread with a vector>.
> Then ~TUScheduler could just loop through:
> 
>   for (const auto &WeakThread : Cleanups)
> if (auto SharedThread = WeakThread.lock()) // thread may have died already
>   SharedThread->join();
> 
> might be simpler? You need to lock the Cleanups vector, but no fiddling with 
> CVs etc.
The problem is that stored vector will have unbounded growth, and I think it 
shouldn't. 
What we could do instead, though, is to have a counter that increments with 
each spawned request and wait for it to go down to 0 when TUScheduler dies. 
That should be simpler than what we have now and we have vectors that can grow 
indefinitely.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573



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


[PATCH] D42735: [clangd] Add a test URI scheme for lit tests to unbreak platform-specific URI failures.

2018-01-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Thanks for fixing this once and for all!




Comment at: clangd/ClangdLSPServer.cpp:23
+/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
+/// The path in a test URi will be combined with a platform-specific fake
+/// directory to form an absolute path. For example, test:///a.cpp is resolved

nit: URi -> URI



Comment at: clangd/ClangdLSPServer.cpp:28
+public:
+  static const char *Scheme;
+

nit: just inline this at the registry site? we shouldn't be using it elsewhere



Comment at: clangd/ClangdLSPServer.cpp:47
+llvm::SmallVector Path(Body.begin(), Body.end());
+auto Err = fs::make_absolute(TestDir, Path);
+assert(!Err);

on windows you're passing `C:\clangd-test` and `/foo.cpp` here.
I think you should probably call `native` on the body before passing it here 
(and no need to do it after)



Comment at: clangd/Protocol.cpp:36
+if (U->scheme() != "file" && U->scheme() != "test") {
+  log(Context::empty(), "Clangd only supports 'file' (and 'test' for lit "
+"tests) URI scheme for workspace files: " +

I'd suggest not mentioning 'test' in the log message, and just making this a 
comment.
If someone passes e.g. http://, mentioning test probably adds more confusion 
than it resolves.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42735



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


[PATCH] D41318: Start setting dso_local in clang

2018-01-31 Thread Sean Fertile via Phabricator via cfe-commits
sfertile added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:750
+  // If we can use a plt entry as the symbol address we can assume it
+  // is local.
+  if (isa(D) && !CGOpts.NoPLT)

I don't think this is the case. I think this would break ppc, where we need to 
restore the toc pointer after the plt stubs returns to the original call site.


https://reviews.llvm.org/D41318



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


[PATCH] D42099: [libclang] Add missing CINDEX_LINKAGE

2018-01-31 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik abandoned this revision.
nik added a comment.

Abandoning since the change is already in.


Repository:
  rC Clang

https://reviews.llvm.org/D42099



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


[PATCH] D42573: [wip] The new threading implementation

2018-01-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/TUScheduler.h:63
+  Context Ctx, ParseInputs Inputs,
+  UniqueFunction>)>
+  OnUpdated);

sammccall wrote:
> do we want to move the callback to be a clangd-global thing, rather than a 
> per-update thing, before this patch or later?
> 
> (And will that change be mirrored here, or will FileASTThread::update still 
> take a callback?)
I think we're fine both ways.
Those changes are pretty much independent of the other parts of the code. 
I'd personally first finish this patch and remove the callback afterwards. But 
I could also later update the patch to have the new callback semantics if you 
beat me to it.



Comment at: clangd/TUScheduler.h:70
+  mutable std::mutex Mutex;
+  bool Done;
+  std::condition_variable RequestsCV;

sammccall wrote:
> (no action required, just random thoughts)
> 
> one day we should really get the threading annotations 
> (REQUIRES_EXCLUSIVE_LOCK etc macros) set up in LLVM - they're *implemented* 
> in llvm for crying out loud...
Yeah, they're certainly great. The sole reason we don't have them enabled is 
because LLVM does not use threading that much?



Comment at: clangd/TUScheduler.h:72
+  std::condition_variable RequestsCV;
+  RequestQueue Requests;
+  std::shared_ptr File;

sammccall wrote:
> Having trouble seeing which parts of this are really used.
> My understanding is that the ThreadPool+Queue abstraction is going away.
> This means this is a deque + lock + ... a "done" state of some kind? Is more 
> of it still live?
> 
> I'd probably expect the 'done' state to be redundant with the one here... If 
> it's just a deque + a lock, I'd lean towards making it really thin, maybe 
> even a plain struct, and putting it in this file.
> 
> But not sure of your thoughts here.
I'll probably remove `RequestsQueue` or turn it into something really simple 
like you suggest.
It certainly has more state than we need with this patch. This is one of the 
reasons this patch is far from being ready.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573



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


[PATCH] D42729: clang-format: Fix formatting of function body followed by semicolon

2018-01-31 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added a comment.

I don't think cases where there is only a semicolon-less macro are particularly 
frequent/important either. You probably could even add a semicolon in those 
cases, right? How frequent are such cases in your codebase? Either way, they 
aren't fixed by this patch, so they aren't a good reason to move forward with 
it.

I still believe that this patch adds complexity for very little gain. And I am 
not even sure it is correct. isFunctionDeclarationName/getFunctionParameterList 
is just yet another heuristic that might go wrong. And it might go wrong in 
both ways. You might still miss some cases and you might start incorrectly 
formatting stuff as functions. Fundamentally clang-format just doesn't have 
enough info to do this correctly.

In https://reviews.llvm.org/D42729#993188, @Typz wrote:

> In https://reviews.llvm.org/D42729#993159, @djasper wrote:
>
> > I think this case is not important enough to fix. Please tell users to just 
> > delete the useless semicolon.
>
>
> I would agree if were simple to spot: but often this may manifest itself only 
> with a missing space between the function parameters and the function body, 
> which can easily be overlooked...


".. which can easily be overlooked". If they are overlooked, nobody cares about 
the space either, so no harm done ;).

> Another option may be to create new pass which "removes" that extra 
> semicolon: this way we would both fix it and get things right on next pass.

I am not sure we can do this reliably enough.

> However, the issue with a function which contains only a macro and which is 
> followed by another function which returns an custom type cannot so easily be 
> fixed:
> 
>   void abort() {
> FOO()
>   }
>   uint32_t bar() {}
> 
> 
> (note that this case works fine if the body of the function contains a 
> semicolon or reserved keyword, or if the next function returns a base type 
> [int, void...])


Repository:
  rC Clang

https://reviews.llvm.org/D42729



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


[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.h:19
+
+/// Check for several deprecated types and classes from  header
+///

massberg wrote:
> massberg wrote:
> > aaron.ballman wrote:
> > > Missing full stop at the end of the sentence.
> > > 
> > > Why should this modernize check be limited to ``? Just like 
> > > we have a "deprecated headers" check, perhaps this should be a 
> > > "deprecated APIs" check?
> > Added full stop.
> > 
> > I'm not sure if this check should be limited to  or be extended 
> > to a full 'deprecated API' check.
> > This change is just a start, several more types and classes which are 
> > removed from  will follow, e.g:
> > 
> > - std::ptr_fun, std::mem_fun, std::mem_fun_ref
> > - std::bind1st, std::bind2nd
> > - std::unary_function, std::binary_function
> > - std::pointer_to_unary_function, std::pointer_to_binary_function, 
> > std::mem_fun_t, std::mem_fun1_t, std::const_mem_fun_t, 
> > - std::const_mem_fun1_t, std::mem_fun_ref_t, std::mem_fun1_ref_t, 
> > std::const_mem_fun_ref_t, std::const_mem_fun1_ref_t
> > - std::binder1st, std::binder2nd
> > 
> > As these are a bunch of functions and types, in my eyes a check just for 
> >  is fine. But I'm also fine with a general 'deprecated API' 
> > check.
> > Alex, can you comment on this?
> There are already other checks for functions which are removed in C++17 like 
> modernize-replace-random-shuffle.
> So I think having an separate check for functions and types removed from 
>  would be OK.
You've hit the nail on the head for what I'm trying to avoid -- we shouldn't 
have multiple checks unless they do drastically different things. Having a 
deprecated check like this really only makes sense for APIs that are deprecated 
but aren't uniformly marked as `[[deprecated]]` by the library. As such, I 
think we really only need one check for this rather than splitting it out over 
multiple checks -- the existing check functionality could be rolled into this 
one and its check become an alias.


https://reviews.llvm.org/D42730



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


[clang-tools-extra] r323885 - [clangd] Add a test URI scheme for lit tests to unbreak platform-specific URI failures.

2018-01-31 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Wed Jan 31 08:26:27 2018
New Revision: 323885

URL: http://llvm.org/viewvc/llvm-project?rev=323885&view=rev
Log:
[clangd] Add a test URI scheme for lit tests to unbreak platform-specific URI 
failures.

Summary:
This should also fix the current windows buildbot breakage
(http://lab.llvm.org:8011/builders/clang-x86-windows-msvc2015/builds/9838/steps/ninja%20check%201/logs/stdio)

Reviewers: sammccall

Subscribers: klimek, ilya-biryukov, jkorous-apple, cfe-commits

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

Added:
clang-tools-extra/trunk/test/clangd/test-uri-posix.test
clang-tools-extra/trunk/test/clangd/test-uri-windows.test
Removed:
clang-tools-extra/trunk/test/clangd/authority-less-uri.test
Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/test/clangd/completion.test
clang-tools-extra/trunk/test/clangd/diagnostics.test
clang-tools-extra/trunk/test/clangd/execute-command.test
clang-tools-extra/trunk/test/clangd/extra-flags.test
clang-tools-extra/trunk/test/clangd/fixits.test
clang-tools-extra/trunk/test/clangd/formatting.test
clang-tools-extra/trunk/test/clangd/input-mirror.test
clang-tools-extra/trunk/test/clangd/protocol.test
clang-tools-extra/trunk/test/clangd/rename.test
clang-tools-extra/trunk/test/clangd/signature-help.test
clang-tools-extra/trunk/test/clangd/trace.test
clang-tools-extra/trunk/test/clangd/unsupported-method.test
clang-tools-extra/trunk/test/clangd/xrefs.test

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=323885&r1=323884&r2=323885&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Wed Jan 31 08:26:27 2018
@@ -12,12 +12,51 @@
 #include "SourceCode.h"
 #include "URI.h"
 #include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/Path.h"
 
 using namespace clang::clangd;
 using namespace clang;
 
 namespace {
 
+/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
+/// The path in a test URI will be combined with a platform-specific fake
+/// directory to form an absolute path. For example, test:///a.cpp is resolved
+/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
+class TestScheme : public URIScheme {
+public:
+  llvm::Expected
+  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+  llvm::StringRef /*HintPath*/) const override {
+using namespace llvm::sys;
+// Still require "/" in body to mimic file scheme, as we want lengths of an
+// equivalent URI in both schemes to be the same.
+if (!Body.startswith("/"))
+  return llvm::make_error(
+  "Expect URI body to be an absolute path starting with '/': " + Body,
+  llvm::inconvertibleErrorCode());
+Body = Body.ltrim('/');
+#ifdef LLVM_ON_WIN32
+constexpr char TestDir[] = "C:\\clangd-test";
+#else
+constexpr char TestDir[] = "/clangd-test";
+#endif
+llvm::SmallVector Path(Body.begin(), Body.end());
+path::native(Path);
+auto Err = fs::make_absolute(TestDir, Path);
+assert(!Err);
+return std::string(Path.begin(), Path.end());
+  }
+
+  llvm::Expected
+  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+llvm_unreachable("Clangd must never create a test URI.");
+  }
+};
+
+static URISchemeRegistry::Add
+X("test", "Test scheme for clangd lit tests.");
+
 TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R) {
   Range ReplacementRange = {
   offsetToPosition(Code, R.getOffset()),

Modified: clang-tools-extra/trunk/clangd/Protocol.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.cpp?rev=323885&r1=323884&r2=323885&view=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.cpp (original)
+++ clang-tools-extra/trunk/clangd/Protocol.cpp Wed Jan 31 08:26:27 2018
@@ -31,7 +31,7 @@ bool fromJSON(const json::Expr &E, URIFo
   log("Failed to parse URI " + *S + ": " + llvm::toString(U.takeError()));
   return false;
 }
-if (U->scheme() != "file") {
+if (U->scheme() != "file" && U->scheme() != "test") {
   log("Clangd only supports 'file' URI scheme for workspace files: " + *S);
   return false;
 }

Removed: clang-tools-extra/trunk/test/clangd/authority-less-uri.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/authority-less-uri.test?rev=323884&view=auto
==
--- clang-tools-extra/trunk/test/clangd/authority-less-uri.test (original)
+++ clang-tools-extra/trunk/test

[PATCH] D42735: [clangd] Add a test URI scheme for lit tests to unbreak platform-specific URI failures.

2018-01-31 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 132180.
ioeric marked 4 inline comments as done.
ioeric added a comment.

- Addressed review comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42735

Files:
  clangd/ClangdLSPServer.cpp
  clangd/Protocol.cpp
  test/clangd/authority-less-uri.test
  test/clangd/completion.test
  test/clangd/diagnostics.test
  test/clangd/execute-command.test
  test/clangd/extra-flags.test
  test/clangd/fixits.test
  test/clangd/formatting.test
  test/clangd/input-mirror.test
  test/clangd/protocol.test
  test/clangd/rename.test
  test/clangd/signature-help.test
  test/clangd/test-uri-posix.test
  test/clangd/test-uri-windows.test
  test/clangd/trace.test
  test/clangd/unsupported-method.test
  test/clangd/xrefs.test

Index: test/clangd/xrefs.test
===
--- test/clangd/xrefs.test
+++ test/clangd/xrefs.test
@@ -7,11 +7,11 @@
 
 Content-Length: 165
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
 
 Content-Length: 148
 
-{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":8}}}
+{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
 #  CHECK:  "id": 1,
 # CHECK-NEXT:  "jsonrpc": "2.0",
 # CHECK-NEXT:  "result": [
@@ -26,12 +26,12 @@
 # CHECK-NEXT:  "line": 0
 # CHECK-NEXT:}
 # CHECK-NEXT:  },
-# CHECK-NEXT:  "uri": "file:///{{([A-Z]:/)?}}main.cpp"
+# CHECK-NEXT:  "uri": "file://{{.*}}/{{([A-Z]:/)?}}main.cpp"
 # CHECK-NEXT:}
 # CHECK-NEXT:  ]
 Content-Length: 155
 
-{"jsonrpc":"2.0","id":1,"method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":8}}}
+{"jsonrpc":"2.0","id":1,"method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
 #  CHECK: "id": 1
 # CHECK-NEXT: "jsonrpc": "2.0",
 # CHECK-NEXT: "result": [
Index: test/clangd/unsupported-method.test
===
--- test/clangd/unsupported-method.test
+++ test/clangd/unsupported-method.test
@@ -7,7 +7,7 @@
 
 Content-Length: 143
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":""}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":""}}}
 
 Content-Length: 92
 
Index: test/clangd/trace.test
===
--- test/clangd/trace.test
+++ test/clangd/trace.test
@@ -7,16 +7,16 @@
 #
 Content-Length: 152
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///foo.c","languageId":"c","version":1,"text":"void main() {}"}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.c","languageId":"c","version":1,"text":"void main() {}"}}}
 #  CHECK: {"displayTimeUnit":"ns","traceEvents":[
 # Start opening the doc.
 #  CHECK: "name": "textDocument/didOpen"
 #  CHECK: "ph": "B"
 # Start building the preamble.
 #  CHECK: "name": "Preamble"
 #  CHECK: },
 # Finish building the preamble, with filename.
-#  CHECK: "File": "/foo.c"
+#  CHECK: "File": "{{.*}}/foo.c"
 # CHECK-NEXT: },
 # CHECK-NEXT: "ph": "E"
 # Start building the file.
Index: test/clangd/test-uri-windows.test
===
--- /dev/null
+++ test/clangd/test-uri-windows.test
@@ -0,0 +1,19 @@
+# RUN: clangd -pretty -run-synchronously < %s | FileCheck -strict-whitespace %s
+# REQUIRES: mingw32 || win32
+# It is absolutely vital that this file has CRLF line endings.
+#
+# Test authority-less URI
+Content-Length: 125
+
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+#
+Content-Length: 152
+
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.c","languageId":"c","version":1,"text":"void main() {}"}}}
+# CHECK:"uri": "file:///C:/clangd-test/foo.c"
+Content-Length: 44
+
+{"jsonrpc":"2.0","id":5,"method":"shutdown"}
+Content-Length: 33
+
+{"jsonrpc":"2.0","method":"exit"}
Index: test/clangd/test-uri-posix.test
===
--- /dev/null
+++ test/clangd/test-uri-posix.test
@@ -0,0 +1,19 @@
+# RUN: clangd -pretty -run-synchronously < %s | FileCheck -stri

[PATCH] D42735: [clangd] Add a test URI scheme for lit tests to unbreak platform-specific URI failures.

2018-01-31 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE323885: [clangd] Add a test URI scheme for lit tests to 
unbreak platform-specific URI… (authored by ioeric, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42735?vs=132180&id=132181#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42735

Files:
  clangd/ClangdLSPServer.cpp
  clangd/Protocol.cpp
  test/clangd/authority-less-uri.test
  test/clangd/completion.test
  test/clangd/diagnostics.test
  test/clangd/execute-command.test
  test/clangd/extra-flags.test
  test/clangd/fixits.test
  test/clangd/formatting.test
  test/clangd/input-mirror.test
  test/clangd/protocol.test
  test/clangd/rename.test
  test/clangd/signature-help.test
  test/clangd/test-uri-posix.test
  test/clangd/test-uri-windows.test
  test/clangd/trace.test
  test/clangd/unsupported-method.test
  test/clangd/xrefs.test

Index: test/clangd/protocol.test
===
--- test/clangd/protocol.test
+++ test/clangd/protocol.test
@@ -17,16 +17,16 @@
 #  CHECK:  }
 Content-Length: 246
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"struct fake { int a, bb, ccc; int f(int i, const float f) const; };\nint main() {\n  fake f;\n  f.\n}\n"}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":"struct fake { int a, bb, ccc; int f(int i, const float f) const; };\nint main() {\n  fake f;\n  f.\n}\n"}}}
 
 Content-Length: 104
 
-{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"file:///main.cpp"}}}
+{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"test:///main.cpp"}}}
 
 Content-Type: application/vscode-jsonrpc; charset-utf-8
 Content-Length: 146
 
-{"jsonrpc":"2.0","id":1,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:/main.cpp"},"position":{"line":3,"character":5}}}
+{"jsonrpc":"2.0","id":1,"method":"textDocument/completion","params":{"textDocument":{"uri":"test:/main.cpp"},"position":{"line":3,"character":5}}}
 # Test message with Content-Type before Content-Length
 #
 #  CHECK:  "id": 1,
@@ -49,13 +49,13 @@
 Content-Type: application/vscode-jsonrpc; charset-utf-8
 X-Testing: Test
 
-{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:/main.cpp"},"position":{"line":3,"character":5}}}
+{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{"textDocument":{"uri":"test:/main.cpp"},"position":{"line":3,"character":5}}}
 
 Content-Type: application/vscode-jsonrpc; charset-utf-8
 Content-Length: 10
 Content-Length: 146
 
-{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:/main.cpp"},"position":{"line":3,"character":5}}}
+{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{"textDocument":{"uri":"test:/main.cpp"},"position":{"line":3,"character":5}}}
 # Test message with duplicate Content-Length headers
 #
 #  CHECK:  "id": 3,
@@ -76,15 +76,15 @@
 Content-Type: application/vscode-jsonrpc; charset-utf-8
 Content-Length: 10
 
-{"jsonrpc":"2.0","id":4,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:/main.cpp"},"position":{"line":3,"character":5}}}
+{"jsonrpc":"2.0","id":4,"method":"textDocument/completion","params":{"textDocument":{"uri":"test:/main.cpp"},"position":{"line":3,"character":5}}}
 # Test message with malformed Content-Length
 #
 # STDERR: JSON parse error
 # Ensure we recover by sending another (valid) message
 
 Content-Length: 146
 
-{"jsonrpc":"2.0","id":5,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:/main.cpp"},"position":{"line":3,"character":5}}}
+{"jsonrpc":"2.0","id":5,"method":"textDocument/completion","params":{"textDocument":{"uri":"test:/main.cpp"},"position":{"line":3,"character":5}}}
 # Test message with Content-Type before Content-Length
 #
 #  CHECK:  "id": 5,
@@ -102,7 +102,7 @@
 # CHECK-NEXT:  }
 Content-Length: 1024
 
-{"jsonrpc":"2.0","id":5,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:/main.cpp"},"position":{"line":3,"character":5}}}
+{"jsonrpc":"2.0","id":5,"method":"textDocument/completion","params":{"textDocument":{"uri":"test:/main.cpp"},"position":{"line":3,"character":5}}}
 # Test message which reads beyond the end of the stream.
 #
 # Ensure this is the last test in the file!
Index: test/clangd/trace.test
===
--- test/clangd/trace.test
+++ test/clangd/trace.test
@@ -7,16 +7,16 @@
 #
 Content-Length: 152
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///foo.c","languageId":"c","version":1,"text":"void main() {}"}}}
+{"jsonrpc":"2.0","method":"t

[PATCH] D42735: [clangd] Add a test URI scheme for lit tests to unbreak platform-specific URI failures.

2018-01-31 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323885: [clangd] Add a test URI scheme for lit tests to 
unbreak platform-specific URI… (authored by ioeric, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42735

Files:
  clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
  clang-tools-extra/trunk/clangd/Protocol.cpp
  clang-tools-extra/trunk/test/clangd/authority-less-uri.test
  clang-tools-extra/trunk/test/clangd/completion.test
  clang-tools-extra/trunk/test/clangd/diagnostics.test
  clang-tools-extra/trunk/test/clangd/execute-command.test
  clang-tools-extra/trunk/test/clangd/extra-flags.test
  clang-tools-extra/trunk/test/clangd/fixits.test
  clang-tools-extra/trunk/test/clangd/formatting.test
  clang-tools-extra/trunk/test/clangd/input-mirror.test
  clang-tools-extra/trunk/test/clangd/protocol.test
  clang-tools-extra/trunk/test/clangd/rename.test
  clang-tools-extra/trunk/test/clangd/signature-help.test
  clang-tools-extra/trunk/test/clangd/test-uri-posix.test
  clang-tools-extra/trunk/test/clangd/test-uri-windows.test
  clang-tools-extra/trunk/test/clangd/trace.test
  clang-tools-extra/trunk/test/clangd/unsupported-method.test
  clang-tools-extra/trunk/test/clangd/xrefs.test

Index: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
@@ -12,12 +12,51 @@
 #include "SourceCode.h"
 #include "URI.h"
 #include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/Path.h"
 
 using namespace clang::clangd;
 using namespace clang;
 
 namespace {
 
+/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
+/// The path in a test URI will be combined with a platform-specific fake
+/// directory to form an absolute path. For example, test:///a.cpp is resolved
+/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
+class TestScheme : public URIScheme {
+public:
+  llvm::Expected
+  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+  llvm::StringRef /*HintPath*/) const override {
+using namespace llvm::sys;
+// Still require "/" in body to mimic file scheme, as we want lengths of an
+// equivalent URI in both schemes to be the same.
+if (!Body.startswith("/"))
+  return llvm::make_error(
+  "Expect URI body to be an absolute path starting with '/': " + Body,
+  llvm::inconvertibleErrorCode());
+Body = Body.ltrim('/');
+#ifdef LLVM_ON_WIN32
+constexpr char TestDir[] = "C:\\clangd-test";
+#else
+constexpr char TestDir[] = "/clangd-test";
+#endif
+llvm::SmallVector Path(Body.begin(), Body.end());
+path::native(Path);
+auto Err = fs::make_absolute(TestDir, Path);
+assert(!Err);
+return std::string(Path.begin(), Path.end());
+  }
+
+  llvm::Expected
+  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+llvm_unreachable("Clangd must never create a test URI.");
+  }
+};
+
+static URISchemeRegistry::Add
+X("test", "Test scheme for clangd lit tests.");
+
 TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R) {
   Range ReplacementRange = {
   offsetToPosition(Code, R.getOffset()),
Index: clang-tools-extra/trunk/clangd/Protocol.cpp
===
--- clang-tools-extra/trunk/clangd/Protocol.cpp
+++ clang-tools-extra/trunk/clangd/Protocol.cpp
@@ -31,7 +31,7 @@
   log("Failed to parse URI " + *S + ": " + llvm::toString(U.takeError()));
   return false;
 }
-if (U->scheme() != "file") {
+if (U->scheme() != "file" && U->scheme() != "test") {
   log("Clangd only supports 'file' URI scheme for workspace files: " + *S);
   return false;
 }
Index: clang-tools-extra/trunk/test/clangd/xrefs.test
===
--- clang-tools-extra/trunk/test/clangd/xrefs.test
+++ clang-tools-extra/trunk/test/clangd/xrefs.test
@@ -7,11 +7,11 @@
 
 Content-Length: 165
 
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
 
 Content-Length: 148
 
-{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":8}}}
+{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
 #  CHECK:  "id": 1,
 # CHECK-NEXT:  "jsonrpc": "2.0",
 # CHECK-NEXT:  "result": [
@@ -26,12 +26,12 @@
 # CHECK-NEXT:  "line": 0

[PATCH] D42742: [clangd] Use pthread instead of thread_local to support more runtimes.

2018-01-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: ilya-biryukov, bkramer.
Herald added subscribers: cfe-commits, ioeric, jkorous-apple, klimek.

thread_local has nice syntax and semantics, but requires __cxa_thread_atexit,
and some not-ancient runtime libraries don't provide it.
The clang-x86_64-linux-selfhost-modules buildbot is one example :-)

It works on windows, and the other platforms clang-tools-extra supports should
all have the relevant pthread API. So we just use that if it's available,
falling back to thread_local (so if a platform has neither, we'll fail to link).

The fallback should really be the other way, that would require cmake changes.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42742

Files:
  clangd/Context.cpp


Index: clangd/Context.cpp
===
--- clangd/Context.cpp
+++ clangd/Context.cpp
@@ -8,8 +8,48 @@
 //===-===//
 
 #include "Context.h"
+#include "llvm/Config/config.h"
 #include 
 
+// The thread-local Context is scoped in a function to avoid init-order issues.
+// It's created by currentContext() when first needed.
+
+#ifdef HAVE_PTHREAD_GETSPECIFIC
+// We'd love to use thread_local everywhere.
+// It requires support from the runtime: __cxa_thread_atexit.
+// Rather than detect this, we use the pthread API where available.
+#include 
+static clang::clangd::Context ¤tContext() {
+  using clang::clangd::Context;
+  static pthread_key_t CtxKey;
+
+  // Once (across threads), set up pthread TLS for Context, and its destructor.
+  static int Dummy = [] { // Create key only once, for all threads.
+if (auto Err = pthread_key_create(&CtxKey, /*destructor=*/+[](void *Ctx) {
+  delete reinterpret_cast(Ctx);
+}))
+  llvm_unreachable(strerror(Err));
+return 0;
+  }();
+  (void)Dummy;
+
+  // Now grab the current context from TLS, and create it if it doesn't exist.
+  void *Ctx = pthread_getspecific(CtxKey);
+  if (!Ctx) {
+Ctx = new Context();
+if (auto Err = pthread_setspecific(CtxKey, Ctx))
+  llvm_unreachable(strerror(Err));
+  }
+  return *reinterpret_cast(Ctx);
+}
+#else
+// Only supported platform without pthread is windows, and thread_local works.
+static clang::clangd::Context ¤tContext() {
+  static thread_local auto C = clang::clangd::Context::empty();
+  return C;
+}
+#endif
+
 namespace clang {
 namespace clangd {
 
@@ -20,13 +60,6 @@
 
 Context Context::clone() const { return Context(DataPtr); }
 
-// The thread-local Context is scoped in a function to avoid
-// initialization-order issues. It's created when first needed.
-static Context ¤tContext() {
-  static thread_local Context C = Context::empty();
-  return C;
-}
-
 const Context &Context::current() { return currentContext(); }
 
 Context Context::swapCurrent(Context Replacement) {


Index: clangd/Context.cpp
===
--- clangd/Context.cpp
+++ clangd/Context.cpp
@@ -8,8 +8,48 @@
 //===-===//
 
 #include "Context.h"
+#include "llvm/Config/config.h"
 #include 
 
+// The thread-local Context is scoped in a function to avoid init-order issues.
+// It's created by currentContext() when first needed.
+
+#ifdef HAVE_PTHREAD_GETSPECIFIC
+// We'd love to use thread_local everywhere.
+// It requires support from the runtime: __cxa_thread_atexit.
+// Rather than detect this, we use the pthread API where available.
+#include 
+static clang::clangd::Context ¤tContext() {
+  using clang::clangd::Context;
+  static pthread_key_t CtxKey;
+
+  // Once (across threads), set up pthread TLS for Context, and its destructor.
+  static int Dummy = [] { // Create key only once, for all threads.
+if (auto Err = pthread_key_create(&CtxKey, /*destructor=*/+[](void *Ctx) {
+  delete reinterpret_cast(Ctx);
+}))
+  llvm_unreachable(strerror(Err));
+return 0;
+  }();
+  (void)Dummy;
+
+  // Now grab the current context from TLS, and create it if it doesn't exist.
+  void *Ctx = pthread_getspecific(CtxKey);
+  if (!Ctx) {
+Ctx = new Context();
+if (auto Err = pthread_setspecific(CtxKey, Ctx))
+  llvm_unreachable(strerror(Err));
+  }
+  return *reinterpret_cast(Ctx);
+}
+#else
+// Only supported platform without pthread is windows, and thread_local works.
+static clang::clangd::Context ¤tContext() {
+  static thread_local auto C = clang::clangd::Context::empty();
+  return C;
+}
+#endif
+
 namespace clang {
 namespace clangd {
 
@@ -20,13 +60,6 @@
 
 Context Context::clone() const { return Context(DataPtr); }
 
-// The thread-local Context is scoped in a function to avoid
-// initialization-order issues. It's created when first needed.
-static Context ¤tContext() {
-  static thread_local Context C = Context::empty();
-  return C;
-}
-
 const Context &Context::current() { return currentConte

[PATCH] D42708: [clang-format] Set BinPackObjCProtocolList to Never for google style

2018-01-31 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 132185.
benhamilton added a comment.

Move to general property section


Repository:
  rC Clang

https://reviews.llvm.org/D42708

Files:
  lib/Format/Format.cpp
  unittests/Format/FormatTestObjC.cpp


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -322,13 +322,16 @@
   verifyFormat("@interface Foo (HackStuff) \n"
"+ (id)init;\n"
"@end");
-  Style.BinPackParameters = false;
-  Style.ColumnLimit = 80;
-  verifyFormat("@interface a () <\n"
-   "a,\n"
-   ",\n"
-   "aa,\n"
-   "> {\n"
+  Style.ColumnLimit = 40;
+  // BinPackParameters should be true by default.
+  verifyFormat("void (int e, int e,\n"
+   "  int e, int e);\n");
+  // BinPackObjCProtocolList should be BPS_Never by default.
+  verifyFormat("@interface f () <\n"
+   "f,\n"
+   "f,\n"
+   "f,\n"
+   "f> {\n"
"}");
 }
 
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -703,6 +703,7 @@
   GoogleStyle.AllowShortLoopsOnASingleLine = true;
   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
+  GoogleStyle.BinPackObjCProtocolList = FormatStyle::BPS_Never;
   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
   GoogleStyle.DerivePointerAlignment = true;
   GoogleStyle.IncludeCategories = {


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -322,13 +322,16 @@
   verifyFormat("@interface Foo (HackStuff) \n"
"+ (id)init;\n"
"@end");
-  Style.BinPackParameters = false;
-  Style.ColumnLimit = 80;
-  verifyFormat("@interface a () <\n"
-   "a,\n"
-   ",\n"
-   "aa,\n"
-   "> {\n"
+  Style.ColumnLimit = 40;
+  // BinPackParameters should be true by default.
+  verifyFormat("void (int e, int e,\n"
+   "  int e, int e);\n");
+  // BinPackObjCProtocolList should be BPS_Never by default.
+  verifyFormat("@interface f () <\n"
+   "f,\n"
+   "f,\n"
+   "f,\n"
+   "f> {\n"
"}");
 }
 
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -703,6 +703,7 @@
   GoogleStyle.AllowShortLoopsOnASingleLine = true;
   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
   GoogleStyle.AlwaysBreakTemplateDeclarations = true;
+  GoogleStyle.BinPackObjCProtocolList = FormatStyle::BPS_Never;
   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
   GoogleStyle.DerivePointerAlignment = true;
   GoogleStyle.IncludeCategories = {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42708: [clang-format] Set BinPackObjCProtocolList to Never for google style

2018-01-31 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton marked an inline comment as done.
benhamilton added inline comments.



Comment at: lib/Format/Format.cpp:765
 GoogleStyle.ColumnLimit = 100;
+GoogleStyle.BinPackObjCProtocolList = FormatStyle::BPS_Never;
   }

jolesiak wrote:
> If I understand correctly this is meant to be ObjC-specific flag. I feel like 
> this should be put in general config (next to 
> GoogleStyle.ObjcSpaceAfterProperty and 
> GoogleStyle.ObjCSpaceBeforeProtocolList; ~50 lines above).
> To me putting it inside 'if' check means different value is used for ObjC 
> than for other languages (what isn't the case here, as this flag shouldn't be 
> used in formatting other languages code). 
Done. It looked like all the modifications were alphabetized, so I moved it 
between `GoogleStyle.AlwaysBreakTemplateDeclarations` and 
`GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine`.


Repository:
  rC Clang

https://reviews.llvm.org/D42708



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


[PATCH] D42650: [clang-format] New format param ObjCBinPackProtocolList

2018-01-31 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 132187.
benhamilton marked 2 inline comments as done.
benhamilton added a comment.

- BinPackObjCProtocolList -> ObjCBinPackProtocolList


Repository:
  rC Clang

https://reviews.llvm.org/D42650

Files:
  include/clang/Format/Format.h
  lib/Format/ContinuationIndenter.cpp
  lib/Format/Format.cpp
  unittests/Format/FormatTestObjC.cpp

Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -281,15 +281,28 @@
"c, c,\n"
"c, c> {\n"
"}");
-
-  Style.BinPackParameters = false;
+  Style.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
   verifyFormat("@interface d () <\n"
"d,\n"
"d,\n"
"d,\n"
"d> {\n"
"}");
 
+  Style.BinPackParameters = false;
+  Style.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
+  verifyFormat("@interface e () <\n"
+   "e,\n"
+   "e,\n"
+   "e,\n"
+   "e> {\n"
+   "}");
+  Style.ObjCBinPackProtocolList = FormatStyle::BPS_Always;
+  verifyFormat("@interface f () <\n"
+   "f, f,\n"
+   "f, f> {\n"
+   "}");
+
   Style = getGoogleStyle(FormatStyle::LK_ObjC);
   verifyFormat("@interface Foo : NSObject  {\n"
" @public\n"
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -105,6 +105,14 @@
   }
 };
 
+template <> struct ScalarEnumerationTraits {
+  static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
+IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
+IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
+IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
+  }
+};
+
 template <> struct ScalarEnumerationTraits {
   static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
 IO.enumCase(Value, "All", FormatStyle::BOS_All);
@@ -378,6 +386,7 @@
 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
+IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
 IO.mapOptional("ObjCSpaceBeforeProtocolList",
@@ -637,6 +646,7 @@
   LLVMStyle.MaxEmptyLinesToKeep = 1;
   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
+  LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
   LLVMStyle.ObjCBlockIndentWidth = 2;
   LLVMStyle.ObjCSpaceAfterProperty = false;
   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1222,9 +1222,20 @@
 Current.MatchingParen->getPreviousNonComment() &&
 Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
 
+// If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
+// for backwards compatibility.
+bool ObjCBinPackProtocolList =
+(Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
+ Style.BinPackParameters) ||
+Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
+
+bool BinPackDeclaration =
+(State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
+(State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
+
 AvoidBinPacking =
 (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
-(State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
+(State.Line->MustBeDeclaration && !BinPackDeclaration) ||
 (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
 (Style.ExperimentalAutoDetectBinPacking &&
  (Current.PackingKind == PPK_OnePerLine ||
Index: include/clang/Format/Format.h
===
--- include/clang/Format/Format.h
+++ include/clang/Format/Format.h
@@ -390,6 +390,17 @@
   /// \endcode
   bool BinPackParameters;
 
+  /// \brief The style of wrapping parameters on the same line (bin-packed) or
+  /// on one line each.
+  enum BinPackStyle {
+/// Automatically determine parameter bin-packing behavior.
+BPS_Auto,
+/// 

[PATCH] D42708: [clang-format] Set ObjCBinPackProtocolList to Never for google style

2018-01-31 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added inline comments.



Comment at: lib/Format/Format.cpp:765
 GoogleStyle.ColumnLimit = 100;
+GoogleStyle.BinPackObjCProtocolList = FormatStyle::BPS_Never;
   }

benhamilton wrote:
> jolesiak wrote:
> > If I understand correctly this is meant to be ObjC-specific flag. I feel 
> > like this should be put in general config (next to 
> > GoogleStyle.ObjcSpaceAfterProperty and 
> > GoogleStyle.ObjCSpaceBeforeProtocolList; ~50 lines above).
> > To me putting it inside 'if' check means different value is used for ObjC 
> > than for other languages (what isn't the case here, as this flag shouldn't 
> > be used in formatting other languages code). 
> Done. It looked like all the modifications were alphabetized, so I moved it 
> between `GoogleStyle.AlwaysBreakTemplateDeclarations` and 
> `GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine`.
Actually, on second thought, I've just renamed it to `ObjCBinPackProtocolList`.


Repository:
  rC Clang

https://reviews.llvm.org/D42708



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


[PATCH] D42708: [clang-format] Set ObjCBinPackProtocolList to Never for google style

2018-01-31 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 132188.
benhamilton marked an inline comment as done.
benhamilton added a comment.

- BinPackObjCProtocolList -> ObjCBinPackProtocolList


Repository:
  rC Clang

https://reviews.llvm.org/D42708

Files:
  lib/Format/Format.cpp
  unittests/Format/FormatTestObjC.cpp


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -322,13 +322,16 @@
   verifyFormat("@interface Foo (HackStuff) \n"
"+ (id)init;\n"
"@end");
-  Style.BinPackParameters = false;
-  Style.ColumnLimit = 80;
-  verifyFormat("@interface a () <\n"
-   "a,\n"
-   ",\n"
-   "aa,\n"
-   "> {\n"
+  Style.ColumnLimit = 40;
+  // BinPackParameters should be true by default.
+  verifyFormat("void (int e, int e,\n"
+   "  int e, int e);\n");
+  // BinPackObjCProtocolList should be BPS_Never by default.
+  verifyFormat("@interface f () <\n"
+   "f,\n"
+   "f,\n"
+   "f,\n"
+   "f> {\n"
"}");
 }
 
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -710,6 +710,7 @@
   GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
   GoogleStyle.IndentCaseLabels = true;
   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
+  GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
   GoogleStyle.ObjCSpaceAfterProperty = false;
   GoogleStyle.ObjCSpaceBeforeProtocolList = true;
   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -322,13 +322,16 @@
   verifyFormat("@interface Foo (HackStuff) \n"
"+ (id)init;\n"
"@end");
-  Style.BinPackParameters = false;
-  Style.ColumnLimit = 80;
-  verifyFormat("@interface a () <\n"
-   "a,\n"
-   ",\n"
-   "aa,\n"
-   "> {\n"
+  Style.ColumnLimit = 40;
+  // BinPackParameters should be true by default.
+  verifyFormat("void (int e, int e,\n"
+   "  int e, int e);\n");
+  // BinPackObjCProtocolList should be BPS_Never by default.
+  verifyFormat("@interface f () <\n"
+   "f,\n"
+   "f,\n"
+   "f,\n"
+   "f> {\n"
"}");
 }
 
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -710,6 +710,7 @@
   GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
   GoogleStyle.IndentCaseLabels = true;
   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
+  GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
   GoogleStyle.ObjCSpaceAfterProperty = false;
   GoogleStyle.ObjCSpaceBeforeProtocolList = true;
   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37831: [WebAssembly] Don't pass -ffunction-section/-fdata-sections

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

In https://reviews.llvm.org/D37831#871238, @dschuff wrote:

> I think the reasoning was really just that code size reduction is even more 
> important on wasm than other platforms, and because it's a new ABI there's no 
> one depending on the default behavior that would break.


I agree. Also, on some platforms, -ffunction-sections and -fdata-sections can 
result in less efficient code, however that's not the case on wasm.


Repository:
  rC Clang

https://reviews.llvm.org/D37831



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


[PATCH] D42708: [clang-format] Set ObjCBinPackProtocolList to Never for google style

2018-01-31 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 132189.
benhamilton added a comment.

Fix comment.


Repository:
  rC Clang

https://reviews.llvm.org/D42708

Files:
  lib/Format/Format.cpp
  unittests/Format/FormatTestObjC.cpp


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -322,13 +322,16 @@
   verifyFormat("@interface Foo (HackStuff) \n"
"+ (id)init;\n"
"@end");
-  Style.BinPackParameters = false;
-  Style.ColumnLimit = 80;
-  verifyFormat("@interface a () <\n"
-   "a,\n"
-   ",\n"
-   "aa,\n"
-   "> {\n"
+  Style.ColumnLimit = 40;
+  // BinPackParameters should be true by default.
+  verifyFormat("void (int e, int e,\n"
+   "  int e, int e);\n");
+  // ObjCBinPackProtocolList should be BPS_Never by default.
+  verifyFormat("@interface f () <\n"
+   "f,\n"
+   "f,\n"
+   "f,\n"
+   "f> {\n"
"}");
 }
 
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -710,6 +710,7 @@
   GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
   GoogleStyle.IndentCaseLabels = true;
   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
+  GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
   GoogleStyle.ObjCSpaceAfterProperty = false;
   GoogleStyle.ObjCSpaceBeforeProtocolList = true;
   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -322,13 +322,16 @@
   verifyFormat("@interface Foo (HackStuff) \n"
"+ (id)init;\n"
"@end");
-  Style.BinPackParameters = false;
-  Style.ColumnLimit = 80;
-  verifyFormat("@interface a () <\n"
-   "a,\n"
-   ",\n"
-   "aa,\n"
-   "> {\n"
+  Style.ColumnLimit = 40;
+  // BinPackParameters should be true by default.
+  verifyFormat("void (int e, int e,\n"
+   "  int e, int e);\n");
+  // ObjCBinPackProtocolList should be BPS_Never by default.
+  verifyFormat("@interface f () <\n"
+   "f,\n"
+   "f,\n"
+   "f,\n"
+   "f> {\n"
"}");
 }
 
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -710,6 +710,7 @@
   GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
   GoogleStyle.IndentCaseLabels = true;
   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
+  GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
   GoogleStyle.ObjCSpaceAfterProperty = false;
   GoogleStyle.ObjCSpaceBeforeProtocolList = true;
   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41698: [DebugInfo] Enable debug information for C99 VLA types

2018-01-31 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl requested changes to this revision.
aprantl added a comment.
This revision now requires changes to proceed.

The correct way to fix this is to generate the stack object unconditionally (it 
will get optimized away by mem2reg when optimizations are enabled) and only 
emit the dbg.declare when -g is present.


https://reviews.llvm.org/D41698



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


[PATCH] D42578: [AMDGPU] Add ds_fadd, ds_fmin, ds_fmax builtins functions

2018-01-31 Thread Daniil Fukalov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323890: [AMDGPU] Add ds_fadd, ds_fmin, ds_fmax builtins 
functions (authored by dfukalov, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42578?vs=131820&id=132191#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42578

Files:
  cfe/trunk/include/clang/Basic/BuiltinsAMDGPU.def
  cfe/trunk/test/CodeGenOpenCL/builtins-amdgcn-vi.cl


Index: cfe/trunk/test/CodeGenOpenCL/builtins-amdgcn-vi.cl
===
--- cfe/trunk/test/CodeGenOpenCL/builtins-amdgcn-vi.cl
+++ cfe/trunk/test/CodeGenOpenCL/builtins-amdgcn-vi.cl
@@ -89,3 +89,23 @@
   *out = __builtin_amdgcn_mov_dpp(src, 0, 0, 0, false);
 }
 
+// CHECK-LABEL: @test_ds_fadd
+// CHECK: call float @llvm.amdgcn.ds.fadd(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fadd(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fadd(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmin
+// CHECK: call float @llvm.amdgcn.ds.fmin(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fmin(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmin(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmax
+// CHECK: call float @llvm.amdgcn.ds.fmax(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fmax(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmax(out, src, 0, 0, false);
+}
Index: cfe/trunk/include/clang/Basic/BuiltinsAMDGPU.def
===
--- cfe/trunk/include/clang/Basic/BuiltinsAMDGPU.def
+++ cfe/trunk/include/clang/Basic/BuiltinsAMDGPU.def
@@ -93,6 +93,9 @@
 BUILTIN(__builtin_amdgcn_readfirstlane, "ii", "nc")
 BUILTIN(__builtin_amdgcn_readlane, "iii", "nc")
 BUILTIN(__builtin_amdgcn_fmed3f, "", "nc")
+BUILTIN(__builtin_amdgcn_ds_fadd, "ff*3fiib", "n")
+BUILTIN(__builtin_amdgcn_ds_fmin, "ff*3fiib", "n")
+BUILTIN(__builtin_amdgcn_ds_fmax, "ff*3fiib", "n")
 
 
//===--===//
 // VI+ only builtins.


Index: cfe/trunk/test/CodeGenOpenCL/builtins-amdgcn-vi.cl
===
--- cfe/trunk/test/CodeGenOpenCL/builtins-amdgcn-vi.cl
+++ cfe/trunk/test/CodeGenOpenCL/builtins-amdgcn-vi.cl
@@ -89,3 +89,23 @@
   *out = __builtin_amdgcn_mov_dpp(src, 0, 0, 0, false);
 }
 
+// CHECK-LABEL: @test_ds_fadd
+// CHECK: call float @llvm.amdgcn.ds.fadd(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fadd(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fadd(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmin
+// CHECK: call float @llvm.amdgcn.ds.fmin(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fmin(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmin(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmax
+// CHECK: call float @llvm.amdgcn.ds.fmax(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fmax(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmax(out, src, 0, 0, false);
+}
Index: cfe/trunk/include/clang/Basic/BuiltinsAMDGPU.def
===
--- cfe/trunk/include/clang/Basic/BuiltinsAMDGPU.def
+++ cfe/trunk/include/clang/Basic/BuiltinsAMDGPU.def
@@ -93,6 +93,9 @@
 BUILTIN(__builtin_amdgcn_readfirstlane, "ii", "nc")
 BUILTIN(__builtin_amdgcn_readlane, "iii", "nc")
 BUILTIN(__builtin_amdgcn_fmed3f, "", "nc")
+BUILTIN(__builtin_amdgcn_ds_fadd, "ff*3fiib", "n")
+BUILTIN(__builtin_amdgcn_ds_fmin, "ff*3fiib", "n")
+BUILTIN(__builtin_amdgcn_ds_fmax, "ff*3fiib", "n")
 
 //===--===//
 // VI+ only builtins.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42578: [AMDGPU] Add ds_fadd, ds_fmin, ds_fmax builtins functions

2018-01-31 Thread Daniil Fukalov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323890: [AMDGPU] Add ds_fadd, ds_fmin, ds_fmax builtins 
functions (authored by dfukalov, committed by ).

Repository:
  rL LLVM

https://reviews.llvm.org/D42578

Files:
  include/clang/Basic/BuiltinsAMDGPU.def
  test/CodeGenOpenCL/builtins-amdgcn-vi.cl


Index: include/clang/Basic/BuiltinsAMDGPU.def
===
--- include/clang/Basic/BuiltinsAMDGPU.def
+++ include/clang/Basic/BuiltinsAMDGPU.def
@@ -93,6 +93,9 @@
 BUILTIN(__builtin_amdgcn_readfirstlane, "ii", "nc")
 BUILTIN(__builtin_amdgcn_readlane, "iii", "nc")
 BUILTIN(__builtin_amdgcn_fmed3f, "", "nc")
+BUILTIN(__builtin_amdgcn_ds_fadd, "ff*3fiib", "n")
+BUILTIN(__builtin_amdgcn_ds_fmin, "ff*3fiib", "n")
+BUILTIN(__builtin_amdgcn_ds_fmax, "ff*3fiib", "n")
 
 
//===--===//
 // VI+ only builtins.
Index: test/CodeGenOpenCL/builtins-amdgcn-vi.cl
===
--- test/CodeGenOpenCL/builtins-amdgcn-vi.cl
+++ test/CodeGenOpenCL/builtins-amdgcn-vi.cl
@@ -89,3 +89,23 @@
   *out = __builtin_amdgcn_mov_dpp(src, 0, 0, 0, false);
 }
 
+// CHECK-LABEL: @test_ds_fadd
+// CHECK: call float @llvm.amdgcn.ds.fadd(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fadd(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fadd(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmin
+// CHECK: call float @llvm.amdgcn.ds.fmin(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fmin(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmin(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmax
+// CHECK: call float @llvm.amdgcn.ds.fmax(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fmax(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmax(out, src, 0, 0, false);
+}


Index: include/clang/Basic/BuiltinsAMDGPU.def
===
--- include/clang/Basic/BuiltinsAMDGPU.def
+++ include/clang/Basic/BuiltinsAMDGPU.def
@@ -93,6 +93,9 @@
 BUILTIN(__builtin_amdgcn_readfirstlane, "ii", "nc")
 BUILTIN(__builtin_amdgcn_readlane, "iii", "nc")
 BUILTIN(__builtin_amdgcn_fmed3f, "", "nc")
+BUILTIN(__builtin_amdgcn_ds_fadd, "ff*3fiib", "n")
+BUILTIN(__builtin_amdgcn_ds_fmin, "ff*3fiib", "n")
+BUILTIN(__builtin_amdgcn_ds_fmax, "ff*3fiib", "n")
 
 //===--===//
 // VI+ only builtins.
Index: test/CodeGenOpenCL/builtins-amdgcn-vi.cl
===
--- test/CodeGenOpenCL/builtins-amdgcn-vi.cl
+++ test/CodeGenOpenCL/builtins-amdgcn-vi.cl
@@ -89,3 +89,23 @@
   *out = __builtin_amdgcn_mov_dpp(src, 0, 0, 0, false);
 }
 
+// CHECK-LABEL: @test_ds_fadd
+// CHECK: call float @llvm.amdgcn.ds.fadd(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fadd(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fadd(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmin
+// CHECK: call float @llvm.amdgcn.ds.fmin(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fmin(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmin(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmax
+// CHECK: call float @llvm.amdgcn.ds.fmax(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fmax(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmax(out, src, 0, 0, false);
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r294872 - CodeGen: annotate ObjC ARC functions with ABI constraints

2018-01-31 Thread Akira Hatanaka via cfe-commits


> On Jan 30, 2018, at 4:32 PM, Saleem Abdulrasool  wrote:
> 
> Thanks for the note here.  I’ll try to take a look at that, but, yes, the 
> frontend change itself is correct.  I’ve seen many, many places where the 
> ObjCARC passes break down in the backend, and I’ve filed a few bugs on it in 
> the hope that someone from Apple would take a look at some point.  I’m happy 
> to work on it if someone could help with some of the issues that crop up.
> 

Sure, I can help you.

> Instruction bundles would only work partially and not really solve the 
> problem.  The issue is that even the Post RA scheduler can break apart call 
> sequences, reordering things.  The Machine Constant Island Pass is another 
> place this breaks down, as it can create water in between the sequence.  The 
> MI passes tend to expect the bundles to have been broken up, and we need 
> something which is kept all the way through the MC level.
> 

Yes, that’s true, instruction bundles work only when the code is in LLVM IR. 
Maybe we can use MachineInstr bundles to prevent backend passes from inserting 
instructions between the calls?

> On Tue, Jan 30, 2018 at 12:38 PM Akira Hatanaka  > wrote:
> Hi Saleem,
> 
> I had to revert this patch since this patch caused crashes in code that was 
> working fine before.
> 
> As I mentioned in the commit message, I believe this patch is correct, but it 
> causes the objc_retainAutoreleasedReturnValue/objc_autoreleaseReturnValue 
> handshake to fail in some cases because middle-end and backend passes insert 
> instructions between the call to the function returning an object and the 
> call to objc_retainAutoreleasedReturnValue. We probably should find a way to 
> prevent inserting instructions between the calls (maybe using instruction 
> bundles), but we haven’t had the time to implement the fix. Feel free to fix 
> the bug if you’d like to do so.
> 
> > On Feb 11, 2017, at 1:34 PM, Saleem Abdulrasool via cfe-commits 
> > mailto:cfe-commits@lists.llvm.org>> wrote:
> >
> > Author: compnerd
> > Date: Sat Feb 11 15:34:18 2017
> > New Revision: 294872
> >
> > URL: http://llvm.org/viewvc/llvm-project?rev=294872&view=rev 
> > 
> > Log:
> > CodeGen: annotate ObjC ARC functions with ABI constraints
> >
> > Certain ARC runtime functions have an ABI contract of being forwarding.
> > Annotate the functions with the appropriate `returned` attribute on the
> > arguments.  This hoists some of the runtime ABI contract information
> > into the frontend rather than the backend transformations.
> >
> > The test adjustments are to mark the returned function parameter as
> > such.  The minor change to the IR output is due to the fact that the
> > returned reference of the object causes it to extend the lifetime of the
> > object by returning an autoreleased return value.  The result is that
> > the explicit objc_autorelease call is no longer formed, as autorelease
> > elision is now possible on the return.
> >
> > Modified:
> >cfe/trunk/lib/CodeGen/CGObjC.cpp
> >cfe/trunk/test/CodeGenObjC/arc.m
> >
> > Modified: cfe/trunk/lib/CodeGen/CGObjC.cpp
> > URL: 
> > http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGObjC.cpp?rev=294872&r1=294871&r2=294872&view=diff
> >  
> > 
> > ==
> > --- cfe/trunk/lib/CodeGen/CGObjC.cpp (original)
> > +++ cfe/trunk/lib/CodeGen/CGObjC.cpp Sat Feb 11 15:34:18 2017
> > @@ -1802,6 +1802,22 @@ void CodeGenFunction::EmitARCIntrinsicUs
> > }
> >
> >
> > +static bool IsForwarding(StringRef Name) {
> > +  return llvm::StringSwitch(Name)
> > +  .Cases("objc_autoreleaseReturnValue", // 
> > ARCInstKind::AutoreleaseRV
> > + "objc_autorelease",// 
> > ARCInstKind::Autorelease
> > + "objc_retainAutoreleaseReturnValue",   // 
> > ARCInstKind::FusedRetainAutoreleaseRV
> > + "objc_retainAutoreleasedReturnValue",  // 
> > ARCInstKind::RetainRV
> > + "objc_retainAutorelease",  // 
> > ARCInstKind::FusedRetainAutorelease
> > + "objc_retainedObject", // 
> > ARCInstKind::NoopCast
> > + "objc_retain", // 
> > ARCInstKind::Retain
> > + "objc_unretainedObject",   // 
> > ARCInstKind::NoopCast
> > + "objc_unretainedPointer",  // 
> > ARCInstKind::NoopCast
> > + "objc_unsafeClaimAutoreleasedReturnValue", // 
> > ARCInstKind::ClaimRV
> > + true)
> > +  .Default(false);
> > +}
> > +
> > static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
> > llvm::FunctionType *FTy,
> >  

[PATCH] D42310: Formalize FreeBSD support of compiler rt

2018-01-31 Thread John Baldwin via Phabricator via cfe-commits
bsdjhb added a comment.

My only question is if we want an OS version check as the FreeBSD driver does 
now for libc++ vs libstdc++?   FreeBSD started using libcompiler_rt for 
libgcc.a in 9.0.


Repository:
  rC Clang

https://reviews.llvm.org/D42310



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


[PATCH] D37831: [WebAssembly] Don't pass -ffunction-section/-fdata-sections

2018-01-31 Thread Derek Schuff via Phabricator via cfe-commits
dschuff added a comment.

In https://reviews.llvm.org/D37831#992822, @sbc100 wrote:

> After a little discussion about this and the -gc-sections linker flag, the 
> augments for the tools having sensible defaults seem to be winning.


Well sure, when you put it that way, nobody can argue against sensible 
defaults, can they :D


Repository:
  rC Clang

https://reviews.llvm.org/D37831



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


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

2018-01-31 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 132198.
Typz added a comment.

Force wrap after multi-line template declaration


Repository:
  rC Clang

https://reviews.llvm.org/D42684

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -5367,7 +5367,7 @@
"const typename  aaa);");
 
   FormatStyle AlwaysBreak = getLLVMStyle();
-  AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
+  AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_All;
   verifyFormat("template \nclass C {};", AlwaysBreak);
   verifyFormat("template \nvoid f();", AlwaysBreak);
   verifyFormat("template \nvoid f() {}", AlwaysBreak);
@@ -5385,6 +5385,32 @@
"public:\n"
"  E *f();\n"
"};");
+
+  FormatStyle NeverBreak = getLLVMStyle();
+  NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_None;
+  verifyFormat("template  class C {};", NeverBreak);
+  verifyFormat("template  void f();", NeverBreak);
+  verifyFormat("template  void f() {}", NeverBreak);
+  verifyFormat("template \nvoid foo(aa ) {}",
+   NeverBreak);
+  verifyFormat("void aaa(\n"
+   "ccc);",
+   NeverBreak);
+  verifyFormat("template  class Fooo,\n"
+   "  template  class Baaar>\n"
+   "struct C {};",
+   NeverBreak);
+  verifyFormat("template  // T can be A, B or C.\n"
+   "struct C {};",
+   NeverBreak);
+  verifyFormat("template  class A {\n"
+   "public:\n"
+   "  E *f();\n"
+   "};", NeverBreak);
+  NeverBreak.PenaltyBreakTemplateDeclaration = 100;
+  verifyFormat("template  void\nfoo(aa ) {}",
+   NeverBreak);
 }
 
 TEST_F(FormatTest, WrapsTemplateParameters) {
@@ -10166,7 +10192,6 @@
   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
   CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
-  CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
   CHECK_PARSE_BOOL(BinPackArguments);
   CHECK_PARSE_BOOL(BinPackParameters);
   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
@@ -10229,6 +10254,8 @@
   PenaltyBreakAssignment, 1234u);
   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
   PenaltyBreakBeforeFirstCallParameter, 1234u);
+  CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
+  PenaltyBreakTemplateDeclaration, 1234u);
   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
   PenaltyReturnTypeOnItsOwnLine, 1234u);
@@ -10383,6 +10410,18 @@
   AlwaysBreakAfterReturnType,
   FormatStyle::RTBS_TopLevelDefinitions);
 
+  Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_All;
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: None", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_None);
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: BeforeFunction", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_BeforeFunction);
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: All", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_All);
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_BeforeFunction);
+  CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", AlwaysBreakTemplateDeclarations,
+  FormatStyle::BTDS_All);
+
   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
   AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2171,6 +2171,8 @@
   return 2;
 return 1;
   }
+  if (Left.ClosesTemplateDeclaration)
+  return Style.PenaltyBreakTemplateDeclaration;
   if (Left.is(TT_ConditionalExpr))
 return prec::Conditional;
   prec::Level Level = Left.getPrecedence();
@@ -2641,7 +2643,7 @@
   if (Right.Previous->ClosesTemplateDeclaration &&
   Right.Previous->MatchingParen &&
   Right.Previous->MatchingParen->NestingLevel == 0 &&
-  Style.AlwaysBreakTemplateDeclarations)
+  Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_All)
 return true;
   if (Right.is(TT_CtorInitializerComma) &&
   Style.BreakC

[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.h:19
+
+/// Check for several deprecated types and classes from  header
+///

aaron.ballman wrote:
> massberg wrote:
> > massberg wrote:
> > > aaron.ballman wrote:
> > > > Missing full stop at the end of the sentence.
> > > > 
> > > > Why should this modernize check be limited to ``? Just like 
> > > > we have a "deprecated headers" check, perhaps this should be a 
> > > > "deprecated APIs" check?
> > > Added full stop.
> > > 
> > > I'm not sure if this check should be limited to  or be 
> > > extended to a full 'deprecated API' check.
> > > This change is just a start, several more types and classes which are 
> > > removed from  will follow, e.g:
> > > 
> > > - std::ptr_fun, std::mem_fun, std::mem_fun_ref
> > > - std::bind1st, std::bind2nd
> > > - std::unary_function, std::binary_function
> > > - std::pointer_to_unary_function, std::pointer_to_binary_function, 
> > > std::mem_fun_t, std::mem_fun1_t, std::const_mem_fun_t, 
> > > - std::const_mem_fun1_t, std::mem_fun_ref_t, std::mem_fun1_ref_t, 
> > > std::const_mem_fun_ref_t, std::const_mem_fun1_ref_t
> > > - std::binder1st, std::binder2nd
> > > 
> > > As these are a bunch of functions and types, in my eyes a check just for 
> > >  is fine. But I'm also fine with a general 'deprecated API' 
> > > check.
> > > Alex, can you comment on this?
> > There are already other checks for functions which are removed in C++17 
> > like modernize-replace-random-shuffle.
> > So I think having an separate check for functions and types removed from 
> >  would be OK.
> You've hit the nail on the head for what I'm trying to avoid -- we shouldn't 
> have multiple checks unless they do drastically different things. Having a 
> deprecated check like this really only makes sense for APIs that are 
> deprecated but aren't uniformly marked as `[[deprecated]]` by the library. As 
> such, I think we really only need one check for this rather than splitting it 
> out over multiple checks -- the existing check functionality could be rolled 
> into this one and its check become an alias.
> I'm not sure if this check should be limited to  or be extended 
> to a full 'deprecated API' check.

IIUC, it should be possible to implement fixits at least for some use cases 
here. My impression was that Jens was at least considering to work on fixits. 
The other check mentioned here - `modernize-replace-random-shuffle` already 
implements fixits. Fixits are specific to the API and some codebases may have 
better replacement APIs than what the standard suggests, so different users may 
want to apply different set of the fixes. Given all that, I wouldn't just merge 
all of the checks dealing with deprecated APIs. Splitting them at least by 
header seems like a good start, maybe even finer granularity may be needed in 
some cases.


https://reviews.llvm.org/D42730



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


[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.h:19
+
+/// Check for several deprecated types and classes from  header
+///

alexfh wrote:
> aaron.ballman wrote:
> > massberg wrote:
> > > massberg wrote:
> > > > aaron.ballman wrote:
> > > > > Missing full stop at the end of the sentence.
> > > > > 
> > > > > Why should this modernize check be limited to ``? Just 
> > > > > like we have a "deprecated headers" check, perhaps this should be a 
> > > > > "deprecated APIs" check?
> > > > Added full stop.
> > > > 
> > > > I'm not sure if this check should be limited to  or be 
> > > > extended to a full 'deprecated API' check.
> > > > This change is just a start, several more types and classes which are 
> > > > removed from  will follow, e.g:
> > > > 
> > > > - std::ptr_fun, std::mem_fun, std::mem_fun_ref
> > > > - std::bind1st, std::bind2nd
> > > > - std::unary_function, std::binary_function
> > > > - std::pointer_to_unary_function, std::pointer_to_binary_function, 
> > > > std::mem_fun_t, std::mem_fun1_t, std::const_mem_fun_t, 
> > > > - std::const_mem_fun1_t, std::mem_fun_ref_t, std::mem_fun1_ref_t, 
> > > > std::const_mem_fun_ref_t, std::const_mem_fun1_ref_t
> > > > - std::binder1st, std::binder2nd
> > > > 
> > > > As these are a bunch of functions and types, in my eyes a check just 
> > > > for  is fine. But I'm also fine with a general 'deprecated 
> > > > API' check.
> > > > Alex, can you comment on this?
> > > There are already other checks for functions which are removed in C++17 
> > > like modernize-replace-random-shuffle.
> > > So I think having an separate check for functions and types removed from 
> > >  would be OK.
> > You've hit the nail on the head for what I'm trying to avoid -- we 
> > shouldn't have multiple checks unless they do drastically different things. 
> > Having a deprecated check like this really only makes sense for APIs that 
> > are deprecated but aren't uniformly marked as `[[deprecated]]` by the 
> > library. As such, I think we really only need one check for this rather 
> > than splitting it out over multiple checks -- the existing check 
> > functionality could be rolled into this one and its check become an alias.
> > I'm not sure if this check should be limited to  or be extended 
> > to a full 'deprecated API' check.
> 
> IIUC, it should be possible to implement fixits at least for some use cases 
> here. My impression was that Jens was at least considering to work on fixits. 
> The other check mentioned here - `modernize-replace-random-shuffle` already 
> implements fixits. Fixits are specific to the API and some codebases may have 
> better replacement APIs than what the standard suggests, so different users 
> may want to apply different set of the fixes. Given all that, I wouldn't just 
> merge all of the checks dealing with deprecated APIs. Splitting them at least 
> by header seems like a good start, maybe even finer granularity may be needed 
> in some cases.
TL;DR "they do drastically different things" is the case for this check and 
modernize-replace-random-shuffle.


https://reviews.llvm.org/D42730



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


[PATCH] D42644: [asan] Intercept std::rethrow_exception indirectly.

2018-01-31 Thread Kuba (Brecka) Mracek via Phabricator via cfe-commits
kubamracek added a comment.

Cool. Can we get a lit test as well?


Repository:
  rCRT Compiler Runtime

https://reviews.llvm.org/D42644



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


[PATCH] D42730: Add clang-tidy check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-01-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.h:19
+
+/// Check for several deprecated types and classes from  header
+///

alexfh wrote:
> alexfh wrote:
> > aaron.ballman wrote:
> > > massberg wrote:
> > > > massberg wrote:
> > > > > aaron.ballman wrote:
> > > > > > Missing full stop at the end of the sentence.
> > > > > > 
> > > > > > Why should this modernize check be limited to ``? Just 
> > > > > > like we have a "deprecated headers" check, perhaps this should be a 
> > > > > > "deprecated APIs" check?
> > > > > Added full stop.
> > > > > 
> > > > > I'm not sure if this check should be limited to  or be 
> > > > > extended to a full 'deprecated API' check.
> > > > > This change is just a start, several more types and classes which are 
> > > > > removed from  will follow, e.g:
> > > > > 
> > > > > - std::ptr_fun, std::mem_fun, std::mem_fun_ref
> > > > > - std::bind1st, std::bind2nd
> > > > > - std::unary_function, std::binary_function
> > > > > - std::pointer_to_unary_function, std::pointer_to_binary_function, 
> > > > > std::mem_fun_t, std::mem_fun1_t, std::const_mem_fun_t, 
> > > > > - std::const_mem_fun1_t, std::mem_fun_ref_t, std::mem_fun1_ref_t, 
> > > > > std::const_mem_fun_ref_t, std::const_mem_fun1_ref_t
> > > > > - std::binder1st, std::binder2nd
> > > > > 
> > > > > As these are a bunch of functions and types, in my eyes a check just 
> > > > > for  is fine. But I'm also fine with a general 
> > > > > 'deprecated API' check.
> > > > > Alex, can you comment on this?
> > > > There are already other checks for functions which are removed in C++17 
> > > > like modernize-replace-random-shuffle.
> > > > So I think having an separate check for functions and types removed 
> > > > from  would be OK.
> > > You've hit the nail on the head for what I'm trying to avoid -- we 
> > > shouldn't have multiple checks unless they do drastically different 
> > > things. Having a deprecated check like this really only makes sense for 
> > > APIs that are deprecated but aren't uniformly marked as `[[deprecated]]` 
> > > by the library. As such, I think we really only need one check for this 
> > > rather than splitting it out over multiple checks -- the existing check 
> > > functionality could be rolled into this one and its check become an alias.
> > > I'm not sure if this check should be limited to  or be 
> > > extended to a full 'deprecated API' check.
> > 
> > IIUC, it should be possible to implement fixits at least for some use cases 
> > here. My impression was that Jens was at least considering to work on 
> > fixits. The other check mentioned here - `modernize-replace-random-shuffle` 
> > already implements fixits. Fixits are specific to the API and some 
> > codebases may have better replacement APIs than what the standard suggests, 
> > so different users may want to apply different set of the fixes. Given all 
> > that, I wouldn't just merge all of the checks dealing with deprecated APIs. 
> > Splitting them at least by header seems like a good start, maybe even finer 
> > granularity may be needed in some cases.
> TL;DR "they do drastically different things" is the case for this check and 
> modernize-replace-random-shuffle.
I disagree that they do drastically different things or that fix-its are a 
problem. Some of these APIs have replacements, others do not. At the end of the 
day, the basics are the same: the functionality is deprecated and you should 
consider a replacement. Sometimes we know that replacement up front, other 
times we don't. I don't think we should make users reach for a per-header file 
answer to that problem unless it provides them some benefit. I don't see users 
caring to update  but not other headers.

I can see benefit to splitting the *implementations* of the checks along 
arbitrary lines, but how we structure the implementation is orthogonal to how 
we surface the functionality.


https://reviews.llvm.org/D42730



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


[PATCH] D16403: Add scope information to CFG

2018-01-31 Thread Maxim Ostapenko via Phabricator via cfe-commits
m.ostapenko added a comment.

In https://reviews.llvm.org/D16403#992452, @NoQ wrote:

> Thank you, this explanation looks very reasonable.
>
> All right, so right after the termination of the loop we have
>
>   [B1]
>   1: ForStmt (LoopExit)
>   2: [B4.5].~A() (Implicit destructor)
>   3: [B5.3].~A() (Implicit destructor)
>   4: CFGScopeEnd(a)
>   5: CFGScopeEnd(b)
>
>
> ... where `[B4.5]` is `A b = a;` and `[B5.3]` is `A a;`. Am i understanding 
> correctly that while destroying `a` you can still use the storage of `b` 
> safely? Or should `a` go out of scope before `b` gets destroyed?


AFAIU, when we destroying `a` we can still use the storage of `b` because 
nothing can be allocated into b's storage between calling destructors for `b` 
and `a`. So, imho the sequence should look like:

  [B4.5].~A() (Implicit destructor)
  [B5.3].~A() (Implicit destructor)
  CFGScopeEnd(b)
  CFGScopeEnd(a)



> Also, is the order of scope ends actually correct here - shouldn't `b` go out 
> of scope earlier? Given that they are in very different lifetime scopes (`a` 
> is one for the whole loop, `b` is per-loop-iteration). I guess the order 
> would matter for the analyzer.

Yeah, this is a bug in a current implementation. Will fix this in the next 
patch version.


Repository:
  rL LLVM

https://reviews.llvm.org/D16403



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


[PATCH] D41655: [clang-tidy] New check bugprone-unused-return-value

2018-01-31 Thread Kalle Huttunen via Phabricator via cfe-commits
khuttun added a comment.
Herald added a subscriber: hintonda.

Any more comments on this?


https://reviews.llvm.org/D41655



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


[PATCH] D42170: Fixit for 'typedef' instead of 'typename' typo

2018-01-31 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai accepted this revision.
vsapsai added a comment.
This revision is now accepted and ready to land.

One small note about `-fdiagnostics-parseable-fixits`. The rest looks good to 
me. And the test looks readable.




Comment at: FixIt/fixit-typedef-instead-of-typename-typo.cpp:1
+// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -verify %s
+

I don't think you need `-fdiagnostics-parseable-fixits` here. Though it is 
required in the second RUN line.


https://reviews.llvm.org/D42170



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


[PATCH] D42745: [analyzer] Add support for __builtin_constant_p to BuiltinFunctionChecker

2018-01-31 Thread Felix Kostenzer via Phabricator via cfe-commits
sp4r74n-117 created this revision.
sp4r74n-117 added reviewers: george.karpenkov, dcoughlin, dergachev.a.
sp4r74n-117 created this object with visibility "All Users".
Herald added subscribers: cfe-commits, a.sidorin, szepet, xazax.hun.

Added evaluation of __builtin_constant_p to the dedicated StaticAnalyzer 
checker along with a test case.

Tested via: make clang-test


Repository:
  rC Clang

https://reviews.llvm.org/D42745

Files:
  lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
  test/Analysis/builtin-functions.cpp


Index: test/Analysis/builtin-functions.cpp
===
--- test/Analysis/builtin-functions.cpp
+++ test/Analysis/builtin-functions.cpp
@@ -64,3 +64,18 @@
 // We give up the analysis on this path.
   }
 }
+
+void test_constant_p() {
+  int i = 1;
+  const int j = 2;
+  constexpr int k = 3;
+  clang_analyzer_eval(__builtin_constant_p(42)); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(i)); // expected-warning {{FALSE}}
+  clang_analyzer_eval(__builtin_constant_p(j)); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(k)); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(i + 42)); // expected-warning 
{{FALSE}}
+  clang_analyzer_eval(__builtin_constant_p(j + 42)); // expected-warning 
{{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(k + 42)); // expected-warning 
{{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(" ")); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(test_constant_p)); // 
expected-warning {{FALSE}}
+}
Index: lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -113,6 +113,24 @@
 C.addTransition(state->BindExpr(CE, LCtx, V));
 return true;
   }
+
+  case Builtin::BI__builtin_constant_p: {
+SVal V;
+SValBuilder& SVB = C.getSValBuilder();
+
+llvm::APSInt Result;
+// Model semantics as 'A return of 0 does not indicate that the value is
+// not a constant, but merely that GCC cannot prove it is a constant [...]'
+if (CE->EvaluateAsInt(Result, C.getASTContext(), Expr::SE_NoSideEffects)) {
+  SVB.getBasicValueFactory().getAPSIntType(CE->getType()).apply(Result);
+  V = SVB.makeIntVal(Result);
+}
+else
+  V = SVB.makeZeroVal(CE->getType());
+
+C.addTransition(state->BindExpr(CE, LCtx, V));
+return true;
+  }
   }
 }
 


Index: test/Analysis/builtin-functions.cpp
===
--- test/Analysis/builtin-functions.cpp
+++ test/Analysis/builtin-functions.cpp
@@ -64,3 +64,18 @@
 // We give up the analysis on this path.
   }
 }
+
+void test_constant_p() {
+  int i = 1;
+  const int j = 2;
+  constexpr int k = 3;
+  clang_analyzer_eval(__builtin_constant_p(42)); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(i)); // expected-warning {{FALSE}}
+  clang_analyzer_eval(__builtin_constant_p(j)); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(k)); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(i + 42)); // expected-warning {{FALSE}}
+  clang_analyzer_eval(__builtin_constant_p(j + 42)); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(k + 42)); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(" ")); // expected-warning {{TRUE}}
+  clang_analyzer_eval(__builtin_constant_p(test_constant_p)); // expected-warning {{FALSE}}
+}
Index: lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -113,6 +113,24 @@
 C.addTransition(state->BindExpr(CE, LCtx, V));
 return true;
   }
+
+  case Builtin::BI__builtin_constant_p: {
+SVal V;
+SValBuilder& SVB = C.getSValBuilder();
+
+llvm::APSInt Result;
+// Model semantics as 'A return of 0 does not indicate that the value is
+// not a constant, but merely that GCC cannot prove it is a constant [...]'
+if (CE->EvaluateAsInt(Result, C.getASTContext(), Expr::SE_NoSideEffects)) {
+  SVB.getBasicValueFactory().getAPSIntType(CE->getType()).apply(Result);
+  V = SVB.makeIntVal(Result);
+}
+else
+  V = SVB.makeZeroVal(CE->getType());
+
+C.addTransition(state->BindExpr(CE, LCtx, V));
+return true;
+  }
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323894 - Revert "Revert rC322769: [RISCV] Propagate -mabi and -march values to GNU assembler."

2018-01-31 Thread Ana Pazos via cfe-commits
Author: apazos
Date: Wed Jan 31 10:11:09 2018
New Revision: 323894

URL: http://llvm.org/viewvc/llvm-project?rev=323894&view=rev
Log:
Revert "Revert rC322769: [RISCV] Propagate -mabi and -march values to GNU 
assembler."

Summary: Bringing back the code change and simplified test cases to test 32/64 
bit targets.

Reviewers: asb, yroux, inouehrs, mgrang

Reviewed By: yroux, inouehrs

Subscribers: cfe-commits, rbar, johnrusso, simoncook, jordy.potman.lists, 
sabuasal, niosHD

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

Added:
cfe/trunk/test/Driver/riscv-gnutools.c
Modified:
cfe/trunk/lib/Driver/ToolChains/Gnu.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Gnu.cpp?rev=323894&r1=323893&r2=323894&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Gnu.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Gnu.cpp Wed Jan 31 10:11:09 2018
@@ -629,6 +629,18 @@ void tools::gnutools::Assembler::Constru
   ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple(;
 break;
   }
+  case llvm::Triple::riscv32:
+  case llvm::Triple::riscv64: {
+StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
+CmdArgs.push_back("-mabi");
+CmdArgs.push_back(ABIName.data());
+if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
+  StringRef MArch = A->getValue();
+  CmdArgs.push_back("-march");
+  CmdArgs.push_back(MArch.data());
+}
+break;
+  }
   case llvm::Triple::sparc:
   case llvm::Triple::sparcel: {
 CmdArgs.push_back("-32");

Added: cfe/trunk/test/Driver/riscv-gnutools.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/riscv-gnutools.c?rev=323894&view=auto
==
--- cfe/trunk/test/Driver/riscv-gnutools.c (added)
+++ cfe/trunk/test/Driver/riscv-gnutools.c Wed Jan 31 10:11:09 2018
@@ -0,0 +1,19 @@
+// Check gnutools are invoked with propagated values for -mabi and -march.
+
+// RUN: %clang -target riscv32 -fno-integrated-as %s -###  -c \
+// RUN: 2>&1 | FileCheck -check-prefix=MABI-ILP32 %s
+
+// RUN: %clang -target riscv32 -fno-integrated-as -march=rv32g %s -### -c \
+// RUN: 2>&1 | FileCheck -check-prefix=MABI-ILP32-MARCH-G %s
+
+// RUN: %clang -target riscv64 -fno-integrated-as %s -###  -c \
+// RUN: 2>&1 | FileCheck -check-prefix=MABI-ILP64 %s
+
+// RUN: %clang -target riscv64 -fno-integrated-as -march=rv64g %s -### -c \
+// RUN: 2>&1 | FileCheck -check-prefix=MABI-ILP64-MARCH-G %s
+
+// MABI-ILP32: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32"
+// MABI-ILP32-MARCH-G: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32" "-march" "rv32g"
+
+// MABI-ILP64: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64"
+// MABI-ILP64-MARCH-G: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64" "-march" "rv64g"


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


  1   2   >