Adds support for auto-detection of compilation databases
from a source file and changes clang-check to make use of this.

This makes clang-check just work on in-tree builds, and allows
easy setup via a symlink per source directory to make clang-check
work without any extra configuration.



git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@159990 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Tooling/CompilationDatabase.cpp b/lib/Tooling/CompilationDatabase.cpp
index 227fa82..8e91112 100644
--- a/lib/Tooling/CompilationDatabase.cpp
+++ b/lib/Tooling/CompilationDatabase.cpp
@@ -12,6 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/Tooling/CompilationDatabase.h"
+#include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/YAMLParser.h"
 #include "llvm/Support/Path.h"
@@ -121,6 +122,23 @@
   return Database.take();
 }
 
+CompilationDatabase *
+CompilationDatabase::autoDetectFromSource(StringRef SourceFile,
+                                          std::string &ErrorMessage) {
+  llvm::SmallString<1024> AbsolutePath(getAbsolutePath(SourceFile));
+  StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
+  while (!Directory.empty()) {
+    std::string LoadErrorMessage;
+    if (CompilationDatabase *DB = loadFromDirectory(Directory,
+                                                    LoadErrorMessage))
+      return DB;
+    Directory = llvm::sys::path::parent_path(Directory);
+  }
+  ErrorMessage = ("Could not auto-detect compilation database for file \"" +
+                  SourceFile + "\"").str();
+  return NULL;
+}
+
 FixedCompilationDatabase *
 FixedCompilationDatabase::loadFromCommandLine(int &Argc,
                                               const char **Argv,
@@ -283,4 +301,3 @@
 
 } // end namespace tooling
 } // end namespace clang
-