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/Job.h"
18 #include "clang/Driver/OptTable.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 
24 #include "clang/Basic/Version.h"
25 
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/Program.h"
35 
36 #include "InputInfo.h"
37 #include "ToolChains.h"
38 
39 #include <map>
40 
41 #include "clang/Config/config.h"
42 
43 using namespace clang::driver;
44 using namespace clang;
45 
46 Driver::Driver(StringRef ClangExecutable,
47                StringRef DefaultTargetTriple,
48                StringRef DefaultImageName,
49                bool IsProduction,
50                DiagnosticsEngine &Diags)
51   : Opts(createDriverOptTable()), Diags(Diags),
52     ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
53     UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
54     DefaultImageName(DefaultImageName),
55     DriverTitle("clang \"gcc-compatible\" driver"),
56     CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
57     CCLogDiagnosticsFilename(0), CCCIsCXX(false),
58     CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
59     CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
60     CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
61     CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true),
62     ForcedClangUse(false), CCCUsePCH(true), SuppressMissingInputWarning(false) {
63   if (IsProduction) {
64     // In a "production" build, only use clang on architectures we expect to
65     // work.
66     //
67     // During development its more convenient to always have the driver use
68     // clang, but we don't want users to be confused when things don't work, or
69     // to file bugs for things we don't support.
70     CCCClangArchs.insert(llvm::Triple::x86);
71     CCCClangArchs.insert(llvm::Triple::x86_64);
72     CCCClangArchs.insert(llvm::Triple::arm);
73   }
74 
75   Name = llvm::sys::path::stem(ClangExecutable);
76   Dir  = llvm::sys::path::parent_path(ClangExecutable);
77 
78   // Compute the path to the resource directory.
79   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
80   SmallString<128> P(Dir);
81   if (ClangResourceDir != "")
82     llvm::sys::path::append(P, ClangResourceDir);
83   else
84     llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
85   ResourceDir = P.str();
86 }
87 
88 Driver::~Driver() {
89   delete Opts;
90 
91   for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(),
92                                               E = ToolChains.end();
93        I != E; ++I)
94     delete I->second;
95 }
96 
97 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
98   llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
99   unsigned MissingArgIndex, MissingArgCount;
100   InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
101                                            MissingArgIndex, MissingArgCount);
102 
103   // Check for missing argument error.
104   if (MissingArgCount)
105     Diag(clang::diag::err_drv_missing_argument)
106       << Args->getArgString(MissingArgIndex) << MissingArgCount;
107 
108   // Check for unsupported options.
109   for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
110        it != ie; ++it) {
111     Arg *A = *it;
112     if (A->getOption().isUnsupported()) {
113       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
114       continue;
115     }
116 
117     // Warn about -mcpu= without an argument.
118     if (A->getOption().matches(options::OPT_mcpu_EQ) &&
119         A->containsValue("")) {
120       Diag(clang::diag::warn_drv_empty_joined_argument) <<
121         A->getAsString(*Args);
122     }
123   }
124 
125   return Args;
126 }
127 
128 // Determine which compilation mode we are in. We look for options which
129 // affect the phase, starting with the earliest phases, and record which
130 // option we used to determine the final phase.
131 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
132 const {
133   Arg *PhaseArg = 0;
134   phases::ID FinalPhase;
135 
136   // -{E,M,MM} only run the preprocessor.
137   if (CCCIsCPP ||
138       (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
139       (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) {
140     FinalPhase = phases::Preprocess;
141 
142     // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
143   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
144              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
145              (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
146              (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
147              (PhaseArg = DAL.getLastArg(options::OPT__analyze,
148                                         options::OPT__analyze_auto)) ||
149              (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
150              (PhaseArg = DAL.getLastArg(options::OPT_S))) {
151     FinalPhase = phases::Compile;
152 
153     // -c only runs up to the assembler.
154   } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
155     FinalPhase = phases::Assemble;
156 
157     // Otherwise do everything.
158   } else
159     FinalPhase = phases::Link;
160 
161   if (FinalPhaseArg)
162     *FinalPhaseArg = PhaseArg;
163 
164   return FinalPhase;
165 }
166 
167 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
168   DerivedArgList *DAL = new DerivedArgList(Args);
169 
170   bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
171   for (ArgList::const_iterator it = Args.begin(),
172          ie = Args.end(); it != ie; ++it) {
173     const Arg *A = *it;
174 
175     // Unfortunately, we have to parse some forwarding options (-Xassembler,
176     // -Xlinker, -Xpreprocessor) because we either integrate their functionality
177     // (assembler and preprocessor), or bypass a previous driver ('collect2').
178 
179     // Rewrite linker options, to replace --no-demangle with a custom internal
180     // option.
181     if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
182          A->getOption().matches(options::OPT_Xlinker)) &&
183         A->containsValue("--no-demangle")) {
184       // Add the rewritten no-demangle argument.
185       DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
186 
187       // Add the remaining values as Xlinker arguments.
188       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
189         if (StringRef(A->getValue(Args, i)) != "--no-demangle")
190           DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
191                               A->getValue(Args, i));
192 
193       continue;
194     }
195 
196     // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
197     // some build systems. We don't try to be complete here because we don't
198     // care to encourage this usage model.
199     if (A->getOption().matches(options::OPT_Wp_COMMA) &&
200         A->getNumValues() == 2 &&
201         (A->getValue(Args, 0) == StringRef("-MD") ||
202          A->getValue(Args, 0) == StringRef("-MMD"))) {
203       // Rewrite to -MD/-MMD along with -MF.
204       if (A->getValue(Args, 0) == StringRef("-MD"))
205         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
206       else
207         DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
208       DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
209                           A->getValue(Args, 1));
210       continue;
211     }
212 
213     // Rewrite reserved library names.
214     if (A->getOption().matches(options::OPT_l)) {
215       StringRef Value = A->getValue(Args);
216 
217       // Rewrite unless -nostdlib is present.
218       if (!HasNostdlib && Value == "stdc++") {
219         DAL->AddFlagArg(A, Opts->getOption(
220                               options::OPT_Z_reserved_lib_stdcxx));
221         continue;
222       }
223 
224       // Rewrite unconditionally.
225       if (Value == "cc_kext") {
226         DAL->AddFlagArg(A, Opts->getOption(
227                               options::OPT_Z_reserved_lib_cckext));
228         continue;
229       }
230     }
231 
232     DAL->append(*it);
233   }
234 
235   // Add a default value of -mlinker-version=, if one was given and the user
236   // didn't specify one.
237 #if defined(HOST_LINK_VERSION)
238   if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
239     DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
240                       HOST_LINK_VERSION);
241     DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
242   }
243 #endif
244 
245   return DAL;
246 }
247 
248 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
249   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
250 
251   // FIXME: Handle environment options which affect driver behavior, somewhere
252   // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
253 
254   if (char *env = ::getenv("COMPILER_PATH")) {
255     StringRef CompilerPath = env;
256     while (!CompilerPath.empty()) {
257       std::pair<StringRef, StringRef> Split = CompilerPath.split(':');
258       PrefixDirs.push_back(Split.first);
259       CompilerPath = Split.second;
260     }
261   }
262 
263   // FIXME: What are we going to do with -V and -b?
264 
265   // FIXME: This stuff needs to go into the Compilation, not the driver.
266   bool CCCPrintOptions = false, CCCPrintActions = false;
267 
268   InputArgList *Args = ParseArgStrings(ArgList.slice(1));
269 
270   // -no-canonical-prefixes is used very early in main.
271   Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
272 
273   // Ignore -pipe.
274   Args->ClaimAllArgs(options::OPT_pipe);
275 
276   // Extract -ccc args.
277   //
278   // FIXME: We need to figure out where this behavior should live. Most of it
279   // should be outside in the client; the parts that aren't should have proper
280   // options, either by introducing new ones or by overloading gcc ones like -V
281   // or -b.
282   CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
283   CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
284   CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
285   CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
286   CCCEcho = Args->hasArg(options::OPT_ccc_echo);
287   if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
288     CCCGenericGCCName = A->getValue(*Args);
289   CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
290                                  options::OPT_ccc_no_clang_cxx,
291                                  CCCUseClangCXX);
292   CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
293                             options::OPT_ccc_pch_is_pth);
294   CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
295   CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
296   if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
297     StringRef Cur = A->getValue(*Args);
298 
299     CCCClangArchs.clear();
300     while (!Cur.empty()) {
301       std::pair<StringRef, StringRef> Split = Cur.split(',');
302 
303       if (!Split.first.empty()) {
304         llvm::Triple::ArchType Arch =
305           llvm::Triple(Split.first, "", "").getArch();
306 
307         if (Arch == llvm::Triple::UnknownArch)
308           Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
309 
310         CCCClangArchs.insert(Arch);
311       }
312 
313       Cur = Split.second;
314     }
315   }
316   // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
317   // and getToolChain is const.
318   if (const Arg *A = Args->getLastArg(options::OPT_target))
319     DefaultTargetTriple = A->getValue(*Args);
320   if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
321     Dir = InstalledDir = A->getValue(*Args);
322   for (arg_iterator it = Args->filtered_begin(options::OPT_B),
323          ie = Args->filtered_end(); it != ie; ++it) {
324     const Arg *A = *it;
325     A->claim();
326     PrefixDirs.push_back(A->getValue(*Args, 0));
327   }
328   if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
329     SysRoot = A->getValue(*Args);
330   if (Args->hasArg(options::OPT_nostdlib))
331     UseStdLib = false;
332 
333   // Perform the default argument translations.
334   DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
335 
336   // Owned by the host.
337   const ToolChain &TC = getToolChain(*Args);
338 
339   // The compilation takes ownership of Args.
340   Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
341 
342   // FIXME: This behavior shouldn't be here.
343   if (CCCPrintOptions) {
344     PrintOptions(C->getInputArgs());
345     return C;
346   }
347 
348   if (!HandleImmediateArgs(*C))
349     return C;
350 
351   // Construct the list of inputs.
352   InputList Inputs;
353   BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
354 
355   // Construct the list of abstract actions to perform for this compilation. On
356   // Darwin target OSes this uses the driver-driver and universal actions.
357   if (TC.getTriple().isOSDarwin())
358     BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
359                           Inputs, C->getActions());
360   else
361     BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
362                  C->getActions());
363 
364   if (CCCPrintActions) {
365     PrintActions(*C);
366     return C;
367   }
368 
369   BuildJobs(*C);
370 
371   return C;
372 }
373 
374 // When clang crashes, produce diagnostic information including the fully
375 // preprocessed source file(s).  Request that the developer attach the
376 // diagnostic information to a bug report.
377 void Driver::generateCompilationDiagnostics(Compilation &C,
378                                             const Command *FailingCommand) {
379   if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
380     return;
381 
382   // Don't try to generate diagnostics for link jobs.
383   if (FailingCommand && FailingCommand->getCreator().isLinkJob())
384     return;
385 
386   // Print the version of the compiler.
387   PrintVersion(C, llvm::errs());
388 
389   Diag(clang::diag::note_drv_command_failed_diag_msg)
390     << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
391     "crash backtrace, preprocessed source, and associated run script.";
392 
393   // Suppress driver output and emit preprocessor output to temp file.
394   CCCIsCPP = true;
395   CCGenDiagnostics = true;
396   C.getArgs().AddFlagArg(0, Opts->getOption(options::OPT_frewrite_includes));
397 
398   // Save the original job command(s).
399   std::string Cmd;
400   llvm::raw_string_ostream OS(Cmd);
401   if (FailingCommand)
402     C.PrintJob(OS, *FailingCommand, "\n", false);
403   else
404     // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an
405     // associated FailingCommand, so just pass all jobs.
406     C.PrintJob(OS, C.getJobs(), "\n", false);
407   OS.flush();
408 
409   // Clear stale state and suppress tool output.
410   C.initCompilationForDiagnostics();
411   Diags.Reset();
412 
413   // Construct the list of inputs.
414   InputList Inputs;
415   BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
416 
417   for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
418     bool IgnoreInput = false;
419 
420     // Ignore input from stdin or any inputs that cannot be preprocessed.
421     if (!strcmp(it->second->getValue(C.getArgs()), "-")) {
422       Diag(clang::diag::note_drv_command_failed_diag_msg)
423         << "Error generating preprocessed source(s) - ignoring input from stdin"
424         ".";
425       IgnoreInput = true;
426     } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
427       IgnoreInput = true;
428     }
429 
430     if (IgnoreInput) {
431       it = Inputs.erase(it);
432       ie = Inputs.end();
433     } else {
434       ++it;
435     }
436   }
437 
438   // Don't attempt to generate preprocessed files if multiple -arch options are
439   // used, unless they're all duplicates.
440   llvm::StringSet<> ArchNames;
441   for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
442        it != ie; ++it) {
443     Arg *A = *it;
444     if (A->getOption().matches(options::OPT_arch)) {
445       StringRef ArchName = A->getValue(C.getArgs());
446       ArchNames.insert(ArchName);
447     }
448   }
449   if (ArchNames.size() > 1) {
450     Diag(clang::diag::note_drv_command_failed_diag_msg)
451       << "Error generating preprocessed source(s) - cannot generate "
452       "preprocessed source with multiple -arch options.";
453     return;
454   }
455 
456   if (Inputs.empty()) {
457     Diag(clang::diag::note_drv_command_failed_diag_msg)
458       << "Error generating preprocessed source(s) - no preprocessable inputs.";
459     return;
460   }
461 
462   // Construct the list of abstract actions to perform for this compilation. On
463   // Darwin OSes this uses the driver-driver and builds universal actions.
464   const ToolChain &TC = C.getDefaultToolChain();
465   if (TC.getTriple().isOSDarwin())
466     BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
467   else
468     BuildActions(TC, C.getArgs(), Inputs, C.getActions());
469 
470   BuildJobs(C);
471 
472   // If there were errors building the compilation, quit now.
473   if (Diags.hasErrorOccurred()) {
474     Diag(clang::diag::note_drv_command_failed_diag_msg)
475       << "Error generating preprocessed source(s).";
476     return;
477   }
478 
479   // Generate preprocessed output.
480   FailingCommand = 0;
481   int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
482 
483   // If the command succeeded, we are done.
484   if (Res == 0) {
485     Diag(clang::diag::note_drv_command_failed_diag_msg)
486       << "\n********************\n\n"
487       "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
488       "Preprocessed source(s) and associated run script(s) are located at:";
489     ArgStringList Files = C.getTempFiles();
490     for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
491          it != ie; ++it) {
492       Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
493 
494       std::string Err;
495       std::string Script = StringRef(*it).rsplit('.').first;
496       Script += ".sh";
497       llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
498                                     llvm::raw_fd_ostream::F_Excl |
499                                     llvm::raw_fd_ostream::F_Binary);
500       if (!Err.empty()) {
501         Diag(clang::diag::note_drv_command_failed_diag_msg)
502           << "Error generating run script: " + Script + " " + Err;
503       } else {
504         // Strip away options not necessary to reproduce the crash.
505         // FIXME: This doesn't work with quotes (e.g., -D "foo bar").
506         SmallVector<std::string, 16> Flag;
507         Flag.push_back("-D ");
508         Flag.push_back("-F");
509         Flag.push_back("-I ");
510         Flag.push_back("-M ");
511         Flag.push_back("-MD ");
512         Flag.push_back("-MF ");
513         Flag.push_back("-MG ");
514         Flag.push_back("-MM ");
515         Flag.push_back("-MMD ");
516         Flag.push_back("-MP ");
517         Flag.push_back("-MQ ");
518         Flag.push_back("-MT ");
519         Flag.push_back("-o ");
520         Flag.push_back("-coverage-file ");
521         Flag.push_back("-dependency-file ");
522         Flag.push_back("-fdebug-compilation-dir ");
523         Flag.push_back("-fmodule-cache-path ");
524         Flag.push_back("-idirafter ");
525         Flag.push_back("-include ");
526         Flag.push_back("-include-pch ");
527         Flag.push_back("-internal-isystem ");
528         Flag.push_back("-internal-externc-isystem ");
529         Flag.push_back("-iprefix ");
530         Flag.push_back("-iwithprefix ");
531         Flag.push_back("-iwithprefixbefore ");
532         Flag.push_back("-isysroot ");
533         Flag.push_back("-isystem ");
534         Flag.push_back("-iquote ");
535         Flag.push_back("-resource-dir ");
536         Flag.push_back("-serialize-diagnostic-file ");
537         for (unsigned i = 0, e = Flag.size(); i < e; ++i) {
538           size_t I = 0, E = 0;
539           do {
540             I = Cmd.find(Flag[i], I);
541             if (I == std::string::npos) break;
542 
543             E = Cmd.find(" ", I + Flag[i].length());
544             if (E == std::string::npos) break;
545             // The -D option is not removed.  Instead, the argument is quoted.
546             if (Flag[i] != "-D ") {
547               Cmd.erase(I, E - I + 1);
548             } else {
549               Cmd.insert(I+3, "\"");
550               Cmd.insert(++E, "\"");
551               I = E;
552             }
553           } while(1);
554         }
555         // Append the new filename with correct preprocessed suffix.
556         size_t I, E;
557         I = Cmd.find("-main-file-name ");
558         assert (I != std::string::npos && "Expected to find -main-file-name");
559         I += 16;
560         E = Cmd.find(" ", I);
561         assert (E != std::string::npos && "-main-file-name missing argument?");
562         StringRef OldFilename = StringRef(Cmd).slice(I, E);
563         StringRef NewFilename = llvm::sys::path::filename(*it);
564         I = StringRef(Cmd).rfind(OldFilename);
565         E = I + OldFilename.size();
566         I = Cmd.rfind(" ", I) + 1;
567         Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size());
568         ScriptOS << Cmd;
569         Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
570       }
571     }
572     Diag(clang::diag::note_drv_command_failed_diag_msg)
573       << "\n\n********************";
574   } else {
575     // Failure, remove preprocessed files.
576     if (!C.getArgs().hasArg(options::OPT_save_temps))
577       C.CleanupFileList(C.getTempFiles(), true);
578 
579     Diag(clang::diag::note_drv_command_failed_diag_msg)
580       << "Error generating preprocessed source(s).";
581   }
582 }
583 
584 int Driver::ExecuteCompilation(const Compilation &C,
585                                const Command *&FailingCommand) const {
586   // Just print if -### was present.
587   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
588     C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
589     return 0;
590   }
591 
592   // If there were errors building the compilation, quit now.
593   if (Diags.hasErrorOccurred())
594     return 1;
595 
596   int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
597 
598   // Remove temp files.
599   C.CleanupFileList(C.getTempFiles());
600 
601   // If the command succeeded, we are done.
602   if (Res == 0)
603     return Res;
604 
605   // Otherwise, remove result files as well.
606   if (!C.getArgs().hasArg(options::OPT_save_temps)) {
607     C.CleanupFileList(C.getResultFiles(), true);
608 
609     // Failure result files are valid unless we crashed.
610     if (Res < 0)
611       C.CleanupFileList(C.getFailureResultFiles(), true);
612   }
613 
614   // Print extra information about abnormal failures, if possible.
615   //
616   // This is ad-hoc, but we don't want to be excessively noisy. If the result
617   // status was 1, assume the command failed normally. In particular, if it was
618   // the compiler then assume it gave a reasonable error code. Failures in other
619   // tools are less common, and they generally have worse diagnostics, so always
620   // print the diagnostic there.
621   const Tool &FailingTool = FailingCommand->getCreator();
622 
623   if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
624     // FIXME: See FIXME above regarding result code interpretation.
625     if (Res < 0)
626       Diag(clang::diag::err_drv_command_signalled)
627         << FailingTool.getShortName();
628     else
629       Diag(clang::diag::err_drv_command_failed)
630         << FailingTool.getShortName() << Res;
631   }
632 
633   return Res;
634 }
635 
636 void Driver::PrintOptions(const ArgList &Args) const {
637   unsigned i = 0;
638   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
639        it != ie; ++it, ++i) {
640     Arg *A = *it;
641     llvm::errs() << "Option " << i << " - "
642                  << "Name: \"" << A->getOption().getName() << "\", "
643                  << "Values: {";
644     for (unsigned j = 0; j < A->getNumValues(); ++j) {
645       if (j)
646         llvm::errs() << ", ";
647       llvm::errs() << '"' << A->getValue(Args, j) << '"';
648     }
649     llvm::errs() << "}\n";
650   }
651 }
652 
653 void Driver::PrintHelp(bool ShowHidden) const {
654   getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
655                       ShowHidden);
656 }
657 
658 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
659   // FIXME: The following handlers should use a callback mechanism, we don't
660   // know what the client would like to do.
661   OS << getClangFullVersion() << '\n';
662   const ToolChain &TC = C.getDefaultToolChain();
663   OS << "Target: " << TC.getTripleString() << '\n';
664 
665   // Print the threading model.
666   //
667   // FIXME: Implement correctly.
668   OS << "Thread model: " << "posix" << '\n';
669 }
670 
671 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
672 /// option.
673 static void PrintDiagnosticCategories(raw_ostream &OS) {
674   // Skip the empty category.
675   for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
676        i != max; ++i)
677     OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
678 }
679 
680 bool Driver::HandleImmediateArgs(const Compilation &C) {
681   // The order these options are handled in gcc is all over the place, but we
682   // don't expect inconsistencies w.r.t. that to matter in practice.
683 
684   if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
685     llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
686     return false;
687   }
688 
689   if (C.getArgs().hasArg(options::OPT_dumpversion)) {
690     // Since -dumpversion is only implemented for pedantic GCC compatibility, we
691     // return an answer which matches our definition of __VERSION__.
692     //
693     // If we want to return a more correct answer some day, then we should
694     // introduce a non-pedantically GCC compatible mode to Clang in which we
695     // provide sensible definitions for -dumpversion, __VERSION__, etc.
696     llvm::outs() << "4.2.1\n";
697     return false;
698   }
699 
700   if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
701     PrintDiagnosticCategories(llvm::outs());
702     return false;
703   }
704 
705   if (C.getArgs().hasArg(options::OPT_help) ||
706       C.getArgs().hasArg(options::OPT__help_hidden)) {
707     PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
708     return false;
709   }
710 
711   if (C.getArgs().hasArg(options::OPT__version)) {
712     // Follow gcc behavior and use stdout for --version and stderr for -v.
713     PrintVersion(C, llvm::outs());
714     return false;
715   }
716 
717   if (C.getArgs().hasArg(options::OPT_v) ||
718       C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
719     PrintVersion(C, llvm::errs());
720     SuppressMissingInputWarning = true;
721   }
722 
723   const ToolChain &TC = C.getDefaultToolChain();
724   if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
725     llvm::outs() << "programs: =";
726     for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
727            ie = TC.getProgramPaths().end(); it != ie; ++it) {
728       if (it != TC.getProgramPaths().begin())
729         llvm::outs() << ':';
730       llvm::outs() << *it;
731     }
732     llvm::outs() << "\n";
733     llvm::outs() << "libraries: =" << ResourceDir;
734 
735     StringRef sysroot = C.getSysRoot();
736 
737     for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
738            ie = TC.getFilePaths().end(); it != ie; ++it) {
739       llvm::outs() << ':';
740       const char *path = it->c_str();
741       if (path[0] == '=')
742         llvm::outs() << sysroot << path + 1;
743       else
744         llvm::outs() << path;
745     }
746     llvm::outs() << "\n";
747     return false;
748   }
749 
750   // FIXME: The following handlers should use a callback mechanism, we don't
751   // know what the client would like to do.
752   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
753     llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
754     return false;
755   }
756 
757   if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
758     llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
759     return false;
760   }
761 
762   if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
763     llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
764     return false;
765   }
766 
767   if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
768     // FIXME: We need tool chain support for this.
769     llvm::outs() << ".;\n";
770 
771     switch (C.getDefaultToolChain().getTriple().getArch()) {
772     default:
773       break;
774 
775     case llvm::Triple::x86_64:
776       llvm::outs() << "x86_64;@m64" << "\n";
777       break;
778 
779     case llvm::Triple::ppc64:
780       llvm::outs() << "ppc64;@m64" << "\n";
781       break;
782     }
783     return false;
784   }
785 
786   // FIXME: What is the difference between print-multi-directory and
787   // print-multi-os-directory?
788   if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
789       C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
790     switch (C.getDefaultToolChain().getTriple().getArch()) {
791     default:
792     case llvm::Triple::x86:
793     case llvm::Triple::ppc:
794       llvm::outs() << "." << "\n";
795       break;
796 
797     case llvm::Triple::x86_64:
798       llvm::outs() << "x86_64" << "\n";
799       break;
800 
801     case llvm::Triple::ppc64:
802       llvm::outs() << "ppc64" << "\n";
803       break;
804     }
805     return false;
806   }
807 
808   return true;
809 }
810 
811 static unsigned PrintActions1(const Compilation &C, Action *A,
812                               std::map<Action*, unsigned> &Ids) {
813   if (Ids.count(A))
814     return Ids[A];
815 
816   std::string str;
817   llvm::raw_string_ostream os(str);
818 
819   os << Action::getClassName(A->getKind()) << ", ";
820   if (InputAction *IA = dyn_cast<InputAction>(A)) {
821     os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
822   } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
823     os << '"' << BIA->getArchName() << '"'
824        << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
825   } else {
826     os << "{";
827     for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
828       os << PrintActions1(C, *it, Ids);
829       ++it;
830       if (it != ie)
831         os << ", ";
832     }
833     os << "}";
834   }
835 
836   unsigned Id = Ids.size();
837   Ids[A] = Id;
838   llvm::errs() << Id << ": " << os.str() << ", "
839                << types::getTypeName(A->getType()) << "\n";
840 
841   return Id;
842 }
843 
844 void Driver::PrintActions(const Compilation &C) const {
845   std::map<Action*, unsigned> Ids;
846   for (ActionList::const_iterator it = C.getActions().begin(),
847          ie = C.getActions().end(); it != ie; ++it)
848     PrintActions1(C, *it, Ids);
849 }
850 
851 /// \brief Check whether the given input tree contains any compilation or
852 /// assembly actions.
853 static bool ContainsCompileOrAssembleAction(const Action *A) {
854   if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
855     return true;
856 
857   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
858     if (ContainsCompileOrAssembleAction(*it))
859       return true;
860 
861   return false;
862 }
863 
864 void Driver::BuildUniversalActions(const ToolChain &TC,
865                                    const DerivedArgList &Args,
866                                    const InputList &BAInputs,
867                                    ActionList &Actions) const {
868   llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
869   // Collect the list of architectures. Duplicates are allowed, but should only
870   // be handled once (in the order seen).
871   llvm::StringSet<> ArchNames;
872   SmallVector<const char *, 4> Archs;
873   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
874        it != ie; ++it) {
875     Arg *A = *it;
876 
877     if (A->getOption().matches(options::OPT_arch)) {
878       // Validate the option here; we don't save the type here because its
879       // particular spelling may participate in other driver choices.
880       llvm::Triple::ArchType Arch =
881         llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
882       if (Arch == llvm::Triple::UnknownArch) {
883         Diag(clang::diag::err_drv_invalid_arch_name)
884           << A->getAsString(Args);
885         continue;
886       }
887 
888       A->claim();
889       if (ArchNames.insert(A->getValue(Args)))
890         Archs.push_back(A->getValue(Args));
891     }
892   }
893 
894   // When there is no explicit arch for this platform, make sure we still bind
895   // the architecture (to the default) so that -Xarch_ is handled correctly.
896   if (!Archs.size())
897     Archs.push_back(Args.MakeArgString(TC.getArchName()));
898 
899   // FIXME: We killed off some others but these aren't yet detected in a
900   // functional manner. If we added information to jobs about which "auxiliary"
901   // files they wrote then we could detect the conflict these cause downstream.
902   if (Archs.size() > 1) {
903     // No recovery needed, the point of this is just to prevent
904     // overwriting the same files.
905     if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
906       Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
907         << A->getAsString(Args);
908   }
909 
910   ActionList SingleActions;
911   BuildActions(TC, Args, BAInputs, SingleActions);
912 
913   // Add in arch bindings for every top level action, as well as lipo and
914   // dsymutil steps if needed.
915   for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
916     Action *Act = SingleActions[i];
917 
918     // Make sure we can lipo this kind of output. If not (and it is an actual
919     // output) then we disallow, since we can't create an output file with the
920     // right name without overwriting it. We could remove this oddity by just
921     // changing the output names to include the arch, which would also fix
922     // -save-temps. Compatibility wins for now.
923 
924     if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
925       Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
926         << types::getTypeName(Act->getType());
927 
928     ActionList Inputs;
929     for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
930       Inputs.push_back(new BindArchAction(Act, Archs[i]));
931       if (i != 0)
932         Inputs.back()->setOwnsInputs(false);
933     }
934 
935     // Lipo if necessary, we do it this way because we need to set the arch flag
936     // so that -Xarch_ gets overwritten.
937     if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
938       Actions.append(Inputs.begin(), Inputs.end());
939     else
940       Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
941 
942     // Handle debug info queries.
943     Arg *A = Args.getLastArg(options::OPT_g_Group);
944     if (A && !A->getOption().matches(options::OPT_g0) &&
945         !A->getOption().matches(options::OPT_gstabs) &&
946         ContainsCompileOrAssembleAction(Actions.back())) {
947 
948       // Add a 'dsymutil' step if necessary, when debug info is enabled and we
949       // have a compile input. We need to run 'dsymutil' ourselves in such cases
950       // because the debug info will refer to a temporary object file which is
951       // will be removed at the end of the compilation process.
952       if (Act->getType() == types::TY_Image) {
953         ActionList Inputs;
954         Inputs.push_back(Actions.back());
955         Actions.pop_back();
956         Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
957       }
958 
959       // Verify the output (debug information only) if we passed '-verify'.
960       if (Args.hasArg(options::OPT_verify)) {
961         ActionList VerifyInputs;
962         VerifyInputs.push_back(Actions.back());
963         Actions.pop_back();
964         Actions.push_back(new VerifyJobAction(VerifyInputs,
965                                               types::TY_Nothing));
966       }
967     }
968   }
969 }
970 
971 // Construct a the list of inputs and their types.
972 void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args,
973                          InputList &Inputs) const {
974   // Track the current user specified (-x) input. We also explicitly track the
975   // argument used to set the type; we only want to claim the type when we
976   // actually use it, so we warn about unused -x arguments.
977   types::ID InputType = types::TY_Nothing;
978   Arg *InputTypeArg = 0;
979 
980   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
981        it != ie; ++it) {
982     Arg *A = *it;
983 
984     if (isa<InputOption>(A->getOption())) {
985       const char *Value = A->getValue(Args);
986       types::ID Ty = types::TY_INVALID;
987 
988       // Infer the input type if necessary.
989       if (InputType == types::TY_Nothing) {
990         // If there was an explicit arg for this, claim it.
991         if (InputTypeArg)
992           InputTypeArg->claim();
993 
994         // stdin must be handled specially.
995         if (memcmp(Value, "-", 2) == 0) {
996           // If running with -E, treat as a C input (this changes the builtin
997           // macros, for example). This may be overridden by -ObjC below.
998           //
999           // Otherwise emit an error but still use a valid type to avoid
1000           // spurious errors (e.g., no inputs).
1001           if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
1002             Diag(clang::diag::err_drv_unknown_stdin_type);
1003           Ty = types::TY_C;
1004         } else {
1005           // Otherwise lookup by extension.
1006           // Fallback is C if invoked as C preprocessor or Object otherwise.
1007           // We use a host hook here because Darwin at least has its own
1008           // idea of what .s is.
1009           if (const char *Ext = strrchr(Value, '.'))
1010             Ty = TC.LookupTypeForExtension(Ext + 1);
1011 
1012           if (Ty == types::TY_INVALID) {
1013             if (CCCIsCPP)
1014               Ty = types::TY_C;
1015             else
1016               Ty = types::TY_Object;
1017           }
1018 
1019           // If the driver is invoked as C++ compiler (like clang++ or c++) it
1020           // should autodetect some input files as C++ for g++ compatibility.
1021           if (CCCIsCXX) {
1022             types::ID OldTy = Ty;
1023             Ty = types::lookupCXXTypeForCType(Ty);
1024 
1025             if (Ty != OldTy)
1026               Diag(clang::diag::warn_drv_treating_input_as_cxx)
1027                 << getTypeName(OldTy) << getTypeName(Ty);
1028           }
1029         }
1030 
1031         // -ObjC and -ObjC++ override the default language, but only for "source
1032         // files". We just treat everything that isn't a linker input as a
1033         // source file.
1034         //
1035         // FIXME: Clean this up if we move the phase sequence into the type.
1036         if (Ty != types::TY_Object) {
1037           if (Args.hasArg(options::OPT_ObjC))
1038             Ty = types::TY_ObjC;
1039           else if (Args.hasArg(options::OPT_ObjCXX))
1040             Ty = types::TY_ObjCXX;
1041         }
1042       } else {
1043         assert(InputTypeArg && "InputType set w/o InputTypeArg");
1044         InputTypeArg->claim();
1045         Ty = InputType;
1046       }
1047 
1048       // Check that the file exists, if enabled.
1049       if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
1050         SmallString<64> Path(Value);
1051         if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1052           SmallString<64> Directory(WorkDir->getValue(Args));
1053           if (llvm::sys::path::is_absolute(Directory.str())) {
1054             llvm::sys::path::append(Directory, Value);
1055             Path.assign(Directory);
1056           }
1057         }
1058 
1059         bool exists = false;
1060         if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
1061           Diag(clang::diag::err_drv_no_such_file) << Path.str();
1062         else
1063           Inputs.push_back(std::make_pair(Ty, A));
1064       } else
1065         Inputs.push_back(std::make_pair(Ty, A));
1066 
1067     } else if (A->getOption().isLinkerInput()) {
1068       // Just treat as object type, we could make a special type for this if
1069       // necessary.
1070       Inputs.push_back(std::make_pair(types::TY_Object, A));
1071 
1072     } else if (A->getOption().matches(options::OPT_x)) {
1073       InputTypeArg = A;
1074       InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
1075       A->claim();
1076 
1077       // Follow gcc behavior and treat as linker input for invalid -x
1078       // options. Its not clear why we shouldn't just revert to unknown; but
1079       // this isn't very important, we might as well be bug compatible.
1080       if (!InputType) {
1081         Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
1082         InputType = types::TY_Object;
1083       }
1084     }
1085   }
1086   if (CCCIsCPP && Inputs.empty()) {
1087     // If called as standalone preprocessor, stdin is processed
1088     // if no other input is present.
1089     unsigned Index = Args.getBaseArgs().MakeIndex("-");
1090     Arg *A = Opts->ParseOneArg(Args, Index);
1091     A->claim();
1092     Inputs.push_back(std::make_pair(types::TY_C, A));
1093   }
1094 }
1095 
1096 void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
1097                           const InputList &Inputs, ActionList &Actions) const {
1098   llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1099 
1100   if (!SuppressMissingInputWarning && Inputs.empty()) {
1101     Diag(clang::diag::err_drv_no_input_files);
1102     return;
1103   }
1104 
1105   Arg *FinalPhaseArg;
1106   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1107 
1108   // Reject -Z* at the top level, these options should never have been exposed
1109   // by gcc.
1110   if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1111     Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1112 
1113   // Construct the actions to perform.
1114   ActionList LinkerInputs;
1115   unsigned NumSteps = 0;
1116   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1117     types::ID InputType = Inputs[i].first;
1118     const Arg *InputArg = Inputs[i].second;
1119 
1120     NumSteps = types::getNumCompilationPhases(InputType);
1121     assert(NumSteps && "Invalid number of steps!");
1122 
1123     // If the first step comes after the final phase we are doing as part of
1124     // this compilation, warn the user about it.
1125     phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
1126     if (InitialPhase > FinalPhase) {
1127       // Claim here to avoid the more general unused warning.
1128       InputArg->claim();
1129 
1130       // Suppress all unused style warnings with -Qunused-arguments
1131       if (Args.hasArg(options::OPT_Qunused_arguments))
1132         continue;
1133 
1134       // Special case '-E' warning on a previously preprocessed file to make
1135       // more sense.
1136       if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
1137           getPreprocessedType(InputType) == types::TY_INVALID)
1138         Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1139           << InputArg->getAsString(Args)
1140           << FinalPhaseArg->getOption().getName();
1141       else
1142         Diag(clang::diag::warn_drv_input_file_unused)
1143           << InputArg->getAsString(Args)
1144           << getPhaseName(InitialPhase)
1145           << FinalPhaseArg->getOption().getName();
1146       continue;
1147     }
1148 
1149     // Build the pipeline for this file.
1150     OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
1151     for (unsigned i = 0; i != NumSteps; ++i) {
1152       phases::ID Phase = types::getCompilationPhase(InputType, i);
1153 
1154       // We are done if this step is past what the user requested.
1155       if (Phase > FinalPhase)
1156         break;
1157 
1158       // Queue linker inputs.
1159       if (Phase == phases::Link) {
1160         assert(i + 1 == NumSteps && "linking must be final compilation step.");
1161         LinkerInputs.push_back(Current.take());
1162         break;
1163       }
1164 
1165       // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1166       // encode this in the steps because the intermediate type depends on
1167       // arguments. Just special case here.
1168       if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1169         continue;
1170 
1171       // Otherwise construct the appropriate action.
1172       Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
1173       if (Current->getType() == types::TY_Nothing)
1174         break;
1175     }
1176 
1177     // If we ended with something, add to the output list.
1178     if (Current)
1179       Actions.push_back(Current.take());
1180   }
1181 
1182   // Add a link action if necessary.
1183   if (!LinkerInputs.empty())
1184     Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1185 
1186   // If we are linking, claim any options which are obviously only used for
1187   // compilation.
1188   if (FinalPhase == phases::Link && (NumSteps == 1))
1189     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1190 }
1191 
1192 Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
1193                                      Action *Input) const {
1194   llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1195   // Build the appropriate action.
1196   switch (Phase) {
1197   case phases::Link: llvm_unreachable("link action invalid here.");
1198   case phases::Preprocess: {
1199     types::ID OutputTy;
1200     // -{M, MM} alter the output type.
1201     if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1202       OutputTy = types::TY_Dependencies;
1203     } else {
1204       OutputTy = Input->getType();
1205       if (!Args.hasFlag(options::OPT_frewrite_includes,
1206                         options::OPT_fno_rewrite_includes, false))
1207         OutputTy = types::getPreprocessedType(OutputTy);
1208       assert(OutputTy != types::TY_INVALID &&
1209              "Cannot preprocess this input type!");
1210     }
1211     return new PreprocessJobAction(Input, OutputTy);
1212   }
1213   case phases::Precompile: {
1214     types::ID OutputTy = types::TY_PCH;
1215     if (Args.hasArg(options::OPT_fsyntax_only)) {
1216       // Syntax checks should not emit a PCH file
1217       OutputTy = types::TY_Nothing;
1218     }
1219     return new PrecompileJobAction(Input, OutputTy);
1220   }
1221   case phases::Compile: {
1222     if (Args.hasArg(options::OPT_fsyntax_only)) {
1223       return new CompileJobAction(Input, types::TY_Nothing);
1224     } else if (Args.hasArg(options::OPT_rewrite_objc)) {
1225       return new CompileJobAction(Input, types::TY_RewrittenObjC);
1226     } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
1227       return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
1228     } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
1229       return new AnalyzeJobAction(Input, types::TY_Plist);
1230     } else if (Args.hasArg(options::OPT__migrate)) {
1231       return new MigrateJobAction(Input, types::TY_Remap);
1232     } else if (Args.hasArg(options::OPT_emit_ast)) {
1233       return new CompileJobAction(Input, types::TY_AST);
1234     } else if (IsUsingLTO(Args)) {
1235       types::ID Output =
1236         Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1237       return new CompileJobAction(Input, Output);
1238     } else {
1239       return new CompileJobAction(Input, types::TY_PP_Asm);
1240     }
1241   }
1242   case phases::Assemble:
1243     return new AssembleJobAction(Input, types::TY_Object);
1244   }
1245 
1246   llvm_unreachable("invalid phase in ConstructPhaseAction");
1247 }
1248 
1249 bool Driver::IsUsingLTO(const ArgList &Args) const {
1250   // Check for -emit-llvm or -flto.
1251   if (Args.hasArg(options::OPT_emit_llvm) ||
1252       Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
1253     return true;
1254 
1255   // Check for -O4.
1256   if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
1257       return A->getOption().matches(options::OPT_O4);
1258 
1259   return false;
1260 }
1261 
1262 void Driver::BuildJobs(Compilation &C) const {
1263   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1264 
1265   Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1266 
1267   // It is an error to provide a -o option if we are making multiple output
1268   // files.
1269   if (FinalOutput) {
1270     unsigned NumOutputs = 0;
1271     for (ActionList::const_iterator it = C.getActions().begin(),
1272            ie = C.getActions().end(); it != ie; ++it)
1273       if ((*it)->getType() != types::TY_Nothing)
1274         ++NumOutputs;
1275 
1276     if (NumOutputs > 1) {
1277       Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1278       FinalOutput = 0;
1279     }
1280   }
1281 
1282   for (ActionList::const_iterator it = C.getActions().begin(),
1283          ie = C.getActions().end(); it != ie; ++it) {
1284     Action *A = *it;
1285 
1286     // If we are linking an image for multiple archs then the linker wants
1287     // -arch_multiple and -final_output <final image name>. Unfortunately, this
1288     // doesn't fit in cleanly because we have to pass this information down.
1289     //
1290     // FIXME: This is a hack; find a cleaner way to integrate this into the
1291     // process.
1292     const char *LinkingOutput = 0;
1293     if (isa<LipoJobAction>(A)) {
1294       if (FinalOutput)
1295         LinkingOutput = FinalOutput->getValue(C.getArgs());
1296       else
1297         LinkingOutput = DefaultImageName.c_str();
1298     }
1299 
1300     InputInfo II;
1301     BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1302                        /*BoundArch*/0,
1303                        /*AtTopLevel*/ true,
1304                        /*LinkingOutput*/ LinkingOutput,
1305                        II);
1306   }
1307 
1308   // If the user passed -Qunused-arguments or there were errors, don't warn
1309   // about any unused arguments.
1310   if (Diags.hasErrorOccurred() ||
1311       C.getArgs().hasArg(options::OPT_Qunused_arguments))
1312     return;
1313 
1314   // Claim -### here.
1315   (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1316 
1317   for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1318        it != ie; ++it) {
1319     Arg *A = *it;
1320 
1321     // FIXME: It would be nice to be able to send the argument to the
1322     // DiagnosticsEngine, so that extra values, position, and so on could be
1323     // printed.
1324     if (!A->isClaimed()) {
1325       if (A->getOption().hasNoArgumentUnused())
1326         continue;
1327 
1328       // Suppress the warning automatically if this is just a flag, and it is an
1329       // instance of an argument we already claimed.
1330       const Option &Opt = A->getOption();
1331       if (isa<FlagOption>(Opt)) {
1332         bool DuplicateClaimed = false;
1333 
1334         for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1335                ie = C.getArgs().filtered_end(); it != ie; ++it) {
1336           if ((*it)->isClaimed()) {
1337             DuplicateClaimed = true;
1338             break;
1339           }
1340         }
1341 
1342         if (DuplicateClaimed)
1343           continue;
1344       }
1345 
1346       Diag(clang::diag::warn_drv_unused_argument)
1347         << A->getAsString(C.getArgs());
1348     }
1349   }
1350 }
1351 
1352 static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1353                                     const JobAction *JA,
1354                                     const ActionList *&Inputs) {
1355   const Tool *ToolForJob = 0;
1356 
1357   // See if we should look for a compiler with an integrated assembler. We match
1358   // bottom up, so what we are actually looking for is an assembler job with a
1359   // compiler input.
1360 
1361   if (C.getArgs().hasFlag(options::OPT_integrated_as,
1362                           options::OPT_no_integrated_as,
1363                           TC->IsIntegratedAssemblerDefault()) &&
1364       !C.getArgs().hasArg(options::OPT_save_temps) &&
1365       isa<AssembleJobAction>(JA) &&
1366       Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1367     const Tool &Compiler = TC->SelectTool(
1368       C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
1369     if (Compiler.hasIntegratedAssembler()) {
1370       Inputs = &(*Inputs)[0]->getInputs();
1371       ToolForJob = &Compiler;
1372     }
1373   }
1374 
1375   // Otherwise use the tool for the current job.
1376   if (!ToolForJob)
1377     ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
1378 
1379   // See if we should use an integrated preprocessor. We do so when we have
1380   // exactly one input, since this is the only use case we care about
1381   // (irrelevant since we don't support combine yet).
1382   if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1383       !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1384       !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1385       !C.getArgs().hasArg(options::OPT_save_temps) &&
1386       ToolForJob->hasIntegratedCPP())
1387     Inputs = &(*Inputs)[0]->getInputs();
1388 
1389   return *ToolForJob;
1390 }
1391 
1392 void Driver::BuildJobsForAction(Compilation &C,
1393                                 const Action *A,
1394                                 const ToolChain *TC,
1395                                 const char *BoundArch,
1396                                 bool AtTopLevel,
1397                                 const char *LinkingOutput,
1398                                 InputInfo &Result) const {
1399   llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1400 
1401   if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1402     // FIXME: It would be nice to not claim this here; maybe the old scheme of
1403     // just using Args was better?
1404     const Arg &Input = IA->getInputArg();
1405     Input.claim();
1406     if (Input.getOption().matches(options::OPT_INPUT)) {
1407       const char *Name = Input.getValue(C.getArgs());
1408       Result = InputInfo(Name, A->getType(), Name);
1409     } else
1410       Result = InputInfo(&Input, A->getType(), "");
1411     return;
1412   }
1413 
1414   if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1415     const ToolChain *TC;
1416     const char *ArchName = BAA->getArchName();
1417 
1418     if (ArchName)
1419       TC = &getToolChain(C.getArgs(), ArchName);
1420     else
1421       TC = &C.getDefaultToolChain();
1422 
1423     BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1424                        AtTopLevel, LinkingOutput, Result);
1425     return;
1426   }
1427 
1428   const ActionList *Inputs = &A->getInputs();
1429 
1430   const JobAction *JA = cast<JobAction>(A);
1431   const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1432 
1433   // Only use pipes when there is exactly one input.
1434   InputInfoList InputInfos;
1435   for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1436        it != ie; ++it) {
1437     // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1438     // temporary output names.
1439     //
1440     // FIXME: Clean this up.
1441     bool SubJobAtTopLevel = false;
1442     if (AtTopLevel && isa<DsymutilJobAction>(A))
1443       SubJobAtTopLevel = true;
1444 
1445     // Also treat verify sub-jobs as being at the top-level. They don't
1446     // produce any output and so don't need temporary output names.
1447     if (AtTopLevel && isa<VerifyJobAction>(A))
1448       SubJobAtTopLevel = true;
1449 
1450     InputInfo II;
1451     BuildJobsForAction(C, *it, TC, BoundArch,
1452                        SubJobAtTopLevel, LinkingOutput, II);
1453     InputInfos.push_back(II);
1454   }
1455 
1456   // Always use the first input as the base input.
1457   const char *BaseInput = InputInfos[0].getBaseInput();
1458 
1459   // ... except dsymutil actions, which use their actual input as the base
1460   // input.
1461   if (JA->getType() == types::TY_dSYM)
1462     BaseInput = InputInfos[0].getFilename();
1463 
1464   // Determine the place to write output to, if any.
1465   if (JA->getType() == types::TY_Nothing) {
1466     Result = InputInfo(A->getType(), BaseInput);
1467   } else {
1468     Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1469                        A->getType(), BaseInput);
1470   }
1471 
1472   if (CCCPrintBindings && !CCGenDiagnostics) {
1473     llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1474                  << " - \"" << T.getName() << "\", inputs: [";
1475     for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1476       llvm::errs() << InputInfos[i].getAsString();
1477       if (i + 1 != e)
1478         llvm::errs() << ", ";
1479     }
1480     llvm::errs() << "], output: " << Result.getAsString() << "\n";
1481   } else {
1482     T.ConstructJob(C, *JA, Result, InputInfos,
1483                    C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1484   }
1485 }
1486 
1487 const char *Driver::GetNamedOutputPath(Compilation &C,
1488                                        const JobAction &JA,
1489                                        const char *BaseInput,
1490                                        bool AtTopLevel) const {
1491   llvm::PrettyStackTraceString CrashInfo("Computing output path");
1492   // Output to a user requested destination?
1493   if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
1494       !isa<VerifyJobAction>(JA)) {
1495     if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1496       return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1497   }
1498 
1499   // Default to writing to stdout?
1500   if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics)
1501     return "-";
1502 
1503   // Output to a temporary file?
1504   if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) ||
1505       CCGenDiagnostics) {
1506     StringRef Name = llvm::sys::path::filename(BaseInput);
1507     std::pair<StringRef, StringRef> Split = Name.split('.');
1508     std::string TmpName =
1509       GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
1510     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1511   }
1512 
1513   SmallString<128> BasePath(BaseInput);
1514   StringRef BaseName;
1515 
1516   // Dsymutil actions should use the full path.
1517   if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
1518     BaseName = BasePath;
1519   else
1520     BaseName = llvm::sys::path::filename(BasePath);
1521 
1522   // Determine what the derived output name should be.
1523   const char *NamedOutput;
1524   if (JA.getType() == types::TY_Image) {
1525     NamedOutput = DefaultImageName.c_str();
1526   } else {
1527     const char *Suffix = types::getTypeTempSuffix(JA.getType());
1528     assert(Suffix && "All types used for output should have a suffix.");
1529 
1530     std::string::size_type End = std::string::npos;
1531     if (!types::appendSuffixForType(JA.getType()))
1532       End = BaseName.rfind('.');
1533     std::string Suffixed(BaseName.substr(0, End));
1534     Suffixed += '.';
1535     Suffixed += Suffix;
1536     NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1537   }
1538 
1539   // If we're saving temps and the temp file conflicts with the input file,
1540   // then avoid overwriting input file.
1541   if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
1542       NamedOutput == BaseName) {
1543 
1544     bool SameFile = false;
1545     SmallString<256> Result;
1546     llvm::sys::fs::current_path(Result);
1547     llvm::sys::path::append(Result, BaseName);
1548     llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
1549     // Must share the same path to conflict.
1550     if (SameFile) {
1551       StringRef Name = llvm::sys::path::filename(BaseInput);
1552       std::pair<StringRef, StringRef> Split = Name.split('.');
1553       std::string TmpName =
1554         GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType()));
1555       return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1556     }
1557   }
1558 
1559   // As an annoying special case, PCH generation doesn't strip the pathname.
1560   if (JA.getType() == types::TY_PCH) {
1561     llvm::sys::path::remove_filename(BasePath);
1562     if (BasePath.empty())
1563       BasePath = NamedOutput;
1564     else
1565       llvm::sys::path::append(BasePath, NamedOutput);
1566     return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1567   } else {
1568     return C.addResultFile(NamedOutput);
1569   }
1570 }
1571 
1572 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1573   // Respect a limited subset of the '-Bprefix' functionality in GCC by
1574   // attempting to use this prefix when lokup up program paths.
1575   for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1576        ie = PrefixDirs.end(); it != ie; ++it) {
1577     std::string Dir(*it);
1578     if (Dir.empty())
1579       continue;
1580     if (Dir[0] == '=')
1581       Dir = SysRoot + Dir.substr(1);
1582     llvm::sys::Path P(Dir);
1583     P.appendComponent(Name);
1584     bool Exists;
1585     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1586       return P.str();
1587   }
1588 
1589   llvm::sys::Path P(ResourceDir);
1590   P.appendComponent(Name);
1591   bool Exists;
1592   if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1593     return P.str();
1594 
1595   const ToolChain::path_list &List = TC.getFilePaths();
1596   for (ToolChain::path_list::const_iterator
1597          it = List.begin(), ie = List.end(); it != ie; ++it) {
1598     std::string Dir(*it);
1599     if (Dir.empty())
1600       continue;
1601     if (Dir[0] == '=')
1602       Dir = SysRoot + Dir.substr(1);
1603     llvm::sys::Path P(Dir);
1604     P.appendComponent(Name);
1605     bool Exists;
1606     if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1607       return P.str();
1608   }
1609 
1610   return Name;
1611 }
1612 
1613 static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) {
1614     bool Exists;
1615     return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1616                  : P.canExecute());
1617 }
1618 
1619 std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1620                                    bool WantFile) const {
1621   // FIXME: Needs a better variable than DefaultTargetTriple
1622   std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
1623   // Respect a limited subset of the '-Bprefix' functionality in GCC by
1624   // attempting to use this prefix when lokup up program paths.
1625   for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1626        ie = PrefixDirs.end(); it != ie; ++it) {
1627     llvm::sys::Path P(*it);
1628     P.appendComponent(TargetSpecificExecutable);
1629     if (isPathExecutable(P, WantFile)) return P.str();
1630     P.eraseComponent();
1631     P.appendComponent(Name);
1632     if (isPathExecutable(P, WantFile)) return P.str();
1633   }
1634 
1635   const ToolChain::path_list &List = TC.getProgramPaths();
1636   for (ToolChain::path_list::const_iterator
1637          it = List.begin(), ie = List.end(); it != ie; ++it) {
1638     llvm::sys::Path P(*it);
1639     P.appendComponent(TargetSpecificExecutable);
1640     if (isPathExecutable(P, WantFile)) return P.str();
1641     P.eraseComponent();
1642     P.appendComponent(Name);
1643     if (isPathExecutable(P, WantFile)) return P.str();
1644   }
1645 
1646   // If all else failed, search the path.
1647   llvm::sys::Path
1648       P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable));
1649   if (!P.empty())
1650     return P.str();
1651 
1652   P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name));
1653   if (!P.empty())
1654     return P.str();
1655 
1656   return Name;
1657 }
1658 
1659 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
1660   const {
1661   // FIXME: This is lame; sys::Path should provide this function (in particular,
1662   // it should know how to find the temporary files dir).
1663   std::string Error;
1664   const char *TmpDir = ::getenv("TMPDIR");
1665   if (!TmpDir)
1666     TmpDir = ::getenv("TEMP");
1667   if (!TmpDir)
1668     TmpDir = ::getenv("TMP");
1669   if (!TmpDir)
1670     TmpDir = "/tmp";
1671   llvm::sys::Path P(TmpDir);
1672   P.appendComponent(Prefix);
1673   if (P.makeUnique(false, &Error)) {
1674     Diag(clang::diag::err_unable_to_make_temp) << Error;
1675     return "";
1676   }
1677 
1678   // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1679   P.eraseFromDisk(false, 0);
1680 
1681   P.appendSuffix(Suffix);
1682   return P.str();
1683 }
1684 
1685 /// \brief Compute target triple from args.
1686 ///
1687 /// This routine provides the logic to compute a target triple from various
1688 /// args passed to the driver and the default triple string.
1689 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
1690                                         const ArgList &Args,
1691                                         StringRef DarwinArchName) {
1692   // FIXME: Already done in Compilation *Driver::BuildCompilation
1693   if (const Arg *A = Args.getLastArg(options::OPT_target))
1694     DefaultTargetTriple = A->getValue(Args);
1695 
1696   llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1697 
1698   // Handle Darwin-specific options available here.
1699   if (Target.isOSDarwin()) {
1700     // If an explict Darwin arch name is given, that trumps all.
1701     if (!DarwinArchName.empty()) {
1702       Target.setArch(
1703         llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName));
1704       return Target;
1705     }
1706 
1707     // Handle the Darwin '-arch' flag.
1708     if (Arg *A = Args.getLastArg(options::OPT_arch)) {
1709       llvm::Triple::ArchType DarwinArch
1710         = llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
1711       if (DarwinArch != llvm::Triple::UnknownArch)
1712         Target.setArch(DarwinArch);
1713     }
1714   }
1715 
1716   // Skip further flag support on OSes which don't support '-m32' or '-m64'.
1717   if (Target.getArchName() == "tce" ||
1718       Target.getOS() == llvm::Triple::AuroraUX ||
1719       Target.getOS() == llvm::Triple::Minix)
1720     return Target;
1721 
1722   // Handle pseudo-target flags '-m32' and '-m64'.
1723   // FIXME: Should this information be in llvm::Triple?
1724   if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
1725     if (A->getOption().matches(options::OPT_m32)) {
1726       if (Target.getArch() == llvm::Triple::x86_64)
1727         Target.setArch(llvm::Triple::x86);
1728       if (Target.getArch() == llvm::Triple::ppc64)
1729         Target.setArch(llvm::Triple::ppc);
1730     } else {
1731       if (Target.getArch() == llvm::Triple::x86)
1732         Target.setArch(llvm::Triple::x86_64);
1733       if (Target.getArch() == llvm::Triple::ppc)
1734         Target.setArch(llvm::Triple::ppc64);
1735     }
1736   }
1737 
1738   return Target;
1739 }
1740 
1741 const ToolChain &Driver::getToolChain(const ArgList &Args,
1742                                       StringRef DarwinArchName) const {
1743   llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
1744                                             DarwinArchName);
1745 
1746   ToolChain *&TC = ToolChains[Target.str()];
1747   if (!TC) {
1748     switch (Target.getOS()) {
1749     case llvm::Triple::AuroraUX:
1750       TC = new toolchains::AuroraUX(*this, Target, Args);
1751       break;
1752     case llvm::Triple::Darwin:
1753     case llvm::Triple::MacOSX:
1754     case llvm::Triple::IOS:
1755       if (Target.getArch() == llvm::Triple::x86 ||
1756           Target.getArch() == llvm::Triple::x86_64 ||
1757           Target.getArch() == llvm::Triple::arm ||
1758           Target.getArch() == llvm::Triple::thumb)
1759         TC = new toolchains::DarwinClang(*this, Target);
1760       else
1761         TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args);
1762       break;
1763     case llvm::Triple::DragonFly:
1764       TC = new toolchains::DragonFly(*this, Target, Args);
1765       break;
1766     case llvm::Triple::OpenBSD:
1767       TC = new toolchains::OpenBSD(*this, Target, Args);
1768       break;
1769     case llvm::Triple::NetBSD:
1770       TC = new toolchains::NetBSD(*this, Target, Args);
1771       break;
1772     case llvm::Triple::FreeBSD:
1773       TC = new toolchains::FreeBSD(*this, Target, Args);
1774       break;
1775     case llvm::Triple::Minix:
1776       TC = new toolchains::Minix(*this, Target, Args);
1777       break;
1778     case llvm::Triple::Linux:
1779       if (Target.getArch() == llvm::Triple::hexagon)
1780         TC = new toolchains::Hexagon_TC(*this, Target);
1781       else
1782         TC = new toolchains::Linux(*this, Target, Args);
1783       break;
1784     case llvm::Triple::Solaris:
1785       TC = new toolchains::Solaris(*this, Target, Args);
1786       break;
1787     case llvm::Triple::Win32:
1788       TC = new toolchains::Windows(*this, Target);
1789       break;
1790     case llvm::Triple::MinGW32:
1791       // FIXME: We need a MinGW toolchain. Fallthrough for now.
1792     default:
1793       // TCE is an OSless target
1794       if (Target.getArchName() == "tce") {
1795         TC = new toolchains::TCEToolChain(*this, Target);
1796         break;
1797       }
1798 
1799       TC = new toolchains::Generic_GCC(*this, Target, Args);
1800       break;
1801     }
1802   }
1803   return *TC;
1804 }
1805 
1806 bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1807                                     const llvm::Triple &Triple) const {
1808   // Check if user requested no clang, or clang doesn't understand this type (we
1809   // only handle single inputs for now).
1810   if (!CCCUseClang || JA.size() != 1 ||
1811       !types::isAcceptedByClang((*JA.begin())->getType()))
1812     return false;
1813 
1814   // Otherwise make sure this is an action clang understands.
1815   if (isa<PreprocessJobAction>(JA)) {
1816     if (!CCCUseClangCPP) {
1817       Diag(clang::diag::warn_drv_not_using_clang_cpp);
1818       return false;
1819     }
1820   } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1821     return false;
1822 
1823   // Use clang for C++?
1824   if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1825     Diag(clang::diag::warn_drv_not_using_clang_cxx);
1826     return false;
1827   }
1828 
1829   // Always use clang for precompiling, AST generation, and rewriting,
1830   // regardless of archs.
1831   if (isa<PrecompileJobAction>(JA) ||
1832       types::isOnlyAcceptedByClang(JA.getType()))
1833     return true;
1834 
1835   // Finally, don't use clang if this isn't one of the user specified archs to
1836   // build.
1837   if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1838     Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1839     return false;
1840   }
1841 
1842   return true;
1843 }
1844 
1845 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1846 /// grouped values as integers. Numbers which are not provided are set to 0.
1847 ///
1848 /// \return True if the entire string was parsed (9.2), or all groups were
1849 /// parsed (10.3.5extrastuff).
1850 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1851                                unsigned &Minor, unsigned &Micro,
1852                                bool &HadExtra) {
1853   HadExtra = false;
1854 
1855   Major = Minor = Micro = 0;
1856   if (*Str == '\0')
1857     return true;
1858 
1859   char *End;
1860   Major = (unsigned) strtol(Str, &End, 10);
1861   if (*Str != '\0' && *End == '\0')
1862     return true;
1863   if (*End != '.')
1864     return false;
1865 
1866   Str = End+1;
1867   Minor = (unsigned) strtol(Str, &End, 10);
1868   if (*Str != '\0' && *End == '\0')
1869     return true;
1870   if (*End != '.')
1871     return false;
1872 
1873   Str = End+1;
1874   Micro = (unsigned) strtol(Str, &End, 10);
1875   if (*Str != '\0' && *End == '\0')
1876     return true;
1877   if (Str == End)
1878     return false;
1879   HadExtra = true;
1880   return true;
1881 }
1882