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