gollvm: support -Bprefix

Support -Bprefix for searching for tools and libraries.

Change-Id: Ic2dfa46ec54964027a5ce09e173dd4cbc358ce50
Reviewed-on: https://go-review.googlesource.com/116217
Reviewed-by: Than McIntosh <thanm@google.com>
diff --git a/driver/Driver.cpp b/driver/Driver.cpp
index 6916894..39e3683 100644
--- a/driver/Driver.cpp
+++ b/driver/Driver.cpp
@@ -47,6 +47,7 @@
   SmallString<128> abspath(executablePath_);
   llvm::sys::fs::make_absolute(abspath);
   installDir_ = llvm::sys::path::parent_path(abspath);
+  prefixes_ = args.getAllArgValues(gollvm::options::OPT_B);
 }
 
 Driver::~Driver()
@@ -66,7 +67,14 @@
 std::string Driver::getFilePath(llvm::StringRef name,
                                 ToolChain &toolchain)
 {
-  // TODO: add support for -Bprefix option.
+  // Include -Bprefixed name in search.
+  SmallVector<std::string, 2> candidates;
+  for (auto p : prefixes_)
+    candidates.push_back((p + name).str());
+  for (auto &cand : candidates) {
+    if (llvm::sys::fs::exists(llvm::Twine(cand)))
+      return cand;
+  }
 
   // Examine toolchain file paths.
   for (const auto &dir : toolchain.filePaths()) {
@@ -82,10 +90,10 @@
 std::string Driver::getProgramPath(llvm::StringRef name,
                                    ToolChain &toolchain)
 {
-  // TODO: add support for -Bprefix option.
-
-  // Include target-prefixed name in search.
-  SmallVector<std::string, 2> candidates;
+  // Include -Bprefixed and target-prefixed name in search.
+  SmallVector<std::string, 3> candidates;
+  for (auto p : prefixes_)
+    candidates.push_back((p + name).str());
   candidates.push_back((triple_.str() + "-" + name).str());
   candidates.push_back(name);
 
diff --git a/driver/Driver.h b/driver/Driver.h
index 24b35c9..748b43c 100644
--- a/driver/Driver.h
+++ b/driver/Driver.h
@@ -121,6 +121,7 @@
   llvm::StringMap<std::unique_ptr<ToolChain>> toolchains_;
   // Maps non-input actions to output artifacts.
   std::unordered_map<Action *, Artifact*> artmap_;
+  std::vector<std::string> prefixes_;
 
   bool processAction(Action *act, Compilation &compilation, bool lastAct);
   ArtifactList collectInputArtifacts(Action *act, InternalTool *it);
diff --git a/driver/GollvmOptions.td b/driver/GollvmOptions.td
index d07de73..4a199ee 100644
--- a/driver/GollvmOptions.td
+++ b/driver/GollvmOptions.td
@@ -105,6 +105,10 @@
 def help : Flag<["-", "--"], "help">,
   HelpText<"Display available options">;
 
+def B : JoinedOrSeparate<["-"], "B">,
+    Flags<[DriverOption]>, MetaVarName<"<prefix>">,
+    HelpText<"Add prefix for searching binaries and libraries">;
+
 def I : JoinedOrSeparate<["-"], "I">,
     Flags<[DriverOption]>, MetaVarName<"<dir>">,
     HelpText<"Add include directory to be searched for packages">;