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