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