Driver.cpp revision 32bef4edba854303800b3b01cb49a282e5da4f69
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
12#include "clang/Driver/Action.h"
13#include "clang/Driver/Arg.h"
14#include "clang/Driver/ArgList.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/DriverDiagnostic.h"
17#include "clang/Driver/HostInfo.h"
18#include "clang/Driver/Job.h"
19#include "clang/Driver/OptTable.h"
20#include "clang/Driver/Option.h"
21#include "clang/Driver/Options.h"
22#include "clang/Driver/Tool.h"
23#include "clang/Driver/ToolChain.h"
24#include "clang/Driver/Types.h"
25
26#include "clang/Basic/Version.h"
27
28#include "llvm/Config/config.h"
29#include "llvm/ADT/StringSet.h"
30#include "llvm/ADT/OwningPtr.h"
31#include "llvm/Support/PrettyStackTrace.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/Path.h"
35#include "llvm/Support/Program.h"
36
37#include "InputInfo.h"
38
39#include <map>
40
41#ifdef __CYGWIN__
42#include <cygwin/version.h>
43#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
44#define IS_CYGWIN15 1
45#endif
46#endif
47
48using namespace clang::driver;
49using namespace clang;
50
51Driver::Driver(llvm::StringRef _ClangExecutable,
52               llvm::StringRef _DefaultHostTriple,
53               llvm::StringRef _DefaultImageName,
54               bool IsProduction, bool CXXIsProduction,
55               Diagnostic &_Diags)
56  : Opts(createDriverOptTable()), Diags(_Diags),
57    ClangExecutable(_ClangExecutable), DefaultHostTriple(_DefaultHostTriple),
58    DefaultImageName(_DefaultImageName),
59    DriverTitle("clang \"gcc-compatible\" driver"),
60    Host(0),
61    CCPrintOptionsFilename(0), CCCIsCXX(false),
62    CCCEcho(false), CCCPrintBindings(false), CCPrintOptions(false), CCCGenericGCCName("gcc"),
63    CheckInputsExist(true), CCCUseClang(true), CCCUseClangCXX(true),
64    CCCUseClangCPP(true), CCCUsePCH(true), SuppressMissingInputWarning(false) {
65  if (IsProduction) {
66    // In a "production" build, only use clang on architectures we expect to
67    // work, and don't use clang C++.
68    //
69    // During development its more convenient to always have the driver use
70    // clang, but we don't want users to be confused when things don't work, or
71    // to file bugs for things we don't support.
72    CCCClangArchs.insert(llvm::Triple::x86);
73    CCCClangArchs.insert(llvm::Triple::x86_64);
74    CCCClangArchs.insert(llvm::Triple::arm);
75
76    if (!CXXIsProduction)
77      CCCUseClangCXX = false;
78  }
79
80  Name = llvm::sys::path::stem(ClangExecutable);
81  Dir  = llvm::sys::path::parent_path(ClangExecutable);
82
83  // Compute the path to the resource directory.
84  llvm::StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
85  llvm::SmallString<128> P(Dir);
86  if (ClangResourceDir != "")
87    llvm::sys::path::append(P, ClangResourceDir);
88  else
89    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
90  ResourceDir = P.str();
91}
92
93Driver::~Driver() {
94  delete Opts;
95  delete Host;
96}
97
98InputArgList *Driver::ParseArgStrings(const char **ArgBegin,
99                                      const char **ArgEnd) {
100  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
101  unsigned MissingArgIndex, MissingArgCount;
102  InputArgList *Args = getOpts().ParseArgs(ArgBegin, ArgEnd,
103                                           MissingArgIndex, MissingArgCount);
104
105  // Check for missing argument error.
106  if (MissingArgCount)
107    Diag(clang::diag::err_drv_missing_argument)
108      << Args->getArgString(MissingArgIndex) << MissingArgCount;
109
110  // Check for unsupported options.
111  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
112       it != ie; ++it) {
113    Arg *A = *it;
114    if (A->getOption().isUnsupported()) {
115      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
116      continue;
117    }
118  }
119
120  return Args;
121}
122
123DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
124  DerivedArgList *DAL = new DerivedArgList(Args);
125
126  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
127  for (ArgList::const_iterator it = Args.begin(),
128         ie = Args.end(); it != ie; ++it) {
129    const Arg *A = *it;
130
131    // Unfortunately, we have to parse some forwarding options (-Xassembler,
132    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
133    // (assembler and preprocessor), or bypass a previous driver ('collect2').
134
135    // Rewrite linker options, to replace --no-demangle with a custom internal
136    // option.
137    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
138         A->getOption().matches(options::OPT_Xlinker)) &&
139        A->containsValue("--no-demangle")) {
140      // Add the rewritten no-demangle argument.
141      DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
142
143      // Add the remaining values as Xlinker arguments.
144      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
145        if (llvm::StringRef(A->getValue(Args, i)) != "--no-demangle")
146          DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
147                              A->getValue(Args, i));
148
149      continue;
150    }
151
152    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
153    // some build systems. We don't try to be complete here because we don't
154    // care to encourage this usage model.
155    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
156        A->getNumValues() == 2 &&
157        (A->getValue(Args, 0) == llvm::StringRef("-MD") ||
158         A->getValue(Args, 0) == llvm::StringRef("-MMD"))) {
159      // Rewrite to -MD/-MMD along with -MF.
160      if (A->getValue(Args, 0) == llvm::StringRef("-MD"))
161        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
162      else
163        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
164      DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
165                          A->getValue(Args, 1));
166      continue;
167    }
168
169    // Rewrite reserved library names.
170    if (A->getOption().matches(options::OPT_l)) {
171      llvm::StringRef Value = A->getValue(Args);
172
173      // Rewrite unless -nostdlib is present.
174      if (!HasNostdlib && Value == "stdc++") {
175        DAL->AddFlagArg(A, Opts->getOption(
176                              options::OPT_Z_reserved_lib_stdcxx));
177        continue;
178      }
179
180      // Rewrite unconditionally.
181      if (Value == "cc_kext") {
182        DAL->AddFlagArg(A, Opts->getOption(
183                              options::OPT_Z_reserved_lib_cckext));
184        continue;
185      }
186    }
187
188    DAL->append(*it);
189  }
190
191  // Add a default value of -mlinker-version=, if one was given and the user
192  // didn't specify one.
193#if defined(HOST_LINK_VERSION)
194  if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
195    DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
196                      HOST_LINK_VERSION);
197    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
198  }
199#endif
200
201  return DAL;
202}
203
204Compilation *Driver::BuildCompilation(int argc, const char **argv) {
205  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
206
207  // FIXME: Handle environment options which effect driver behavior, somewhere
208  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
209  // CC_PRINT_OPTIONS.
210
211  // FIXME: What are we going to do with -V and -b?
212
213  // FIXME: This stuff needs to go into the Compilation, not the driver.
214  bool CCCPrintOptions = false, CCCPrintActions = false;
215
216  const char **Start = argv + 1, **End = argv + argc;
217
218  InputArgList *Args = ParseArgStrings(Start, End);
219
220  // -no-canonical-prefixes is used very early in main.
221  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
222
223  // Ignore -pipe.
224  Args->ClaimAllArgs(options::OPT_pipe);
225
226  // Extract -ccc args.
227  //
228  // FIXME: We need to figure out where this behavior should live. Most of it
229  // should be outside in the client; the parts that aren't should have proper
230  // options, either by introducing new ones or by overloading gcc ones like -V
231  // or -b.
232  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
233  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
234  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
235  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
236  if (CCCIsCXX) {
237#ifdef IS_CYGWIN15
238    CCCGenericGCCName = "g++-4";
239#else
240    CCCGenericGCCName = "g++";
241#endif
242  }
243  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
244  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
245    CCCGenericGCCName = A->getValue(*Args);
246  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
247                                 options::OPT_ccc_no_clang_cxx,
248                                 CCCUseClangCXX);
249  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
250                            options::OPT_ccc_pch_is_pth);
251  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
252  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
253  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
254    llvm::StringRef Cur = A->getValue(*Args);
255
256    CCCClangArchs.clear();
257    while (!Cur.empty()) {
258      std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
259
260      if (!Split.first.empty()) {
261        llvm::Triple::ArchType Arch =
262          llvm::Triple(Split.first, "", "").getArch();
263
264        if (Arch == llvm::Triple::UnknownArch)
265          Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
266
267        CCCClangArchs.insert(Arch);
268      }
269
270      Cur = Split.second;
271    }
272  }
273  // FIXME: We shouldn't overwrite the default host triple here, but we have
274  // nowhere else to put this currently.
275  if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple))
276    DefaultHostTriple = A->getValue(*Args);
277  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
278    Dir = InstalledDir = A->getValue(*Args);
279  if (const Arg *A = Args->getLastArg(options::OPT_B))
280    PrefixDir = A->getValue(*Args);
281
282  Host = GetHostInfo(DefaultHostTriple.c_str());
283
284  // Perform the default argument translations.
285  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
286
287  // The compilation takes ownership of Args.
288  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args,
289                                   TranslatedArgs);
290
291  // FIXME: This behavior shouldn't be here.
292  if (CCCPrintOptions) {
293    PrintOptions(C->getInputArgs());
294    return C;
295  }
296
297  if (!HandleImmediateArgs(*C))
298    return C;
299
300  // Construct the list of abstract actions to perform for this compilation.
301  if (Host->useDriverDriver())
302    BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
303                          C->getActions());
304  else
305    BuildActions(C->getDefaultToolChain(), C->getArgs(), C->getActions());
306
307  if (CCCPrintActions) {
308    PrintActions(*C);
309    return C;
310  }
311
312  BuildJobs(*C);
313
314  return C;
315}
316
317int Driver::ExecuteCompilation(const Compilation &C) const {
318  // Just print if -### was present.
319  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
320    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
321    return 0;
322  }
323
324  // If there were errors building the compilation, quit now.
325  if (getDiags().hasErrorOccurred())
326    return 1;
327
328  const Command *FailingCommand = 0;
329  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
330
331  // Remove temp files.
332  C.CleanupFileList(C.getTempFiles());
333
334  // If the command succeeded, we are done.
335  if (Res == 0)
336    return Res;
337
338  // Otherwise, remove result files as well.
339  if (!C.getArgs().hasArg(options::OPT_save_temps))
340    C.CleanupFileList(C.getResultFiles(), true);
341
342  // Print extra information about abnormal failures, if possible.
343  //
344  // This is ad-hoc, but we don't want to be excessively noisy. If the result
345  // status was 1, assume the command failed normally. In particular, if it was
346  // the compiler then assume it gave a reasonable error code. Failures in other
347  // tools are less common, and they generally have worse diagnostics, so always
348  // print the diagnostic there.
349  const Tool &FailingTool = FailingCommand->getCreator();
350
351  if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
352    // FIXME: See FIXME above regarding result code interpretation.
353    if (Res < 0)
354      Diag(clang::diag::err_drv_command_signalled)
355        << FailingTool.getShortName() << -Res;
356    else
357      Diag(clang::diag::err_drv_command_failed)
358        << FailingTool.getShortName() << Res;
359  }
360
361  return Res;
362}
363
364void Driver::PrintOptions(const ArgList &Args) const {
365  unsigned i = 0;
366  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
367       it != ie; ++it, ++i) {
368    Arg *A = *it;
369    llvm::errs() << "Option " << i << " - "
370                 << "Name: \"" << A->getOption().getName() << "\", "
371                 << "Values: {";
372    for (unsigned j = 0; j < A->getNumValues(); ++j) {
373      if (j)
374        llvm::errs() << ", ";
375      llvm::errs() << '"' << A->getValue(Args, j) << '"';
376    }
377    llvm::errs() << "}\n";
378  }
379}
380
381void Driver::PrintHelp(bool ShowHidden) const {
382  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
383                      ShowHidden);
384}
385
386void Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
387  // FIXME: The following handlers should use a callback mechanism, we don't
388  // know what the client would like to do.
389  OS << getClangFullVersion() << '\n';
390  const ToolChain &TC = C.getDefaultToolChain();
391  OS << "Target: " << TC.getTripleString() << '\n';
392
393  // Print the threading model.
394  //
395  // FIXME: Implement correctly.
396  OS << "Thread model: " << "posix" << '\n';
397}
398
399/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
400/// option.
401static void PrintDiagnosticCategories(llvm::raw_ostream &OS) {
402  for (unsigned i = 1; // Skip the empty category.
403       const char *CategoryName = DiagnosticIDs::getCategoryNameFromID(i); ++i)
404    OS << i << ',' << CategoryName << '\n';
405}
406
407bool Driver::HandleImmediateArgs(const Compilation &C) {
408  // The order these options are handled in gcc is all over the place, but we
409  // don't expect inconsistencies w.r.t. that to matter in practice.
410
411  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
412    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
413    return false;
414  }
415
416  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
417    llvm::outs() << CLANG_VERSION_STRING "\n";
418    return false;
419  }
420
421  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
422    PrintDiagnosticCategories(llvm::outs());
423    return false;
424  }
425
426  if (C.getArgs().hasArg(options::OPT__help) ||
427      C.getArgs().hasArg(options::OPT__help_hidden)) {
428    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
429    return false;
430  }
431
432  if (C.getArgs().hasArg(options::OPT__version)) {
433    // Follow gcc behavior and use stdout for --version and stderr for -v.
434    PrintVersion(C, llvm::outs());
435    return false;
436  }
437
438  if (C.getArgs().hasArg(options::OPT_v) ||
439      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
440    PrintVersion(C, llvm::errs());
441    SuppressMissingInputWarning = true;
442  }
443
444  const ToolChain &TC = C.getDefaultToolChain();
445  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
446    llvm::outs() << "programs: =";
447    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
448           ie = TC.getProgramPaths().end(); it != ie; ++it) {
449      if (it != TC.getProgramPaths().begin())
450        llvm::outs() << ':';
451      llvm::outs() << *it;
452    }
453    llvm::outs() << "\n";
454    llvm::outs() << "libraries: =";
455    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
456           ie = TC.getFilePaths().end(); it != ie; ++it) {
457      if (it != TC.getFilePaths().begin())
458        llvm::outs() << ':';
459      llvm::outs() << *it;
460    }
461    llvm::outs() << "\n";
462    return false;
463  }
464
465  // FIXME: The following handlers should use a callback mechanism, we don't
466  // know what the client would like to do.
467  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
468    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
469    return false;
470  }
471
472  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
473    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
474    return false;
475  }
476
477  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
478    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
479    return false;
480  }
481
482  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
483    // FIXME: We need tool chain support for this.
484    llvm::outs() << ".;\n";
485
486    switch (C.getDefaultToolChain().getTriple().getArch()) {
487    default:
488      break;
489
490    case llvm::Triple::x86_64:
491      llvm::outs() << "x86_64;@m64" << "\n";
492      break;
493
494    case llvm::Triple::ppc64:
495      llvm::outs() << "ppc64;@m64" << "\n";
496      break;
497    }
498    return false;
499  }
500
501  // FIXME: What is the difference between print-multi-directory and
502  // print-multi-os-directory?
503  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
504      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
505    switch (C.getDefaultToolChain().getTriple().getArch()) {
506    default:
507    case llvm::Triple::x86:
508    case llvm::Triple::ppc:
509      llvm::outs() << "." << "\n";
510      break;
511
512    case llvm::Triple::x86_64:
513      llvm::outs() << "x86_64" << "\n";
514      break;
515
516    case llvm::Triple::ppc64:
517      llvm::outs() << "ppc64" << "\n";
518      break;
519    }
520    return false;
521  }
522
523  return true;
524}
525
526static unsigned PrintActions1(const Compilation &C, Action *A,
527                              std::map<Action*, unsigned> &Ids) {
528  if (Ids.count(A))
529    return Ids[A];
530
531  std::string str;
532  llvm::raw_string_ostream os(str);
533
534  os << Action::getClassName(A->getKind()) << ", ";
535  if (InputAction *IA = dyn_cast<InputAction>(A)) {
536    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
537  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
538    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
539                  C.getDefaultToolChain().getArchName()) << '"'
540       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
541  } else {
542    os << "{";
543    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
544      os << PrintActions1(C, *it, Ids);
545      ++it;
546      if (it != ie)
547        os << ", ";
548    }
549    os << "}";
550  }
551
552  unsigned Id = Ids.size();
553  Ids[A] = Id;
554  llvm::errs() << Id << ": " << os.str() << ", "
555               << types::getTypeName(A->getType()) << "\n";
556
557  return Id;
558}
559
560void Driver::PrintActions(const Compilation &C) const {
561  std::map<Action*, unsigned> Ids;
562  for (ActionList::const_iterator it = C.getActions().begin(),
563         ie = C.getActions().end(); it != ie; ++it)
564    PrintActions1(C, *it, Ids);
565}
566
567/// \brief Check whether the given input tree contains any compilation (or
568/// assembly) actions.
569static bool ContainsCompileAction(const Action *A) {
570  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
571    return true;
572
573  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
574    if (ContainsCompileAction(*it))
575      return true;
576
577  return false;
578}
579
580void Driver::BuildUniversalActions(const ToolChain &TC,
581                                   const ArgList &Args,
582                                   ActionList &Actions) const {
583  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
584  // Collect the list of architectures. Duplicates are allowed, but should only
585  // be handled once (in the order seen).
586  llvm::StringSet<> ArchNames;
587  llvm::SmallVector<const char *, 4> Archs;
588  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
589       it != ie; ++it) {
590    Arg *A = *it;
591
592    if (A->getOption().matches(options::OPT_arch)) {
593      // Validate the option here; we don't save the type here because its
594      // particular spelling may participate in other driver choices.
595      llvm::Triple::ArchType Arch =
596        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
597      if (Arch == llvm::Triple::UnknownArch) {
598        Diag(clang::diag::err_drv_invalid_arch_name)
599          << A->getAsString(Args);
600        continue;
601      }
602
603      A->claim();
604      if (ArchNames.insert(A->getValue(Args)))
605        Archs.push_back(A->getValue(Args));
606    }
607  }
608
609  // When there is no explicit arch for this platform, make sure we still bind
610  // the architecture (to the default) so that -Xarch_ is handled correctly.
611  if (!Archs.size())
612    Archs.push_back(0);
613
614  // FIXME: We killed off some others but these aren't yet detected in a
615  // functional manner. If we added information to jobs about which "auxiliary"
616  // files they wrote then we could detect the conflict these cause downstream.
617  if (Archs.size() > 1) {
618    // No recovery needed, the point of this is just to prevent
619    // overwriting the same files.
620    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
621      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
622        << A->getAsString(Args);
623  }
624
625  ActionList SingleActions;
626  BuildActions(TC, Args, SingleActions);
627
628  // Add in arch bindings for every top level action, as well as lipo and
629  // dsymutil steps if needed.
630  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
631    Action *Act = SingleActions[i];
632
633    // Make sure we can lipo this kind of output. If not (and it is an actual
634    // output) then we disallow, since we can't create an output file with the
635    // right name without overwriting it. We could remove this oddity by just
636    // changing the output names to include the arch, which would also fix
637    // -save-temps. Compatibility wins for now.
638
639    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
640      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
641        << types::getTypeName(Act->getType());
642
643    ActionList Inputs;
644    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
645      Inputs.push_back(new BindArchAction(Act, Archs[i]));
646      if (i != 0)
647        Inputs.back()->setOwnsInputs(false);
648    }
649
650    // Lipo if necessary, we do it this way because we need to set the arch flag
651    // so that -Xarch_ gets overwritten.
652    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
653      Actions.append(Inputs.begin(), Inputs.end());
654    else
655      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
656
657    // Add a 'dsymutil' step if necessary, when debug info is enabled and we
658    // have a compile input. We need to run 'dsymutil' ourselves in such cases
659    // because the debug info will refer to a temporary object file which is
660    // will be removed at the end of the compilation process.
661    if (Act->getType() == types::TY_Image) {
662      Arg *A = Args.getLastArg(options::OPT_g_Group);
663      if (A && !A->getOption().matches(options::OPT_g0) &&
664          !A->getOption().matches(options::OPT_gstabs) &&
665          ContainsCompileAction(Actions.back())) {
666        ActionList Inputs;
667        Inputs.push_back(Actions.back());
668        Actions.pop_back();
669
670        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
671      }
672    }
673  }
674}
675
676void Driver::BuildActions(const ToolChain &TC, const ArgList &Args,
677                          ActionList &Actions) const {
678  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
679  // Start by constructing the list of inputs and their types.
680
681  // Track the current user specified (-x) input. We also explicitly track the
682  // argument used to set the type; we only want to claim the type when we
683  // actually use it, so we warn about unused -x arguments.
684  types::ID InputType = types::TY_Nothing;
685  Arg *InputTypeArg = 0;
686
687  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
688  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
689       it != ie; ++it) {
690    Arg *A = *it;
691
692    if (isa<InputOption>(A->getOption())) {
693      const char *Value = A->getValue(Args);
694      types::ID Ty = types::TY_INVALID;
695
696      // Infer the input type if necessary.
697      if (InputType == types::TY_Nothing) {
698        // If there was an explicit arg for this, claim it.
699        if (InputTypeArg)
700          InputTypeArg->claim();
701
702        // stdin must be handled specially.
703        if (memcmp(Value, "-", 2) == 0) {
704          // If running with -E, treat as a C input (this changes the builtin
705          // macros, for example). This may be overridden by -ObjC below.
706          //
707          // Otherwise emit an error but still use a valid type to avoid
708          // spurious errors (e.g., no inputs).
709          if (!Args.hasArgNoClaim(options::OPT_E))
710            Diag(clang::diag::err_drv_unknown_stdin_type);
711          Ty = types::TY_C;
712        } else {
713          // Otherwise lookup by extension, and fallback to ObjectType if not
714          // found. We use a host hook here because Darwin at least has its own
715          // idea of what .s is.
716          if (const char *Ext = strrchr(Value, '.'))
717            Ty = TC.LookupTypeForExtension(Ext + 1);
718
719          if (Ty == types::TY_INVALID)
720            Ty = types::TY_Object;
721
722          // If the driver is invoked as C++ compiler (like clang++ or c++) it
723          // should autodetect some input files as C++ for g++ compatibility.
724          if (CCCIsCXX) {
725            types::ID OldTy = Ty;
726            Ty = types::lookupCXXTypeForCType(Ty);
727
728            if (Ty != OldTy)
729              Diag(clang::diag::warn_drv_treating_input_as_cxx)
730                << getTypeName(OldTy) << getTypeName(Ty);
731          }
732        }
733
734        // -ObjC and -ObjC++ override the default language, but only for "source
735        // files". We just treat everything that isn't a linker input as a
736        // source file.
737        //
738        // FIXME: Clean this up if we move the phase sequence into the type.
739        if (Ty != types::TY_Object) {
740          if (Args.hasArg(options::OPT_ObjC))
741            Ty = types::TY_ObjC;
742          else if (Args.hasArg(options::OPT_ObjCXX))
743            Ty = types::TY_ObjCXX;
744        }
745      } else {
746        assert(InputTypeArg && "InputType set w/o InputTypeArg");
747        InputTypeArg->claim();
748        Ty = InputType;
749      }
750
751      // Check that the file exists, if enabled.
752      if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
753        llvm::SmallString<64> Path(Value);
754        if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory))
755          if (llvm::sys::path::is_absolute(Path.str())) {
756            Path = WorkDir->getValue(Args);
757            llvm::sys::path::append(Path, Value);
758          }
759
760        bool exists = false;
761        if (/*error_code ec =*/llvm::sys::fs::exists(Value, exists) || !exists)
762          Diag(clang::diag::err_drv_no_such_file) << Path.str();
763        else
764          Inputs.push_back(std::make_pair(Ty, A));
765      } else
766        Inputs.push_back(std::make_pair(Ty, A));
767
768    } else if (A->getOption().isLinkerInput()) {
769      // Just treat as object type, we could make a special type for this if
770      // necessary.
771      Inputs.push_back(std::make_pair(types::TY_Object, A));
772
773    } else if (A->getOption().matches(options::OPT_x)) {
774      InputTypeArg = A;
775      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
776
777      // Follow gcc behavior and treat as linker input for invalid -x
778      // options. Its not clear why we shouldn't just revert to unknown; but
779      // this isn't very important, we might as well be bug compatible.
780      if (!InputType) {
781        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
782        InputType = types::TY_Object;
783      }
784    }
785  }
786
787  if (!SuppressMissingInputWarning && Inputs.empty()) {
788    Diag(clang::diag::err_drv_no_input_files);
789    return;
790  }
791
792  // Determine which compilation mode we are in. We look for options which
793  // affect the phase, starting with the earliest phases, and record which
794  // option we used to determine the final phase.
795  Arg *FinalPhaseArg = 0;
796  phases::ID FinalPhase;
797
798  // -{E,M,MM} only run the preprocessor.
799  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
800      (FinalPhaseArg = Args.getLastArg(options::OPT_M, options::OPT_MM))) {
801    FinalPhase = phases::Preprocess;
802
803    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
804  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
805             (FinalPhaseArg = Args.getLastArg(options::OPT_rewrite_objc)) ||
806             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
807                                              options::OPT__analyze_auto)) ||
808             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
809             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
810    FinalPhase = phases::Compile;
811
812    // -c only runs up to the assembler.
813  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
814    FinalPhase = phases::Assemble;
815
816    // Otherwise do everything.
817  } else
818    FinalPhase = phases::Link;
819
820  // Reject -Z* at the top level, these options should never have been exposed
821  // by gcc.
822  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
823    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
824
825  // Construct the actions to perform.
826  ActionList LinkerInputs;
827  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
828    types::ID InputType = Inputs[i].first;
829    const Arg *InputArg = Inputs[i].second;
830
831    unsigned NumSteps = types::getNumCompilationPhases(InputType);
832    assert(NumSteps && "Invalid number of steps!");
833
834    // If the first step comes after the final phase we are doing as part of
835    // this compilation, warn the user about it.
836    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
837    if (InitialPhase > FinalPhase) {
838      // Claim here to avoid the more general unused warning.
839      InputArg->claim();
840
841      // Special case '-E' warning on a previously preprocessed file to make
842      // more sense.
843      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
844          getPreprocessedType(InputType) == types::TY_INVALID)
845        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
846          << InputArg->getAsString(Args)
847          << FinalPhaseArg->getOption().getName();
848      else
849        Diag(clang::diag::warn_drv_input_file_unused)
850          << InputArg->getAsString(Args)
851          << getPhaseName(InitialPhase)
852          << FinalPhaseArg->getOption().getName();
853      continue;
854    }
855
856    // Build the pipeline for this file.
857    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
858    for (unsigned i = 0; i != NumSteps; ++i) {
859      phases::ID Phase = types::getCompilationPhase(InputType, i);
860
861      // We are done if this step is past what the user requested.
862      if (Phase > FinalPhase)
863        break;
864
865      // Queue linker inputs.
866      if (Phase == phases::Link) {
867        assert(i + 1 == NumSteps && "linking must be final compilation step.");
868        LinkerInputs.push_back(Current.take());
869        break;
870      }
871
872      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
873      // encode this in the steps because the intermediate type depends on
874      // arguments. Just special case here.
875      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
876        continue;
877
878      // Otherwise construct the appropriate action.
879      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
880      if (Current->getType() == types::TY_Nothing)
881        break;
882    }
883
884    // If we ended with something, add to the output list.
885    if (Current)
886      Actions.push_back(Current.take());
887  }
888
889  // Add a link action if necessary.
890  if (!LinkerInputs.empty())
891    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
892
893  // If we are linking, claim any options which are obviously only used for
894  // compilation.
895  if (FinalPhase == phases::Link)
896    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
897}
898
899Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
900                                     Action *Input) const {
901  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
902  // Build the appropriate action.
903  switch (Phase) {
904  case phases::Link: assert(0 && "link action invalid here.");
905  case phases::Preprocess: {
906    types::ID OutputTy;
907    // -{M, MM} alter the output type.
908    if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
909      OutputTy = types::TY_Dependencies;
910    } else {
911      OutputTy = types::getPreprocessedType(Input->getType());
912      assert(OutputTy != types::TY_INVALID &&
913             "Cannot preprocess this input type!");
914    }
915    return new PreprocessJobAction(Input, OutputTy);
916  }
917  case phases::Precompile:
918    return new PrecompileJobAction(Input, types::TY_PCH);
919  case phases::Compile: {
920    bool HasO4 = false;
921    if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
922      HasO4 = A->getOption().matches(options::OPT_O4);
923
924    if (Args.hasArg(options::OPT_fsyntax_only)) {
925      return new CompileJobAction(Input, types::TY_Nothing);
926    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
927      return new CompileJobAction(Input, types::TY_RewrittenObjC);
928    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
929      return new AnalyzeJobAction(Input, types::TY_Plist);
930    } else if (Args.hasArg(options::OPT_emit_ast)) {
931      return new CompileJobAction(Input, types::TY_AST);
932    } else if (Args.hasArg(options::OPT_emit_llvm) ||
933               Args.hasArg(options::OPT_flto) || HasO4) {
934      types::ID Output =
935        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
936      return new CompileJobAction(Input, Output);
937    } else {
938      return new CompileJobAction(Input, types::TY_PP_Asm);
939    }
940  }
941  case phases::Assemble:
942    return new AssembleJobAction(Input, types::TY_Object);
943  }
944
945  assert(0 && "invalid phase in ConstructPhaseAction");
946  return 0;
947}
948
949void Driver::BuildJobs(Compilation &C) const {
950  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
951
952  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
953
954  // It is an error to provide a -o option if we are making multiple output
955  // files.
956  if (FinalOutput) {
957    unsigned NumOutputs = 0;
958    for (ActionList::const_iterator it = C.getActions().begin(),
959           ie = C.getActions().end(); it != ie; ++it)
960      if ((*it)->getType() != types::TY_Nothing)
961        ++NumOutputs;
962
963    if (NumOutputs > 1) {
964      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
965      FinalOutput = 0;
966    }
967  }
968
969  for (ActionList::const_iterator it = C.getActions().begin(),
970         ie = C.getActions().end(); it != ie; ++it) {
971    Action *A = *it;
972
973    // If we are linking an image for multiple archs then the linker wants
974    // -arch_multiple and -final_output <final image name>. Unfortunately, this
975    // doesn't fit in cleanly because we have to pass this information down.
976    //
977    // FIXME: This is a hack; find a cleaner way to integrate this into the
978    // process.
979    const char *LinkingOutput = 0;
980    if (isa<LipoJobAction>(A)) {
981      if (FinalOutput)
982        LinkingOutput = FinalOutput->getValue(C.getArgs());
983      else
984        LinkingOutput = DefaultImageName.c_str();
985    }
986
987    InputInfo II;
988    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
989                       /*BoundArch*/0,
990                       /*AtTopLevel*/ true,
991                       /*LinkingOutput*/ LinkingOutput,
992                       II);
993  }
994
995  // If the user passed -Qunused-arguments or there were errors, don't warn
996  // about any unused arguments.
997  if (Diags.hasErrorOccurred() ||
998      C.getArgs().hasArg(options::OPT_Qunused_arguments))
999    return;
1000
1001  // Claim -### here.
1002  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1003
1004  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1005       it != ie; ++it) {
1006    Arg *A = *it;
1007
1008    // FIXME: It would be nice to be able to send the argument to the
1009    // Diagnostic, so that extra values, position, and so on could be printed.
1010    if (!A->isClaimed()) {
1011      if (A->getOption().hasNoArgumentUnused())
1012        continue;
1013
1014      // Suppress the warning automatically if this is just a flag, and it is an
1015      // instance of an argument we already claimed.
1016      const Option &Opt = A->getOption();
1017      if (isa<FlagOption>(Opt)) {
1018        bool DuplicateClaimed = false;
1019
1020        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1021               ie = C.getArgs().filtered_end(); it != ie; ++it) {
1022          if ((*it)->isClaimed()) {
1023            DuplicateClaimed = true;
1024            break;
1025          }
1026        }
1027
1028        if (DuplicateClaimed)
1029          continue;
1030      }
1031
1032      Diag(clang::diag::warn_drv_unused_argument)
1033        << A->getAsString(C.getArgs());
1034    }
1035  }
1036}
1037
1038static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1039                                    const JobAction *JA,
1040                                    const ActionList *&Inputs) {
1041  const Tool *ToolForJob = 0;
1042
1043  // See if we should look for a compiler with an integrated assembler. We match
1044  // bottom up, so what we are actually looking for is an assembler job with a
1045  // compiler input.
1046
1047  // FIXME: This doesn't belong here, but ideally we will support static soon
1048  // anyway.
1049  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
1050                    C.getArgs().hasArg(options::OPT_static) ||
1051                    C.getArgs().hasArg(options::OPT_fapple_kext));
1052  bool IsIADefault = (TC->IsIntegratedAssemblerDefault() && !HasStatic);
1053  if (C.getArgs().hasFlag(options::OPT_integrated_as,
1054                         options::OPT_no_integrated_as,
1055                         IsIADefault) &&
1056      !C.getArgs().hasArg(options::OPT_save_temps) &&
1057      isa<AssembleJobAction>(JA) &&
1058      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1059    const Tool &Compiler = TC->SelectTool(C,cast<JobAction>(**Inputs->begin()));
1060    if (Compiler.hasIntegratedAssembler()) {
1061      Inputs = &(*Inputs)[0]->getInputs();
1062      ToolForJob = &Compiler;
1063    }
1064  }
1065
1066  // Otherwise use the tool for the current job.
1067  if (!ToolForJob)
1068    ToolForJob = &TC->SelectTool(C, *JA);
1069
1070  // See if we should use an integrated preprocessor. We do so when we have
1071  // exactly one input, since this is the only use case we care about
1072  // (irrelevant since we don't support combine yet).
1073  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1074      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1075      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1076      !C.getArgs().hasArg(options::OPT_save_temps) &&
1077      ToolForJob->hasIntegratedCPP())
1078    Inputs = &(*Inputs)[0]->getInputs();
1079
1080  return *ToolForJob;
1081}
1082
1083void Driver::BuildJobsForAction(Compilation &C,
1084                                const Action *A,
1085                                const ToolChain *TC,
1086                                const char *BoundArch,
1087                                bool AtTopLevel,
1088                                const char *LinkingOutput,
1089                                InputInfo &Result) const {
1090  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1091
1092  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1093    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1094    // just using Args was better?
1095    const Arg &Input = IA->getInputArg();
1096    Input.claim();
1097    if (Input.getOption().matches(options::OPT_INPUT)) {
1098      const char *Name = Input.getValue(C.getArgs());
1099      Result = InputInfo(Name, A->getType(), Name);
1100    } else
1101      Result = InputInfo(&Input, A->getType(), "");
1102    return;
1103  }
1104
1105  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1106    const ToolChain *TC = &C.getDefaultToolChain();
1107
1108    std::string Arch;
1109    if (BAA->getArchName())
1110      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1111
1112    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1113                       AtTopLevel, LinkingOutput, Result);
1114    return;
1115  }
1116
1117  const ActionList *Inputs = &A->getInputs();
1118
1119  const JobAction *JA = cast<JobAction>(A);
1120  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1121
1122  // Only use pipes when there is exactly one input.
1123  InputInfoList InputInfos;
1124  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1125       it != ie; ++it) {
1126    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1127    // temporary output names.
1128    //
1129    // FIXME: Clean this up.
1130    bool SubJobAtTopLevel = false;
1131    if (AtTopLevel && isa<DsymutilJobAction>(A))
1132      SubJobAtTopLevel = true;
1133
1134    InputInfo II;
1135    BuildJobsForAction(C, *it, TC, BoundArch,
1136                       SubJobAtTopLevel, LinkingOutput, II);
1137    InputInfos.push_back(II);
1138  }
1139
1140  // Always use the first input as the base input.
1141  const char *BaseInput = InputInfos[0].getBaseInput();
1142
1143  // ... except dsymutil actions, which use their actual input as the base
1144  // input.
1145  if (JA->getType() == types::TY_dSYM)
1146    BaseInput = InputInfos[0].getFilename();
1147
1148  // Determine the place to write output to, if any.
1149  if (JA->getType() == types::TY_Nothing) {
1150    Result = InputInfo(A->getType(), BaseInput);
1151  } else {
1152    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1153                       A->getType(), BaseInput);
1154  }
1155
1156  if (CCCPrintBindings) {
1157    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1158                 << " - \"" << T.getName() << "\", inputs: [";
1159    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1160      llvm::errs() << InputInfos[i].getAsString();
1161      if (i + 1 != e)
1162        llvm::errs() << ", ";
1163    }
1164    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1165  } else {
1166    T.ConstructJob(C, *JA, Result, InputInfos,
1167                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1168  }
1169}
1170
1171const char *Driver::GetNamedOutputPath(Compilation &C,
1172                                       const JobAction &JA,
1173                                       const char *BaseInput,
1174                                       bool AtTopLevel) const {
1175  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1176  // Output to a user requested destination?
1177  if (AtTopLevel && !isa<DsymutilJobAction>(JA)) {
1178    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1179      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1180  }
1181
1182  // Default to writing to stdout?
1183  if (AtTopLevel && isa<PreprocessJobAction>(JA))
1184    return "-";
1185
1186  // Output to a temporary file?
1187  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1188    std::string TmpName =
1189      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1190    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1191  }
1192
1193  llvm::SmallString<128> BasePath(BaseInput);
1194  llvm::StringRef BaseName = llvm::sys::path::filename(BasePath);
1195
1196  // Determine what the derived output name should be.
1197  const char *NamedOutput;
1198  if (JA.getType() == types::TY_Image) {
1199    NamedOutput = DefaultImageName.c_str();
1200  } else {
1201    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1202    assert(Suffix && "All types used for output should have a suffix.");
1203
1204    std::string::size_type End = std::string::npos;
1205    if (!types::appendSuffixForType(JA.getType()))
1206      End = BaseName.rfind('.');
1207    std::string Suffixed(BaseName.substr(0, End));
1208    Suffixed += '.';
1209    Suffixed += Suffix;
1210    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1211  }
1212
1213  // As an annoying special case, PCH generation doesn't strip the pathname.
1214  if (JA.getType() == types::TY_PCH) {
1215    llvm::sys::path::remove_filename(BasePath);
1216    if (BasePath.empty())
1217      BasePath = NamedOutput;
1218    else
1219      llvm::sys::path::append(BasePath, NamedOutput);
1220    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1221  } else {
1222    return C.addResultFile(NamedOutput);
1223  }
1224}
1225
1226std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1227  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1228  // attempting to use this prefix when lokup up program paths.
1229  if (!PrefixDir.empty()) {
1230    llvm::sys::Path P(PrefixDir);
1231    P.appendComponent(Name);
1232    bool Exists;
1233    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1234      return P.str();
1235  }
1236
1237  const ToolChain::path_list &List = TC.getFilePaths();
1238  for (ToolChain::path_list::const_iterator
1239         it = List.begin(), ie = List.end(); it != ie; ++it) {
1240    llvm::sys::Path P(*it);
1241    P.appendComponent(Name);
1242    bool Exists;
1243    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1244      return P.str();
1245  }
1246
1247  return Name;
1248}
1249
1250std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1251                                   bool WantFile) const {
1252  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1253  // attempting to use this prefix when lokup up program paths.
1254  if (!PrefixDir.empty()) {
1255    llvm::sys::Path P(PrefixDir);
1256    P.appendComponent(Name);
1257    bool Exists;
1258    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1259                 : P.canExecute())
1260      return P.str();
1261  }
1262
1263  const ToolChain::path_list &List = TC.getProgramPaths();
1264  for (ToolChain::path_list::const_iterator
1265         it = List.begin(), ie = List.end(); it != ie; ++it) {
1266    llvm::sys::Path P(*it);
1267    P.appendComponent(Name);
1268    bool Exists;
1269    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1270                 : P.canExecute())
1271      return P.str();
1272  }
1273
1274  // If all else failed, search the path.
1275  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1276  if (!P.empty())
1277    return P.str();
1278
1279  return Name;
1280}
1281
1282std::string Driver::GetTemporaryPath(const char *Suffix) const {
1283  // FIXME: This is lame; sys::Path should provide this function (in particular,
1284  // it should know how to find the temporary files dir).
1285  std::string Error;
1286  const char *TmpDir = ::getenv("TMPDIR");
1287  if (!TmpDir)
1288    TmpDir = ::getenv("TEMP");
1289  if (!TmpDir)
1290    TmpDir = ::getenv("TMP");
1291  if (!TmpDir)
1292    TmpDir = "/tmp";
1293  llvm::sys::Path P(TmpDir);
1294  P.appendComponent("cc");
1295  if (P.makeUnique(false, &Error)) {
1296    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1297    return "";
1298  }
1299
1300  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1301  P.eraseFromDisk(false, 0);
1302
1303  P.appendSuffix(Suffix);
1304  return P.str();
1305}
1306
1307const HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1308  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1309  llvm::Triple Triple(TripleStr);
1310
1311  // TCE is an osless target
1312  if (Triple.getArchName() == "tce")
1313    return createTCEHostInfo(*this, Triple);
1314
1315  switch (Triple.getOS()) {
1316  case llvm::Triple::AuroraUX:
1317    return createAuroraUXHostInfo(*this, Triple);
1318  case llvm::Triple::Darwin:
1319    return createDarwinHostInfo(*this, Triple);
1320  case llvm::Triple::DragonFly:
1321    return createDragonFlyHostInfo(*this, Triple);
1322  case llvm::Triple::OpenBSD:
1323    return createOpenBSDHostInfo(*this, Triple);
1324  case llvm::Triple::FreeBSD:
1325    return createFreeBSDHostInfo(*this, Triple);
1326  case llvm::Triple::Minix:
1327    return createMinixHostInfo(*this, Triple);
1328  case llvm::Triple::Linux:
1329    return createLinuxHostInfo(*this, Triple);
1330  case llvm::Triple::Win32:
1331    return createWindowsHostInfo(*this, Triple);
1332  case llvm::Triple::MinGW32:
1333  case llvm::Triple::MinGW64:
1334    return createMinGWHostInfo(*this, Triple);
1335  default:
1336    return createUnknownHostInfo(*this, Triple);
1337  }
1338}
1339
1340bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1341                                    const llvm::Triple &Triple) const {
1342  // Check if user requested no clang, or clang doesn't understand this type (we
1343  // only handle single inputs for now).
1344  if (!CCCUseClang || JA.size() != 1 ||
1345      !types::isAcceptedByClang((*JA.begin())->getType()))
1346    return false;
1347
1348  // Otherwise make sure this is an action clang understands.
1349  if (isa<PreprocessJobAction>(JA)) {
1350    if (!CCCUseClangCPP) {
1351      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1352      return false;
1353    }
1354  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1355    return false;
1356
1357  // Use clang for C++?
1358  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1359    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1360    return false;
1361  }
1362
1363  // Always use clang for precompiling, AST generation, and rewriting,
1364  // regardless of archs.
1365  if (isa<PrecompileJobAction>(JA) ||
1366      types::isOnlyAcceptedByClang(JA.getType()))
1367    return true;
1368
1369  // Finally, don't use clang if this isn't one of the user specified archs to
1370  // build.
1371  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1372    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1373    return false;
1374  }
1375
1376  return true;
1377}
1378
1379/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1380/// grouped values as integers. Numbers which are not provided are set to 0.
1381///
1382/// \return True if the entire string was parsed (9.2), or all groups were
1383/// parsed (10.3.5extrastuff).
1384bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1385                               unsigned &Minor, unsigned &Micro,
1386                               bool &HadExtra) {
1387  HadExtra = false;
1388
1389  Major = Minor = Micro = 0;
1390  if (*Str == '\0')
1391    return true;
1392
1393  char *End;
1394  Major = (unsigned) strtol(Str, &End, 10);
1395  if (*Str != '\0' && *End == '\0')
1396    return true;
1397  if (*End != '.')
1398    return false;
1399
1400  Str = End+1;
1401  Minor = (unsigned) strtol(Str, &End, 10);
1402  if (*Str != '\0' && *End == '\0')
1403    return true;
1404  if (*End != '.')
1405    return false;
1406
1407  Str = End+1;
1408  Micro = (unsigned) strtol(Str, &End, 10);
1409  if (*Str != '\0' && *End == '\0')
1410    return true;
1411  if (Str == End)
1412    return false;
1413  HadExtra = true;
1414  return true;
1415}
1416