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