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