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