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