Driver.cpp revision 218893
1218893Sdim//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed
10218893Sdim#ifdef HAVE_CLANG_CONFIG_H
11218893Sdim# include "clang/Config/config.h"
12218893Sdim#endif
13218893Sdim
14193326Sed#include "clang/Driver/Driver.h"
15193326Sed
16193326Sed#include "clang/Driver/Action.h"
17193326Sed#include "clang/Driver/Arg.h"
18193326Sed#include "clang/Driver/ArgList.h"
19193326Sed#include "clang/Driver/Compilation.h"
20193326Sed#include "clang/Driver/DriverDiagnostic.h"
21193326Sed#include "clang/Driver/HostInfo.h"
22193326Sed#include "clang/Driver/Job.h"
23199512Srdivacky#include "clang/Driver/OptTable.h"
24193326Sed#include "clang/Driver/Option.h"
25193326Sed#include "clang/Driver/Options.h"
26193326Sed#include "clang/Driver/Tool.h"
27193326Sed#include "clang/Driver/ToolChain.h"
28193326Sed#include "clang/Driver/Types.h"
29193326Sed
30193326Sed#include "clang/Basic/Version.h"
31193326Sed
32212904Sdim#include "llvm/Config/config.h"
33193326Sed#include "llvm/ADT/StringSet.h"
34202879Srdivacky#include "llvm/ADT/OwningPtr.h"
35193326Sed#include "llvm/Support/PrettyStackTrace.h"
36193326Sed#include "llvm/Support/raw_ostream.h"
37218893Sdim#include "llvm/Support/FileSystem.h"
38218893Sdim#include "llvm/Support/Path.h"
39218893Sdim#include "llvm/Support/Program.h"
40193326Sed
41193326Sed#include "InputInfo.h"
42193326Sed
43193326Sed#include <map>
44193326Sed
45218893Sdim#ifdef __CYGWIN__
46218893Sdim#include <cygwin/version.h>
47218893Sdim#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
48218893Sdim#define IS_CYGWIN15 1
49218893Sdim#endif
50218893Sdim#endif
51218893Sdim
52193326Sedusing namespace clang::driver;
53193326Sedusing namespace clang;
54193326Sed
55212904SdimDriver::Driver(llvm::StringRef _ClangExecutable,
56200583Srdivacky               llvm::StringRef _DefaultHostTriple,
57200583Srdivacky               llvm::StringRef _DefaultImageName,
58206084Srdivacky               bool IsProduction, bool CXXIsProduction,
59206084Srdivacky               Diagnostic &_Diags)
60199512Srdivacky  : Opts(createDriverOptTable()), Diags(_Diags),
61212904Sdim    ClangExecutable(_ClangExecutable), DefaultHostTriple(_DefaultHostTriple),
62193326Sed    DefaultImageName(_DefaultImageName),
63204643Srdivacky    DriverTitle("clang \"gcc-compatible\" driver"),
64193326Sed    Host(0),
65218893Sdim    CCPrintOptionsFilename(0), CCPrintHeadersFilename(0), CCCIsCXX(false),
66205408Srdivacky    CCCEcho(false), CCCPrintBindings(false), CCPrintOptions(false),
67218893Sdim    CCPrintHeaders(false), CCCGenericGCCName("gcc"),
68205408Srdivacky    CheckInputsExist(true), CCCUseClang(true), CCCUseClangCXX(true),
69205408Srdivacky    CCCUseClangCPP(true), CCCUsePCH(true), SuppressMissingInputWarning(false) {
70198092Srdivacky  if (IsProduction) {
71198092Srdivacky    // In a "production" build, only use clang on architectures we expect to
72198092Srdivacky    // work, and don't use clang C++.
73198092Srdivacky    //
74198092Srdivacky    // During development its more convenient to always have the driver use
75198092Srdivacky    // clang, but we don't want users to be confused when things don't work, or
76198092Srdivacky    // to file bugs for things we don't support.
77198092Srdivacky    CCCClangArchs.insert(llvm::Triple::x86);
78198092Srdivacky    CCCClangArchs.insert(llvm::Triple::x86_64);
79198092Srdivacky    CCCClangArchs.insert(llvm::Triple::arm);
80198092Srdivacky
81206084Srdivacky    if (!CXXIsProduction)
82206084Srdivacky      CCCUseClangCXX = false;
83198092Srdivacky  }
84202879Srdivacky
85218893Sdim  Name = llvm::sys::path::stem(ClangExecutable);
86218893Sdim  Dir  = llvm::sys::path::parent_path(ClangExecutable);
87212904Sdim
88202879Srdivacky  // Compute the path to the resource directory.
89218893Sdim  llvm::StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
90218893Sdim  llvm::SmallString<128> P(Dir);
91218893Sdim  if (ClangResourceDir != "")
92218893Sdim    llvm::sys::path::append(P, ClangResourceDir);
93218893Sdim  else
94218893Sdim    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
95202879Srdivacky  ResourceDir = P.str();
96193326Sed}
97193326Sed
98193326SedDriver::~Driver() {
99193326Sed  delete Opts;
100193326Sed  delete Host;
101193326Sed}
102193326Sed
103198092SrdivackyInputArgList *Driver::ParseArgStrings(const char **ArgBegin,
104193326Sed                                      const char **ArgEnd) {
105193326Sed  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
106199512Srdivacky  unsigned MissingArgIndex, MissingArgCount;
107199512Srdivacky  InputArgList *Args = getOpts().ParseArgs(ArgBegin, ArgEnd,
108199512Srdivacky                                           MissingArgIndex, MissingArgCount);
109198092Srdivacky
110199512Srdivacky  // Check for missing argument error.
111199512Srdivacky  if (MissingArgCount)
112199512Srdivacky    Diag(clang::diag::err_drv_missing_argument)
113199512Srdivacky      << Args->getArgString(MissingArgIndex) << MissingArgCount;
114193326Sed
115199512Srdivacky  // Check for unsupported options.
116199512Srdivacky  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
117199512Srdivacky       it != ie; ++it) {
118199512Srdivacky    Arg *A = *it;
119193326Sed    if (A->getOption().isUnsupported()) {
120193326Sed      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
121193326Sed      continue;
122193326Sed    }
123193326Sed  }
124193326Sed
125193326Sed  return Args;
126193326Sed}
127193326Sed
128210299SedDerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
129210299Sed  DerivedArgList *DAL = new DerivedArgList(Args);
130210299Sed
131218893Sdim  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
132210299Sed  for (ArgList::const_iterator it = Args.begin(),
133210299Sed         ie = Args.end(); it != ie; ++it) {
134210299Sed    const Arg *A = *it;
135210299Sed
136210299Sed    // Unfortunately, we have to parse some forwarding options (-Xassembler,
137210299Sed    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
138210299Sed    // (assembler and preprocessor), or bypass a previous driver ('collect2').
139210299Sed
140210299Sed    // Rewrite linker options, to replace --no-demangle with a custom internal
141210299Sed    // option.
142210299Sed    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
143210299Sed         A->getOption().matches(options::OPT_Xlinker)) &&
144210299Sed        A->containsValue("--no-demangle")) {
145210299Sed      // Add the rewritten no-demangle argument.
146210299Sed      DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
147210299Sed
148210299Sed      // Add the remaining values as Xlinker arguments.
149210299Sed      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
150210299Sed        if (llvm::StringRef(A->getValue(Args, i)) != "--no-demangle")
151210299Sed          DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
152210299Sed                              A->getValue(Args, i));
153210299Sed
154210299Sed      continue;
155210299Sed    }
156210299Sed
157210299Sed    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
158210299Sed    // some build systems. We don't try to be complete here because we don't
159210299Sed    // care to encourage this usage model.
160210299Sed    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
161210299Sed        A->getNumValues() == 2 &&
162210299Sed        (A->getValue(Args, 0) == llvm::StringRef("-MD") ||
163210299Sed         A->getValue(Args, 0) == llvm::StringRef("-MMD"))) {
164210299Sed      // Rewrite to -MD/-MMD along with -MF.
165210299Sed      if (A->getValue(Args, 0) == llvm::StringRef("-MD"))
166210299Sed        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
167210299Sed      else
168210299Sed        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
169210299Sed      DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
170210299Sed                          A->getValue(Args, 1));
171210299Sed      continue;
172210299Sed    }
173210299Sed
174218893Sdim    // Rewrite reserved library names.
175218893Sdim    if (A->getOption().matches(options::OPT_l)) {
176218893Sdim      llvm::StringRef Value = A->getValue(Args);
177218893Sdim
178218893Sdim      // Rewrite unless -nostdlib is present.
179218893Sdim      if (!HasNostdlib && Value == "stdc++") {
180218893Sdim        DAL->AddFlagArg(A, Opts->getOption(
181218893Sdim                              options::OPT_Z_reserved_lib_stdcxx));
182218893Sdim        continue;
183218893Sdim      }
184218893Sdim
185218893Sdim      // Rewrite unconditionally.
186218893Sdim      if (Value == "cc_kext") {
187218893Sdim        DAL->AddFlagArg(A, Opts->getOption(
188218893Sdim                              options::OPT_Z_reserved_lib_cckext));
189218893Sdim        continue;
190218893Sdim      }
191218893Sdim    }
192218893Sdim
193210299Sed    DAL->append(*it);
194210299Sed  }
195210299Sed
196212904Sdim  // Add a default value of -mlinker-version=, if one was given and the user
197212904Sdim  // didn't specify one.
198212904Sdim#if defined(HOST_LINK_VERSION)
199212904Sdim  if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
200212904Sdim    DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
201212904Sdim                      HOST_LINK_VERSION);
202212904Sdim    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
203212904Sdim  }
204212904Sdim#endif
205212904Sdim
206210299Sed  return DAL;
207210299Sed}
208210299Sed
209193326SedCompilation *Driver::BuildCompilation(int argc, const char **argv) {
210193326Sed  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
211193326Sed
212198092Srdivacky  // FIXME: Handle environment options which effect driver behavior, somewhere
213198092Srdivacky  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
214198092Srdivacky  // CC_PRINT_OPTIONS.
215193326Sed
216193326Sed  // FIXME: What are we going to do with -V and -b?
217193326Sed
218198092Srdivacky  // FIXME: This stuff needs to go into the Compilation, not the driver.
219193326Sed  bool CCCPrintOptions = false, CCCPrintActions = false;
220193326Sed
221193326Sed  const char **Start = argv + 1, **End = argv + argc;
222193326Sed
223200583Srdivacky  InputArgList *Args = ParseArgStrings(Start, End);
224200583Srdivacky
225200583Srdivacky  // -no-canonical-prefixes is used very early in main.
226200583Srdivacky  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
227200583Srdivacky
228212904Sdim  // Ignore -pipe.
229212904Sdim  Args->ClaimAllArgs(options::OPT_pipe);
230212904Sdim
231200583Srdivacky  // Extract -ccc args.
232193326Sed  //
233198092Srdivacky  // FIXME: We need to figure out where this behavior should live. Most of it
234198092Srdivacky  // should be outside in the client; the parts that aren't should have proper
235198092Srdivacky  // options, either by introducing new ones or by overloading gcc ones like -V
236198092Srdivacky  // or -b.
237200583Srdivacky  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
238200583Srdivacky  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
239200583Srdivacky  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
240200583Srdivacky  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
241218893Sdim  if (CCCIsCXX) {
242218893Sdim#ifdef IS_CYGWIN15
243218893Sdim    CCCGenericGCCName = "g++-4";
244218893Sdim#else
245218893Sdim    CCCGenericGCCName = "g++";
246218893Sdim#endif
247218893Sdim  }
248200583Srdivacky  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
249200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
250200583Srdivacky    CCCGenericGCCName = A->getValue(*Args);
251200583Srdivacky  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
252200583Srdivacky                                 options::OPT_ccc_no_clang_cxx,
253200583Srdivacky                                 CCCUseClangCXX);
254200583Srdivacky  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
255200583Srdivacky                            options::OPT_ccc_pch_is_pth);
256200583Srdivacky  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
257200583Srdivacky  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
258200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
259200583Srdivacky    llvm::StringRef Cur = A->getValue(*Args);
260198092Srdivacky
261200583Srdivacky    CCCClangArchs.clear();
262200583Srdivacky    while (!Cur.empty()) {
263200583Srdivacky      std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
264198092Srdivacky
265200583Srdivacky      if (!Split.first.empty()) {
266200583Srdivacky        llvm::Triple::ArchType Arch =
267200583Srdivacky          llvm::Triple(Split.first, "", "").getArch();
268193326Sed
269203955Srdivacky        if (Arch == llvm::Triple::UnknownArch)
270203955Srdivacky          Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
271198092Srdivacky
272200583Srdivacky        CCCClangArchs.insert(Arch);
273193326Sed      }
274193326Sed
275200583Srdivacky      Cur = Split.second;
276193326Sed    }
277193326Sed  }
278212904Sdim  // FIXME: We shouldn't overwrite the default host triple here, but we have
279212904Sdim  // nowhere else to put this currently.
280200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple))
281212904Sdim    DefaultHostTriple = A->getValue(*Args);
282200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
283212904Sdim    Dir = InstalledDir = A->getValue(*Args);
284218893Sdim  for (arg_iterator it = Args->filtered_begin(options::OPT_B),
285218893Sdim         ie = Args->filtered_end(); it != ie; ++it) {
286218893Sdim    const Arg *A = *it;
287218893Sdim    A->claim();
288218893Sdim    PrefixDirs.push_back(A->getValue(*Args, 0));
289218893Sdim  }
290193326Sed
291212904Sdim  Host = GetHostInfo(DefaultHostTriple.c_str());
292193326Sed
293210299Sed  // Perform the default argument translations.
294210299Sed  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
295210299Sed
296193326Sed  // The compilation takes ownership of Args.
297210299Sed  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args,
298210299Sed                                   TranslatedArgs);
299193326Sed
300193326Sed  // FIXME: This behavior shouldn't be here.
301193326Sed  if (CCCPrintOptions) {
302210299Sed    PrintOptions(C->getInputArgs());
303193326Sed    return C;
304193326Sed  }
305193326Sed
306193326Sed  if (!HandleImmediateArgs(*C))
307193326Sed    return C;
308193326Sed
309212904Sdim  // Construct the list of abstract actions to perform for this compilation.
310193326Sed  if (Host->useDriverDriver())
311212904Sdim    BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
312212904Sdim                          C->getActions());
313193326Sed  else
314212904Sdim    BuildActions(C->getDefaultToolChain(), C->getArgs(), C->getActions());
315193326Sed
316193326Sed  if (CCCPrintActions) {
317193326Sed    PrintActions(*C);
318193326Sed    return C;
319193326Sed  }
320193326Sed
321193326Sed  BuildJobs(*C);
322193326Sed
323193326Sed  return C;
324193326Sed}
325193326Sed
326195341Sedint Driver::ExecuteCompilation(const Compilation &C) const {
327195341Sed  // Just print if -### was present.
328195341Sed  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
329195341Sed    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
330195341Sed    return 0;
331195341Sed  }
332195341Sed
333195341Sed  // If there were errors building the compilation, quit now.
334218893Sdim  if (getDiags().hasErrorOccurred())
335195341Sed    return 1;
336195341Sed
337195341Sed  const Command *FailingCommand = 0;
338195341Sed  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
339198092Srdivacky
340195341Sed  // Remove temp files.
341195341Sed  C.CleanupFileList(C.getTempFiles());
342195341Sed
343208600Srdivacky  // If the command succeeded, we are done.
344208600Srdivacky  if (Res == 0)
345208600Srdivacky    return Res;
346208600Srdivacky
347208600Srdivacky  // Otherwise, remove result files as well.
348208600Srdivacky  if (!C.getArgs().hasArg(options::OPT_save_temps))
349195341Sed    C.CleanupFileList(C.getResultFiles(), true);
350195341Sed
351195341Sed  // Print extra information about abnormal failures, if possible.
352208600Srdivacky  //
353208600Srdivacky  // This is ad-hoc, but we don't want to be excessively noisy. If the result
354208600Srdivacky  // status was 1, assume the command failed normally. In particular, if it was
355208600Srdivacky  // the compiler then assume it gave a reasonable error code. Failures in other
356208600Srdivacky  // tools are less common, and they generally have worse diagnostics, so always
357208600Srdivacky  // print the diagnostic there.
358208600Srdivacky  const Tool &FailingTool = FailingCommand->getCreator();
359195341Sed
360208600Srdivacky  if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
361208600Srdivacky    // FIXME: See FIXME above regarding result code interpretation.
362208600Srdivacky    if (Res < 0)
363208600Srdivacky      Diag(clang::diag::err_drv_command_signalled)
364208600Srdivacky        << FailingTool.getShortName() << -Res;
365208600Srdivacky    else
366208600Srdivacky      Diag(clang::diag::err_drv_command_failed)
367208600Srdivacky        << FailingTool.getShortName() << Res;
368195341Sed  }
369195341Sed
370195341Sed  return Res;
371195341Sed}
372195341Sed
373193326Sedvoid Driver::PrintOptions(const ArgList &Args) const {
374193326Sed  unsigned i = 0;
375198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
376193326Sed       it != ie; ++it, ++i) {
377193326Sed    Arg *A = *it;
378193326Sed    llvm::errs() << "Option " << i << " - "
379193326Sed                 << "Name: \"" << A->getOption().getName() << "\", "
380193326Sed                 << "Values: {";
381193326Sed    for (unsigned j = 0; j < A->getNumValues(); ++j) {
382193326Sed      if (j)
383193326Sed        llvm::errs() << ", ";
384193326Sed      llvm::errs() << '"' << A->getValue(Args, j) << '"';
385193326Sed    }
386193326Sed    llvm::errs() << "}\n";
387193326Sed  }
388193326Sed}
389193326Sed
390193326Sedvoid Driver::PrintHelp(bool ShowHidden) const {
391204643Srdivacky  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
392204643Srdivacky                      ShowHidden);
393193326Sed}
394193326Sed
395198092Srdivackyvoid Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
396198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
397198092Srdivacky  // know what the client would like to do.
398202879Srdivacky  OS << getClangFullVersion() << '\n';
399193326Sed  const ToolChain &TC = C.getDefaultToolChain();
400198092Srdivacky  OS << "Target: " << TC.getTripleString() << '\n';
401194613Sed
402194613Sed  // Print the threading model.
403194613Sed  //
404194613Sed  // FIXME: Implement correctly.
405198092Srdivacky  OS << "Thread model: " << "posix" << '\n';
406193326Sed}
407193326Sed
408208600Srdivacky/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
409208600Srdivacky/// option.
410208600Srdivackystatic void PrintDiagnosticCategories(llvm::raw_ostream &OS) {
411208600Srdivacky  for (unsigned i = 1; // Skip the empty category.
412218893Sdim       const char *CategoryName = DiagnosticIDs::getCategoryNameFromID(i); ++i)
413208600Srdivacky    OS << i << ',' << CategoryName << '\n';
414208600Srdivacky}
415208600Srdivacky
416193326Sedbool Driver::HandleImmediateArgs(const Compilation &C) {
417210299Sed  // The order these options are handled in gcc is all over the place, but we
418198092Srdivacky  // don't expect inconsistencies w.r.t. that to matter in practice.
419193326Sed
420218893Sdim  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
421218893Sdim    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
422218893Sdim    return false;
423218893Sdim  }
424218893Sdim
425193326Sed  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
426218893Sdim    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
427218893Sdim    // return an answer which matches our definition of __VERSION__.
428218893Sdim    //
429218893Sdim    // If we want to return a more correct answer some day, then we should
430218893Sdim    // introduce a non-pedantically GCC compatible mode to Clang in which we
431218893Sdim    // provide sensible definitions for -dumpversion, __VERSION__, etc.
432218893Sdim    llvm::outs() << "4.2.1\n";
433193326Sed    return false;
434193326Sed  }
435210299Sed
436208600Srdivacky  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
437208600Srdivacky    PrintDiagnosticCategories(llvm::outs());
438208600Srdivacky    return false;
439208600Srdivacky  }
440193326Sed
441198092Srdivacky  if (C.getArgs().hasArg(options::OPT__help) ||
442193326Sed      C.getArgs().hasArg(options::OPT__help_hidden)) {
443193326Sed    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
444193326Sed    return false;
445193326Sed  }
446193326Sed
447193326Sed  if (C.getArgs().hasArg(options::OPT__version)) {
448198092Srdivacky    // Follow gcc behavior and use stdout for --version and stderr for -v.
449198092Srdivacky    PrintVersion(C, llvm::outs());
450193326Sed    return false;
451193326Sed  }
452193326Sed
453198092Srdivacky  if (C.getArgs().hasArg(options::OPT_v) ||
454193326Sed      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
455198092Srdivacky    PrintVersion(C, llvm::errs());
456193326Sed    SuppressMissingInputWarning = true;
457193326Sed  }
458193326Sed
459193326Sed  const ToolChain &TC = C.getDefaultToolChain();
460193326Sed  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
461193326Sed    llvm::outs() << "programs: =";
462193326Sed    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
463193326Sed           ie = TC.getProgramPaths().end(); it != ie; ++it) {
464193326Sed      if (it != TC.getProgramPaths().begin())
465193326Sed        llvm::outs() << ':';
466193326Sed      llvm::outs() << *it;
467193326Sed    }
468193326Sed    llvm::outs() << "\n";
469193326Sed    llvm::outs() << "libraries: =";
470198092Srdivacky    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
471193326Sed           ie = TC.getFilePaths().end(); it != ie; ++it) {
472193326Sed      if (it != TC.getFilePaths().begin())
473193326Sed        llvm::outs() << ':';
474193326Sed      llvm::outs() << *it;
475193326Sed    }
476193326Sed    llvm::outs() << "\n";
477193326Sed    return false;
478193326Sed  }
479193326Sed
480198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
481198092Srdivacky  // know what the client would like to do.
482193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
483198092Srdivacky    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
484193326Sed    return false;
485193326Sed  }
486193326Sed
487193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
488198092Srdivacky    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
489193326Sed    return false;
490193326Sed  }
491193326Sed
492193326Sed  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
493198092Srdivacky    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
494193326Sed    return false;
495193326Sed  }
496193326Sed
497194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
498194613Sed    // FIXME: We need tool chain support for this.
499194613Sed    llvm::outs() << ".;\n";
500194613Sed
501194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
502194613Sed    default:
503194613Sed      break;
504198092Srdivacky
505194613Sed    case llvm::Triple::x86_64:
506194613Sed      llvm::outs() << "x86_64;@m64" << "\n";
507194613Sed      break;
508194613Sed
509194613Sed    case llvm::Triple::ppc64:
510194613Sed      llvm::outs() << "ppc64;@m64" << "\n";
511194613Sed      break;
512194613Sed    }
513194613Sed    return false;
514194613Sed  }
515194613Sed
516194613Sed  // FIXME: What is the difference between print-multi-directory and
517194613Sed  // print-multi-os-directory?
518194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
519194613Sed      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
520194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
521194613Sed    default:
522194613Sed    case llvm::Triple::x86:
523194613Sed    case llvm::Triple::ppc:
524194613Sed      llvm::outs() << "." << "\n";
525194613Sed      break;
526198092Srdivacky
527194613Sed    case llvm::Triple::x86_64:
528213492Sdim      llvm::outs() << "." << "\n";
529194613Sed      break;
530194613Sed
531194613Sed    case llvm::Triple::ppc64:
532194613Sed      llvm::outs() << "ppc64" << "\n";
533194613Sed      break;
534194613Sed    }
535194613Sed    return false;
536194613Sed  }
537194613Sed
538193326Sed  return true;
539193326Sed}
540193326Sed
541198092Srdivackystatic unsigned PrintActions1(const Compilation &C, Action *A,
542193326Sed                              std::map<Action*, unsigned> &Ids) {
543193326Sed  if (Ids.count(A))
544193326Sed    return Ids[A];
545198092Srdivacky
546193326Sed  std::string str;
547193326Sed  llvm::raw_string_ostream os(str);
548198092Srdivacky
549193326Sed  os << Action::getClassName(A->getKind()) << ", ";
550198092Srdivacky  if (InputAction *IA = dyn_cast<InputAction>(A)) {
551193326Sed    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
552193326Sed  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
553198092Srdivacky    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
554193326Sed                  C.getDefaultToolChain().getArchName()) << '"'
555193326Sed       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
556193326Sed  } else {
557193326Sed    os << "{";
558193326Sed    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
559193326Sed      os << PrintActions1(C, *it, Ids);
560193326Sed      ++it;
561193326Sed      if (it != ie)
562193326Sed        os << ", ";
563193326Sed    }
564193326Sed    os << "}";
565193326Sed  }
566193326Sed
567193326Sed  unsigned Id = Ids.size();
568193326Sed  Ids[A] = Id;
569198092Srdivacky  llvm::errs() << Id << ": " << os.str() << ", "
570193326Sed               << types::getTypeName(A->getType()) << "\n";
571193326Sed
572193326Sed  return Id;
573193326Sed}
574193326Sed
575193326Sedvoid Driver::PrintActions(const Compilation &C) const {
576193326Sed  std::map<Action*, unsigned> Ids;
577198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
578193326Sed         ie = C.getActions().end(); it != ie; ++it)
579193326Sed    PrintActions1(C, *it, Ids);
580193326Sed}
581193326Sed
582210299Sed/// \brief Check whether the given input tree contains any compilation (or
583210299Sed/// assembly) actions.
584210299Sedstatic bool ContainsCompileAction(const Action *A) {
585210299Sed  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
586210299Sed    return true;
587210299Sed
588210299Sed  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
589210299Sed    if (ContainsCompileAction(*it))
590210299Sed      return true;
591210299Sed
592210299Sed  return false;
593210299Sed}
594210299Sed
595212904Sdimvoid Driver::BuildUniversalActions(const ToolChain &TC,
596212904Sdim                                   const ArgList &Args,
597193326Sed                                   ActionList &Actions) const {
598198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
599198092Srdivacky  // Collect the list of architectures. Duplicates are allowed, but should only
600198092Srdivacky  // be handled once (in the order seen).
601193326Sed  llvm::StringSet<> ArchNames;
602193326Sed  llvm::SmallVector<const char *, 4> Archs;
603198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
604193326Sed       it != ie; ++it) {
605193326Sed    Arg *A = *it;
606193326Sed
607199512Srdivacky    if (A->getOption().matches(options::OPT_arch)) {
608198092Srdivacky      // Validate the option here; we don't save the type here because its
609198092Srdivacky      // particular spelling may participate in other driver choices.
610198092Srdivacky      llvm::Triple::ArchType Arch =
611198092Srdivacky        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
612198092Srdivacky      if (Arch == llvm::Triple::UnknownArch) {
613198092Srdivacky        Diag(clang::diag::err_drv_invalid_arch_name)
614198092Srdivacky          << A->getAsString(Args);
615198092Srdivacky        continue;
616198092Srdivacky      }
617193326Sed
618193326Sed      A->claim();
619198092Srdivacky      if (ArchNames.insert(A->getValue(Args)))
620198092Srdivacky        Archs.push_back(A->getValue(Args));
621193326Sed    }
622193326Sed  }
623193326Sed
624198092Srdivacky  // When there is no explicit arch for this platform, make sure we still bind
625198092Srdivacky  // the architecture (to the default) so that -Xarch_ is handled correctly.
626193326Sed  if (!Archs.size())
627193326Sed    Archs.push_back(0);
628193326Sed
629198092Srdivacky  // FIXME: We killed off some others but these aren't yet detected in a
630198092Srdivacky  // functional manner. If we added information to jobs about which "auxiliary"
631198092Srdivacky  // files they wrote then we could detect the conflict these cause downstream.
632193326Sed  if (Archs.size() > 1) {
633193326Sed    // No recovery needed, the point of this is just to prevent
634193326Sed    // overwriting the same files.
635193326Sed    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
636198092Srdivacky      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
637193326Sed        << A->getAsString(Args);
638193326Sed  }
639193326Sed
640193326Sed  ActionList SingleActions;
641212904Sdim  BuildActions(TC, Args, SingleActions);
642193326Sed
643210299Sed  // Add in arch bindings for every top level action, as well as lipo and
644210299Sed  // dsymutil steps if needed.
645193326Sed  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
646193326Sed    Action *Act = SingleActions[i];
647193326Sed
648198092Srdivacky    // Make sure we can lipo this kind of output. If not (and it is an actual
649198092Srdivacky    // output) then we disallow, since we can't create an output file with the
650198092Srdivacky    // right name without overwriting it. We could remove this oddity by just
651198092Srdivacky    // changing the output names to include the arch, which would also fix
652193326Sed    // -save-temps. Compatibility wins for now.
653193326Sed
654193326Sed    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
655193326Sed      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
656193326Sed        << types::getTypeName(Act->getType());
657193326Sed
658193326Sed    ActionList Inputs;
659205219Srdivacky    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
660193326Sed      Inputs.push_back(new BindArchAction(Act, Archs[i]));
661205219Srdivacky      if (i != 0)
662205219Srdivacky        Inputs.back()->setOwnsInputs(false);
663205219Srdivacky    }
664193326Sed
665198092Srdivacky    // Lipo if necessary, we do it this way because we need to set the arch flag
666198092Srdivacky    // so that -Xarch_ gets overwritten.
667193326Sed    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
668193326Sed      Actions.append(Inputs.begin(), Inputs.end());
669193326Sed    else
670193326Sed      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
671210299Sed
672210299Sed    // Add a 'dsymutil' step if necessary, when debug info is enabled and we
673210299Sed    // have a compile input. We need to run 'dsymutil' ourselves in such cases
674210299Sed    // because the debug info will refer to a temporary object file which is
675210299Sed    // will be removed at the end of the compilation process.
676210299Sed    if (Act->getType() == types::TY_Image) {
677210299Sed      Arg *A = Args.getLastArg(options::OPT_g_Group);
678210299Sed      if (A && !A->getOption().matches(options::OPT_g0) &&
679210299Sed          !A->getOption().matches(options::OPT_gstabs) &&
680210299Sed          ContainsCompileAction(Actions.back())) {
681210299Sed        ActionList Inputs;
682210299Sed        Inputs.push_back(Actions.back());
683210299Sed        Actions.pop_back();
684210299Sed
685210299Sed        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
686210299Sed      }
687210299Sed    }
688193326Sed  }
689193326Sed}
690193326Sed
691212904Sdimvoid Driver::BuildActions(const ToolChain &TC, const ArgList &Args,
692212904Sdim                          ActionList &Actions) const {
693193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
694193326Sed  // Start by constructing the list of inputs and their types.
695193326Sed
696198092Srdivacky  // Track the current user specified (-x) input. We also explicitly track the
697198092Srdivacky  // argument used to set the type; we only want to claim the type when we
698198092Srdivacky  // actually use it, so we warn about unused -x arguments.
699193326Sed  types::ID InputType = types::TY_Nothing;
700193326Sed  Arg *InputTypeArg = 0;
701193326Sed
702193326Sed  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
703198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
704193326Sed       it != ie; ++it) {
705193326Sed    Arg *A = *it;
706193326Sed
707193326Sed    if (isa<InputOption>(A->getOption())) {
708193326Sed      const char *Value = A->getValue(Args);
709193326Sed      types::ID Ty = types::TY_INVALID;
710193326Sed
711193326Sed      // Infer the input type if necessary.
712193326Sed      if (InputType == types::TY_Nothing) {
713193326Sed        // If there was an explicit arg for this, claim it.
714193326Sed        if (InputTypeArg)
715193326Sed          InputTypeArg->claim();
716193326Sed
717193326Sed        // stdin must be handled specially.
718193326Sed        if (memcmp(Value, "-", 2) == 0) {
719198092Srdivacky          // If running with -E, treat as a C input (this changes the builtin
720198092Srdivacky          // macros, for example). This may be overridden by -ObjC below.
721193326Sed          //
722198092Srdivacky          // Otherwise emit an error but still use a valid type to avoid
723198092Srdivacky          // spurious errors (e.g., no inputs).
724199512Srdivacky          if (!Args.hasArgNoClaim(options::OPT_E))
725193326Sed            Diag(clang::diag::err_drv_unknown_stdin_type);
726193326Sed          Ty = types::TY_C;
727193326Sed        } else {
728198092Srdivacky          // Otherwise lookup by extension, and fallback to ObjectType if not
729198092Srdivacky          // found. We use a host hook here because Darwin at least has its own
730198092Srdivacky          // idea of what .s is.
731193326Sed          if (const char *Ext = strrchr(Value, '.'))
732212904Sdim            Ty = TC.LookupTypeForExtension(Ext + 1);
733193326Sed
734193326Sed          if (Ty == types::TY_INVALID)
735193326Sed            Ty = types::TY_Object;
736204643Srdivacky
737204643Srdivacky          // If the driver is invoked as C++ compiler (like clang++ or c++) it
738204643Srdivacky          // should autodetect some input files as C++ for g++ compatibility.
739204643Srdivacky          if (CCCIsCXX) {
740204643Srdivacky            types::ID OldTy = Ty;
741204643Srdivacky            Ty = types::lookupCXXTypeForCType(Ty);
742204643Srdivacky
743204643Srdivacky            if (Ty != OldTy)
744204643Srdivacky              Diag(clang::diag::warn_drv_treating_input_as_cxx)
745204643Srdivacky                << getTypeName(OldTy) << getTypeName(Ty);
746204643Srdivacky          }
747193326Sed        }
748193326Sed
749193326Sed        // -ObjC and -ObjC++ override the default language, but only for "source
750193326Sed        // files". We just treat everything that isn't a linker input as a
751193326Sed        // source file.
752198092Srdivacky        //
753193326Sed        // FIXME: Clean this up if we move the phase sequence into the type.
754193326Sed        if (Ty != types::TY_Object) {
755193326Sed          if (Args.hasArg(options::OPT_ObjC))
756193326Sed            Ty = types::TY_ObjC;
757193326Sed          else if (Args.hasArg(options::OPT_ObjCXX))
758193326Sed            Ty = types::TY_ObjCXX;
759193326Sed        }
760193326Sed      } else {
761193326Sed        assert(InputTypeArg && "InputType set w/o InputTypeArg");
762193326Sed        InputTypeArg->claim();
763193326Sed        Ty = InputType;
764193326Sed      }
765193326Sed
766203955Srdivacky      // Check that the file exists, if enabled.
767218893Sdim      if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
768218893Sdim        llvm::SmallString<64> Path(Value);
769218893Sdim        if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory))
770218893Sdim          if (llvm::sys::path::is_absolute(Path.str())) {
771218893Sdim            Path = WorkDir->getValue(Args);
772218893Sdim            llvm::sys::path::append(Path, Value);
773218893Sdim          }
774218893Sdim
775218893Sdim        bool exists = false;
776218893Sdim        if (/*error_code ec =*/llvm::sys::fs::exists(Value, exists) || !exists)
777218893Sdim          Diag(clang::diag::err_drv_no_such_file) << Path.str();
778218893Sdim        else
779218893Sdim          Inputs.push_back(std::make_pair(Ty, A));
780218893Sdim      } else
781193326Sed        Inputs.push_back(std::make_pair(Ty, A));
782193326Sed
783193326Sed    } else if (A->getOption().isLinkerInput()) {
784198092Srdivacky      // Just treat as object type, we could make a special type for this if
785198092Srdivacky      // necessary.
786193326Sed      Inputs.push_back(std::make_pair(types::TY_Object, A));
787193326Sed
788199512Srdivacky    } else if (A->getOption().matches(options::OPT_x)) {
789198092Srdivacky      InputTypeArg = A;
790193326Sed      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
791193326Sed
792193326Sed      // Follow gcc behavior and treat as linker input for invalid -x
793198092Srdivacky      // options. Its not clear why we shouldn't just revert to unknown; but
794218893Sdim      // this isn't very important, we might as well be bug compatible.
795193326Sed      if (!InputType) {
796193326Sed        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
797193326Sed        InputType = types::TY_Object;
798193326Sed      }
799193326Sed    }
800193326Sed  }
801193326Sed
802193326Sed  if (!SuppressMissingInputWarning && Inputs.empty()) {
803193326Sed    Diag(clang::diag::err_drv_no_input_files);
804193326Sed    return;
805193326Sed  }
806193326Sed
807198092Srdivacky  // Determine which compilation mode we are in. We look for options which
808198092Srdivacky  // affect the phase, starting with the earliest phases, and record which
809198092Srdivacky  // option we used to determine the final phase.
810193326Sed  Arg *FinalPhaseArg = 0;
811193326Sed  phases::ID FinalPhase;
812193326Sed
813193326Sed  // -{E,M,MM} only run the preprocessor.
814193326Sed  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
815218893Sdim      (FinalPhaseArg = Args.getLastArg(options::OPT_M, options::OPT_MM))) {
816193326Sed    FinalPhase = phases::Preprocess;
817198092Srdivacky
818198092Srdivacky    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
819193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
820203955Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_rewrite_objc)) ||
821193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
822193326Sed                                              options::OPT__analyze_auto)) ||
823198092Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
824193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
825193326Sed    FinalPhase = phases::Compile;
826193326Sed
827193326Sed    // -c only runs up to the assembler.
828193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
829193326Sed    FinalPhase = phases::Assemble;
830198092Srdivacky
831193326Sed    // Otherwise do everything.
832193326Sed  } else
833193326Sed    FinalPhase = phases::Link;
834193326Sed
835198092Srdivacky  // Reject -Z* at the top level, these options should never have been exposed
836198092Srdivacky  // by gcc.
837193326Sed  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
838193326Sed    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
839193326Sed
840193326Sed  // Construct the actions to perform.
841193326Sed  ActionList LinkerInputs;
842193326Sed  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
843193326Sed    types::ID InputType = Inputs[i].first;
844193326Sed    const Arg *InputArg = Inputs[i].second;
845193326Sed
846193326Sed    unsigned NumSteps = types::getNumCompilationPhases(InputType);
847193326Sed    assert(NumSteps && "Invalid number of steps!");
848193326Sed
849198092Srdivacky    // If the first step comes after the final phase we are doing as part of
850198092Srdivacky    // this compilation, warn the user about it.
851193326Sed    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
852193326Sed    if (InitialPhase > FinalPhase) {
853193326Sed      // Claim here to avoid the more general unused warning.
854193326Sed      InputArg->claim();
855198092Srdivacky
856198092Srdivacky      // Special case '-E' warning on a previously preprocessed file to make
857198092Srdivacky      // more sense.
858198092Srdivacky      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
859198092Srdivacky          getPreprocessedType(InputType) == types::TY_INVALID)
860198092Srdivacky        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
861198092Srdivacky          << InputArg->getAsString(Args)
862198092Srdivacky          << FinalPhaseArg->getOption().getName();
863198092Srdivacky      else
864198092Srdivacky        Diag(clang::diag::warn_drv_input_file_unused)
865198092Srdivacky          << InputArg->getAsString(Args)
866198092Srdivacky          << getPhaseName(InitialPhase)
867198092Srdivacky          << FinalPhaseArg->getOption().getName();
868193326Sed      continue;
869193326Sed    }
870198092Srdivacky
871193326Sed    // Build the pipeline for this file.
872202879Srdivacky    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
873193326Sed    for (unsigned i = 0; i != NumSteps; ++i) {
874193326Sed      phases::ID Phase = types::getCompilationPhase(InputType, i);
875193326Sed
876193326Sed      // We are done if this step is past what the user requested.
877193326Sed      if (Phase > FinalPhase)
878193326Sed        break;
879193326Sed
880193326Sed      // Queue linker inputs.
881193326Sed      if (Phase == phases::Link) {
882193326Sed        assert(i + 1 == NumSteps && "linking must be final compilation step.");
883202879Srdivacky        LinkerInputs.push_back(Current.take());
884193326Sed        break;
885193326Sed      }
886193326Sed
887198092Srdivacky      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
888198092Srdivacky      // encode this in the steps because the intermediate type depends on
889198092Srdivacky      // arguments. Just special case here.
890193326Sed      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
891193326Sed        continue;
892193326Sed
893193326Sed      // Otherwise construct the appropriate action.
894202879Srdivacky      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
895193326Sed      if (Current->getType() == types::TY_Nothing)
896193326Sed        break;
897193326Sed    }
898193326Sed
899193326Sed    // If we ended with something, add to the output list.
900193326Sed    if (Current)
901202879Srdivacky      Actions.push_back(Current.take());
902193326Sed  }
903193326Sed
904193326Sed  // Add a link action if necessary.
905193326Sed  if (!LinkerInputs.empty())
906193326Sed    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
907201361Srdivacky
908201361Srdivacky  // If we are linking, claim any options which are obviously only used for
909201361Srdivacky  // compilation.
910201361Srdivacky  if (FinalPhase == phases::Link)
911201361Srdivacky    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
912193326Sed}
913193326Sed
914193326SedAction *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
915193326Sed                                     Action *Input) const {
916193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
917193326Sed  // Build the appropriate action.
918193326Sed  switch (Phase) {
919193326Sed  case phases::Link: assert(0 && "link action invalid here.");
920193326Sed  case phases::Preprocess: {
921193326Sed    types::ID OutputTy;
922193326Sed    // -{M, MM} alter the output type.
923218893Sdim    if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
924193326Sed      OutputTy = types::TY_Dependencies;
925193326Sed    } else {
926193326Sed      OutputTy = types::getPreprocessedType(Input->getType());
927193326Sed      assert(OutputTy != types::TY_INVALID &&
928193326Sed             "Cannot preprocess this input type!");
929193326Sed    }
930193326Sed    return new PreprocessJobAction(Input, OutputTy);
931193326Sed  }
932193326Sed  case phases::Precompile:
933198092Srdivacky    return new PrecompileJobAction(Input, types::TY_PCH);
934193326Sed  case phases::Compile: {
935201361Srdivacky    bool HasO4 = false;
936201361Srdivacky    if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
937201361Srdivacky      HasO4 = A->getOption().matches(options::OPT_O4);
938201361Srdivacky
939193326Sed    if (Args.hasArg(options::OPT_fsyntax_only)) {
940193326Sed      return new CompileJobAction(Input, types::TY_Nothing);
941203955Srdivacky    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
942203955Srdivacky      return new CompileJobAction(Input, types::TY_RewrittenObjC);
943193326Sed    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
944193326Sed      return new AnalyzeJobAction(Input, types::TY_Plist);
945198092Srdivacky    } else if (Args.hasArg(options::OPT_emit_ast)) {
946198092Srdivacky      return new CompileJobAction(Input, types::TY_AST);
947193326Sed    } else if (Args.hasArg(options::OPT_emit_llvm) ||
948201361Srdivacky               Args.hasArg(options::OPT_flto) || HasO4) {
949198092Srdivacky      types::ID Output =
950210299Sed        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
951193326Sed      return new CompileJobAction(Input, Output);
952193326Sed    } else {
953193326Sed      return new CompileJobAction(Input, types::TY_PP_Asm);
954193326Sed    }
955193326Sed  }
956193326Sed  case phases::Assemble:
957193326Sed    return new AssembleJobAction(Input, types::TY_Object);
958193326Sed  }
959193326Sed
960193326Sed  assert(0 && "invalid phase in ConstructPhaseAction");
961193326Sed  return 0;
962193326Sed}
963193326Sed
964193326Sedvoid Driver::BuildJobs(Compilation &C) const {
965193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
966193326Sed
967193326Sed  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
968193326Sed
969198092Srdivacky  // It is an error to provide a -o option if we are making multiple output
970198092Srdivacky  // files.
971193326Sed  if (FinalOutput) {
972193326Sed    unsigned NumOutputs = 0;
973198092Srdivacky    for (ActionList::const_iterator it = C.getActions().begin(),
974193326Sed           ie = C.getActions().end(); it != ie; ++it)
975193326Sed      if ((*it)->getType() != types::TY_Nothing)
976193326Sed        ++NumOutputs;
977198092Srdivacky
978193326Sed    if (NumOutputs > 1) {
979193326Sed      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
980193326Sed      FinalOutput = 0;
981193326Sed    }
982193326Sed  }
983193326Sed
984198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
985193326Sed         ie = C.getActions().end(); it != ie; ++it) {
986193326Sed    Action *A = *it;
987193326Sed
988198092Srdivacky    // If we are linking an image for multiple archs then the linker wants
989198092Srdivacky    // -arch_multiple and -final_output <final image name>. Unfortunately, this
990198092Srdivacky    // doesn't fit in cleanly because we have to pass this information down.
991193326Sed    //
992198092Srdivacky    // FIXME: This is a hack; find a cleaner way to integrate this into the
993198092Srdivacky    // process.
994193326Sed    const char *LinkingOutput = 0;
995193326Sed    if (isa<LipoJobAction>(A)) {
996193326Sed      if (FinalOutput)
997193326Sed        LinkingOutput = FinalOutput->getValue(C.getArgs());
998193326Sed      else
999193326Sed        LinkingOutput = DefaultImageName.c_str();
1000193326Sed    }
1001193326Sed
1002193326Sed    InputInfo II;
1003198092Srdivacky    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1004198092Srdivacky                       /*BoundArch*/0,
1005193326Sed                       /*AtTopLevel*/ true,
1006193326Sed                       /*LinkingOutput*/ LinkingOutput,
1007193326Sed                       II);
1008193326Sed  }
1009193326Sed
1010198092Srdivacky  // If the user passed -Qunused-arguments or there were errors, don't warn
1011198092Srdivacky  // about any unused arguments.
1012218893Sdim  if (Diags.hasErrorOccurred() ||
1013193326Sed      C.getArgs().hasArg(options::OPT_Qunused_arguments))
1014193326Sed    return;
1015193326Sed
1016193326Sed  // Claim -### here.
1017193326Sed  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1018198092Srdivacky
1019193326Sed  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1020193326Sed       it != ie; ++it) {
1021193326Sed    Arg *A = *it;
1022198092Srdivacky
1023193326Sed    // FIXME: It would be nice to be able to send the argument to the
1024198092Srdivacky    // Diagnostic, so that extra values, position, and so on could be printed.
1025193326Sed    if (!A->isClaimed()) {
1026193326Sed      if (A->getOption().hasNoArgumentUnused())
1027193326Sed        continue;
1028193326Sed
1029198092Srdivacky      // Suppress the warning automatically if this is just a flag, and it is an
1030198092Srdivacky      // instance of an argument we already claimed.
1031193326Sed      const Option &Opt = A->getOption();
1032193326Sed      if (isa<FlagOption>(Opt)) {
1033193326Sed        bool DuplicateClaimed = false;
1034193326Sed
1035199990Srdivacky        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1036199990Srdivacky               ie = C.getArgs().filtered_end(); it != ie; ++it) {
1037199990Srdivacky          if ((*it)->isClaimed()) {
1038193326Sed            DuplicateClaimed = true;
1039193326Sed            break;
1040193326Sed          }
1041193326Sed        }
1042193326Sed
1043193326Sed        if (DuplicateClaimed)
1044193326Sed          continue;
1045193326Sed      }
1046193326Sed
1047198092Srdivacky      Diag(clang::diag::warn_drv_unused_argument)
1048193326Sed        << A->getAsString(C.getArgs());
1049193326Sed    }
1050193326Sed  }
1051193326Sed}
1052193326Sed
1053203955Srdivackystatic const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1054203955Srdivacky                                    const JobAction *JA,
1055203955Srdivacky                                    const ActionList *&Inputs) {
1056203955Srdivacky  const Tool *ToolForJob = 0;
1057203955Srdivacky
1058203955Srdivacky  // See if we should look for a compiler with an integrated assembler. We match
1059203955Srdivacky  // bottom up, so what we are actually looking for is an assembler job with a
1060203955Srdivacky  // compiler input.
1061208600Srdivacky
1062208600Srdivacky  // FIXME: This doesn't belong here, but ideally we will support static soon
1063208600Srdivacky  // anyway.
1064208600Srdivacky  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
1065208600Srdivacky                    C.getArgs().hasArg(options::OPT_static) ||
1066208600Srdivacky                    C.getArgs().hasArg(options::OPT_fapple_kext));
1067208600Srdivacky  bool IsIADefault = (TC->IsIntegratedAssemblerDefault() && !HasStatic);
1068208600Srdivacky  if (C.getArgs().hasFlag(options::OPT_integrated_as,
1069203955Srdivacky                         options::OPT_no_integrated_as,
1070208600Srdivacky                         IsIADefault) &&
1071203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1072203955Srdivacky      isa<AssembleJobAction>(JA) &&
1073203955Srdivacky      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1074203955Srdivacky    const Tool &Compiler = TC->SelectTool(C,cast<JobAction>(**Inputs->begin()));
1075203955Srdivacky    if (Compiler.hasIntegratedAssembler()) {
1076203955Srdivacky      Inputs = &(*Inputs)[0]->getInputs();
1077203955Srdivacky      ToolForJob = &Compiler;
1078203955Srdivacky    }
1079203955Srdivacky  }
1080203955Srdivacky
1081203955Srdivacky  // Otherwise use the tool for the current job.
1082203955Srdivacky  if (!ToolForJob)
1083203955Srdivacky    ToolForJob = &TC->SelectTool(C, *JA);
1084203955Srdivacky
1085203955Srdivacky  // See if we should use an integrated preprocessor. We do so when we have
1086203955Srdivacky  // exactly one input, since this is the only use case we care about
1087203955Srdivacky  // (irrelevant since we don't support combine yet).
1088203955Srdivacky  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1089203955Srdivacky      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1090203955Srdivacky      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1091203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1092203955Srdivacky      ToolForJob->hasIntegratedCPP())
1093203955Srdivacky    Inputs = &(*Inputs)[0]->getInputs();
1094203955Srdivacky
1095203955Srdivacky  return *ToolForJob;
1096203955Srdivacky}
1097203955Srdivacky
1098193326Sedvoid Driver::BuildJobsForAction(Compilation &C,
1099193326Sed                                const Action *A,
1100193326Sed                                const ToolChain *TC,
1101198092Srdivacky                                const char *BoundArch,
1102193326Sed                                bool AtTopLevel,
1103193326Sed                                const char *LinkingOutput,
1104193326Sed                                InputInfo &Result) const {
1105198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1106193326Sed
1107193326Sed  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1108198092Srdivacky    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1109198092Srdivacky    // just using Args was better?
1110193326Sed    const Arg &Input = IA->getInputArg();
1111193326Sed    Input.claim();
1112210299Sed    if (Input.getOption().matches(options::OPT_INPUT)) {
1113193326Sed      const char *Name = Input.getValue(C.getArgs());
1114193326Sed      Result = InputInfo(Name, A->getType(), Name);
1115193326Sed    } else
1116193326Sed      Result = InputInfo(&Input, A->getType(), "");
1117193326Sed    return;
1118193326Sed  }
1119193326Sed
1120193326Sed  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1121198092Srdivacky    const ToolChain *TC = &C.getDefaultToolChain();
1122198092Srdivacky
1123193326Sed    std::string Arch;
1124198092Srdivacky    if (BAA->getArchName())
1125198092Srdivacky      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1126198092Srdivacky
1127198092Srdivacky    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1128212904Sdim                       AtTopLevel, LinkingOutput, Result);
1129193326Sed    return;
1130193326Sed  }
1131193326Sed
1132203955Srdivacky  const ActionList *Inputs = &A->getInputs();
1133203955Srdivacky
1134193326Sed  const JobAction *JA = cast<JobAction>(A);
1135203955Srdivacky  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1136198092Srdivacky
1137193326Sed  // Only use pipes when there is exactly one input.
1138193326Sed  InputInfoList InputInfos;
1139193326Sed  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1140193326Sed       it != ie; ++it) {
1141210299Sed    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1142210299Sed    // temporary output names.
1143210299Sed    //
1144210299Sed    // FIXME: Clean this up.
1145210299Sed    bool SubJobAtTopLevel = false;
1146210299Sed    if (AtTopLevel && isa<DsymutilJobAction>(A))
1147210299Sed      SubJobAtTopLevel = true;
1148210299Sed
1149193326Sed    InputInfo II;
1150212904Sdim    BuildJobsForAction(C, *it, TC, BoundArch,
1151210299Sed                       SubJobAtTopLevel, LinkingOutput, II);
1152193326Sed    InputInfos.push_back(II);
1153193326Sed  }
1154193326Sed
1155193326Sed  // Always use the first input as the base input.
1156193326Sed  const char *BaseInput = InputInfos[0].getBaseInput();
1157193326Sed
1158210299Sed  // ... except dsymutil actions, which use their actual input as the base
1159210299Sed  // input.
1160210299Sed  if (JA->getType() == types::TY_dSYM)
1161210299Sed    BaseInput = InputInfos[0].getFilename();
1162210299Sed
1163212904Sdim  // Determine the place to write output to, if any.
1164193326Sed  if (JA->getType() == types::TY_Nothing) {
1165193326Sed    Result = InputInfo(A->getType(), BaseInput);
1166193326Sed  } else {
1167193326Sed    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1168193326Sed                       A->getType(), BaseInput);
1169193326Sed  }
1170193326Sed
1171193326Sed  if (CCCPrintBindings) {
1172193326Sed    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1173193326Sed                 << " - \"" << T.getName() << "\", inputs: [";
1174193326Sed    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1175193326Sed      llvm::errs() << InputInfos[i].getAsString();
1176193326Sed      if (i + 1 != e)
1177193326Sed        llvm::errs() << ", ";
1178193326Sed    }
1179193326Sed    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1180193326Sed  } else {
1181212904Sdim    T.ConstructJob(C, *JA, Result, InputInfos,
1182198092Srdivacky                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1183193326Sed  }
1184193326Sed}
1185193326Sed
1186198092Srdivackyconst char *Driver::GetNamedOutputPath(Compilation &C,
1187193326Sed                                       const JobAction &JA,
1188193326Sed                                       const char *BaseInput,
1189193326Sed                                       bool AtTopLevel) const {
1190193326Sed  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1191193326Sed  // Output to a user requested destination?
1192210299Sed  if (AtTopLevel && !isa<DsymutilJobAction>(JA)) {
1193193326Sed    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1194193326Sed      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1195193326Sed  }
1196193326Sed
1197212904Sdim  // Default to writing to stdout?
1198212904Sdim  if (AtTopLevel && isa<PreprocessJobAction>(JA))
1199212904Sdim    return "-";
1200212904Sdim
1201193326Sed  // Output to a temporary file?
1202193326Sed  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1203198092Srdivacky    std::string TmpName =
1204193326Sed      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1205193326Sed    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1206193326Sed  }
1207193326Sed
1208218893Sdim  llvm::SmallString<128> BasePath(BaseInput);
1209218893Sdim  llvm::StringRef BaseName = llvm::sys::path::filename(BasePath);
1210193326Sed
1211193326Sed  // Determine what the derived output name should be.
1212193326Sed  const char *NamedOutput;
1213193326Sed  if (JA.getType() == types::TY_Image) {
1214193326Sed    NamedOutput = DefaultImageName.c_str();
1215193326Sed  } else {
1216193326Sed    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1217193326Sed    assert(Suffix && "All types used for output should have a suffix.");
1218193326Sed
1219193326Sed    std::string::size_type End = std::string::npos;
1220193326Sed    if (!types::appendSuffixForType(JA.getType()))
1221193326Sed      End = BaseName.rfind('.');
1222193326Sed    std::string Suffixed(BaseName.substr(0, End));
1223193326Sed    Suffixed += '.';
1224193326Sed    Suffixed += Suffix;
1225193326Sed    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1226193326Sed  }
1227193326Sed
1228198092Srdivacky  // As an annoying special case, PCH generation doesn't strip the pathname.
1229193326Sed  if (JA.getType() == types::TY_PCH) {
1230218893Sdim    llvm::sys::path::remove_filename(BasePath);
1231218893Sdim    if (BasePath.empty())
1232193326Sed      BasePath = NamedOutput;
1233193326Sed    else
1234218893Sdim      llvm::sys::path::append(BasePath, NamedOutput);
1235193326Sed    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1236193326Sed  } else {
1237193326Sed    return C.addResultFile(NamedOutput);
1238193326Sed  }
1239193326Sed}
1240193326Sed
1241198092Srdivackystd::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1242206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1243206084Srdivacky  // attempting to use this prefix when lokup up program paths.
1244218893Sdim  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1245218893Sdim       ie = PrefixDirs.end(); it != ie; ++it) {
1246218893Sdim    llvm::sys::Path P(*it);
1247206084Srdivacky    P.appendComponent(Name);
1248218893Sdim    bool Exists;
1249218893Sdim    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1250206084Srdivacky      return P.str();
1251206084Srdivacky  }
1252206084Srdivacky
1253193326Sed  const ToolChain::path_list &List = TC.getFilePaths();
1254198092Srdivacky  for (ToolChain::path_list::const_iterator
1255193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1256193326Sed    llvm::sys::Path P(*it);
1257193326Sed    P.appendComponent(Name);
1258218893Sdim    bool Exists;
1259218893Sdim    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1260198092Srdivacky      return P.str();
1261193326Sed  }
1262193326Sed
1263198092Srdivacky  return Name;
1264193326Sed}
1265193326Sed
1266198092Srdivackystd::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1267198092Srdivacky                                   bool WantFile) const {
1268206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1269206084Srdivacky  // attempting to use this prefix when lokup up program paths.
1270218893Sdim  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1271218893Sdim       ie = PrefixDirs.end(); it != ie; ++it) {
1272218893Sdim    llvm::sys::Path P(*it);
1273206084Srdivacky    P.appendComponent(Name);
1274218893Sdim    bool Exists;
1275218893Sdim    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1276218893Sdim                 : P.canExecute())
1277206084Srdivacky      return P.str();
1278206084Srdivacky  }
1279206084Srdivacky
1280193326Sed  const ToolChain::path_list &List = TC.getProgramPaths();
1281198092Srdivacky  for (ToolChain::path_list::const_iterator
1282193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1283193326Sed    llvm::sys::Path P(*it);
1284193326Sed    P.appendComponent(Name);
1285218893Sdim    bool Exists;
1286218893Sdim    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1287218893Sdim                 : P.canExecute())
1288198092Srdivacky      return P.str();
1289193326Sed  }
1290193326Sed
1291193326Sed  // If all else failed, search the path.
1292193326Sed  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1293193326Sed  if (!P.empty())
1294198092Srdivacky    return P.str();
1295193326Sed
1296198092Srdivacky  return Name;
1297193326Sed}
1298193326Sed
1299193326Sedstd::string Driver::GetTemporaryPath(const char *Suffix) const {
1300198092Srdivacky  // FIXME: This is lame; sys::Path should provide this function (in particular,
1301198092Srdivacky  // it should know how to find the temporary files dir).
1302193326Sed  std::string Error;
1303193326Sed  const char *TmpDir = ::getenv("TMPDIR");
1304193326Sed  if (!TmpDir)
1305193326Sed    TmpDir = ::getenv("TEMP");
1306193326Sed  if (!TmpDir)
1307193326Sed    TmpDir = ::getenv("TMP");
1308193326Sed  if (!TmpDir)
1309193326Sed    TmpDir = "/tmp";
1310193326Sed  llvm::sys::Path P(TmpDir);
1311193326Sed  P.appendComponent("cc");
1312193326Sed  if (P.makeUnique(false, &Error)) {
1313193326Sed    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1314193326Sed    return "";
1315193326Sed  }
1316193326Sed
1317198092Srdivacky  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1318193326Sed  P.eraseFromDisk(false, 0);
1319193326Sed
1320193326Sed  P.appendSuffix(Suffix);
1321198092Srdivacky  return P.str();
1322193326Sed}
1323193326Sed
1324193326Sedconst HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1325193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1326193326Sed  llvm::Triple Triple(TripleStr);
1327193326Sed
1328204793Srdivacky  // TCE is an osless target
1329204793Srdivacky  if (Triple.getArchName() == "tce")
1330210299Sed    return createTCEHostInfo(*this, Triple);
1331204793Srdivacky
1332193326Sed  switch (Triple.getOS()) {
1333198092Srdivacky  case llvm::Triple::AuroraUX:
1334198092Srdivacky    return createAuroraUXHostInfo(*this, Triple);
1335193326Sed  case llvm::Triple::Darwin:
1336193326Sed    return createDarwinHostInfo(*this, Triple);
1337193326Sed  case llvm::Triple::DragonFly:
1338193326Sed    return createDragonFlyHostInfo(*this, Triple);
1339195341Sed  case llvm::Triple::OpenBSD:
1340195341Sed    return createOpenBSDHostInfo(*this, Triple);
1341218893Sdim  case llvm::Triple::NetBSD:
1342218893Sdim    return createNetBSDHostInfo(*this, Triple);
1343193326Sed  case llvm::Triple::FreeBSD:
1344193326Sed    return createFreeBSDHostInfo(*this, Triple);
1345210299Sed  case llvm::Triple::Minix:
1346210299Sed    return createMinixHostInfo(*this, Triple);
1347193326Sed  case llvm::Triple::Linux:
1348193326Sed    return createLinuxHostInfo(*this, Triple);
1349212904Sdim  case llvm::Triple::Win32:
1350212904Sdim    return createWindowsHostInfo(*this, Triple);
1351212904Sdim  case llvm::Triple::MinGW32:
1352212904Sdim    return createMinGWHostInfo(*this, Triple);
1353193326Sed  default:
1354193326Sed    return createUnknownHostInfo(*this, Triple);
1355193326Sed  }
1356193326Sed}
1357193326Sed
1358193326Sedbool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1359198092Srdivacky                                    const llvm::Triple &Triple) const {
1360198092Srdivacky  // Check if user requested no clang, or clang doesn't understand this type (we
1361198092Srdivacky  // only handle single inputs for now).
1362198092Srdivacky  if (!CCCUseClang || JA.size() != 1 ||
1363193326Sed      !types::isAcceptedByClang((*JA.begin())->getType()))
1364193326Sed    return false;
1365193326Sed
1366193326Sed  // Otherwise make sure this is an action clang understands.
1367193326Sed  if (isa<PreprocessJobAction>(JA)) {
1368193326Sed    if (!CCCUseClangCPP) {
1369193326Sed      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1370193326Sed      return false;
1371193326Sed    }
1372193326Sed  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1373193326Sed    return false;
1374193326Sed
1375193326Sed  // Use clang for C++?
1376193326Sed  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1377193326Sed    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1378193326Sed    return false;
1379193326Sed  }
1380193326Sed
1381203955Srdivacky  // Always use clang for precompiling, AST generation, and rewriting,
1382203955Srdivacky  // regardless of archs.
1383210299Sed  if (isa<PrecompileJobAction>(JA) ||
1384210299Sed      types::isOnlyAcceptedByClang(JA.getType()))
1385193326Sed    return true;
1386193326Sed
1387198092Srdivacky  // Finally, don't use clang if this isn't one of the user specified archs to
1388198092Srdivacky  // build.
1389198092Srdivacky  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1390198092Srdivacky    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1391193326Sed    return false;
1392193326Sed  }
1393193326Sed
1394193326Sed  return true;
1395193326Sed}
1396193326Sed
1397198092Srdivacky/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1398198092Srdivacky/// grouped values as integers. Numbers which are not provided are set to 0.
1399193326Sed///
1400198092Srdivacky/// \return True if the entire string was parsed (9.2), or all groups were
1401198092Srdivacky/// parsed (10.3.5extrastuff).
1402198092Srdivackybool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1403193326Sed                               unsigned &Minor, unsigned &Micro,
1404193326Sed                               bool &HadExtra) {
1405193326Sed  HadExtra = false;
1406193326Sed
1407193326Sed  Major = Minor = Micro = 0;
1408198092Srdivacky  if (*Str == '\0')
1409193326Sed    return true;
1410193326Sed
1411193326Sed  char *End;
1412193326Sed  Major = (unsigned) strtol(Str, &End, 10);
1413193326Sed  if (*Str != '\0' && *End == '\0')
1414193326Sed    return true;
1415193326Sed  if (*End != '.')
1416193326Sed    return false;
1417198092Srdivacky
1418193326Sed  Str = End+1;
1419193326Sed  Minor = (unsigned) strtol(Str, &End, 10);
1420193326Sed  if (*Str != '\0' && *End == '\0')
1421193326Sed    return true;
1422193326Sed  if (*End != '.')
1423193326Sed    return false;
1424193326Sed
1425193326Sed  Str = End+1;
1426193326Sed  Micro = (unsigned) strtol(Str, &End, 10);
1427193326Sed  if (*Str != '\0' && *End == '\0')
1428193326Sed    return true;
1429193326Sed  if (Str == End)
1430193326Sed    return false;
1431193326Sed  HadExtra = true;
1432193326Sed  return true;
1433193326Sed}
1434