Home | History | Annotate | Download | only in Driver
      1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "clang/Driver/Driver.h"
     11 
     12 #include "clang/Driver/Action.h"
     13 #include "clang/Driver/Arg.h"
     14 #include "clang/Driver/ArgList.h"
     15 #include "clang/Driver/Compilation.h"
     16 #include "clang/Driver/DriverDiagnostic.h"
     17 #include "clang/Driver/Job.h"
     18 #include "clang/Driver/OptTable.h"
     19 #include "clang/Driver/Option.h"
     20 #include "clang/Driver/Options.h"
     21 #include "clang/Driver/Tool.h"
     22 #include "clang/Driver/ToolChain.h"
     23 
     24 #include "clang/Basic/Version.h"
     25 
     26 #include "llvm/ADT/ArrayRef.h"
     27 #include "llvm/ADT/StringSet.h"
     28 #include "llvm/ADT/OwningPtr.h"
     29 #include "llvm/Support/ErrorHandling.h"
     30 #include "llvm/Support/PrettyStackTrace.h"
     31 #include "llvm/Support/raw_ostream.h"
     32 #include "llvm/Support/FileSystem.h"
     33 #include "llvm/Support/Path.h"
     34 #include "llvm/Support/Program.h"
     35 
     36 #include "InputInfo.h"
     37 #include "ToolChains.h"
     38 
     39 #include <map>
     40 
     41 #include "clang/Config/config.h"
     42 
     43 using namespace clang::driver;
     44 using namespace clang;
     45 
     46 Driver::Driver(StringRef ClangExecutable,
     47                StringRef DefaultTargetTriple,
     48                StringRef DefaultImageName,
     49                bool IsProduction,
     50                DiagnosticsEngine &Diags)
     51   : Opts(createDriverOptTable()), Diags(Diags),
     52     ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
     53     UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
     54     DefaultImageName(DefaultImageName),
     55     DriverTitle("clang \"gcc-compatible\" driver"),
     56     CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
     57     CCLogDiagnosticsFilename(0), CCCIsCXX(false),
     58     CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
     59     CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
     60     CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
     61     CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true),
     62     CCCUsePCH(true), SuppressMissingInputWarning(false) {
     63   if (IsProduction) {
     64     // In a "production" build, only use clang on architectures we expect to
     65     // work.
     66     //
     67     // During development its more convenient to always have the driver use
     68     // clang, but we don't want users to be confused when things don't work, or
     69     // to file bugs for things we don't support.
     70     CCCClangArchs.insert(llvm::Triple::x86);
     71     CCCClangArchs.insert(llvm::Triple::x86_64);
     72     CCCClangArchs.insert(llvm::Triple::arm);
     73   }
     74 
     75   Name = llvm::sys::path::stem(ClangExecutable);
     76   Dir  = llvm::sys::path::parent_path(ClangExecutable);
     77 
     78   // Compute the path to the resource directory.
     79   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
     80   SmallString<128> P(Dir);
     81   if (ClangResourceDir != "")
     82     llvm::sys::path::append(P, ClangResourceDir);
     83   else
     84     llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
     85   ResourceDir = P.str();
     86 }
     87 
     88 Driver::~Driver() {
     89   delete Opts;
     90 
     91   for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(),
     92                                               E = ToolChains.end();
     93        I != E; ++I)
     94     delete I->second;
     95 }
     96 
     97 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
     98   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
     99   unsigned MissingArgIndex, MissingArgCount;
    100   InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
    101                                            MissingArgIndex, MissingArgCount);
    102 
    103   // Check for missing argument error.
    104   if (MissingArgCount)
    105     Diag(clang::diag::err_drv_missing_argument)
    106       << Args->getArgString(MissingArgIndex) << MissingArgCount;
    107 
    108   // Check for unsupported options.
    109   for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
    110        it != ie; ++it) {
    111     Arg *A = *it;
    112     if (A->getOption().isUnsupported()) {
    113       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
    114       continue;
    115     }
    116 
    117     // Warn about -mcpu= without an argument.
    118     if (A->getOption().matches(options::OPT_mcpu_EQ) &&
    119         A->containsValue("")) {
    120       Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(*Args);
    121     }
    122   }
    123 
    124   return Args;
    125 }
    126 
    127 // Determine which compilation mode we are in. We look for options which
    128 // affect the phase, starting with the earliest phases, and record which
    129 // option we used to determine the final phase.
    130 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
    131 const {
    132   Arg *PhaseArg = 0;
    133   phases::ID FinalPhase;
    134 
    135   // -{E,M,MM} only run the preprocessor.
    136   if (CCCIsCPP ||
    137       (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
    138       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
    139     FinalPhase = phases::Preprocess;
    140 
    141     // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
    142   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
    143              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
    144              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
    145              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
    146              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
    147                                         options::OPT__analyze_auto)) ||
    148              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
    149              (PhaseArg = DAL.getLastArg(options::OPT_S))) {
    150     FinalPhase = phases::Compile;
    151 
    152     // -c only runs up to the assembler.
    153   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
    154     FinalPhase = phases::Assemble;
    155 
    156     // Otherwise do everything.
    157   } else
    158     FinalPhase = phases::Link;
    159 
    160   if (FinalPhaseArg)
    161     *FinalPhaseArg = PhaseArg;
    162 
    163   return FinalPhase;
    164 }
    165 
    166 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
    167   DerivedArgList *DAL = new DerivedArgList(Args);
    168 
    169   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
    170   for (ArgList::const_iterator it = Args.begin(),
    171          ie = Args.end(); it != ie; ++it) {
    172     const Arg *A = *it;
    173 
    174     // Unfortunately, we have to parse some forwarding options (-Xassembler,
    175     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
    176     // (assembler and preprocessor), or bypass a previous driver ('collect2').
    177 
    178     // Rewrite linker options, to replace --no-demangle with a custom internal
    179     // option.
    180     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
    181          A->getOption().matches(options::OPT_Xlinker)) &&
    182         A->containsValue("--no-demangle")) {
    183       // Add the rewritten no-demangle argument.
    184       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
    185 
    186       // Add the remaining values as Xlinker arguments.
    187       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
    188         if (StringRef(A->getValue(Args, i)) != "--no-demangle")
    189           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
    190                               A->getValue(Args, i));
    191 
    192       continue;
    193     }
    194 
    195     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
    196     // some build systems. We don't try to be complete here because we don't
    197     // care to encourage this usage model.
    198     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
    199         A->getNumValues() == 2 &&
    200         (A->getValue(Args, 0) == StringRef("-MD") ||
    201          A->getValue(Args, 0) == StringRef("-MMD"))) {
    202       // Rewrite to -MD/-MMD along with -MF.
    203       if (A->getValue(Args, 0) == StringRef("-MD"))
    204         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
    205       else
    206         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
    207       DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
    208                           A->getValue(Args, 1));
    209       continue;
    210     }
    211 
    212     // Rewrite reserved library names.
    213     if (A->getOption().matches(options::OPT_l)) {
    214       StringRef Value = A->getValue(Args);
    215 
    216       // Rewrite unless -nostdlib is present.
    217       if (!HasNostdlib && Value == "stdc++") {
    218         DAL->AddFlagArg(A, Opts->getOption(
    219                               options::OPT_Z_reserved_lib_stdcxx));
    220         continue;
    221       }
    222 
    223       // Rewrite unconditionally.
    224       if (Value == "cc_kext") {
    225         DAL->AddFlagArg(A, Opts->getOption(
    226                               options::OPT_Z_reserved_lib_cckext));
    227         continue;
    228       }
    229     }
    230 
    231     DAL->append(*it);
    232   }
    233 
    234   // Add a default value of -mlinker-version=, if one was given and the user
    235   // didn't specify one.
    236 #if defined(HOST_LINK_VERSION)
    237   if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
    238     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
    239                       HOST_LINK_VERSION);
    240     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
    241   }
    242 #endif
    243 
    244   return DAL;
    245 }
    246 
    247 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
    248   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
    249 
    250   // FIXME: Handle environment options which affect driver behavior, somewhere
    251   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
    252 
    253   if (char *env = ::getenv("COMPILER_PATH")) {
    254     StringRef CompilerPath = env;
    255     while (!CompilerPath.empty()) {
    256       std::pair<StringRef, StringRef> Split = CompilerPath.split(':');
    257       PrefixDirs.push_back(Split.first);
    258       CompilerPath = Split.second;
    259     }
    260   }
    261 
    262   // FIXME: What are we going to do with -V and -b?
    263 
    264   // FIXME: This stuff needs to go into the Compilation, not the driver.
    265   bool CCCPrintOptions = false, CCCPrintActions = false;
    266 
    267   InputArgList *Args = ParseArgStrings(ArgList.slice(1));
    268 
    269   // -no-canonical-prefixes is used very early in main.
    270   Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
    271 
    272   // Ignore -pipe.
    273   Args->ClaimAllArgs(options::OPT_pipe);
    274 
    275   // Extract -ccc args.
    276   //
    277   // FIXME: We need to figure out where this behavior should live. Most of it
    278   // should be outside in the client; the parts that aren't should have proper
    279   // options, either by introducing new ones or by overloading gcc ones like -V
    280   // or -b.
    281   CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
    282   CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
    283   CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
    284   CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
    285   CCCEcho = Args->hasArg(options::OPT_ccc_echo);
    286   if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
    287     CCCGenericGCCName = A->getValue(*Args);
    288   CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
    289                                  options::OPT_ccc_no_clang_cxx,
    290                                  CCCUseClangCXX);
    291   CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
    292                             options::OPT_ccc_pch_is_pth);
    293   CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
    294   CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
    295   if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
    296     StringRef Cur = A->getValue(*Args);
    297 
    298     CCCClangArchs.clear();
    299     while (!Cur.empty()) {
    300       std::pair<StringRef, StringRef> Split = Cur.split(',');
    301 
    302       if (!Split.first.empty()) {
    303         llvm::Triple::ArchType Arch =
    304           llvm::Triple(Split.first, "", "").getArch();
    305 
    306         if (Arch == llvm::Triple::UnknownArch)
    307           Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
    308 
    309         CCCClangArchs.insert(Arch);
    310       }
    311 
    312       Cur = Split.second;
    313     }
    314   }
    315   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
    316   // and getToolChain is const.
    317   if (const Arg *A = Args->getLastArg(options::OPT_target))
    318     DefaultTargetTriple = A->getValue(*Args);
    319   if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
    320     Dir = InstalledDir = A->getValue(*Args);
    321   for (arg_iterator it = Args->filtered_begin(options::OPT_B),
    322          ie = Args->filtered_end(); it != ie; ++it) {
    323     const Arg *A = *it;
    324     A->claim();
    325     PrefixDirs.push_back(A->getValue(*Args, 0));
    326   }
    327   if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
    328     SysRoot = A->getValue(*Args);
    329   if (Args->hasArg(options::OPT_nostdlib))
    330     UseStdLib = false;
    331 
    332   // Perform the default argument translations.
    333   DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
    334 
    335   // Owned by the host.
    336   const ToolChain &TC = getToolChain(*Args);
    337 
    338   // The compilation takes ownership of Args.
    339   Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
    340 
    341   // FIXME: This behavior shouldn't be here.
    342   if (CCCPrintOptions) {
    343     PrintOptions(C->getInputArgs());
    344     return C;
    345   }
    346 
    347   if (!HandleImmediateArgs(*C))
    348     return C;
    349 
    350   // Construct the list of inputs.
    351   InputList Inputs;
    352   BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
    353 
    354   // Construct the list of abstract actions to perform for this compilation. On
    355   // Darwin target OSes this uses the driver-driver and universal actions.
    356   if (TC.getTriple().isOSDarwin())
    357     BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
    358                           Inputs, C->getActions());
    359   else
    360     BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
    361                  C->getActions());
    362 
    363   if (CCCPrintActions) {
    364     PrintActions(*C);
    365     return C;
    366   }
    367 
    368   BuildJobs(*C);
    369 
    370   return C;
    371 }
    372 
    373 // When clang crashes, produce diagnostic information including the fully
    374 // preprocessed source file(s).  Request that the developer attach the
    375 // diagnostic information to a bug report.
    376 void Driver::generateCompilationDiagnostics(Compilation &C,
    377                                             const Command *FailingCommand) {
    378   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
    379     return;
    380 
    381   // Don't try to generate diagnostics for link jobs.
    382   if (FailingCommand->getCreator().isLinkJob())
    383     return;
    384 
    385   Diag(clang::diag::note_drv_command_failed_diag_msg)
    386     << "Please submit a bug report to " BUG_REPORT_URL " and include command"
    387     " line arguments and all diagnostic information.";
    388 
    389   // Suppress driver output and emit preprocessor output to temp file.
    390   CCCIsCPP = true;
    391   CCGenDiagnostics = true;
    392 
    393   // Save the original job command(s).
    394   std::string Cmd;
    395   llvm::raw_string_ostream OS(Cmd);
    396   C.PrintJob(OS, C.getJobs(), "\n", false);
    397   OS.flush();
    398 
    399   // Clear stale state and suppress tool output.
    400   C.initCompilationForDiagnostics();
    401   Diags.Reset();
    402 
    403   // Construct the list of inputs.
    404   InputList Inputs;
    405   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
    406 
    407   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
    408     bool IgnoreInput = false;
    409 
    410     // Ignore input from stdin or any inputs that cannot be preprocessed.
    411     if (!strcmp(it->second->getValue(C.getArgs()), "-")) {
    412       Diag(clang::diag::note_drv_command_failed_diag_msg)
    413         << "Error generating preprocessed source(s) - ignoring input from stdin"
    414         ".";
    415       IgnoreInput = true;
    416     } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
    417       IgnoreInput = true;
    418     }
    419 
    420     if (IgnoreInput) {
    421       it = Inputs.erase(it);
    422       ie = Inputs.end();
    423     } else {
    424       ++it;
    425     }
    426   }
    427 
    428   // Don't attempt to generate preprocessed files if multiple -arch options are
    429   // used, unless they're all duplicates.
    430   llvm::StringSet<> ArchNames;
    431   for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
    432        it != ie; ++it) {
    433     Arg *A = *it;
    434     if (A->getOption().matches(options::OPT_arch)) {
    435       StringRef ArchName = A->getValue(C.getArgs());
    436       ArchNames.insert(ArchName);
    437     }
    438   }
    439   if (ArchNames.size() > 1) {
    440     Diag(clang::diag::note_drv_command_failed_diag_msg)
    441       << "Error generating preprocessed source(s) - cannot generate "
    442       "preprocessed source with multiple -arch options.";
    443     return;
    444   }
    445 
    446   if (Inputs.empty()) {
    447     Diag(clang::diag::note_drv_command_failed_diag_msg)
    448       << "Error generating preprocessed source(s) - no preprocessable inputs.";
    449     return;
    450   }
    451 
    452   // Construct the list of abstract actions to perform for this compilation. On
    453   // Darwin OSes this uses the driver-driver and builds universal actions.
    454   const ToolChain &TC = C.getDefaultToolChain();
    455   if (TC.getTriple().isOSDarwin())
    456     BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
    457   else
    458     BuildActions(TC, C.getArgs(), Inputs, C.getActions());
    459 
    460   BuildJobs(C);
    461 
    462   // If there were errors building the compilation, quit now.
    463   if (Diags.hasErrorOccurred()) {
    464     Diag(clang::diag::note_drv_command_failed_diag_msg)
    465       << "Error generating preprocessed source(s).";
    466     return;
    467   }
    468 
    469   // Generate preprocessed output.
    470   FailingCommand = 0;
    471   int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
    472 
    473   // If the command succeeded, we are done.
    474   if (Res == 0) {
    475     Diag(clang::diag::note_drv_command_failed_diag_msg)
    476       << "Preprocessed source(s) and associated run script(s) are located at:";
    477     ArgStringList Files = C.getTempFiles();
    478     for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
    479          it != ie; ++it) {
    480       Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
    481 
    482       std::string Err;
    483       std::string Script = StringRef(*it).rsplit('.').first;
    484       Script += ".sh";
    485       llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
    486                                     llvm::raw_fd_ostream::F_Excl |
    487                                     llvm::raw_fd_ostream::F_Binary);
    488       if (!Err.empty()) {
    489         Diag(clang::diag::note_drv_command_failed_diag_msg)
    490           << "Error generating run script: " + Script + " " + Err;
    491       } else {
    492         ScriptOS << Cmd;
    493         Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
    494       }
    495     }
    496   } else {
    497     // Failure, remove preprocessed files.
    498     if (!C.getArgs().hasArg(options::OPT_save_temps))
    499       C.CleanupFileList(C.getTempFiles(), true);
    500 
    501     Diag(clang::diag::note_drv_command_failed_diag_msg)
    502       << "Error generating preprocessed source(s).";
    503   }
    504 }
    505 
    506 int Driver::ExecuteCompilation(const Compilation &C,
    507                                const Command *&FailingCommand) const {
    508   // Just print if -### was present.
    509   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
    510     C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
    511     return 0;
    512   }
    513 
    514   // If there were errors building the compilation, quit now.
    515   if (Diags.hasErrorOccurred())
    516     return 1;
    517 
    518   int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
    519 
    520   // Remove temp files.
    521   C.CleanupFileList(C.getTempFiles());
    522 
    523   // If the command succeeded, we are done.
    524   if (Res == 0)
    525     return Res;
    526 
    527   // Otherwise, remove result files as well.
    528   if (!C.getArgs().hasArg(options::OPT_save_temps)) {
    529     C.CleanupFileList(C.getResultFiles(), true);
    530 
    531     // Failure result files are valid unless we crashed.
    532     if (Res < 0) {
    533       C.CleanupFileList(C.getFailureResultFiles(), true);
    534 #ifdef _WIN32
    535       // Exit status should not be negative on Win32,
    536       // unless abnormal termination.
    537       Res = 1;
    538 #endif
    539     }
    540   }
    541 
    542   // Print extra information about abnormal failures, if possible.
    543   //
    544   // This is ad-hoc, but we don't want to be excessively noisy. If the result
    545   // status was 1, assume the command failed normally. In particular, if it was
    546   // the compiler then assume it gave a reasonable error code. Failures in other
    547   // tools are less common, and they generally have worse diagnostics, so always
    548   // print the diagnostic there.
    549   const Tool &FailingTool = FailingCommand->getCreator();
    550 
    551   if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
    552     // FIXME: See FIXME above regarding result code interpretation.
    553     if (Res < 0)
    554       Diag(clang::diag::err_drv_command_signalled)
    555         << FailingTool.getShortName();
    556     else
    557       Diag(clang::diag::err_drv_command_failed)
    558         << FailingTool.getShortName() << Res;
    559   }
    560 
    561   return Res;
    562 }
    563 
    564 void Driver::PrintOptions(const ArgList &Args) const {
    565   unsigned i = 0;
    566   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
    567        it != ie; ++it, ++i) {
    568     Arg *A = *it;
    569     llvm::errs() << "Option " << i << " - "
    570                  << "Name: \"" << A->getOption().getName() << "\", "
    571                  << "Values: {";
    572     for (unsigned j = 0; j < A->getNumValues(); ++j) {
    573       if (j)
    574         llvm::errs() << ", ";
    575       llvm::errs() << '"' << A->getValue(Args, j) << '"';
    576     }
    577     llvm::errs() << "}\n";
    578   }
    579 }
    580 
    581 void Driver::PrintHelp(bool ShowHidden) const {
    582   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
    583                       ShowHidden);
    584 }
    585 
    586 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
    587   // FIXME: The following handlers should use a callback mechanism, we don't
    588   // know what the client would like to do.
    589   OS << getClangFullVersion() << '\n';
    590   const ToolChain &TC = C.getDefaultToolChain();
    591   OS << "Target: " << TC.getTripleString() << '\n';
    592 
    593   // Print the threading model.
    594   //
    595   // FIXME: Implement correctly.
    596   OS << "Thread model: " << "posix" << '\n';
    597 }
    598 
    599 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
    600 /// option.
    601 static void PrintDiagnosticCategories(raw_ostream &OS) {
    602   // Skip the empty category.
    603   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
    604        i != max; ++i)
    605     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
    606 }
    607 
    608 bool Driver::HandleImmediateArgs(const Compilation &C) {
    609   // The order these options are handled in gcc is all over the place, but we
    610   // don't expect inconsistencies w.r.t. that to matter in practice.
    611 
    612   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
    613     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
    614     return false;
    615   }
    616 
    617   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
    618     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
    619     // return an answer which matches our definition of __VERSION__.
    620     //
    621     // If we want to return a more correct answer some day, then we should
    622     // introduce a non-pedantically GCC compatible mode to Clang in which we
    623     // provide sensible definitions for -dumpversion, __VERSION__, etc.
    624     llvm::outs() << "4.2.1\n";
    625     return false;
    626   }
    627 
    628   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
    629     PrintDiagnosticCategories(llvm::outs());
    630     return false;
    631   }
    632 
    633   if (C.getArgs().hasArg(options::OPT__help) ||
    634       C.getArgs().hasArg(options::OPT__help_hidden)) {
    635     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
    636     return false;
    637   }
    638 
    639   if (C.getArgs().hasArg(options::OPT__version)) {
    640     // Follow gcc behavior and use stdout for --version and stderr for -v.
    641     PrintVersion(C, llvm::outs());
    642     return false;
    643   }
    644 
    645   if (C.getArgs().hasArg(options::OPT_v) ||
    646       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
    647     PrintVersion(C, llvm::errs());
    648     SuppressMissingInputWarning = true;
    649   }
    650 
    651   const ToolChain &TC = C.getDefaultToolChain();
    652   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
    653     llvm::outs() << "programs: =";
    654     for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
    655            ie = TC.getProgramPaths().end(); it != ie; ++it) {
    656       if (it != TC.getProgramPaths().begin())
    657         llvm::outs() << ':';
    658       llvm::outs() << *it;
    659     }
    660     llvm::outs() << "\n";
    661     llvm::outs() << "libraries: =" << ResourceDir;
    662 
    663     StringRef sysroot = C.getSysRoot();
    664 
    665     for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
    666            ie = TC.getFilePaths().end(); it != ie; ++it) {
    667       llvm::outs() << ':';
    668       const char *path = it->c_str();
    669       if (path[0] == '=')
    670         llvm::outs() << sysroot << path + 1;
    671       else
    672         llvm::outs() << path;
    673     }
    674     llvm::outs() << "\n";
    675     return false;
    676   }
    677 
    678   // FIXME: The following handlers should use a callback mechanism, we don't
    679   // know what the client would like to do.
    680   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
    681     llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
    682     return false;
    683   }
    684 
    685   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
    686     llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
    687     return false;
    688   }
    689 
    690   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
    691     llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
    692     return false;
    693   }
    694 
    695   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
    696     // FIXME: We need tool chain support for this.
    697     llvm::outs() << ".;\n";
    698 
    699     switch (C.getDefaultToolChain().getTriple().getArch()) {
    700     default:
    701       break;
    702 
    703     case llvm::Triple::x86_64:
    704       llvm::outs() << "x86_64;@m64" << "\n";
    705       break;
    706 
    707     case llvm::Triple::ppc64:
    708       llvm::outs() << "ppc64;@m64" << "\n";
    709       break;
    710     }
    711     return false;
    712   }
    713 
    714   // FIXME: What is the difference between print-multi-directory and
    715   // print-multi-os-directory?
    716   if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
    717       C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
    718     switch (C.getDefaultToolChain().getTriple().getArch()) {
    719     default:
    720     case llvm::Triple::x86:
    721     case llvm::Triple::ppc:
    722       llvm::outs() << "." << "\n";
    723       break;
    724 
    725     case llvm::Triple::x86_64:
    726       llvm::outs() << "x86_64" << "\n";
    727       break;
    728 
    729     case llvm::Triple::ppc64:
    730       llvm::outs() << "ppc64" << "\n";
    731       break;
    732     }
    733     return false;
    734   }
    735 
    736   return true;
    737 }
    738 
    739 static unsigned PrintActions1(const Compilation &C, Action *A,
    740                               std::map<Action*, unsigned> &Ids) {
    741   if (Ids.count(A))
    742     return Ids[A];
    743 
    744   std::string str;
    745   llvm::raw_string_ostream os(str);
    746 
    747   os << Action::getClassName(A->getKind()) << ", ";
    748   if (InputAction *IA = dyn_cast<InputAction>(A)) {
    749     os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
    750   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
    751     os << '"' << (BIA->getArchName() ? BIA->getArchName() :
    752                   C.getDefaultToolChain().getArchName()) << '"'
    753        << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
    754   } else {
    755     os << "{";
    756     for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
    757       os << PrintActions1(C, *it, Ids);
    758       ++it;
    759       if (it != ie)
    760         os << ", ";
    761     }
    762     os << "}";
    763   }
    764 
    765   unsigned Id = Ids.size();
    766   Ids[A] = Id;
    767   llvm::errs() << Id << ": " << os.str() << ", "
    768                << types::getTypeName(A->getType()) << "\n";
    769 
    770   return Id;
    771 }
    772 
    773 void Driver::PrintActions(const Compilation &C) const {
    774   std::map<Action*, unsigned> Ids;
    775   for (ActionList::const_iterator it = C.getActions().begin(),
    776          ie = C.getActions().end(); it != ie; ++it)
    777     PrintActions1(C, *it, Ids);
    778 }
    779 
    780 /// \brief Check whether the given input tree contains any compilation or
    781 /// assembly actions.
    782 static bool ContainsCompileOrAssembleAction(const Action *A) {
    783   if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
    784     return true;
    785 
    786   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
    787     if (ContainsCompileOrAssembleAction(*it))
    788       return true;
    789 
    790   return false;
    791 }
    792 
    793 void Driver::BuildUniversalActions(const ToolChain &TC,
    794                                    const DerivedArgList &Args,
    795                                    const InputList &BAInputs,
    796                                    ActionList &Actions) const {
    797   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
    798   // Collect the list of architectures. Duplicates are allowed, but should only
    799   // be handled once (in the order seen).
    800   llvm::StringSet<> ArchNames;
    801   SmallVector<const char *, 4> Archs;
    802   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
    803        it != ie; ++it) {
    804     Arg *A = *it;
    805 
    806     if (A->getOption().matches(options::OPT_arch)) {
    807       // Validate the option here; we don't save the type here because its
    808       // particular spelling may participate in other driver choices.
    809       llvm::Triple::ArchType Arch =
    810         llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
    811       if (Arch == llvm::Triple::UnknownArch) {
    812         Diag(clang::diag::err_drv_invalid_arch_name)
    813           << A->getAsString(Args);
    814         continue;
    815       }
    816 
    817       A->claim();
    818       if (ArchNames.insert(A->getValue(Args)))
    819         Archs.push_back(A->getValue(Args));
    820     }
    821   }
    822 
    823   // When there is no explicit arch for this platform, make sure we still bind
    824   // the architecture (to the default) so that -Xarch_ is handled correctly.
    825   if (!Archs.size())
    826     Archs.push_back(0);
    827 
    828   // FIXME: We killed off some others but these aren't yet detected in a
    829   // functional manner. If we added information to jobs about which "auxiliary"
    830   // files they wrote then we could detect the conflict these cause downstream.
    831   if (Archs.size() > 1) {
    832     // No recovery needed, the point of this is just to prevent
    833     // overwriting the same files.
    834     if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
    835       Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
    836         << A->getAsString(Args);
    837   }
    838 
    839   ActionList SingleActions;
    840   BuildActions(TC, Args, BAInputs, SingleActions);
    841 
    842   // Add in arch bindings for every top level action, as well as lipo and
    843   // dsymutil steps if needed.
    844   for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
    845     Action *Act = SingleActions[i];
    846 
    847     // Make sure we can lipo this kind of output. If not (and it is an actual
    848     // output) then we disallow, since we can't create an output file with the
    849     // right name without overwriting it. We could remove this oddity by just
    850     // changing the output names to include the arch, which would also fix
    851     // -save-temps. Compatibility wins for now.
    852 
    853     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
    854       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
    855         << types::getTypeName(Act->getType());
    856 
    857     ActionList Inputs;
    858     for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
    859       Inputs.push_back(new BindArchAction(Act, Archs[i]));
    860       if (i != 0)
    861         Inputs.back()->setOwnsInputs(false);
    862     }
    863 
    864     // Lipo if necessary, we do it this way because we need to set the arch flag
    865     // so that -Xarch_ gets overwritten.
    866     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
    867       Actions.append(Inputs.begin(), Inputs.end());
    868     else
    869       Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
    870 
    871     // Handle debug info queries.
    872     Arg *A = Args.getLastArg(options::OPT_g_Group);
    873     if (A && !A->getOption().matches(options::OPT_g0) &&
    874         !A->getOption().matches(options::OPT_gstabs) &&
    875         ContainsCompileOrAssembleAction(Actions.back())) {
    876 
    877       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
    878       // have a compile input. We need to run 'dsymutil' ourselves in such cases
    879       // because the debug info will refer to a temporary object file which is
    880       // will be removed at the end of the compilation process.
    881       if (Act->getType() == types::TY_Image) {
    882         ActionList Inputs;
    883         Inputs.push_back(Actions.back());
    884         Actions.pop_back();
    885         Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
    886       }
    887 
    888       // Verify the output (debug information only) if we passed '-verify'.
    889       if (Args.hasArg(options::OPT_verify)) {
    890         ActionList VerifyInputs;
    891         VerifyInputs.push_back(Actions.back());
    892         Actions.pop_back();
    893         Actions.push_back(new VerifyJobAction(VerifyInputs,
    894                                               types::TY_Nothing));
    895       }
    896     }
    897   }
    898 }
    899 
    900 // Construct a the list of inputs and their types.
    901 void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
    902                          InputList &Inputs) const {
    903   // Track the current user specified (-x) input. We also explicitly track the
    904   // argument used to set the type; we only want to claim the type when we
    905   // actually use it, so we warn about unused -x arguments.
    906   types::ID InputType = types::TY_Nothing;
    907   Arg *InputTypeArg = 0;
    908 
    909   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
    910        it != ie; ++it) {
    911     Arg *A = *it;
    912 
    913     if (isa<InputOption>(A->getOption())) {
    914       const char *Value = A->getValue(Args);
    915       types::ID Ty = types::TY_INVALID;
    916 
    917       // Infer the input type if necessary.
    918       if (InputType == types::TY_Nothing) {
    919         // If there was an explicit arg for this, claim it.
    920         if (InputTypeArg)
    921           InputTypeArg->claim();
    922 
    923         // stdin must be handled specially.
    924         if (memcmp(Value, "-", 2) == 0) {
    925           // If running with -E, treat as a C input (this changes the builtin
    926           // macros, for example). This may be overridden by -ObjC below.
    927           //
    928           // Otherwise emit an error but still use a valid type to avoid
    929           // spurious errors (e.g., no inputs).
    930           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
    931             Diag(clang::diag::err_drv_unknown_stdin_type);
    932           Ty = types::TY_C;
    933         } else {
    934           // Otherwise lookup by extension.
    935           // Fallback is C if invoked as C preprocessor or Object otherwise.
    936           // We use a host hook here because Darwin at least has its own
    937           // idea of what .s is.
    938           if (const char *Ext = strrchr(Value, '.'))
    939             Ty = TC.LookupTypeForExtension(Ext + 1);
    940 
    941           if (Ty == types::TY_INVALID) {
    942             if (CCCIsCPP)
    943               Ty = types::TY_C;
    944             else
    945               Ty = types::TY_Object;
    946           }
    947 
    948           // If the driver is invoked as C++ compiler (like clang++ or c++) it
    949           // should autodetect some input files as C++ for g++ compatibility.
    950           if (CCCIsCXX) {
    951             types::ID OldTy = Ty;
    952             Ty = types::lookupCXXTypeForCType(Ty);
    953 
    954             if (Ty != OldTy)
    955               Diag(clang::diag::warn_drv_treating_input_as_cxx)
    956                 << getTypeName(OldTy) << getTypeName(Ty);
    957           }
    958         }
    959 
    960         // -ObjC and -ObjC++ override the default language, but only for "source
    961         // files". We just treat everything that isn't a linker input as a
    962         // source file.
    963         //
    964         // FIXME: Clean this up if we move the phase sequence into the type.
    965         if (Ty != types::TY_Object) {
    966           if (Args.hasArg(options::OPT_ObjC))
    967             Ty = types::TY_ObjC;
    968           else if (Args.hasArg(options::OPT_ObjCXX))
    969             Ty = types::TY_ObjCXX;
    970         }
    971       } else {
    972         assert(InputTypeArg && "InputType set w/o InputTypeArg");
    973         InputTypeArg->claim();
    974         Ty = InputType;
    975       }
    976 
    977       // Check that the file exists, if enabled.
    978       if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
    979         SmallString<64> Path(Value);
    980         if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
    981           SmallString<64> Directory(WorkDir->getValue(Args));
    982           if (llvm::sys::path::is_absolute(Directory.str())) {
    983             llvm::sys::path::append(Directory, Value);
    984             Path.assign(Directory);
    985           }
    986         }
    987 
    988         bool exists = false;
    989         if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
    990           Diag(clang::diag::err_drv_no_such_file) << Path.str();
    991         else
    992           Inputs.push_back(std::make_pair(Ty, A));
    993       } else
    994         Inputs.push_back(std::make_pair(Ty, A));
    995 
    996     } else if (A->getOption().isLinkerInput()) {
    997       // Just treat as object type, we could make a special type for this if
    998       // necessary.
    999       Inputs.push_back(std::make_pair(types::TY_Object, A));
   1000 
   1001     } else if (A->getOption().matches(options::OPT_x)) {
   1002       InputTypeArg = A;
   1003       InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
   1004       A->claim();
   1005 
   1006       // Follow gcc behavior and treat as linker input for invalid -x
   1007       // options. Its not clear why we shouldn't just revert to unknown; but
   1008       // this isn't very important, we might as well be bug compatible.
   1009       if (!InputType) {
   1010         Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
   1011         InputType = types::TY_Object;
   1012       }
   1013     }
   1014   }
   1015   if (CCCIsCPP && Inputs.empty()) {
   1016     // If called as standalone preprocessor, stdin is processed
   1017     // if no other input is present.
   1018     unsigned Index = Args.getBaseArgs().MakeIndex("-");
   1019     Arg *A = Opts->ParseOneArg(Args, Index);
   1020     A->claim();
   1021     Inputs.push_back(std::make_pair(types::TY_C, A));
   1022   }
   1023 }
   1024 
   1025 void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
   1026                           const InputList &Inputs, ActionList &Actions) const {
   1027   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
   1028 
   1029   if (!SuppressMissingInputWarning && Inputs.empty()) {
   1030     Diag(clang::diag::err_drv_no_input_files);
   1031     return;
   1032   }
   1033 
   1034   Arg *FinalPhaseArg;
   1035   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
   1036 
   1037   // Reject -Z* at the top level, these options should never have been exposed
   1038   // by gcc.
   1039   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
   1040     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
   1041 
   1042   // Construct the actions to perform.
   1043   ActionList LinkerInputs;
   1044   unsigned NumSteps = 0;
   1045   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
   1046     types::ID InputType = Inputs[i].first;
   1047     const Arg *InputArg = Inputs[i].second;
   1048 
   1049     NumSteps = types::getNumCompilationPhases(InputType);
   1050     assert(NumSteps && "Invalid number of steps!");
   1051 
   1052     // If the first step comes after the final phase we are doing as part of
   1053     // this compilation, warn the user about it.
   1054     phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
   1055     if (InitialPhase > FinalPhase) {
   1056       // Claim here to avoid the more general unused warning.
   1057       InputArg->claim();
   1058 
   1059       // Suppress all unused style warnings with -Qunused-arguments
   1060       if (Args.hasArg(options::OPT_Qunused_arguments))
   1061         continue;
   1062 
   1063       // Special case '-E' warning on a previously preprocessed file to make
   1064       // more sense.
   1065       if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
   1066           getPreprocessedType(InputType) == types::TY_INVALID)
   1067         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
   1068           << InputArg->getAsString(Args)
   1069           << FinalPhaseArg->getOption().getName();
   1070       else
   1071         Diag(clang::diag::warn_drv_input_file_unused)
   1072           << InputArg->getAsString(Args)
   1073           << getPhaseName(InitialPhase)
   1074           << FinalPhaseArg->getOption().getName();
   1075       continue;
   1076     }
   1077 
   1078     // Build the pipeline for this file.
   1079     OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
   1080     for (unsigned i = 0; i != NumSteps; ++i) {
   1081       phases::ID Phase = types::getCompilationPhase(InputType, i);
   1082 
   1083       // We are done if this step is past what the user requested.
   1084       if (Phase > FinalPhase)
   1085         break;
   1086 
   1087       // Queue linker inputs.
   1088       if (Phase == phases::Link) {
   1089         assert(i + 1 == NumSteps && "linking must be final compilation step.");
   1090         LinkerInputs.push_back(Current.take());
   1091         break;
   1092       }
   1093 
   1094       // Some types skip the assembler phase (e.g., llvm-bc), but we can't
   1095       // encode this in the steps because the intermediate type depends on
   1096       // arguments. Just special case here.
   1097       if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
   1098         continue;
   1099 
   1100       // Otherwise construct the appropriate action.
   1101       Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
   1102       if (Current->getType() == types::TY_Nothing)
   1103         break;
   1104     }
   1105 
   1106     // If we ended with something, add to the output list.
   1107     if (Current)
   1108       Actions.push_back(Current.take());
   1109   }
   1110 
   1111   // Add a link action if necessary.
   1112   if (!LinkerInputs.empty())
   1113     Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
   1114 
   1115   // If we are linking, claim any options which are obviously only used for
   1116   // compilation.
   1117   if (FinalPhase == phases::Link && (NumSteps == 1))
   1118     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
   1119 }
   1120 
   1121 Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
   1122                                      Action *Input) const {
   1123   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
   1124   // Build the appropriate action.
   1125   switch (Phase) {
   1126   case phases::Link: llvm_unreachable("link action invalid here.");
   1127   case phases::Preprocess: {
   1128     types::ID OutputTy;
   1129     // -{M, MM} alter the output type.
   1130     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
   1131       OutputTy = types::TY_Dependencies;
   1132     } else {
   1133       OutputTy = types::getPreprocessedType(Input->getType());
   1134       assert(OutputTy != types::TY_INVALID &&
   1135              "Cannot preprocess this input type!");
   1136     }
   1137     return new PreprocessJobAction(Input, OutputTy);
   1138   }
   1139   case phases::Precompile:
   1140     return new PrecompileJobAction(Input, types::TY_PCH);
   1141   case phases::Compile: {
   1142     if (Args.hasArg(options::OPT_fsyntax_only)) {
   1143       return new CompileJobAction(Input, types::TY_Nothing);
   1144     } else if (Args.hasArg(options::OPT_rewrite_objc)) {
   1145       return new CompileJobAction(Input, types::TY_RewrittenObjC);
   1146     } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
   1147       return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
   1148     } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
   1149       return new AnalyzeJobAction(Input, types::TY_Plist);
   1150     } else if (Args.hasArg(options::OPT__migrate)) {
   1151       return new MigrateJobAction(Input, types::TY_Remap);
   1152     } else if (Args.hasArg(options::OPT_emit_ast)) {
   1153       return new CompileJobAction(Input, types::TY_AST);
   1154     } else if (IsUsingLTO(Args)) {
   1155       types::ID Output =
   1156         Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
   1157       return new CompileJobAction(Input, Output);
   1158     } else {
   1159       return new CompileJobAction(Input, types::TY_PP_Asm);
   1160     }
   1161   }
   1162   case phases::Assemble:
   1163     return new AssembleJobAction(Input, types::TY_Object);
   1164   }
   1165 
   1166   llvm_unreachable("invalid phase in ConstructPhaseAction");
   1167 }
   1168 
   1169 bool Driver::IsUsingLTO(const ArgList &Args) const {
   1170   // Check for -emit-llvm or -flto.
   1171   if (Args.hasArg(options::OPT_emit_llvm) ||
   1172       Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
   1173     return true;
   1174 
   1175   // Check for -O4.
   1176   if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
   1177       return A->getOption().matches(options::OPT_O4);
   1178 
   1179   return false;
   1180 }
   1181 
   1182 void Driver::BuildJobs(Compilation &C) const {
   1183   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
   1184 
   1185   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
   1186 
   1187   // It is an error to provide a -o option if we are making multiple output
   1188   // files.
   1189   if (FinalOutput) {
   1190     unsigned NumOutputs = 0;
   1191     for (ActionList::const_iterator it = C.getActions().begin(),
   1192            ie = C.getActions().end(); it != ie; ++it)
   1193       if ((*it)->getType() != types::TY_Nothing)
   1194         ++NumOutputs;
   1195 
   1196     if (NumOutputs > 1) {
   1197       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
   1198       FinalOutput = 0;
   1199     }
   1200   }
   1201 
   1202   for (ActionList::const_iterator it = C.getActions().begin(),
   1203          ie = C.getActions().end(); it != ie; ++it) {
   1204     Action *A = *it;
   1205 
   1206     // If we are linking an image for multiple archs then the linker wants
   1207     // -arch_multiple and -final_output <final image name>. Unfortunately, this
   1208     // doesn't fit in cleanly because we have to pass this information down.
   1209     //
   1210     // FIXME: This is a hack; find a cleaner way to integrate this into the
   1211     // process.
   1212     const char *LinkingOutput = 0;
   1213     if (isa<LipoJobAction>(A)) {
   1214       if (FinalOutput)
   1215         LinkingOutput = FinalOutput->getValue(C.getArgs());
   1216       else
   1217         LinkingOutput = DefaultImageName.c_str();
   1218     }
   1219 
   1220     InputInfo II;
   1221     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
   1222                        /*BoundArch*/0,
   1223                        /*AtTopLevel*/ true,
   1224                        /*LinkingOutput*/ LinkingOutput,
   1225                        II);
   1226   }
   1227 
   1228   // If the user passed -Qunused-arguments or there were errors, don't warn
   1229   // about any unused arguments.
   1230   if (Diags.hasErrorOccurred() ||
   1231       C.getArgs().hasArg(options::OPT_Qunused_arguments))
   1232     return;
   1233 
   1234   // Claim -### here.
   1235   (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
   1236 
   1237   for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
   1238        it != ie; ++it) {
   1239     Arg *A = *it;
   1240 
   1241     // FIXME: It would be nice to be able to send the argument to the
   1242     // DiagnosticsEngine, so that extra values, position, and so on could be
   1243     // printed.
   1244     if (!A->isClaimed()) {
   1245       if (A->getOption().hasNoArgumentUnused())
   1246         continue;
   1247 
   1248       // Suppress the warning automatically if this is just a flag, and it is an
   1249       // instance of an argument we already claimed.
   1250       const Option &Opt = A->getOption();
   1251       if (isa<FlagOption>(Opt)) {
   1252         bool DuplicateClaimed = false;
   1253 
   1254         for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
   1255                ie = C.getArgs().filtered_end(); it != ie; ++it) {
   1256           if ((*it)->isClaimed()) {
   1257             DuplicateClaimed = true;
   1258             break;
   1259           }
   1260         }
   1261 
   1262         if (DuplicateClaimed)
   1263           continue;
   1264       }
   1265 
   1266       Diag(clang::diag::warn_drv_unused_argument)
   1267         << A->getAsString(C.getArgs());
   1268     }
   1269   }
   1270 }
   1271 
   1272 static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
   1273                                     const JobAction *JA,
   1274                                     const ActionList *&Inputs) {
   1275   const Tool *ToolForJob = 0;
   1276 
   1277   // See if we should look for a compiler with an integrated assembler. We match
   1278   // bottom up, so what we are actually looking for is an assembler job with a
   1279   // compiler input.
   1280 
   1281   if (C.getArgs().hasFlag(options::OPT_integrated_as,
   1282                           options::OPT_no_integrated_as,
   1283                           TC->IsIntegratedAssemblerDefault()) &&
   1284       !C.getArgs().hasArg(options::OPT_save_temps) &&
   1285       isa<AssembleJobAction>(JA) &&
   1286       Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
   1287     const Tool &Compiler = TC->SelectTool(
   1288       C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
   1289     if (Compiler.hasIntegratedAssembler()) {
   1290       Inputs = &(*Inputs)[0]->getInputs();
   1291       ToolForJob = &Compiler;
   1292     }
   1293   }
   1294 
   1295   // Otherwise use the tool for the current job.
   1296   if (!ToolForJob)
   1297     ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
   1298 
   1299   // See if we should use an integrated preprocessor. We do so when we have
   1300   // exactly one input, since this is the only use case we care about
   1301   // (irrelevant since we don't support combine yet).
   1302   if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
   1303       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
   1304       !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
   1305       !C.getArgs().hasArg(options::OPT_save_temps) &&
   1306       ToolForJob->hasIntegratedCPP())
   1307     Inputs = &(*Inputs)[0]->getInputs();
   1308 
   1309   return *ToolForJob;
   1310 }
   1311 
   1312 void Driver::BuildJobsForAction(Compilation &C,
   1313                                 const Action *A,
   1314                                 const ToolChain *TC,
   1315                                 const char *BoundArch,
   1316                                 bool AtTopLevel,
   1317                                 const char *LinkingOutput,
   1318                                 InputInfo &Result) const {
   1319   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
   1320 
   1321   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
   1322     // FIXME: It would be nice to not claim this here; maybe the old scheme of
   1323     // just using Args was better?
   1324     const Arg &Input = IA->getInputArg();
   1325     Input.claim();
   1326     if (Input.getOption().matches(options::OPT_INPUT)) {
   1327       const char *Name = Input.getValue(C.getArgs());
   1328       Result = InputInfo(Name, A->getType(), Name);
   1329     } else
   1330       Result = InputInfo(&Input, A->getType(), "");
   1331     return;
   1332   }
   1333 
   1334   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
   1335     const ToolChain *TC = &C.getDefaultToolChain();
   1336 
   1337     if (BAA->getArchName())
   1338       TC = &getToolChain(C.getArgs(), BAA->getArchName());
   1339 
   1340     BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
   1341                        AtTopLevel, LinkingOutput, Result);
   1342     return;
   1343   }
   1344 
   1345   const ActionList *Inputs = &A->getInputs();
   1346 
   1347   const JobAction *JA = cast<JobAction>(A);
   1348   const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
   1349 
   1350   // Only use pipes when there is exactly one input.
   1351   InputInfoList InputInfos;
   1352   for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
   1353        it != ie; ++it) {
   1354     // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
   1355     // temporary output names.
   1356     //
   1357     // FIXME: Clean this up.
   1358     bool SubJobAtTopLevel = false;
   1359     if (AtTopLevel && isa<DsymutilJobAction>(A))
   1360       SubJobAtTopLevel = true;
   1361 
   1362     // Also treat verify sub-jobs as being at the top-level. They don't
   1363     // produce any output and so don't need temporary output names.
   1364     if (AtTopLevel && isa<VerifyJobAction>(A))
   1365       SubJobAtTopLevel = true;
   1366 
   1367     InputInfo II;
   1368     BuildJobsForAction(C, *it, TC, BoundArch,
   1369                        SubJobAtTopLevel, LinkingOutput, II);
   1370     InputInfos.push_back(II);
   1371   }
   1372 
   1373   // Always use the first input as the base input.
   1374   const char *BaseInput = InputInfos[0].getBaseInput();
   1375 
   1376   // ... except dsymutil actions, which use their actual input as the base
   1377   // input.
   1378   if (JA->getType() == types::TY_dSYM)
   1379     BaseInput = InputInfos[0].getFilename();
   1380 
   1381   // Determine the place to write output to, if any.
   1382   if (JA->getType() == types::TY_Nothing) {
   1383     Result = InputInfo(A->getType(), BaseInput);
   1384   } else {
   1385     Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
   1386                        A->getType(), BaseInput);
   1387   }
   1388 
   1389   if (CCCPrintBindings && !CCGenDiagnostics) {
   1390     llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
   1391                  << " - \"" << T.getName() << "\", inputs: [";
   1392     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
   1393       llvm::errs() << InputInfos[i].getAsString();
   1394       if (i + 1 != e)
   1395         llvm::errs() << ", ";
   1396     }
   1397     llvm::errs() << "], output: " << Result.getAsString() << "\n";
   1398   } else {
   1399     T.ConstructJob(C, *JA, Result, InputInfos,
   1400                    C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
   1401   }
   1402 }
   1403 
   1404 const char *Driver::GetNamedOutputPath(Compilation &C,
   1405                                        const JobAction &JA,
   1406                                        const char *BaseInput,
   1407                                        bool AtTopLevel) const {
   1408   llvm::PrettyStackTraceString CrashInfo("Computing output path");
   1409   // Output to a user requested destination?
   1410   if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
   1411       !isa<VerifyJobAction>(JA)) {
   1412     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
   1413       return C.addResultFile(FinalOutput->getValue(C.getArgs()));
   1414   }
   1415 
   1416   // Default to writing to stdout?
   1417   if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics)
   1418     return "-";
   1419 
   1420   // Output to a temporary file?
   1421   if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
   1422       CCGenDiagnostics) {
   1423     StringRef Name = llvm::sys::path::filename(BaseInput);
   1424     std::pair<StringRef, StringRef> Split = Name.split('.');
   1425     std::string TmpName =
   1426       GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
   1427     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
   1428   }
   1429 
   1430   SmallString<128> BasePath(BaseInput);
   1431   StringRef BaseName;
   1432 
   1433   // Dsymutil actions should use the full path.
   1434   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
   1435     BaseName = BasePath;
   1436   else
   1437     BaseName = llvm::sys::path::filename(BasePath);
   1438 
   1439   // Determine what the derived output name should be.
   1440   const char *NamedOutput;
   1441   if (JA.getType() == types::TY_Image) {
   1442     NamedOutput = DefaultImageName.c_str();
   1443   } else {
   1444     const char *Suffix = types::getTypeTempSuffix(JA.getType());
   1445     assert(Suffix && "All types used for output should have a suffix.");
   1446 
   1447     std::string::size_type End = std::string::npos;
   1448     if (!types::appendSuffixForType(JA.getType()))
   1449       End = BaseName.rfind('.');
   1450     std::string Suffixed(BaseName.substr(0, End));
   1451     Suffixed += '.';
   1452     Suffixed += Suffix;
   1453     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
   1454   }
   1455 
   1456   // If we're saving temps and the temp filename conflicts with the input
   1457   // filename, then avoid overwriting input file.
   1458   if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
   1459       NamedOutput == BaseName) {
   1460     StringRef Name = llvm::sys::path::filename(BaseInput);
   1461     std::pair<StringRef, StringRef> Split = Name.split('.');
   1462     std::string TmpName =
   1463       GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
   1464     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
   1465   }
   1466 
   1467   // As an annoying special case, PCH generation doesn't strip the pathname.
   1468   if (JA.getType() == types::TY_PCH) {
   1469     llvm::sys::path::remove_filename(BasePath);
   1470     if (BasePath.empty())
   1471       BasePath = NamedOutput;
   1472     else
   1473       llvm::sys::path::append(BasePath, NamedOutput);
   1474     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
   1475   } else {
   1476     return C.addResultFile(NamedOutput);
   1477   }
   1478 }
   1479 
   1480 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
   1481   // Respect a limited subset of the '-Bprefix' functionality in GCC by
   1482   // attempting to use this prefix when lokup up program paths.
   1483   for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
   1484        ie = PrefixDirs.end(); it != ie; ++it) {
   1485     std::string Dir(*it);
   1486     if (Dir.empty())
   1487       continue;
   1488     if (Dir[0] == '=')
   1489       Dir = SysRoot + Dir.substr(1);
   1490     llvm::sys::Path P(Dir);
   1491     P.appendComponent(Name);
   1492     bool Exists;
   1493     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
   1494       return P.str();
   1495   }
   1496 
   1497   llvm::sys::Path P(ResourceDir);
   1498   P.appendComponent(Name);
   1499   bool Exists;
   1500   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
   1501     return P.str();
   1502 
   1503   const ToolChain::path_list &List = TC.getFilePaths();
   1504   for (ToolChain::path_list::const_iterator
   1505          it = List.begin(), ie = List.end(); it != ie; ++it) {
   1506     std::string Dir(*it);
   1507     if (Dir.empty())
   1508       continue;
   1509     if (Dir[0] == '=')
   1510       Dir = SysRoot + Dir.substr(1);
   1511     llvm::sys::Path P(Dir);
   1512     P.appendComponent(Name);
   1513     bool Exists;
   1514     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
   1515       return P.str();
   1516   }
   1517 
   1518   return Name;
   1519 }
   1520 
   1521 static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) {
   1522     bool Exists;
   1523     return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
   1524                  : P.canExecute());
   1525 }
   1526 
   1527 std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
   1528                                    bool WantFile) const {
   1529   // FIXME: Needs a better variable than DefaultTargetTriple
   1530   std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
   1531   // Respect a limited subset of the '-Bprefix' functionality in GCC by
   1532   // attempting to use this prefix when lokup up program paths.
   1533   for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
   1534        ie = PrefixDirs.end(); it != ie; ++it) {
   1535     llvm::sys::Path P(*it);
   1536     P.appendComponent(TargetSpecificExecutable);
   1537     if (isPathExecutable(P, WantFile)) return P.str();
   1538     P.eraseComponent();
   1539     P.appendComponent(Name);
   1540     if (isPathExecutable(P, WantFile)) return P.str();
   1541   }
   1542 
   1543   const ToolChain::path_list &List = TC.getProgramPaths();
   1544   for (ToolChain::path_list::const_iterator
   1545          it = List.begin(), ie = List.end(); it != ie; ++it) {
   1546     llvm::sys::Path P(*it);
   1547     P.appendComponent(TargetSpecificExecutable);
   1548     if (isPathExecutable(P, WantFile)) return P.str();
   1549     P.eraseComponent();
   1550     P.appendComponent(Name);
   1551     if (isPathExecutable(P, WantFile)) return P.str();
   1552   }
   1553 
   1554   // If all else failed, search the path.
   1555   llvm::sys::Path
   1556       P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
   1557   if (!P.empty())
   1558     return P.str();
   1559 
   1560   P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
   1561   if (!P.empty())
   1562     return P.str();
   1563 
   1564   return Name;
   1565 }
   1566 
   1567 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
   1568   const {
   1569   // FIXME: This is lame; sys::Path should provide this function (in particular,
   1570   // it should know how to find the temporary files dir).
   1571   std::string Error;
   1572   const char *TmpDir = ::getenv("TMPDIR");
   1573   if (!TmpDir)
   1574     TmpDir = ::getenv("TEMP");
   1575   if (!TmpDir)
   1576     TmpDir = ::getenv("TMP");
   1577   if (!TmpDir)
   1578     TmpDir = "/tmp";
   1579   llvm::sys::Path P(TmpDir);
   1580   P.appendComponent(Prefix);
   1581   if (P.makeUnique(false, &Error)) {
   1582     Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
   1583     return "";
   1584   }
   1585 
   1586   // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
   1587   P.eraseFromDisk(false, 0);
   1588 
   1589   P.appendSuffix(Suffix);
   1590   return P.str();
   1591 }
   1592 
   1593 /// \brief Compute target triple from args.
   1594 ///
   1595 /// This routine provides the logic to compute a target triple from various
   1596 /// args passed to the driver and the default triple string.
   1597 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
   1598                                         const ArgList &Args,
   1599                                         StringRef DarwinArchName) {
   1600   // FIXME: Already done in Compilation *Driver::BuildCompilation
   1601   if (const Arg *A = Args.getLastArg(options::OPT_target))
   1602     DefaultTargetTriple = A->getValue(Args);
   1603 
   1604   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
   1605 
   1606   // Handle Darwin-specific options available here.
   1607   if (Target.isOSDarwin()) {
   1608     // If an explict Darwin arch name is given, that trumps all.
   1609     if (!DarwinArchName.empty()) {
   1610       Target.setArch(
   1611         llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName));
   1612       return Target;
   1613     }
   1614 
   1615     // Handle the Darwin '-arch' flag.
   1616     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
   1617       llvm::Triple::ArchType DarwinArch
   1618         = llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
   1619       if (DarwinArch != llvm::Triple::UnknownArch)
   1620         Target.setArch(DarwinArch);
   1621     }
   1622   }
   1623 
   1624   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
   1625   if (Target.getArchName() == "tce" ||
   1626       Target.getOS() == llvm::Triple::AuroraUX ||
   1627       Target.getOS() == llvm::Triple::Minix)
   1628     return Target;
   1629 
   1630   // Handle pseudo-target flags '-m32' and '-m64'.
   1631   // FIXME: Should this information be in llvm::Triple?
   1632   if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
   1633     if (A->getOption().matches(options::OPT_m32)) {
   1634       if (Target.getArch() == llvm::Triple::x86_64)
   1635         Target.setArch(llvm::Triple::x86);
   1636       if (Target.getArch() == llvm::Triple::ppc64)
   1637         Target.setArch(llvm::Triple::ppc);
   1638     } else {
   1639       if (Target.getArch() == llvm::Triple::x86)
   1640         Target.setArch(llvm::Triple::x86_64);
   1641       if (Target.getArch() == llvm::Triple::ppc)
   1642         Target.setArch(llvm::Triple::ppc64);
   1643     }
   1644   }
   1645 
   1646   return Target;
   1647 }
   1648 
   1649 const ToolChain &Driver::getToolChain(const ArgList &Args,
   1650                                       StringRef DarwinArchName) const {
   1651   llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
   1652                                             DarwinArchName);
   1653 
   1654   ToolChain *&TC = ToolChains[Target.str()];
   1655   if (!TC) {
   1656     switch (Target.getOS()) {
   1657     case llvm::Triple::AuroraUX:
   1658       TC = new toolchains::AuroraUX(*this, Target, Args);
   1659       break;
   1660     case llvm::Triple::Darwin:
   1661     case llvm::Triple::MacOSX:
   1662     case llvm::Triple::IOS:
   1663       if (Target.getArch() == llvm::Triple::x86 ||
   1664           Target.getArch() == llvm::Triple::x86_64 ||
   1665           Target.getArch() == llvm::Triple::arm ||
   1666           Target.getArch() == llvm::Triple::thumb)
   1667         TC = new toolchains::DarwinClang(*this, Target);
   1668       else
   1669         TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args);
   1670       break;
   1671     case llvm::Triple::DragonFly:
   1672       TC = new toolchains::DragonFly(*this, Target, Args);
   1673       break;
   1674     case llvm::Triple::OpenBSD:
   1675       TC = new toolchains::OpenBSD(*this, Target, Args);
   1676       break;
   1677     case llvm::Triple::NetBSD:
   1678       TC = new toolchains::NetBSD(*this, Target, Args);
   1679       break;
   1680     case llvm::Triple::FreeBSD:
   1681       TC = new toolchains::FreeBSD(*this, Target, Args);
   1682       break;
   1683     case llvm::Triple::Minix:
   1684       TC = new toolchains::Minix(*this, Target, Args);
   1685       break;
   1686     case llvm::Triple::Linux:
   1687       if (Target.getArch() == llvm::Triple::hexagon)
   1688         TC = new toolchains::Hexagon_TC(*this, Target);
   1689       else
   1690         TC = new toolchains::Linux(*this, Target, Args);
   1691       break;
   1692     case llvm::Triple::Solaris:
   1693       TC = new toolchains::Solaris(*this, Target, Args);
   1694       break;
   1695     case llvm::Triple::Win32:
   1696       TC = new toolchains::Windows(*this, Target);
   1697       break;
   1698     case llvm::Triple::MinGW32:
   1699       // FIXME: We need a MinGW toolchain. Fallthrough for now.
   1700     default:
   1701       // TCE is an OSless target
   1702       if (Target.getArchName() == "tce") {
   1703         TC = new toolchains::TCEToolChain(*this, Target);
   1704         break;
   1705       }
   1706 
   1707       TC = new toolchains::Generic_GCC(*this, Target, Args);
   1708       break;
   1709     }
   1710   }
   1711   return *TC;
   1712 }
   1713 
   1714 bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
   1715                                     const llvm::Triple &Triple) const {
   1716   // Check if user requested no clang, or clang doesn't understand this type (we
   1717   // only handle single inputs for now).
   1718   if (!CCCUseClang || JA.size() != 1 ||
   1719       !types::isAcceptedByClang((*JA.begin())->getType()))
   1720     return false;
   1721 
   1722   // Otherwise make sure this is an action clang understands.
   1723   if (isa<PreprocessJobAction>(JA)) {
   1724     if (!CCCUseClangCPP) {
   1725       Diag(clang::diag::warn_drv_not_using_clang_cpp);
   1726       return false;
   1727     }
   1728   } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
   1729     return false;
   1730 
   1731   // Use clang for C++?
   1732   if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
   1733     Diag(clang::diag::warn_drv_not_using_clang_cxx);
   1734     return false;
   1735   }
   1736 
   1737   // Always use clang for precompiling, AST generation, and rewriting,
   1738   // regardless of archs.
   1739   if (isa<PrecompileJobAction>(JA) ||
   1740       types::isOnlyAcceptedByClang(JA.getType()))
   1741     return true;
   1742 
   1743   // Finally, don't use clang if this isn't one of the user specified archs to
   1744   // build.
   1745   if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
   1746     Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
   1747     return false;
   1748   }
   1749 
   1750   return true;
   1751 }
   1752 
   1753 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
   1754 /// grouped values as integers. Numbers which are not provided are set to 0.
   1755 ///
   1756 /// \return True if the entire string was parsed (9.2), or all groups were
   1757 /// parsed (10.3.5extrastuff).
   1758 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
   1759                                unsigned &Minor, unsigned &Micro,
   1760                                bool &HadExtra) {
   1761   HadExtra = false;
   1762 
   1763   Major = Minor = Micro = 0;
   1764   if (*Str == '\0')
   1765     return true;
   1766 
   1767   char *End;
   1768   Major = (unsigned) strtol(Str, &End, 10);
   1769   if (*Str != '\0' && *End == '\0')
   1770     return true;
   1771   if (*End != '.')
   1772     return false;
   1773 
   1774   Str = End+1;
   1775   Minor = (unsigned) strtol(Str, &End, 10);
   1776   if (*Str != '\0' && *End == '\0')
   1777     return true;
   1778   if (*End != '.')
   1779     return false;
   1780 
   1781   Str = End+1;
   1782   Micro = (unsigned) strtol(Str, &End, 10);
   1783   if (*Str != '\0' && *End == '\0')
   1784     return true;
   1785   if (Str == End)
   1786     return false;
   1787   HadExtra = true;
   1788   return true;
   1789 }
   1790