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