Driver.cpp revision d7502d0a662b5c299125aba04245aefce67cbc22
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/HostInfo.h"
18#include "clang/Driver/Job.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#include "clang/Driver/Types.h"
24
25#include "clang/Basic/Version.h"
26
27#include "llvm/ADT/StringSet.h"
28#include "llvm/Support/PrettyStackTrace.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/System/Path.h"
31#include "llvm/System/Program.h"
32
33#include "InputInfo.h"
34
35#include <map>
36
37using namespace clang::driver;
38using namespace clang;
39
40// Used to set values for "production" clang, for releases.
41// #define USE_PRODUCTION_CLANG
42
43Driver::Driver(const char *_Name, const char *_Dir,
44               const char *_DefaultHostTriple,
45               const char *_DefaultImageName,
46               Diagnostic &_Diags)
47  : Opts(new OptTable()), Diags(_Diags),
48    Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
49    DefaultImageName(_DefaultImageName),
50    Host(0),
51    CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
52    CCCGenericGCCName("gcc"), CCCUseClang(true),
53#ifdef USE_PRODUCTION_CLANG
54    CCCUseClangCXX(false),
55#else
56    CCCUseClangCXX(true),
57#endif
58    CCCUseClangCPP(true), CCCUsePCH(true),
59    SuppressMissingInputWarning(false)
60{
61#ifdef USE_PRODUCTION_CLANG
62  // In a "production" build, only use clang on architectures we expect to work.
63  CCCClangArchs.insert(llvm::Triple::x86);
64  CCCClangArchs.insert(llvm::Triple::x86_64);
65  CCCClangArchs.insert(llvm::Triple::arm);
66#endif
67}
68
69Driver::~Driver() {
70  delete Opts;
71  delete Host;
72}
73
74InputArgList *Driver::ParseArgStrings(const char **ArgBegin,
75                                      const char **ArgEnd) {
76  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
77  InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
78
79  // FIXME: Handle '@' args (or at least error on them).
80
81  unsigned Index = 0, End = ArgEnd - ArgBegin;
82  while (Index < End) {
83    // gcc's handling of empty arguments doesn't make sense, but this is not a
84    // common use case. :)
85    //
86    // We just ignore them here (note that other things may still take them as
87    // arguments).
88    if (Args->getArgString(Index)[0] == '\0') {
89      ++Index;
90      continue;
91    }
92
93    unsigned Prev = Index;
94    Arg *A = getOpts().ParseOneArg(*Args, Index);
95    assert(Index > Prev && "Parser failed to consume argument.");
96
97    // Check for missing argument error.
98    if (!A) {
99      assert(Index >= End && "Unexpected parser error.");
100      Diag(clang::diag::err_drv_missing_argument)
101        << Args->getArgString(Prev)
102        << (Index - Prev - 1);
103      break;
104    }
105
106    if (A->getOption().isUnsupported()) {
107      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
108      continue;
109    }
110    Args->append(A);
111  }
112
113  return Args;
114}
115
116Compilation *Driver::BuildCompilation(int argc, const char **argv) {
117  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
118
119  // FIXME: Handle environment options which effect driver behavior, somewhere
120  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
121  // CC_PRINT_OPTIONS.
122
123  // FIXME: What are we going to do with -V and -b?
124
125  // FIXME: This stuff needs to go into the Compilation, not the driver.
126  bool CCCPrintOptions = false, CCCPrintActions = false;
127
128  const char **Start = argv + 1, **End = argv + argc;
129  const char *HostTriple = DefaultHostTriple.c_str();
130
131  // Read -ccc args.
132  //
133  // FIXME: We need to figure out where this behavior should live. Most of it
134  // should be outside in the client; the parts that aren't should have proper
135  // options, either by introducing new ones or by overloading gcc ones like -V
136  // or -b.
137  for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
138    const char *Opt = *Start + 5;
139
140    if (!strcmp(Opt, "print-options")) {
141      CCCPrintOptions = true;
142    } else if (!strcmp(Opt, "print-phases")) {
143      CCCPrintActions = true;
144    } else if (!strcmp(Opt, "print-bindings")) {
145      CCCPrintBindings = true;
146    } else if (!strcmp(Opt, "cxx")) {
147      CCCIsCXX = true;
148    } else if (!strcmp(Opt, "echo")) {
149      CCCEcho = true;
150
151    } else if (!strcmp(Opt, "gcc-name")) {
152      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
153      CCCGenericGCCName = *++Start;
154
155    } else if (!strcmp(Opt, "clang-cxx")) {
156      CCCUseClangCXX = true;
157    } else if (!strcmp(Opt, "no-clang-cxx")) {
158      CCCUseClangCXX = false;
159    } else if (!strcmp(Opt, "pch-is-pch")) {
160      CCCUsePCH = true;
161    } else if (!strcmp(Opt, "pch-is-pth")) {
162      CCCUsePCH = false;
163    } else if (!strcmp(Opt, "no-clang")) {
164      CCCUseClang = false;
165    } else if (!strcmp(Opt, "no-clang-cpp")) {
166      CCCUseClangCPP = false;
167    } else if (!strcmp(Opt, "clang-archs")) {
168      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
169      llvm::StringRef Cur = *++Start;
170
171      CCCClangArchs.clear();
172      while (!Cur.empty()) {
173        std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
174
175        if (!Split.first.empty()) {
176          llvm::Triple::ArchType Arch =
177            llvm::Triple(Split.first, "", "").getArch();
178
179          if (Arch == llvm::Triple::UnknownArch) {
180            // FIXME: Error handling.
181            llvm::errs() << "invalid arch name: " << Split.first << "\n";
182            exit(1);
183          }
184
185          CCCClangArchs.insert(Arch);
186        }
187
188        Cur = Split.second;
189      }
190    } else if (!strcmp(Opt, "host-triple")) {
191      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
192      HostTriple = *++Start;
193
194    } else if (!strcmp(Opt, "install-dir")) {
195      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
196      Dir = *++Start;
197
198    } else {
199      // FIXME: Error handling.
200      llvm::errs() << "invalid option: " << *Start << "\n";
201      exit(1);
202    }
203  }
204
205  InputArgList *Args = ParseArgStrings(Start, End);
206
207  Host = GetHostInfo(HostTriple);
208
209  // The compilation takes ownership of Args.
210  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args);
211
212  // FIXME: This behavior shouldn't be here.
213  if (CCCPrintOptions) {
214    PrintOptions(C->getArgs());
215    return C;
216  }
217
218  if (!HandleImmediateArgs(*C))
219    return C;
220
221  // Construct the list of abstract actions to perform for this compilation. We
222  // avoid passing a Compilation here simply to enforce the abstraction that
223  // pipelining is not host or toolchain dependent (other than the driver driver
224  // test).
225  if (Host->useDriverDriver())
226    BuildUniversalActions(C->getArgs(), C->getActions());
227  else
228    BuildActions(C->getArgs(), C->getActions());
229
230  if (CCCPrintActions) {
231    PrintActions(*C);
232    return C;
233  }
234
235  BuildJobs(*C);
236
237  return C;
238}
239
240int Driver::ExecuteCompilation(const Compilation &C) const {
241  // Just print if -### was present.
242  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
243    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
244    return 0;
245  }
246
247  // If there were errors building the compilation, quit now.
248  if (getDiags().getNumErrors())
249    return 1;
250
251  const Command *FailingCommand = 0;
252  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
253
254  // Remove temp files.
255  C.CleanupFileList(C.getTempFiles());
256
257  // If the compilation failed, remove result files as well.
258  if (Res != 0 && !C.getArgs().hasArg(options::OPT_save_temps))
259    C.CleanupFileList(C.getResultFiles(), true);
260
261  // Print extra information about abnormal failures, if possible.
262  if (Res) {
263    // This is ad-hoc, but we don't want to be excessively noisy. If the result
264    // status was 1, assume the command failed normally. In particular, if it
265    // was the compiler then assume it gave a reasonable error code. Failures in
266    // other tools are less common, and they generally have worse diagnostics,
267    // so always print the diagnostic there.
268    const Action &Source = FailingCommand->getSource();
269    bool IsFriendlyTool = (isa<PreprocessJobAction>(Source) ||
270                           isa<PrecompileJobAction>(Source) ||
271                           isa<AnalyzeJobAction>(Source) ||
272                           isa<CompileJobAction>(Source));
273
274    if (!IsFriendlyTool || Res != 1) {
275      // FIXME: See FIXME above regarding result code interpretation.
276      if (Res < 0)
277        Diag(clang::diag::err_drv_command_signalled)
278          << Source.getClassName() << -Res;
279      else
280        Diag(clang::diag::err_drv_command_failed)
281          << Source.getClassName() << Res;
282    }
283  }
284
285  return Res;
286}
287
288void Driver::PrintOptions(const ArgList &Args) const {
289  unsigned i = 0;
290  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
291       it != ie; ++it, ++i) {
292    Arg *A = *it;
293    llvm::errs() << "Option " << i << " - "
294                 << "Name: \"" << A->getOption().getName() << "\", "
295                 << "Values: {";
296    for (unsigned j = 0; j < A->getNumValues(); ++j) {
297      if (j)
298        llvm::errs() << ", ";
299      llvm::errs() << '"' << A->getValue(Args, j) << '"';
300    }
301    llvm::errs() << "}\n";
302  }
303}
304
305static std::string getOptionHelpName(const OptTable &Opts, options::ID Id) {
306  std::string Name = Opts.getOptionName(Id);
307
308  // Add metavar, if used.
309  switch (Opts.getOptionKind(Id)) {
310  case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
311    assert(0 && "Invalid option with help text.");
312
313  case Option::MultiArgClass: case Option::JoinedAndSeparateClass:
314    assert(0 && "Cannot print metavar for this kind of option.");
315
316  case Option::FlagClass:
317    break;
318
319  case Option::SeparateClass: case Option::JoinedOrSeparateClass:
320    Name += ' ';
321    // FALLTHROUGH
322  case Option::JoinedClass: case Option::CommaJoinedClass:
323    Name += Opts.getOptionMetaVar(Id);
324    break;
325  }
326
327  return Name;
328}
329
330void Driver::PrintHelp(bool ShowHidden) const {
331  llvm::raw_ostream &OS = llvm::outs();
332
333  OS << "OVERVIEW: clang \"gcc-compatible\" driver\n";
334  OS << '\n';
335  OS << "USAGE: " << Name << " [options] <input files>\n";
336  OS << '\n';
337  OS << "OPTIONS:\n";
338
339  // Render help text into (option, help) pairs.
340  std::vector< std::pair<std::string, const char*> > OptionHelp;
341
342  for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) {
343    options::ID Id = (options::ID) i;
344    if (const char *Text = getOpts().getOptionHelpText(Id))
345      OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id),
346                                          Text));
347  }
348
349  if (ShowHidden) {
350    OptionHelp.push_back(std::make_pair("\nDRIVER OPTIONS:",""));
351    OptionHelp.push_back(std::make_pair("-ccc-cxx",
352                                        "Act as a C++ driver"));
353    OptionHelp.push_back(std::make_pair("-ccc-gcc-name",
354                                        "Name for native GCC compiler"));
355    OptionHelp.push_back(std::make_pair("-ccc-clang-cxx",
356                                        "Enable the clang compiler for C++"));
357    OptionHelp.push_back(std::make_pair("-ccc-no-clang-cxx",
358                                        "Disable the clang compiler for C++"));
359    OptionHelp.push_back(std::make_pair("-ccc-no-clang",
360                                        "Disable the clang compiler"));
361    OptionHelp.push_back(std::make_pair("-ccc-no-clang-cpp",
362                                        "Disable the clang preprocessor"));
363    OptionHelp.push_back(std::make_pair("-ccc-clang-archs",
364                                        "Comma separate list of architectures "
365                                        "to use the clang compiler for"));
366    OptionHelp.push_back(std::make_pair("-ccc-pch-is-pch",
367                                     "Use lazy PCH for precompiled headers"));
368    OptionHelp.push_back(std::make_pair("-ccc-pch-is-pth",
369                         "Use pretokenized headers for precompiled headers"));
370
371    OptionHelp.push_back(std::make_pair("\nDEBUG/DEVELOPMENT OPTIONS:",""));
372    OptionHelp.push_back(std::make_pair("-ccc-host-triple",
373                                       "Simulate running on the given target"));
374    OptionHelp.push_back(std::make_pair("-ccc-install-dir",
375                               "Simulate installation in the given directory"));
376    OptionHelp.push_back(std::make_pair("-ccc-print-options",
377                                        "Dump parsed command line arguments"));
378    OptionHelp.push_back(std::make_pair("-ccc-print-phases",
379                                        "Dump list of actions to perform"));
380    OptionHelp.push_back(std::make_pair("-ccc-print-bindings",
381                                        "Show bindings of tools to actions"));
382    OptionHelp.push_back(std::make_pair("CCC_ADD_ARGS",
383                               "(ENVIRONMENT VARIABLE) Comma separated list of "
384                               "arguments to prepend to the command line"));
385  }
386
387  // Find the maximum option length.
388  unsigned OptionFieldWidth = 0;
389  for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
390    // Skip titles.
391    if (!OptionHelp[i].second)
392      continue;
393
394    // Limit the amount of padding we are willing to give up for alignment.
395    unsigned Length = OptionHelp[i].first.size();
396    if (Length <= 23)
397      OptionFieldWidth = std::max(OptionFieldWidth, Length);
398  }
399
400  for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
401    const std::string &Option = OptionHelp[i].first;
402    OS << "  " << Option;
403    for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j)
404      OS << ' ';
405    OS << ' ' << OptionHelp[i].second << '\n';
406  }
407
408  OS.flush();
409}
410
411void Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
412  static char buf[] = "$URL$";
413  char *zap = strstr(buf, "/lib/Driver");
414  if (zap)
415    *zap = 0;
416  zap = strstr(buf, "/clang/tools/clang");
417  if (zap)
418    *zap = 0;
419  const char *vers = buf+6;
420  // FIXME: Add cmake support and remove #ifdef
421#ifdef SVN_REVISION
422  const char *revision = SVN_REVISION;
423#else
424  const char *revision = "";
425#endif
426  // FIXME: The following handlers should use a callback mechanism, we don't
427  // know what the client would like to do.
428  OS << "clang version " CLANG_VERSION_STRING " ("
429     << vers << " " << revision << ")" << '\n';
430
431  const ToolChain &TC = C.getDefaultToolChain();
432  OS << "Target: " << TC.getTripleString() << '\n';
433
434  // Print the threading model.
435  //
436  // FIXME: Implement correctly.
437  OS << "Thread model: " << "posix" << '\n';
438}
439
440bool Driver::HandleImmediateArgs(const Compilation &C) {
441  // The order these options are handled in in gcc is all over the place, but we
442  // don't expect inconsistencies w.r.t. that to matter in practice.
443
444  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
445    llvm::outs() << CLANG_VERSION_STRING "\n";
446    return false;
447  }
448
449  if (C.getArgs().hasArg(options::OPT__help) ||
450      C.getArgs().hasArg(options::OPT__help_hidden)) {
451    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
452    return false;
453  }
454
455  if (C.getArgs().hasArg(options::OPT__version)) {
456    // Follow gcc behavior and use stdout for --version and stderr for -v.
457    PrintVersion(C, llvm::outs());
458    return false;
459  }
460
461  if (C.getArgs().hasArg(options::OPT_v) ||
462      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
463    PrintVersion(C, llvm::errs());
464    SuppressMissingInputWarning = true;
465  }
466
467  const ToolChain &TC = C.getDefaultToolChain();
468  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
469    llvm::outs() << "programs: =";
470    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
471           ie = TC.getProgramPaths().end(); it != ie; ++it) {
472      if (it != TC.getProgramPaths().begin())
473        llvm::outs() << ':';
474      llvm::outs() << *it;
475    }
476    llvm::outs() << "\n";
477    llvm::outs() << "libraries: =";
478    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
479           ie = TC.getFilePaths().end(); it != ie; ++it) {
480      if (it != TC.getFilePaths().begin())
481        llvm::outs() << ':';
482      llvm::outs() << *it;
483    }
484    llvm::outs() << "\n";
485    return false;
486  }
487
488  // FIXME: The following handlers should use a callback mechanism, we don't
489  // know what the client would like to do.
490  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
491    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).str()
492                 << "\n";
493    return false;
494  }
495
496  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
497    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).str()
498                 << "\n";
499    return false;
500  }
501
502  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
503    llvm::outs() << GetFilePath("libgcc.a", TC).str() << "\n";
504    return false;
505  }
506
507  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
508    // FIXME: We need tool chain support for this.
509    llvm::outs() << ".;\n";
510
511    switch (C.getDefaultToolChain().getTriple().getArch()) {
512    default:
513      break;
514
515    case llvm::Triple::x86_64:
516      llvm::outs() << "x86_64;@m64" << "\n";
517      break;
518
519    case llvm::Triple::ppc64:
520      llvm::outs() << "ppc64;@m64" << "\n";
521      break;
522    }
523    return false;
524  }
525
526  // FIXME: What is the difference between print-multi-directory and
527  // print-multi-os-directory?
528  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
529      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
530    switch (C.getDefaultToolChain().getTriple().getArch()) {
531    default:
532    case llvm::Triple::x86:
533    case llvm::Triple::ppc:
534      llvm::outs() << "." << "\n";
535      break;
536
537    case llvm::Triple::x86_64:
538      llvm::outs() << "x86_64" << "\n";
539      break;
540
541    case llvm::Triple::ppc64:
542      llvm::outs() << "ppc64" << "\n";
543      break;
544    }
545    return false;
546  }
547
548  return true;
549}
550
551static unsigned PrintActions1(const Compilation &C, Action *A,
552                              std::map<Action*, unsigned> &Ids) {
553  if (Ids.count(A))
554    return Ids[A];
555
556  std::string str;
557  llvm::raw_string_ostream os(str);
558
559  os << Action::getClassName(A->getKind()) << ", ";
560  if (InputAction *IA = dyn_cast<InputAction>(A)) {
561    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
562  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
563    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
564                  C.getDefaultToolChain().getArchName()) << '"'
565       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
566  } else {
567    os << "{";
568    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
569      os << PrintActions1(C, *it, Ids);
570      ++it;
571      if (it != ie)
572        os << ", ";
573    }
574    os << "}";
575  }
576
577  unsigned Id = Ids.size();
578  Ids[A] = Id;
579  llvm::errs() << Id << ": " << os.str() << ", "
580               << types::getTypeName(A->getType()) << "\n";
581
582  return Id;
583}
584
585void Driver::PrintActions(const Compilation &C) const {
586  std::map<Action*, unsigned> Ids;
587  for (ActionList::const_iterator it = C.getActions().begin(),
588         ie = C.getActions().end(); it != ie; ++it)
589    PrintActions1(C, *it, Ids);
590}
591
592void Driver::BuildUniversalActions(const ArgList &Args,
593                                   ActionList &Actions) const {
594  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
595  // Collect the list of architectures. Duplicates are allowed, but should only
596  // be handled once (in the order seen).
597  llvm::StringSet<> ArchNames;
598  llvm::SmallVector<const char *, 4> Archs;
599  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
600       it != ie; ++it) {
601    Arg *A = *it;
602
603    if (A->getOption().getId() == options::OPT_arch) {
604      A->claim();
605      if (ArchNames.insert(A->getValue(Args)))
606        Archs.push_back(A->getValue(Args));
607    }
608  }
609
610  // When there is no explicit arch for this platform, make sure we still bind
611  // the architecture (to the default) so that -Xarch_ is handled correctly.
612  if (!Archs.size())
613    Archs.push_back(0);
614
615  // FIXME: We killed off some others but these aren't yet detected in a
616  // functional manner. If we added information to jobs about which "auxiliary"
617  // files they wrote then we could detect the conflict these cause downstream.
618  if (Archs.size() > 1) {
619    // No recovery needed, the point of this is just to prevent
620    // overwriting the same files.
621    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
622      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
623        << A->getAsString(Args);
624  }
625
626  ActionList SingleActions;
627  BuildActions(Args, SingleActions);
628
629  // Add in arch binding and lipo (if necessary) for every top level action.
630  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
631    Action *Act = SingleActions[i];
632
633    // Make sure we can lipo this kind of output. If not (and it is an actual
634    // output) then we disallow, since we can't create an output file with the
635    // right name without overwriting it. We could remove this oddity by just
636    // changing the output names to include the arch, which would also fix
637    // -save-temps. Compatibility wins for now.
638
639    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
640      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
641        << types::getTypeName(Act->getType());
642
643    ActionList Inputs;
644    for (unsigned i = 0, e = Archs.size(); i != e; ++i)
645      Inputs.push_back(new BindArchAction(Act, Archs[i]));
646
647    // Lipo if necessary, we do it this way because we need to set the arch flag
648    // so that -Xarch_ gets overwritten.
649    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
650      Actions.append(Inputs.begin(), Inputs.end());
651    else
652      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
653  }
654}
655
656void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
657  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
658  // Start by constructing the list of inputs and their types.
659
660  // Track the current user specified (-x) input. We also explicitly track the
661  // argument used to set the type; we only want to claim the type when we
662  // actually use it, so we warn about unused -x arguments.
663  types::ID InputType = types::TY_Nothing;
664  Arg *InputTypeArg = 0;
665
666  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
667  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
668       it != ie; ++it) {
669    Arg *A = *it;
670
671    if (isa<InputOption>(A->getOption())) {
672      const char *Value = A->getValue(Args);
673      types::ID Ty = types::TY_INVALID;
674
675      // Infer the input type if necessary.
676      if (InputType == types::TY_Nothing) {
677        // If there was an explicit arg for this, claim it.
678        if (InputTypeArg)
679          InputTypeArg->claim();
680
681        // stdin must be handled specially.
682        if (memcmp(Value, "-", 2) == 0) {
683          // If running with -E, treat as a C input (this changes the builtin
684          // macros, for example). This may be overridden by -ObjC below.
685          //
686          // Otherwise emit an error but still use a valid type to avoid
687          // spurious errors (e.g., no inputs).
688          if (!Args.hasArg(options::OPT_E, false))
689            Diag(clang::diag::err_drv_unknown_stdin_type);
690          Ty = types::TY_C;
691        } else {
692          // Otherwise lookup by extension, and fallback to ObjectType if not
693          // found. We use a host hook here because Darwin at least has its own
694          // idea of what .s is.
695          if (const char *Ext = strrchr(Value, '.'))
696            Ty = Host->lookupTypeForExtension(Ext + 1);
697
698          if (Ty == types::TY_INVALID)
699            Ty = types::TY_Object;
700        }
701
702        // -ObjC and -ObjC++ override the default language, but only for "source
703        // files". We just treat everything that isn't a linker input as a
704        // source file.
705        //
706        // FIXME: Clean this up if we move the phase sequence into the type.
707        if (Ty != types::TY_Object) {
708          if (Args.hasArg(options::OPT_ObjC))
709            Ty = types::TY_ObjC;
710          else if (Args.hasArg(options::OPT_ObjCXX))
711            Ty = types::TY_ObjCXX;
712        }
713      } else {
714        assert(InputTypeArg && "InputType set w/o InputTypeArg");
715        InputTypeArg->claim();
716        Ty = InputType;
717      }
718
719      // Check that the file exists. It isn't clear this is worth doing, since
720      // the tool presumably does this anyway, and this just adds an extra stat
721      // to the equation, but this is gcc compatible.
722      if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
723        Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
724      else
725        Inputs.push_back(std::make_pair(Ty, A));
726
727    } else if (A->getOption().isLinkerInput()) {
728      // Just treat as object type, we could make a special type for this if
729      // necessary.
730      Inputs.push_back(std::make_pair(types::TY_Object, A));
731
732    } else if (A->getOption().getId() == options::OPT_x) {
733      InputTypeArg = A;
734      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
735
736      // Follow gcc behavior and treat as linker input for invalid -x
737      // options. Its not clear why we shouldn't just revert to unknown; but
738      // this isn't very important, we might as well be bug comatible.
739      if (!InputType) {
740        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
741        InputType = types::TY_Object;
742      }
743    }
744  }
745
746  if (!SuppressMissingInputWarning && Inputs.empty()) {
747    Diag(clang::diag::err_drv_no_input_files);
748    return;
749  }
750
751  // Determine which compilation mode we are in. We look for options which
752  // affect the phase, starting with the earliest phases, and record which
753  // option we used to determine the final phase.
754  Arg *FinalPhaseArg = 0;
755  phases::ID FinalPhase;
756
757  // -{E,M,MM} only run the preprocessor.
758  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
759      (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
760      (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
761    FinalPhase = phases::Preprocess;
762
763    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
764  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
765             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
766                                              options::OPT__analyze_auto)) ||
767             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
768             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
769    FinalPhase = phases::Compile;
770
771    // -c only runs up to the assembler.
772  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
773    FinalPhase = phases::Assemble;
774
775    // Otherwise do everything.
776  } else
777    FinalPhase = phases::Link;
778
779  // Reject -Z* at the top level, these options should never have been exposed
780  // by gcc.
781  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
782    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
783
784  // Construct the actions to perform.
785  ActionList LinkerInputs;
786  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
787    types::ID InputType = Inputs[i].first;
788    const Arg *InputArg = Inputs[i].second;
789
790    unsigned NumSteps = types::getNumCompilationPhases(InputType);
791    assert(NumSteps && "Invalid number of steps!");
792
793    // If the first step comes after the final phase we are doing as part of
794    // this compilation, warn the user about it.
795    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
796    if (InitialPhase > FinalPhase) {
797      // Claim here to avoid the more general unused warning.
798      InputArg->claim();
799      Diag(clang::diag::warn_drv_input_file_unused)
800        << InputArg->getAsString(Args)
801        << getPhaseName(InitialPhase)
802        << FinalPhaseArg->getOption().getName();
803      continue;
804    }
805
806    // Build the pipeline for this file.
807    Action *Current = new InputAction(*InputArg, InputType);
808    for (unsigned i = 0; i != NumSteps; ++i) {
809      phases::ID Phase = types::getCompilationPhase(InputType, i);
810
811      // We are done if this step is past what the user requested.
812      if (Phase > FinalPhase)
813        break;
814
815      // Queue linker inputs.
816      if (Phase == phases::Link) {
817        assert(i + 1 == NumSteps && "linking must be final compilation step.");
818        LinkerInputs.push_back(Current);
819        Current = 0;
820        break;
821      }
822
823      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
824      // encode this in the steps because the intermediate type depends on
825      // arguments. Just special case here.
826      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
827        continue;
828
829      // Otherwise construct the appropriate action.
830      Current = ConstructPhaseAction(Args, Phase, Current);
831      if (Current->getType() == types::TY_Nothing)
832        break;
833    }
834
835    // If we ended with something, add to the output list.
836    if (Current)
837      Actions.push_back(Current);
838  }
839
840  // Add a link action if necessary.
841  if (!LinkerInputs.empty())
842    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
843}
844
845Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
846                                     Action *Input) const {
847  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
848  // Build the appropriate action.
849  switch (Phase) {
850  case phases::Link: assert(0 && "link action invalid here.");
851  case phases::Preprocess: {
852    types::ID OutputTy;
853    // -{M, MM} alter the output type.
854    if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
855      OutputTy = types::TY_Dependencies;
856    } else {
857      OutputTy = types::getPreprocessedType(Input->getType());
858      assert(OutputTy != types::TY_INVALID &&
859             "Cannot preprocess this input type!");
860    }
861    return new PreprocessJobAction(Input, OutputTy);
862  }
863  case phases::Precompile:
864    return new PrecompileJobAction(Input, types::TY_PCH);
865  case phases::Compile: {
866    if (Args.hasArg(options::OPT_fsyntax_only)) {
867      return new CompileJobAction(Input, types::TY_Nothing);
868    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
869      return new AnalyzeJobAction(Input, types::TY_Plist);
870    } else if (Args.hasArg(options::OPT_emit_ast)) {
871      return new CompileJobAction(Input, types::TY_AST);
872    } else if (Args.hasArg(options::OPT_emit_llvm) ||
873               Args.hasArg(options::OPT_flto) ||
874               Args.hasArg(options::OPT_O4)) {
875      types::ID Output =
876        Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
877      return new CompileJobAction(Input, Output);
878    } else {
879      return new CompileJobAction(Input, types::TY_PP_Asm);
880    }
881  }
882  case phases::Assemble:
883    return new AssembleJobAction(Input, types::TY_Object);
884  }
885
886  assert(0 && "invalid phase in ConstructPhaseAction");
887  return 0;
888}
889
890void Driver::BuildJobs(Compilation &C) const {
891  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
892  bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
893  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
894
895  // FIXME: Pipes are forcibly disabled until we support executing them.
896  if (!CCCPrintBindings)
897    UsePipes = false;
898
899  // -save-temps inhibits pipes.
900  if (SaveTemps && UsePipes) {
901    Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
902    UsePipes = true;
903  }
904
905  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
906
907  // It is an error to provide a -o option if we are making multiple output
908  // files.
909  if (FinalOutput) {
910    unsigned NumOutputs = 0;
911    for (ActionList::const_iterator it = C.getActions().begin(),
912           ie = C.getActions().end(); it != ie; ++it)
913      if ((*it)->getType() != types::TY_Nothing)
914        ++NumOutputs;
915
916    if (NumOutputs > 1) {
917      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
918      FinalOutput = 0;
919    }
920  }
921
922  for (ActionList::const_iterator it = C.getActions().begin(),
923         ie = C.getActions().end(); it != ie; ++it) {
924    Action *A = *it;
925
926    // If we are linking an image for multiple archs then the linker wants
927    // -arch_multiple and -final_output <final image name>. Unfortunately, this
928    // doesn't fit in cleanly because we have to pass this information down.
929    //
930    // FIXME: This is a hack; find a cleaner way to integrate this into the
931    // process.
932    const char *LinkingOutput = 0;
933    if (isa<LipoJobAction>(A)) {
934      if (FinalOutput)
935        LinkingOutput = FinalOutput->getValue(C.getArgs());
936      else
937        LinkingOutput = DefaultImageName.c_str();
938    }
939
940    InputInfo II;
941    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
942                       /*CanAcceptPipe*/ true,
943                       /*AtTopLevel*/ true,
944                       /*LinkingOutput*/ LinkingOutput,
945                       II);
946  }
947
948  // If the user passed -Qunused-arguments or there were errors, don't warn
949  // about any unused arguments.
950  if (Diags.getNumErrors() ||
951      C.getArgs().hasArg(options::OPT_Qunused_arguments))
952    return;
953
954  // Claim -### here.
955  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
956
957  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
958       it != ie; ++it) {
959    Arg *A = *it;
960
961    // FIXME: It would be nice to be able to send the argument to the
962    // Diagnostic, so that extra values, position, and so on could be printed.
963    if (!A->isClaimed()) {
964      if (A->getOption().hasNoArgumentUnused())
965        continue;
966
967      // Suppress the warning automatically if this is just a flag, and it is an
968      // instance of an argument we already claimed.
969      const Option &Opt = A->getOption();
970      if (isa<FlagOption>(Opt)) {
971        bool DuplicateClaimed = false;
972
973        // FIXME: Use iterator.
974        for (ArgList::const_iterator it = C.getArgs().begin(),
975               ie = C.getArgs().end(); it != ie; ++it) {
976          if ((*it)->isClaimed() && (*it)->getOption().matches(Opt.getId())) {
977            DuplicateClaimed = true;
978            break;
979          }
980        }
981
982        if (DuplicateClaimed)
983          continue;
984      }
985
986      Diag(clang::diag::warn_drv_unused_argument)
987        << A->getAsString(C.getArgs());
988    }
989  }
990}
991
992void Driver::BuildJobsForAction(Compilation &C,
993                                const Action *A,
994                                const ToolChain *TC,
995                                bool CanAcceptPipe,
996                                bool AtTopLevel,
997                                const char *LinkingOutput,
998                                InputInfo &Result) const {
999  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1000
1001  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
1002  // FIXME: Pipes are forcibly disabled until we support executing them.
1003  if (!CCCPrintBindings)
1004    UsePipes = false;
1005
1006  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1007    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1008    // just using Args was better?
1009    const Arg &Input = IA->getInputArg();
1010    Input.claim();
1011    if (isa<PositionalArg>(Input)) {
1012      const char *Name = Input.getValue(C.getArgs());
1013      Result = InputInfo(Name, A->getType(), Name);
1014    } else
1015      Result = InputInfo(&Input, A->getType(), "");
1016    return;
1017  }
1018
1019  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1020    const ToolChain *TC = &C.getDefaultToolChain();
1021
1022    std::string Arch;
1023    if (BAA->getArchName())
1024      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1025
1026    BuildJobsForAction(C, *BAA->begin(), TC, CanAcceptPipe, AtTopLevel,
1027                       LinkingOutput, Result);
1028    return;
1029  }
1030
1031  const JobAction *JA = cast<JobAction>(A);
1032  const Tool &T = TC->SelectTool(C, *JA);
1033
1034  // See if we should use an integrated preprocessor. We do so when we have
1035  // exactly one input, since this is the only use case we care about
1036  // (irrelevant since we don't support combine yet).
1037  bool UseIntegratedCPP = false;
1038  const ActionList *Inputs = &A->getInputs();
1039  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
1040    if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1041        !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1042        !C.getArgs().hasArg(options::OPT_save_temps) &&
1043        T.hasIntegratedCPP()) {
1044      UseIntegratedCPP = true;
1045      Inputs = &(*Inputs)[0]->getInputs();
1046    }
1047  }
1048
1049  // Only use pipes when there is exactly one input.
1050  bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
1051  InputInfoList InputInfos;
1052  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1053       it != ie; ++it) {
1054    InputInfo II;
1055    BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
1056                       /*AtTopLevel*/false,
1057                       LinkingOutput,
1058                       II);
1059    InputInfos.push_back(II);
1060  }
1061
1062  // Determine if we should output to a pipe.
1063  bool OutputToPipe = false;
1064  if (CanAcceptPipe && T.canPipeOutput()) {
1065    // Some actions default to writing to a pipe if they are the top level phase
1066    // and there was no user override.
1067    //
1068    // FIXME: Is there a better way to handle this?
1069    if (AtTopLevel) {
1070      if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
1071        OutputToPipe = true;
1072    } else if (UsePipes)
1073      OutputToPipe = true;
1074  }
1075
1076  // Figure out where to put the job (pipes).
1077  Job *Dest = &C.getJobs();
1078  if (InputInfos[0].isPipe()) {
1079    assert(TryToUsePipeInput && "Unrequested pipe!");
1080    assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
1081    Dest = &InputInfos[0].getPipe();
1082  }
1083
1084  // Always use the first input as the base input.
1085  const char *BaseInput = InputInfos[0].getBaseInput();
1086
1087  // Determine the place to write output to (nothing, pipe, or filename) and
1088  // where to put the new job.
1089  if (JA->getType() == types::TY_Nothing) {
1090    Result = InputInfo(A->getType(), BaseInput);
1091  } else if (OutputToPipe) {
1092    // Append to current piped job or create a new one as appropriate.
1093    PipedJob *PJ = dyn_cast<PipedJob>(Dest);
1094    if (!PJ) {
1095      PJ = new PipedJob();
1096      // FIXME: Temporary hack so that -ccc-print-bindings work until we have
1097      // pipe support. Please remove later.
1098      if (!CCCPrintBindings)
1099        cast<JobList>(Dest)->addJob(PJ);
1100      Dest = PJ;
1101    }
1102    Result = InputInfo(PJ, A->getType(), BaseInput);
1103  } else {
1104    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1105                       A->getType(), BaseInput);
1106  }
1107
1108  if (CCCPrintBindings) {
1109    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1110                 << " - \"" << T.getName() << "\", inputs: [";
1111    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1112      llvm::errs() << InputInfos[i].getAsString();
1113      if (i + 1 != e)
1114        llvm::errs() << ", ";
1115    }
1116    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1117  } else {
1118    T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
1119                   C.getArgsForToolChain(TC), LinkingOutput);
1120  }
1121}
1122
1123const char *Driver::GetNamedOutputPath(Compilation &C,
1124                                       const JobAction &JA,
1125                                       const char *BaseInput,
1126                                       bool AtTopLevel) const {
1127  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1128  // Output to a user requested destination?
1129  if (AtTopLevel) {
1130    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1131      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1132  }
1133
1134  // Output to a temporary file?
1135  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1136    std::string TmpName =
1137      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1138    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1139  }
1140
1141  llvm::sys::Path BasePath(BaseInput);
1142  std::string BaseName(BasePath.getLast());
1143
1144  // Determine what the derived output name should be.
1145  const char *NamedOutput;
1146  if (JA.getType() == types::TY_Image) {
1147    NamedOutput = DefaultImageName.c_str();
1148  } else {
1149    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1150    assert(Suffix && "All types used for output should have a suffix.");
1151
1152    std::string::size_type End = std::string::npos;
1153    if (!types::appendSuffixForType(JA.getType()))
1154      End = BaseName.rfind('.');
1155    std::string Suffixed(BaseName.substr(0, End));
1156    Suffixed += '.';
1157    Suffixed += Suffix;
1158    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1159  }
1160
1161  // As an annoying special case, PCH generation doesn't strip the pathname.
1162  if (JA.getType() == types::TY_PCH) {
1163    BasePath.eraseComponent();
1164    if (BasePath.isEmpty())
1165      BasePath = NamedOutput;
1166    else
1167      BasePath.appendComponent(NamedOutput);
1168    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1169  } else {
1170    return C.addResultFile(NamedOutput);
1171  }
1172}
1173
1174llvm::sys::Path Driver::GetFilePath(const char *Name,
1175                                    const ToolChain &TC) const {
1176  const ToolChain::path_list &List = TC.getFilePaths();
1177  for (ToolChain::path_list::const_iterator
1178         it = List.begin(), ie = List.end(); it != ie; ++it) {
1179    llvm::sys::Path P(*it);
1180    P.appendComponent(Name);
1181    if (P.exists())
1182      return P;
1183  }
1184
1185  return llvm::sys::Path(Name);
1186}
1187
1188llvm::sys::Path Driver::GetProgramPath(const char *Name,
1189                                       const ToolChain &TC,
1190                                       bool WantFile) const {
1191  const ToolChain::path_list &List = TC.getProgramPaths();
1192  for (ToolChain::path_list::const_iterator
1193         it = List.begin(), ie = List.end(); it != ie; ++it) {
1194    llvm::sys::Path P(*it);
1195    P.appendComponent(Name);
1196    if (WantFile ? P.exists() : P.canExecute())
1197      return P;
1198  }
1199
1200  // If all else failed, search the path.
1201  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1202  if (!P.empty())
1203    return P;
1204
1205  return llvm::sys::Path(Name);
1206}
1207
1208std::string Driver::GetTemporaryPath(const char *Suffix) const {
1209  // FIXME: This is lame; sys::Path should provide this function (in particular,
1210  // it should know how to find the temporary files dir).
1211  std::string Error;
1212  const char *TmpDir = ::getenv("TMPDIR");
1213  if (!TmpDir)
1214    TmpDir = ::getenv("TEMP");
1215  if (!TmpDir)
1216    TmpDir = ::getenv("TMP");
1217  if (!TmpDir)
1218    TmpDir = "/tmp";
1219  llvm::sys::Path P(TmpDir);
1220  P.appendComponent("cc");
1221  if (P.makeUnique(false, &Error)) {
1222    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1223    return "";
1224  }
1225
1226  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1227  P.eraseFromDisk(false, 0);
1228
1229  P.appendSuffix(Suffix);
1230  return P.str();
1231}
1232
1233const HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1234  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1235  llvm::Triple Triple(TripleStr);
1236
1237  switch (Triple.getOS()) {
1238  case llvm::Triple::AuroraUX:
1239    return createAuroraUXHostInfo(*this, Triple);
1240  case llvm::Triple::Darwin:
1241    return createDarwinHostInfo(*this, Triple);
1242  case llvm::Triple::DragonFly:
1243    return createDragonFlyHostInfo(*this, Triple);
1244  case llvm::Triple::OpenBSD:
1245    return createOpenBSDHostInfo(*this, Triple);
1246  case llvm::Triple::FreeBSD:
1247    return createFreeBSDHostInfo(*this, Triple);
1248  case llvm::Triple::Linux:
1249    return createLinuxHostInfo(*this, Triple);
1250  default:
1251    return createUnknownHostInfo(*this, Triple);
1252  }
1253}
1254
1255bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1256                                    const llvm::Triple &Triple) const {
1257  // Check if user requested no clang, or clang doesn't understand this type (we
1258  // only handle single inputs for now).
1259  if (!CCCUseClang || JA.size() != 1 ||
1260      !types::isAcceptedByClang((*JA.begin())->getType()))
1261    return false;
1262
1263  // Otherwise make sure this is an action clang understands.
1264  if (isa<PreprocessJobAction>(JA)) {
1265    if (!CCCUseClangCPP) {
1266      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1267      return false;
1268    }
1269  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1270    return false;
1271
1272  // Use clang for C++?
1273  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1274    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1275    return false;
1276  }
1277
1278  // Always use clang for precompiling and AST generation, regardless of archs.
1279  if (isa<PrecompileJobAction>(JA) || JA.getType() == types::TY_AST)
1280    return true;
1281
1282  // Finally, don't use clang if this isn't one of the user specified archs to
1283  // build.
1284  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1285    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1286    return false;
1287  }
1288
1289  return true;
1290}
1291
1292/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1293/// grouped values as integers. Numbers which are not provided are set to 0.
1294///
1295/// \return True if the entire string was parsed (9.2), or all groups were
1296/// parsed (10.3.5extrastuff).
1297bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1298                               unsigned &Minor, unsigned &Micro,
1299                               bool &HadExtra) {
1300  HadExtra = false;
1301
1302  Major = Minor = Micro = 0;
1303  if (*Str == '\0')
1304    return true;
1305
1306  char *End;
1307  Major = (unsigned) strtol(Str, &End, 10);
1308  if (*Str != '\0' && *End == '\0')
1309    return true;
1310  if (*End != '.')
1311    return false;
1312
1313  Str = End+1;
1314  Minor = (unsigned) strtol(Str, &End, 10);
1315  if (*Str != '\0' && *End == '\0')
1316    return true;
1317  if (*End != '.')
1318    return false;
1319
1320  Str = End+1;
1321  Micro = (unsigned) strtol(Str, &End, 10);
1322  if (*Str != '\0' && *End == '\0')
1323    return true;
1324  if (Str == End)
1325    return false;
1326  HadExtra = true;
1327  return true;
1328}
1329