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