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