Driver.cpp revision 7f9fc3f7ce076645cb6aefc99c64d9446caf13d6
17d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
27d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)//
37d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
47d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)//
57d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
67d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)// License. See LICENSE.TXT for details.
77d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)//
85d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===//
97d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
107d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#ifdef HAVE_CLANG_CONFIG_H
1123730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)# include "clang/Config/config.h"
127d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#endif
137d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
147d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/Driver.h"
1546d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
168bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)#include "clang/Driver/Action.h"
177d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/Arg.h"
187d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/ArgList.h"
19f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/Driver/Compilation.h"
207d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/DriverDiagnostic.h"
217d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/HostInfo.h"
227d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/Job.h"
237d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/OptTable.h"
247d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/Driver/Option.h"
258bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)#include "clang/Driver/Options.h"
268bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles)#include "clang/Driver/Tool.h"
274e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "clang/Driver/ToolChain.h"
284e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)#include "clang/Driver/Types.h"
290529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
30a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)#include "clang/Basic/Version.h"
31effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch
32a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "llvm/Config/config.h"
33a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "llvm/ADT/ArrayRef.h"
34a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "llvm/ADT/StringSet.h"
35effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch#include "llvm/ADT/OwningPtr.h"
36effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch#include "llvm/Support/PrettyStackTrace.h"
3746d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)#include "llvm/Support/raw_ostream.h"
3846d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)#include "llvm/Support/FileSystem.h"
3946d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)#include "llvm/Support/Path.h"
4046d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)#include "llvm/Support/Program.h"
417d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
427d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "InputInfo.h"
4358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
4458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include <map>
451e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)
461e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)#ifdef __CYGWIN__
47a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include <cygwin/version.h>
48a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
495d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#define IS_CYGWIN15 1
505d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#endif
51f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#endif
525d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
535d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)using namespace clang::driver;
54a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)using namespace clang;
557d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
567d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)Driver::Driver(llvm::StringRef _ClangExecutable,
577d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)               llvm::StringRef _DefaultHostTriple,
587d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)               llvm::StringRef _DefaultImageName,
597dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch               bool IsProduction, bool CXXIsProduction,
607d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)               Diagnostic &_Diags)
617d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  : Opts(createDriverOptTable()), Diags(_Diags),
627d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    ClangExecutable(_ClangExecutable), UseStdLib(true),
637d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    DefaultHostTriple(_DefaultHostTriple), DefaultImageName(_DefaultImageName),
647d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    DriverTitle("clang \"gcc-compatible\" driver"),
657d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    Host(0),
667d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    CCPrintOptionsFilename(0), CCPrintHeadersFilename(0), CCCIsCXX(false),
677d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
687d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    CCPrintOptions(false), CCPrintHeaders(false), CCCGenericGCCName("gcc"),
697d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    CheckInputsExist(true), CCCUseClang(true), CCCUseClangCXX(true),
707d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    CCCUseClangCPP(true), CCCUsePCH(true), SuppressMissingInputWarning(false) {
717d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  if (IsProduction) {
727d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    // In a "production" build, only use clang on architectures we expect to
73a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    // work, and don't use clang C++.
74a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    //
75a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    // During development its more convenient to always have the driver use
767d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    // clang, but we don't want users to be confused when things don't work, or
777d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    // to file bugs for things we don't support.
787d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::x86);
797d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::x86_64);
807d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::arm);
817d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
82a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch    if (!CXXIsProduction)
834e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)      CCCUseClangCXX = false;
844e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  }
851e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)
861e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  Name = llvm::sys::path::stem(ClangExecutable);
871e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  Dir  = llvm::sys::path::parent_path(ClangExecutable);
887d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
897d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  // Compute the path to the resource directory.
907d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  llvm::StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
917d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  llvm::SmallString<128> P(Dir);
927d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  if (ClangResourceDir != "")
937d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    llvm::sys::path::append(P, ClangResourceDir);
94d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)  else
957d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
967d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  ResourceDir = P.str();
977d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)}
984e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
994e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)Driver::~Driver() {
1004e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  delete Opts;
101a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  delete Host;
102effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch}
103effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch
104a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)InputArgList *Driver::ParseArgStrings(llvm::ArrayRef<const char *> ArgList) {
105a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
106a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  unsigned MissingArgIndex, MissingArgCount;
107a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
1087d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)                                           MissingArgIndex, MissingArgCount);
1097d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
110a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  // Check for missing argument error.
1117d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  if (MissingArgCount)
1127d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    Diag(clang::diag::err_drv_missing_argument)
1137d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)      << Args->getArgString(MissingArgIndex) << MissingArgCount;
1147d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
1154e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  // Check for unsupported options.
1164e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
1177d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)       it != ie; ++it) {
1187dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    Arg *A = *it;
119f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    if (A->getOption().isUnsupported()) {
1207dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
1217d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)      continue;
1227d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    }
1237d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  }
1247d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
1257d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  return Args;
1267d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)}
1277d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
1287d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
1297d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  DerivedArgList *DAL = new DerivedArgList(Args);
1307d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
1317d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
1327d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  for (ArgList::const_iterator it = Args.begin(),
1337d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)         ie = Args.end(); it != ie; ++it) {
1347d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    const Arg *A = *it;
135ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch
136cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    // Unfortunately, we have to parse some forwarding options (-Xassembler,
137cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
138cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    // (assembler and preprocessor), or bypass a previous driver ('collect2').
1394e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
1404e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)    // Rewrite linker options, to replace --no-demangle with a custom internal
1414e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)    // option.
14223730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
143c2db58bd994c04d98e4ee2cd7565b71548655fe3Ben Murdoch         A->getOption().matches(options::OPT_Xlinker)) &&
144424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)        A->containsValue("--no-demangle")) {
145cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)      // Add the rewritten no-demangle argument.
1464e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)      DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
1470f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)
148cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)      // Add the remaining values as Xlinker arguments.
149cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
150cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)        if (llvm::StringRef(A->getValue(Args, i)) != "--no-demangle")
1515d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)          DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
1525d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                              A->getValue(Args, i));
1535d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
1540f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)      continue;
1550f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)    }
1565d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
1575d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
1585d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // some build systems. We don't try to be complete here because we don't
159a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    // care to encourage this usage model.
160a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
161a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)        A->getNumValues() == 2 &&
162010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        (A->getValue(Args, 0) == llvm::StringRef("-MD") ||
163010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)         A->getValue(Args, 0) == llvm::StringRef("-MMD"))) {
164010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // Rewrite to -MD/-MMD along with -MF.
165cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)      if (A->getValue(Args, 0) == llvm::StringRef("-MD"))
166cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
167cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)      else
1687d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
1697d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)      DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
1707d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)                          A->getValue(Args, 1));
171      continue;
172    }
173
174    // Rewrite reserved library names.
175    if (A->getOption().matches(options::OPT_l)) {
176      llvm::StringRef Value = A->getValue(Args);
177
178      // Rewrite unless -nostdlib is present.
179      if (!HasNostdlib && Value == "stdc++") {
180        DAL->AddFlagArg(A, Opts->getOption(
181                              options::OPT_Z_reserved_lib_stdcxx));
182        continue;
183      }
184
185      // Rewrite unconditionally.
186      if (Value == "cc_kext") {
187        DAL->AddFlagArg(A, Opts->getOption(
188                              options::OPT_Z_reserved_lib_cckext));
189        continue;
190      }
191    }
192
193    DAL->append(*it);
194  }
195
196  // Add a default value of -mlinker-version=, if one was given and the user
197  // didn't specify one.
198#if defined(HOST_LINK_VERSION)
199  if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
200    DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
201                      HOST_LINK_VERSION);
202    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
203  }
204#endif
205
206  return DAL;
207}
208
209Compilation *Driver::BuildCompilation(llvm::ArrayRef<const char *> ArgList) {
210  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
211
212  // FIXME: Handle environment options which effect driver behavior, somewhere
213  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
214  // CC_PRINT_OPTIONS.
215
216  // FIXME: What are we going to do with -V and -b?
217
218  // FIXME: This stuff needs to go into the Compilation, not the driver.
219  bool CCCPrintOptions = false, CCCPrintActions = false;
220
221  InputArgList *Args = ParseArgStrings(ArgList.slice(1));
222
223  // -no-canonical-prefixes is used very early in main.
224  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
225
226  // Ignore -pipe.
227  Args->ClaimAllArgs(options::OPT_pipe);
228
229  // Extract -ccc args.
230  //
231  // FIXME: We need to figure out where this behavior should live. Most of it
232  // should be outside in the client; the parts that aren't should have proper
233  // options, either by introducing new ones or by overloading gcc ones like -V
234  // or -b.
235  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
236  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
237  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
238  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
239  if (CCCIsCXX) {
240#ifdef IS_CYGWIN15
241    CCCGenericGCCName = "g++-4";
242#else
243    CCCGenericGCCName = "g++";
244#endif
245  }
246  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
247  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
248    CCCGenericGCCName = A->getValue(*Args);
249  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
250                                 options::OPT_ccc_no_clang_cxx,
251                                 CCCUseClangCXX);
252  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
253                            options::OPT_ccc_pch_is_pth);
254  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
255  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
256  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
257    llvm::StringRef Cur = A->getValue(*Args);
258
259    CCCClangArchs.clear();
260    while (!Cur.empty()) {
261      std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
262
263      if (!Split.first.empty()) {
264        llvm::Triple::ArchType Arch =
265          llvm::Triple(Split.first, "", "").getArch();
266
267        if (Arch == llvm::Triple::UnknownArch)
268          Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
269
270        CCCClangArchs.insert(Arch);
271      }
272
273      Cur = Split.second;
274    }
275  }
276  // FIXME: We shouldn't overwrite the default host triple here, but we have
277  // nowhere else to put this currently.
278  if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple))
279    DefaultHostTriple = A->getValue(*Args);
280  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
281    Dir = InstalledDir = A->getValue(*Args);
282  for (arg_iterator it = Args->filtered_begin(options::OPT_B),
283         ie = Args->filtered_end(); it != ie; ++it) {
284    const Arg *A = *it;
285    A->claim();
286    PrefixDirs.push_back(A->getValue(*Args, 0));
287  }
288  if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
289    SysRoot = A->getValue(*Args);
290  if (Args->hasArg(options::OPT_nostdlib))
291    UseStdLib = false;
292
293  Host = GetHostInfo(DefaultHostTriple.c_str());
294
295  // Perform the default argument translations.
296  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
297
298  // The compilation takes ownership of Args.
299  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args,
300                                   TranslatedArgs);
301
302  // FIXME: This behavior shouldn't be here.
303  if (CCCPrintOptions) {
304    PrintOptions(C->getInputArgs());
305    return C;
306  }
307
308  if (!HandleImmediateArgs(*C))
309    return C;
310
311  // Construct the list of abstract actions to perform for this compilation.
312  if (Host->useDriverDriver())
313    BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
314                          C->getActions());
315  else
316    BuildActions(C->getDefaultToolChain(), C->getArgs(), C->getActions());
317
318  if (CCCPrintActions) {
319    PrintActions(*C);
320    return C;
321  }
322
323  BuildJobs(*C);
324
325  return C;
326}
327
328int Driver::ExecuteCompilation(const Compilation &C) const {
329  // Just print if -### was present.
330  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
331    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
332    return 0;
333  }
334
335  // If there were errors building the compilation, quit now.
336  if (getDiags().hasErrorOccurred())
337    return 1;
338
339  const Command *FailingCommand = 0;
340  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
341
342  // Remove temp files.
343  C.CleanupFileList(C.getTempFiles());
344
345  // If the command succeeded, we are done.
346  if (Res == 0)
347    return Res;
348
349  // Otherwise, remove result files as well.
350  if (!C.getArgs().hasArg(options::OPT_save_temps))
351    C.CleanupFileList(C.getResultFiles(), true);
352
353  // Print extra information about abnormal failures, if possible.
354  //
355  // This is ad-hoc, but we don't want to be excessively noisy. If the result
356  // status was 1, assume the command failed normally. In particular, if it was
357  // the compiler then assume it gave a reasonable error code. Failures in other
358  // tools are less common, and they generally have worse diagnostics, so always
359  // print the diagnostic there.
360  const Tool &FailingTool = FailingCommand->getCreator();
361
362  if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
363    // FIXME: See FIXME above regarding result code interpretation.
364    if (Res < 0)
365      Diag(clang::diag::err_drv_command_signalled)
366        << FailingTool.getShortName() << -Res;
367    else
368      Diag(clang::diag::err_drv_command_failed)
369        << FailingTool.getShortName() << Res;
370  }
371
372  return Res;
373}
374
375void Driver::PrintOptions(const ArgList &Args) const {
376  unsigned i = 0;
377  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
378       it != ie; ++it, ++i) {
379    Arg *A = *it;
380    llvm::errs() << "Option " << i << " - "
381                 << "Name: \"" << A->getOption().getName() << "\", "
382                 << "Values: {";
383    for (unsigned j = 0; j < A->getNumValues(); ++j) {
384      if (j)
385        llvm::errs() << ", ";
386      llvm::errs() << '"' << A->getValue(Args, j) << '"';
387    }
388    llvm::errs() << "}\n";
389  }
390}
391
392void Driver::PrintHelp(bool ShowHidden) const {
393  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
394                      ShowHidden);
395}
396
397void Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
398  // FIXME: The following handlers should use a callback mechanism, we don't
399  // know what the client would like to do.
400  OS << getClangFullVersion() << '\n';
401  const ToolChain &TC = C.getDefaultToolChain();
402  OS << "Target: " << TC.getTripleString() << '\n';
403
404  // Print the threading model.
405  //
406  // FIXME: Implement correctly.
407  OS << "Thread model: " << "posix" << '\n';
408}
409
410/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
411/// option.
412static void PrintDiagnosticCategories(llvm::raw_ostream &OS) {
413  for (unsigned i = 1; // Skip the empty category.
414       const char *CategoryName = DiagnosticIDs::getCategoryNameFromID(i); ++i)
415    OS << i << ',' << CategoryName << '\n';
416}
417
418bool Driver::HandleImmediateArgs(const Compilation &C) {
419  // The order these options are handled in gcc is all over the place, but we
420  // don't expect inconsistencies w.r.t. that to matter in practice.
421
422  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
423    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
424    return false;
425  }
426
427  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
428    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
429    // return an answer which matches our definition of __VERSION__.
430    //
431    // If we want to return a more correct answer some day, then we should
432    // introduce a non-pedantically GCC compatible mode to Clang in which we
433    // provide sensible definitions for -dumpversion, __VERSION__, etc.
434    llvm::outs() << "4.2.1\n";
435    return false;
436  }
437
438  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
439    PrintDiagnosticCategories(llvm::outs());
440    return false;
441  }
442
443  if (C.getArgs().hasArg(options::OPT__help) ||
444      C.getArgs().hasArg(options::OPT__help_hidden)) {
445    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
446    return false;
447  }
448
449  if (C.getArgs().hasArg(options::OPT__version)) {
450    // Follow gcc behavior and use stdout for --version and stderr for -v.
451    PrintVersion(C, llvm::outs());
452    return false;
453  }
454
455  if (C.getArgs().hasArg(options::OPT_v) ||
456      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
457    PrintVersion(C, llvm::errs());
458    SuppressMissingInputWarning = true;
459  }
460
461  const ToolChain &TC = C.getDefaultToolChain();
462  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
463    llvm::outs() << "programs: =";
464    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
465           ie = TC.getProgramPaths().end(); it != ie; ++it) {
466      if (it != TC.getProgramPaths().begin())
467        llvm::outs() << ':';
468      llvm::outs() << *it;
469    }
470    llvm::outs() << "\n";
471    llvm::outs() << "libraries: =";
472    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
473           ie = TC.getFilePaths().end(); it != ie; ++it) {
474      if (it != TC.getFilePaths().begin())
475        llvm::outs() << ':';
476      llvm::outs() << *it;
477    }
478    llvm::outs() << "\n";
479    return false;
480  }
481
482  // FIXME: The following handlers should use a callback mechanism, we don't
483  // know what the client would like to do.
484  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
485    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
486    return false;
487  }
488
489  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
490    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
491    return false;
492  }
493
494  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
495    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
496    return false;
497  }
498
499  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
500    // FIXME: We need tool chain support for this.
501    llvm::outs() << ".;\n";
502
503    switch (C.getDefaultToolChain().getTriple().getArch()) {
504    default:
505      break;
506
507    case llvm::Triple::x86_64:
508      llvm::outs() << "x86_64;@m64" << "\n";
509      break;
510
511    case llvm::Triple::ppc64:
512      llvm::outs() << "ppc64;@m64" << "\n";
513      break;
514    }
515    return false;
516  }
517
518  // FIXME: What is the difference between print-multi-directory and
519  // print-multi-os-directory?
520  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
521      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
522    switch (C.getDefaultToolChain().getTriple().getArch()) {
523    default:
524    case llvm::Triple::x86:
525    case llvm::Triple::ppc:
526      llvm::outs() << "." << "\n";
527      break;
528
529    case llvm::Triple::x86_64:
530      llvm::outs() << "x86_64" << "\n";
531      break;
532
533    case llvm::Triple::ppc64:
534      llvm::outs() << "ppc64" << "\n";
535      break;
536    }
537    return false;
538  }
539
540  return true;
541}
542
543static unsigned PrintActions1(const Compilation &C, Action *A,
544                              std::map<Action*, unsigned> &Ids) {
545  if (Ids.count(A))
546    return Ids[A];
547
548  std::string str;
549  llvm::raw_string_ostream os(str);
550
551  os << Action::getClassName(A->getKind()) << ", ";
552  if (InputAction *IA = dyn_cast<InputAction>(A)) {
553    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
554  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
555    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
556                  C.getDefaultToolChain().getArchName()) << '"'
557       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
558  } else {
559    os << "{";
560    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
561      os << PrintActions1(C, *it, Ids);
562      ++it;
563      if (it != ie)
564        os << ", ";
565    }
566    os << "}";
567  }
568
569  unsigned Id = Ids.size();
570  Ids[A] = Id;
571  llvm::errs() << Id << ": " << os.str() << ", "
572               << types::getTypeName(A->getType()) << "\n";
573
574  return Id;
575}
576
577void Driver::PrintActions(const Compilation &C) const {
578  std::map<Action*, unsigned> Ids;
579  for (ActionList::const_iterator it = C.getActions().begin(),
580         ie = C.getActions().end(); it != ie; ++it)
581    PrintActions1(C, *it, Ids);
582}
583
584/// \brief Check whether the given input tree contains any compilation (or
585/// assembly) actions.
586static bool ContainsCompileAction(const Action *A) {
587  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
588    return true;
589
590  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
591    if (ContainsCompileAction(*it))
592      return true;
593
594  return false;
595}
596
597void Driver::BuildUniversalActions(const ToolChain &TC,
598                                   const DerivedArgList &Args,
599                                   ActionList &Actions) const {
600  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
601  // Collect the list of architectures. Duplicates are allowed, but should only
602  // be handled once (in the order seen).
603  llvm::StringSet<> ArchNames;
604  llvm::SmallVector<const char *, 4> Archs;
605  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
606       it != ie; ++it) {
607    Arg *A = *it;
608
609    if (A->getOption().matches(options::OPT_arch)) {
610      // Validate the option here; we don't save the type here because its
611      // particular spelling may participate in other driver choices.
612      llvm::Triple::ArchType Arch =
613        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
614      if (Arch == llvm::Triple::UnknownArch) {
615        Diag(clang::diag::err_drv_invalid_arch_name)
616          << A->getAsString(Args);
617        continue;
618      }
619
620      A->claim();
621      if (ArchNames.insert(A->getValue(Args)))
622        Archs.push_back(A->getValue(Args));
623    }
624  }
625
626  // When there is no explicit arch for this platform, make sure we still bind
627  // the architecture (to the default) so that -Xarch_ is handled correctly.
628  if (!Archs.size())
629    Archs.push_back(0);
630
631  // FIXME: We killed off some others but these aren't yet detected in a
632  // functional manner. If we added information to jobs about which "auxiliary"
633  // files they wrote then we could detect the conflict these cause downstream.
634  if (Archs.size() > 1) {
635    // No recovery needed, the point of this is just to prevent
636    // overwriting the same files.
637    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
638      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
639        << A->getAsString(Args);
640  }
641
642  ActionList SingleActions;
643  BuildActions(TC, Args, SingleActions);
644
645  // Add in arch bindings for every top level action, as well as lipo and
646  // dsymutil steps if needed.
647  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
648    Action *Act = SingleActions[i];
649
650    // Make sure we can lipo this kind of output. If not (and it is an actual
651    // output) then we disallow, since we can't create an output file with the
652    // right name without overwriting it. We could remove this oddity by just
653    // changing the output names to include the arch, which would also fix
654    // -save-temps. Compatibility wins for now.
655
656    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
657      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
658        << types::getTypeName(Act->getType());
659
660    ActionList Inputs;
661    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
662      Inputs.push_back(new BindArchAction(Act, Archs[i]));
663      if (i != 0)
664        Inputs.back()->setOwnsInputs(false);
665    }
666
667    // Lipo if necessary, we do it this way because we need to set the arch flag
668    // so that -Xarch_ gets overwritten.
669    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
670      Actions.append(Inputs.begin(), Inputs.end());
671    else
672      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
673
674    // Add a 'dsymutil' step if necessary, when debug info is enabled and we
675    // have a compile input. We need to run 'dsymutil' ourselves in such cases
676    // because the debug info will refer to a temporary object file which is
677    // will be removed at the end of the compilation process.
678    if (Act->getType() == types::TY_Image) {
679      Arg *A = Args.getLastArg(options::OPT_g_Group);
680      if (A && !A->getOption().matches(options::OPT_g0) &&
681          !A->getOption().matches(options::OPT_gstabs) &&
682          ContainsCompileAction(Actions.back())) {
683        ActionList Inputs;
684        Inputs.push_back(Actions.back());
685        Actions.pop_back();
686
687        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
688      }
689    }
690  }
691}
692
693void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
694                          ActionList &Actions) const {
695  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
696  // Start by constructing the list of inputs and their types.
697
698  // Track the current user specified (-x) input. We also explicitly track the
699  // argument used to set the type; we only want to claim the type when we
700  // actually use it, so we warn about unused -x arguments.
701  types::ID InputType = types::TY_Nothing;
702  Arg *InputTypeArg = 0;
703
704  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
705  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
706       it != ie; ++it) {
707    Arg *A = *it;
708
709    if (isa<InputOption>(A->getOption())) {
710      const char *Value = A->getValue(Args);
711      types::ID Ty = types::TY_INVALID;
712
713      // Infer the input type if necessary.
714      if (InputType == types::TY_Nothing) {
715        // If there was an explicit arg for this, claim it.
716        if (InputTypeArg)
717          InputTypeArg->claim();
718
719        // stdin must be handled specially.
720        if (memcmp(Value, "-", 2) == 0) {
721          // If running with -E, treat as a C input (this changes the builtin
722          // macros, for example). This may be overridden by -ObjC below.
723          //
724          // Otherwise emit an error but still use a valid type to avoid
725          // spurious errors (e.g., no inputs).
726          if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
727            Diag(clang::diag::err_drv_unknown_stdin_type);
728          Ty = types::TY_C;
729        } else {
730          // Otherwise lookup by extension.
731          // Fallback is C if invoked as C preprocessor or Object otherwise.
732          // We use a host hook here because Darwin at least has its own
733          // idea of what .s is.
734          if (const char *Ext = strrchr(Value, '.'))
735            Ty = TC.LookupTypeForExtension(Ext + 1);
736
737          if (Ty == types::TY_INVALID) {
738            if (CCCIsCPP)
739              Ty = types::TY_C;
740            else
741              Ty = types::TY_Object;
742          }
743
744          // If the driver is invoked as C++ compiler (like clang++ or c++) it
745          // should autodetect some input files as C++ for g++ compatibility.
746          if (CCCIsCXX) {
747            types::ID OldTy = Ty;
748            Ty = types::lookupCXXTypeForCType(Ty);
749
750            if (Ty != OldTy)
751              Diag(clang::diag::warn_drv_treating_input_as_cxx)
752                << getTypeName(OldTy) << getTypeName(Ty);
753          }
754        }
755
756        // -ObjC and -ObjC++ override the default language, but only for "source
757        // files". We just treat everything that isn't a linker input as a
758        // source file.
759        //
760        // FIXME: Clean this up if we move the phase sequence into the type.
761        if (Ty != types::TY_Object) {
762          if (Args.hasArg(options::OPT_ObjC))
763            Ty = types::TY_ObjC;
764          else if (Args.hasArg(options::OPT_ObjCXX))
765            Ty = types::TY_ObjCXX;
766        }
767      } else {
768        assert(InputTypeArg && "InputType set w/o InputTypeArg");
769        InputTypeArg->claim();
770        Ty = InputType;
771      }
772
773      // Check that the file exists, if enabled.
774      if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
775        llvm::SmallString<64> Path(Value);
776        if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory))
777          if (llvm::sys::path::is_absolute(Path.str())) {
778            Path = WorkDir->getValue(Args);
779            llvm::sys::path::append(Path, Value);
780          }
781
782        bool exists = false;
783        if (/*error_code ec =*/llvm::sys::fs::exists(Value, exists) || !exists)
784          Diag(clang::diag::err_drv_no_such_file) << Path.str();
785        else
786          Inputs.push_back(std::make_pair(Ty, A));
787      } else
788        Inputs.push_back(std::make_pair(Ty, A));
789
790    } else if (A->getOption().isLinkerInput()) {
791      // Just treat as object type, we could make a special type for this if
792      // necessary.
793      Inputs.push_back(std::make_pair(types::TY_Object, A));
794
795    } else if (A->getOption().matches(options::OPT_x)) {
796      InputTypeArg = A;
797      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
798
799      // Follow gcc behavior and treat as linker input for invalid -x
800      // options. Its not clear why we shouldn't just revert to unknown; but
801      // this isn't very important, we might as well be bug compatible.
802      if (!InputType) {
803        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
804        InputType = types::TY_Object;
805      }
806    }
807  }
808
809  if (CCCIsCPP && Inputs.empty()) {
810    // If called as standalone preprocessor, stdin is processed
811    // if no other input is present.
812    unsigned Index = Args.getBaseArgs().MakeIndex("-");
813    Arg *A = Opts->ParseOneArg(Args, Index);
814    A->claim();
815    Inputs.push_back(std::make_pair(types::TY_C, A));
816  }
817
818  if (!SuppressMissingInputWarning && Inputs.empty()) {
819    Diag(clang::diag::err_drv_no_input_files);
820    return;
821  }
822
823  // Determine which compilation mode we are in. We look for options which
824  // affect the phase, starting with the earliest phases, and record which
825  // option we used to determine the final phase.
826  Arg *FinalPhaseArg = 0;
827  phases::ID FinalPhase;
828
829  // -{E,M,MM} only run the preprocessor.
830  if (CCCIsCPP ||
831      (FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
832      (FinalPhaseArg = Args.getLastArg(options::OPT_M, options::OPT_MM))) {
833    FinalPhase = phases::Preprocess;
834
835    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
836  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
837             (FinalPhaseArg = Args.getLastArg(options::OPT_rewrite_objc)) ||
838             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
839                                              options::OPT__analyze_auto)) ||
840             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
841             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
842    FinalPhase = phases::Compile;
843
844    // -c only runs up to the assembler.
845  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
846    FinalPhase = phases::Assemble;
847
848    // Otherwise do everything.
849  } else
850    FinalPhase = phases::Link;
851
852  // Reject -Z* at the top level, these options should never have been exposed
853  // by gcc.
854  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
855    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
856
857  // Construct the actions to perform.
858  ActionList LinkerInputs;
859  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
860    types::ID InputType = Inputs[i].first;
861    const Arg *InputArg = Inputs[i].second;
862
863    unsigned NumSteps = types::getNumCompilationPhases(InputType);
864    assert(NumSteps && "Invalid number of steps!");
865
866    // If the first step comes after the final phase we are doing as part of
867    // this compilation, warn the user about it.
868    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
869    if (InitialPhase > FinalPhase) {
870      // Claim here to avoid the more general unused warning.
871      InputArg->claim();
872
873      // Special case '-E' warning on a previously preprocessed file to make
874      // more sense.
875      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
876          getPreprocessedType(InputType) == types::TY_INVALID)
877        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
878          << InputArg->getAsString(Args)
879          << FinalPhaseArg->getOption().getName();
880      else
881        Diag(clang::diag::warn_drv_input_file_unused)
882          << InputArg->getAsString(Args)
883          << getPhaseName(InitialPhase)
884          << FinalPhaseArg->getOption().getName();
885      continue;
886    }
887
888    // Build the pipeline for this file.
889    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
890    for (unsigned i = 0; i != NumSteps; ++i) {
891      phases::ID Phase = types::getCompilationPhase(InputType, i);
892
893      // We are done if this step is past what the user requested.
894      if (Phase > FinalPhase)
895        break;
896
897      // Queue linker inputs.
898      if (Phase == phases::Link) {
899        assert(i + 1 == NumSteps && "linking must be final compilation step.");
900        LinkerInputs.push_back(Current.take());
901        break;
902      }
903
904      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
905      // encode this in the steps because the intermediate type depends on
906      // arguments. Just special case here.
907      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
908        continue;
909
910      // Otherwise construct the appropriate action.
911      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
912      if (Current->getType() == types::TY_Nothing)
913        break;
914    }
915
916    // If we ended with something, add to the output list.
917    if (Current)
918      Actions.push_back(Current.take());
919  }
920
921  // Add a link action if necessary.
922  if (!LinkerInputs.empty())
923    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
924
925  // If we are linking, claim any options which are obviously only used for
926  // compilation.
927  if (FinalPhase == phases::Link)
928    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
929}
930
931Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
932                                     Action *Input) const {
933  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
934  // Build the appropriate action.
935  switch (Phase) {
936  case phases::Link: assert(0 && "link action invalid here.");
937  case phases::Preprocess: {
938    types::ID OutputTy;
939    // -{M, MM} alter the output type.
940    if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
941      OutputTy = types::TY_Dependencies;
942    } else {
943      OutputTy = types::getPreprocessedType(Input->getType());
944      assert(OutputTy != types::TY_INVALID &&
945             "Cannot preprocess this input type!");
946    }
947    return new PreprocessJobAction(Input, OutputTy);
948  }
949  case phases::Precompile:
950    return new PrecompileJobAction(Input, types::TY_PCH);
951  case phases::Compile: {
952    bool HasO4 = false;
953    if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
954      HasO4 = A->getOption().matches(options::OPT_O4);
955
956    if (Args.hasArg(options::OPT_fsyntax_only)) {
957      return new CompileJobAction(Input, types::TY_Nothing);
958    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
959      return new CompileJobAction(Input, types::TY_RewrittenObjC);
960    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
961      return new AnalyzeJobAction(Input, types::TY_Plist);
962    } else if (Args.hasArg(options::OPT_emit_ast)) {
963      return new CompileJobAction(Input, types::TY_AST);
964    } else if (Args.hasArg(options::OPT_emit_llvm) ||
965               Args.hasArg(options::OPT_flto) || HasO4) {
966      types::ID Output =
967        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
968      return new CompileJobAction(Input, Output);
969    } else {
970      return new CompileJobAction(Input, types::TY_PP_Asm);
971    }
972  }
973  case phases::Assemble:
974    return new AssembleJobAction(Input, types::TY_Object);
975  }
976
977  assert(0 && "invalid phase in ConstructPhaseAction");
978  return 0;
979}
980
981void Driver::BuildJobs(Compilation &C) const {
982  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
983
984  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
985
986  // It is an error to provide a -o option if we are making multiple output
987  // files.
988  if (FinalOutput) {
989    unsigned NumOutputs = 0;
990    for (ActionList::const_iterator it = C.getActions().begin(),
991           ie = C.getActions().end(); it != ie; ++it)
992      if ((*it)->getType() != types::TY_Nothing)
993        ++NumOutputs;
994
995    if (NumOutputs > 1) {
996      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
997      FinalOutput = 0;
998    }
999  }
1000
1001  for (ActionList::const_iterator it = C.getActions().begin(),
1002         ie = C.getActions().end(); it != ie; ++it) {
1003    Action *A = *it;
1004
1005    // If we are linking an image for multiple archs then the linker wants
1006    // -arch_multiple and -final_output <final image name>. Unfortunately, this
1007    // doesn't fit in cleanly because we have to pass this information down.
1008    //
1009    // FIXME: This is a hack; find a cleaner way to integrate this into the
1010    // process.
1011    const char *LinkingOutput = 0;
1012    if (isa<LipoJobAction>(A)) {
1013      if (FinalOutput)
1014        LinkingOutput = FinalOutput->getValue(C.getArgs());
1015      else
1016        LinkingOutput = DefaultImageName.c_str();
1017    }
1018
1019    InputInfo II;
1020    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1021                       /*BoundArch*/0,
1022                       /*AtTopLevel*/ true,
1023                       /*LinkingOutput*/ LinkingOutput,
1024                       II);
1025  }
1026
1027  // If the user passed -Qunused-arguments or there were errors, don't warn
1028  // about any unused arguments.
1029  if (Diags.hasErrorOccurred() ||
1030      C.getArgs().hasArg(options::OPT_Qunused_arguments))
1031    return;
1032
1033  // Claim -### here.
1034  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1035
1036  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1037       it != ie; ++it) {
1038    Arg *A = *it;
1039
1040    // FIXME: It would be nice to be able to send the argument to the
1041    // Diagnostic, so that extra values, position, and so on could be printed.
1042    if (!A->isClaimed()) {
1043      if (A->getOption().hasNoArgumentUnused())
1044        continue;
1045
1046      // Suppress the warning automatically if this is just a flag, and it is an
1047      // instance of an argument we already claimed.
1048      const Option &Opt = A->getOption();
1049      if (isa<FlagOption>(Opt)) {
1050        bool DuplicateClaimed = false;
1051
1052        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1053               ie = C.getArgs().filtered_end(); it != ie; ++it) {
1054          if ((*it)->isClaimed()) {
1055            DuplicateClaimed = true;
1056            break;
1057          }
1058        }
1059
1060        if (DuplicateClaimed)
1061          continue;
1062      }
1063
1064      Diag(clang::diag::warn_drv_unused_argument)
1065        << A->getAsString(C.getArgs());
1066    }
1067  }
1068}
1069
1070static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1071                                    const JobAction *JA,
1072                                    const ActionList *&Inputs) {
1073  const Tool *ToolForJob = 0;
1074
1075  // See if we should look for a compiler with an integrated assembler. We match
1076  // bottom up, so what we are actually looking for is an assembler job with a
1077  // compiler input.
1078
1079  // FIXME: This doesn't belong here, but ideally we will support static soon
1080  // anyway.
1081  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
1082                    C.getArgs().hasArg(options::OPT_static) ||
1083                    C.getArgs().hasArg(options::OPT_fapple_kext));
1084  bool IsDarwin = TC->getTriple().getOS() == llvm::Triple::Darwin;
1085  bool IsIADefault = TC->IsIntegratedAssemblerDefault() &&
1086    !(HasStatic && IsDarwin);
1087  if (C.getArgs().hasFlag(options::OPT_integrated_as,
1088                         options::OPT_no_integrated_as,
1089                         IsIADefault) &&
1090      !C.getArgs().hasArg(options::OPT_save_temps) &&
1091      isa<AssembleJobAction>(JA) &&
1092      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1093    const Tool &Compiler = TC->SelectTool(
1094      C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
1095    if (Compiler.hasIntegratedAssembler()) {
1096      Inputs = &(*Inputs)[0]->getInputs();
1097      ToolForJob = &Compiler;
1098    }
1099  }
1100
1101  // Otherwise use the tool for the current job.
1102  if (!ToolForJob)
1103    ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
1104
1105  // See if we should use an integrated preprocessor. We do so when we have
1106  // exactly one input, since this is the only use case we care about
1107  // (irrelevant since we don't support combine yet).
1108  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1109      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1110      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1111      !C.getArgs().hasArg(options::OPT_save_temps) &&
1112      ToolForJob->hasIntegratedCPP())
1113    Inputs = &(*Inputs)[0]->getInputs();
1114
1115  return *ToolForJob;
1116}
1117
1118void Driver::BuildJobsForAction(Compilation &C,
1119                                const Action *A,
1120                                const ToolChain *TC,
1121                                const char *BoundArch,
1122                                bool AtTopLevel,
1123                                const char *LinkingOutput,
1124                                InputInfo &Result) const {
1125  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1126
1127  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1128    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1129    // just using Args was better?
1130    const Arg &Input = IA->getInputArg();
1131    Input.claim();
1132    if (Input.getOption().matches(options::OPT_INPUT)) {
1133      const char *Name = Input.getValue(C.getArgs());
1134      Result = InputInfo(Name, A->getType(), Name);
1135    } else
1136      Result = InputInfo(&Input, A->getType(), "");
1137    return;
1138  }
1139
1140  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1141    const ToolChain *TC = &C.getDefaultToolChain();
1142
1143    std::string Arch;
1144    if (BAA->getArchName())
1145      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1146
1147    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1148                       AtTopLevel, LinkingOutput, Result);
1149    return;
1150  }
1151
1152  const ActionList *Inputs = &A->getInputs();
1153
1154  const JobAction *JA = cast<JobAction>(A);
1155  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1156
1157  // Only use pipes when there is exactly one input.
1158  InputInfoList InputInfos;
1159  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1160       it != ie; ++it) {
1161    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1162    // temporary output names.
1163    //
1164    // FIXME: Clean this up.
1165    bool SubJobAtTopLevel = false;
1166    if (AtTopLevel && isa<DsymutilJobAction>(A))
1167      SubJobAtTopLevel = true;
1168
1169    InputInfo II;
1170    BuildJobsForAction(C, *it, TC, BoundArch,
1171                       SubJobAtTopLevel, LinkingOutput, II);
1172    InputInfos.push_back(II);
1173  }
1174
1175  // Always use the first input as the base input.
1176  const char *BaseInput = InputInfos[0].getBaseInput();
1177
1178  // ... except dsymutil actions, which use their actual input as the base
1179  // input.
1180  if (JA->getType() == types::TY_dSYM)
1181    BaseInput = InputInfos[0].getFilename();
1182
1183  // Determine the place to write output to, if any.
1184  if (JA->getType() == types::TY_Nothing) {
1185    Result = InputInfo(A->getType(), BaseInput);
1186  } else {
1187    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1188                       A->getType(), BaseInput);
1189  }
1190
1191  if (CCCPrintBindings) {
1192    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1193                 << " - \"" << T.getName() << "\", inputs: [";
1194    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1195      llvm::errs() << InputInfos[i].getAsString();
1196      if (i + 1 != e)
1197        llvm::errs() << ", ";
1198    }
1199    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1200  } else {
1201    T.ConstructJob(C, *JA, Result, InputInfos,
1202                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1203  }
1204}
1205
1206const char *Driver::GetNamedOutputPath(Compilation &C,
1207                                       const JobAction &JA,
1208                                       const char *BaseInput,
1209                                       bool AtTopLevel) const {
1210  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1211  // Output to a user requested destination?
1212  if (AtTopLevel && !isa<DsymutilJobAction>(JA)) {
1213    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1214      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1215  }
1216
1217  // Default to writing to stdout?
1218  if (AtTopLevel && isa<PreprocessJobAction>(JA))
1219    return "-";
1220
1221  // Output to a temporary file?
1222  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1223    std::string TmpName =
1224      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1225    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1226  }
1227
1228  llvm::SmallString<128> BasePath(BaseInput);
1229  llvm::StringRef BaseName = llvm::sys::path::filename(BasePath);
1230
1231  // Determine what the derived output name should be.
1232  const char *NamedOutput;
1233  if (JA.getType() == types::TY_Image) {
1234    NamedOutput = DefaultImageName.c_str();
1235  } else {
1236    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1237    assert(Suffix && "All types used for output should have a suffix.");
1238
1239    std::string::size_type End = std::string::npos;
1240    if (!types::appendSuffixForType(JA.getType()))
1241      End = BaseName.rfind('.');
1242    std::string Suffixed(BaseName.substr(0, End));
1243    Suffixed += '.';
1244    Suffixed += Suffix;
1245    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1246  }
1247
1248  // As an annoying special case, PCH generation doesn't strip the pathname.
1249  if (JA.getType() == types::TY_PCH) {
1250    llvm::sys::path::remove_filename(BasePath);
1251    if (BasePath.empty())
1252      BasePath = NamedOutput;
1253    else
1254      llvm::sys::path::append(BasePath, NamedOutput);
1255    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1256  } else {
1257    return C.addResultFile(NamedOutput);
1258  }
1259}
1260
1261std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1262  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1263  // attempting to use this prefix when lokup up program paths.
1264  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1265       ie = PrefixDirs.end(); it != ie; ++it) {
1266    std::string Dir(*it);
1267    if (Dir.empty())
1268      continue;
1269    if (Dir[0] == '=')
1270      Dir = SysRoot + Dir.substr(1);
1271    llvm::sys::Path P(Dir);
1272    P.appendComponent(Name);
1273    bool Exists;
1274    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1275      return P.str();
1276  }
1277
1278  const ToolChain::path_list &List = TC.getFilePaths();
1279  for (ToolChain::path_list::const_iterator
1280         it = List.begin(), ie = List.end(); it != ie; ++it) {
1281    std::string Dir(*it);
1282    if (Dir.empty())
1283      continue;
1284    if (Dir[0] == '=')
1285      Dir = SysRoot + Dir.substr(1);
1286    llvm::sys::Path P(Dir);
1287    P.appendComponent(Name);
1288    bool Exists;
1289    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1290      return P.str();
1291  }
1292
1293  return Name;
1294}
1295
1296std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1297                                   bool WantFile) const {
1298  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1299  // attempting to use this prefix when lokup up program paths.
1300  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1301       ie = PrefixDirs.end(); it != ie; ++it) {
1302    llvm::sys::Path P(*it);
1303    P.appendComponent(Name);
1304    bool Exists;
1305    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1306                 : P.canExecute())
1307      return P.str();
1308  }
1309
1310  const ToolChain::path_list &List = TC.getProgramPaths();
1311  for (ToolChain::path_list::const_iterator
1312         it = List.begin(), ie = List.end(); it != ie; ++it) {
1313    llvm::sys::Path P(*it);
1314    P.appendComponent(Name);
1315    bool Exists;
1316    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1317                 : P.canExecute())
1318      return P.str();
1319  }
1320
1321  // If all else failed, search the path.
1322  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1323  if (!P.empty())
1324    return P.str();
1325
1326  return Name;
1327}
1328
1329std::string Driver::GetTemporaryPath(const char *Suffix) const {
1330  // FIXME: This is lame; sys::Path should provide this function (in particular,
1331  // it should know how to find the temporary files dir).
1332  std::string Error;
1333  const char *TmpDir = ::getenv("TMPDIR");
1334  if (!TmpDir)
1335    TmpDir = ::getenv("TEMP");
1336  if (!TmpDir)
1337    TmpDir = ::getenv("TMP");
1338  if (!TmpDir)
1339    TmpDir = "/tmp";
1340  llvm::sys::Path P(TmpDir);
1341  P.appendComponent("cc");
1342  if (P.makeUnique(false, &Error)) {
1343    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1344    return "";
1345  }
1346
1347  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1348  P.eraseFromDisk(false, 0);
1349
1350  P.appendSuffix(Suffix);
1351  return P.str();
1352}
1353
1354const HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1355  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1356  llvm::Triple Triple(llvm::Triple::normalize(TripleStr).c_str());
1357
1358  // TCE is an osless target
1359  if (Triple.getArchName() == "tce")
1360    return createTCEHostInfo(*this, Triple);
1361
1362  switch (Triple.getOS()) {
1363  case llvm::Triple::AuroraUX:
1364    return createAuroraUXHostInfo(*this, Triple);
1365  case llvm::Triple::Darwin:
1366    return createDarwinHostInfo(*this, Triple);
1367  case llvm::Triple::DragonFly:
1368    return createDragonFlyHostInfo(*this, Triple);
1369  case llvm::Triple::OpenBSD:
1370    return createOpenBSDHostInfo(*this, Triple);
1371  case llvm::Triple::NetBSD:
1372    return createNetBSDHostInfo(*this, Triple);
1373  case llvm::Triple::FreeBSD:
1374    return createFreeBSDHostInfo(*this, Triple);
1375  case llvm::Triple::Minix:
1376    return createMinixHostInfo(*this, Triple);
1377  case llvm::Triple::Linux:
1378    return createLinuxHostInfo(*this, Triple);
1379  case llvm::Triple::Win32:
1380    return createWindowsHostInfo(*this, Triple);
1381  case llvm::Triple::MinGW32:
1382    return createMinGWHostInfo(*this, Triple);
1383  default:
1384    return createUnknownHostInfo(*this, Triple);
1385  }
1386}
1387
1388bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1389                                    const llvm::Triple &Triple) const {
1390  // Check if user requested no clang, or clang doesn't understand this type (we
1391  // only handle single inputs for now).
1392  if (!CCCUseClang || JA.size() != 1 ||
1393      !types::isAcceptedByClang((*JA.begin())->getType()))
1394    return false;
1395
1396  // Otherwise make sure this is an action clang understands.
1397  if (isa<PreprocessJobAction>(JA)) {
1398    if (!CCCUseClangCPP) {
1399      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1400      return false;
1401    }
1402  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1403    return false;
1404
1405  // Use clang for C++?
1406  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1407    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1408    return false;
1409  }
1410
1411  // Always use clang for precompiling, AST generation, and rewriting,
1412  // regardless of archs.
1413  if (isa<PrecompileJobAction>(JA) ||
1414      types::isOnlyAcceptedByClang(JA.getType()))
1415    return true;
1416
1417  // Finally, don't use clang if this isn't one of the user specified archs to
1418  // build.
1419  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1420    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1421    return false;
1422  }
1423
1424  return true;
1425}
1426
1427/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1428/// grouped values as integers. Numbers which are not provided are set to 0.
1429///
1430/// \return True if the entire string was parsed (9.2), or all groups were
1431/// parsed (10.3.5extrastuff).
1432bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1433                               unsigned &Minor, unsigned &Micro,
1434                               bool &HadExtra) {
1435  HadExtra = false;
1436
1437  Major = Minor = Micro = 0;
1438  if (*Str == '\0')
1439    return true;
1440
1441  char *End;
1442  Major = (unsigned) strtol(Str, &End, 10);
1443  if (*Str != '\0' && *End == '\0')
1444    return true;
1445  if (*End != '.')
1446    return false;
1447
1448  Str = End+1;
1449  Minor = (unsigned) strtol(Str, &End, 10);
1450  if (*Str != '\0' && *End == '\0')
1451    return true;
1452  if (*End != '.')
1453    return false;
1454
1455  Str = End+1;
1456  Micro = (unsigned) strtol(Str, &End, 10);
1457  if (*Str != '\0' && *End == '\0')
1458    return true;
1459  if (Str == End)
1460    return false;
1461  HadExtra = true;
1462  return true;
1463}
1464