Driver.cpp revision 221345
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"
33221345Sdim#include "llvm/ADT/ArrayRef.h"
34193326Sed#include "llvm/ADT/StringSet.h"
35202879Srdivacky#include "llvm/ADT/OwningPtr.h"
36193326Sed#include "llvm/Support/PrettyStackTrace.h"
37193326Sed#include "llvm/Support/raw_ostream.h"
38218893Sdim#include "llvm/Support/FileSystem.h"
39218893Sdim#include "llvm/Support/Path.h"
40218893Sdim#include "llvm/Support/Program.h"
41193326Sed
42193326Sed#include "InputInfo.h"
43193326Sed
44193326Sed#include <map>
45193326Sed
46193326Sedusing namespace clang::driver;
47193326Sedusing namespace clang;
48193326Sed
49212904SdimDriver::Driver(llvm::StringRef _ClangExecutable,
50200583Srdivacky               llvm::StringRef _DefaultHostTriple,
51200583Srdivacky               llvm::StringRef _DefaultImageName,
52206084Srdivacky               bool IsProduction, bool CXXIsProduction,
53206084Srdivacky               Diagnostic &_Diags)
54199512Srdivacky  : Opts(createDriverOptTable()), Diags(_Diags),
55221345Sdim    ClangExecutable(_ClangExecutable), UseStdLib(true),
56221345Sdim    DefaultHostTriple(_DefaultHostTriple), DefaultImageName(_DefaultImageName),
57204643Srdivacky    DriverTitle("clang \"gcc-compatible\" driver"),
58193326Sed    Host(0),
59221345Sdim    CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
60221345Sdim    CCLogDiagnosticsFilename(0), CCCIsCXX(false),
61221345Sdim    CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
62221345Sdim    CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
63221345Sdim    CCCGenericGCCName(""), CheckInputsExist(true), CCCUseClang(true),
64221345Sdim    CCCUseClangCXX(true), CCCUseClangCPP(true), CCCUsePCH(true),
65221345Sdim    SuppressMissingInputWarning(false) {
66198092Srdivacky  if (IsProduction) {
67198092Srdivacky    // In a "production" build, only use clang on architectures we expect to
68198092Srdivacky    // work, and don't use clang C++.
69198092Srdivacky    //
70198092Srdivacky    // During development its more convenient to always have the driver use
71198092Srdivacky    // clang, but we don't want users to be confused when things don't work, or
72198092Srdivacky    // to file bugs for things we don't support.
73198092Srdivacky    CCCClangArchs.insert(llvm::Triple::x86);
74198092Srdivacky    CCCClangArchs.insert(llvm::Triple::x86_64);
75198092Srdivacky    CCCClangArchs.insert(llvm::Triple::arm);
76198092Srdivacky
77206084Srdivacky    if (!CXXIsProduction)
78206084Srdivacky      CCCUseClangCXX = false;
79198092Srdivacky  }
80202879Srdivacky
81218893Sdim  Name = llvm::sys::path::stem(ClangExecutable);
82218893Sdim  Dir  = llvm::sys::path::parent_path(ClangExecutable);
83212904Sdim
84202879Srdivacky  // Compute the path to the resource directory.
85218893Sdim  llvm::StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
86218893Sdim  llvm::SmallString<128> P(Dir);
87218893Sdim  if (ClangResourceDir != "")
88218893Sdim    llvm::sys::path::append(P, ClangResourceDir);
89218893Sdim  else
90218893Sdim    llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
91202879Srdivacky  ResourceDir = P.str();
92193326Sed}
93193326Sed
94193326SedDriver::~Driver() {
95193326Sed  delete Opts;
96193326Sed  delete Host;
97193326Sed}
98193326Sed
99221345SdimInputArgList *Driver::ParseArgStrings(llvm::ArrayRef<const char *> ArgList) {
100193326Sed  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
101199512Srdivacky  unsigned MissingArgIndex, MissingArgCount;
102221345Sdim  InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(),
103199512Srdivacky                                           MissingArgIndex, MissingArgCount);
104198092Srdivacky
105199512Srdivacky  // Check for missing argument error.
106199512Srdivacky  if (MissingArgCount)
107199512Srdivacky    Diag(clang::diag::err_drv_missing_argument)
108199512Srdivacky      << Args->getArgString(MissingArgIndex) << MissingArgCount;
109193326Sed
110199512Srdivacky  // Check for unsupported options.
111199512Srdivacky  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
112199512Srdivacky       it != ie; ++it) {
113199512Srdivacky    Arg *A = *it;
114193326Sed    if (A->getOption().isUnsupported()) {
115193326Sed      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
116193326Sed      continue;
117193326Sed    }
118193326Sed  }
119193326Sed
120193326Sed  return Args;
121193326Sed}
122193326Sed
123210299SedDerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
124210299Sed  DerivedArgList *DAL = new DerivedArgList(Args);
125210299Sed
126218893Sdim  bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
127210299Sed  for (ArgList::const_iterator it = Args.begin(),
128210299Sed         ie = Args.end(); it != ie; ++it) {
129210299Sed    const Arg *A = *it;
130210299Sed
131210299Sed    // Unfortunately, we have to parse some forwarding options (-Xassembler,
132210299Sed    // -Xlinker, -Xpreprocessor) because we either integrate their functionality
133210299Sed    // (assembler and preprocessor), or bypass a previous driver ('collect2').
134210299Sed
135210299Sed    // Rewrite linker options, to replace --no-demangle with a custom internal
136210299Sed    // option.
137210299Sed    if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
138210299Sed         A->getOption().matches(options::OPT_Xlinker)) &&
139210299Sed        A->containsValue("--no-demangle")) {
140210299Sed      // Add the rewritten no-demangle argument.
141210299Sed      DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
142210299Sed
143210299Sed      // Add the remaining values as Xlinker arguments.
144210299Sed      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
145210299Sed        if (llvm::StringRef(A->getValue(Args, i)) != "--no-demangle")
146210299Sed          DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
147210299Sed                              A->getValue(Args, i));
148210299Sed
149210299Sed      continue;
150210299Sed    }
151210299Sed
152210299Sed    // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
153210299Sed    // some build systems. We don't try to be complete here because we don't
154210299Sed    // care to encourage this usage model.
155210299Sed    if (A->getOption().matches(options::OPT_Wp_COMMA) &&
156210299Sed        A->getNumValues() == 2 &&
157210299Sed        (A->getValue(Args, 0) == llvm::StringRef("-MD") ||
158210299Sed         A->getValue(Args, 0) == llvm::StringRef("-MMD"))) {
159210299Sed      // Rewrite to -MD/-MMD along with -MF.
160210299Sed      if (A->getValue(Args, 0) == llvm::StringRef("-MD"))
161210299Sed        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
162210299Sed      else
163210299Sed        DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
164210299Sed      DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
165210299Sed                          A->getValue(Args, 1));
166210299Sed      continue;
167210299Sed    }
168210299Sed
169218893Sdim    // Rewrite reserved library names.
170218893Sdim    if (A->getOption().matches(options::OPT_l)) {
171218893Sdim      llvm::StringRef Value = A->getValue(Args);
172218893Sdim
173218893Sdim      // Rewrite unless -nostdlib is present.
174218893Sdim      if (!HasNostdlib && Value == "stdc++") {
175218893Sdim        DAL->AddFlagArg(A, Opts->getOption(
176218893Sdim                              options::OPT_Z_reserved_lib_stdcxx));
177218893Sdim        continue;
178218893Sdim      }
179218893Sdim
180218893Sdim      // Rewrite unconditionally.
181218893Sdim      if (Value == "cc_kext") {
182218893Sdim        DAL->AddFlagArg(A, Opts->getOption(
183218893Sdim                              options::OPT_Z_reserved_lib_cckext));
184218893Sdim        continue;
185218893Sdim      }
186218893Sdim    }
187218893Sdim
188210299Sed    DAL->append(*it);
189210299Sed  }
190210299Sed
191212904Sdim  // Add a default value of -mlinker-version=, if one was given and the user
192212904Sdim  // didn't specify one.
193212904Sdim#if defined(HOST_LINK_VERSION)
194212904Sdim  if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
195212904Sdim    DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
196212904Sdim                      HOST_LINK_VERSION);
197212904Sdim    DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
198212904Sdim  }
199212904Sdim#endif
200212904Sdim
201210299Sed  return DAL;
202210299Sed}
203210299Sed
204221345SdimCompilation *Driver::BuildCompilation(llvm::ArrayRef<const char *> ArgList) {
205193326Sed  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
206193326Sed
207198092Srdivacky  // FIXME: Handle environment options which effect driver behavior, somewhere
208198092Srdivacky  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
209198092Srdivacky  // CC_PRINT_OPTIONS.
210193326Sed
211193326Sed  // FIXME: What are we going to do with -V and -b?
212193326Sed
213198092Srdivacky  // FIXME: This stuff needs to go into the Compilation, not the driver.
214193326Sed  bool CCCPrintOptions = false, CCCPrintActions = false;
215193326Sed
216221345Sdim  InputArgList *Args = ParseArgStrings(ArgList.slice(1));
217193326Sed
218200583Srdivacky  // -no-canonical-prefixes is used very early in main.
219200583Srdivacky  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
220200583Srdivacky
221212904Sdim  // Ignore -pipe.
222212904Sdim  Args->ClaimAllArgs(options::OPT_pipe);
223212904Sdim
224200583Srdivacky  // Extract -ccc args.
225193326Sed  //
226198092Srdivacky  // FIXME: We need to figure out where this behavior should live. Most of it
227198092Srdivacky  // should be outside in the client; the parts that aren't should have proper
228198092Srdivacky  // options, either by introducing new ones or by overloading gcc ones like -V
229198092Srdivacky  // or -b.
230200583Srdivacky  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
231200583Srdivacky  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
232200583Srdivacky  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
233200583Srdivacky  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
234200583Srdivacky  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
235200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
236200583Srdivacky    CCCGenericGCCName = A->getValue(*Args);
237200583Srdivacky  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
238200583Srdivacky                                 options::OPT_ccc_no_clang_cxx,
239200583Srdivacky                                 CCCUseClangCXX);
240200583Srdivacky  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
241200583Srdivacky                            options::OPT_ccc_pch_is_pth);
242200583Srdivacky  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
243200583Srdivacky  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
244200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
245200583Srdivacky    llvm::StringRef Cur = A->getValue(*Args);
246198092Srdivacky
247200583Srdivacky    CCCClangArchs.clear();
248200583Srdivacky    while (!Cur.empty()) {
249200583Srdivacky      std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
250198092Srdivacky
251200583Srdivacky      if (!Split.first.empty()) {
252200583Srdivacky        llvm::Triple::ArchType Arch =
253200583Srdivacky          llvm::Triple(Split.first, "", "").getArch();
254193326Sed
255203955Srdivacky        if (Arch == llvm::Triple::UnknownArch)
256203955Srdivacky          Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
257198092Srdivacky
258200583Srdivacky        CCCClangArchs.insert(Arch);
259193326Sed      }
260193326Sed
261200583Srdivacky      Cur = Split.second;
262193326Sed    }
263193326Sed  }
264212904Sdim  // FIXME: We shouldn't overwrite the default host triple here, but we have
265212904Sdim  // nowhere else to put this currently.
266200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple))
267212904Sdim    DefaultHostTriple = A->getValue(*Args);
268200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
269212904Sdim    Dir = InstalledDir = A->getValue(*Args);
270218893Sdim  for (arg_iterator it = Args->filtered_begin(options::OPT_B),
271218893Sdim         ie = Args->filtered_end(); it != ie; ++it) {
272218893Sdim    const Arg *A = *it;
273218893Sdim    A->claim();
274218893Sdim    PrefixDirs.push_back(A->getValue(*Args, 0));
275218893Sdim  }
276221345Sdim  if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
277221345Sdim    SysRoot = A->getValue(*Args);
278221345Sdim  if (Args->hasArg(options::OPT_nostdlib))
279221345Sdim    UseStdLib = false;
280193326Sed
281212904Sdim  Host = GetHostInfo(DefaultHostTriple.c_str());
282193326Sed
283210299Sed  // Perform the default argument translations.
284210299Sed  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
285210299Sed
286193326Sed  // The compilation takes ownership of Args.
287210299Sed  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args,
288210299Sed                                   TranslatedArgs);
289193326Sed
290193326Sed  // FIXME: This behavior shouldn't be here.
291193326Sed  if (CCCPrintOptions) {
292210299Sed    PrintOptions(C->getInputArgs());
293193326Sed    return C;
294193326Sed  }
295193326Sed
296193326Sed  if (!HandleImmediateArgs(*C))
297193326Sed    return C;
298193326Sed
299212904Sdim  // Construct the list of abstract actions to perform for this compilation.
300193326Sed  if (Host->useDriverDriver())
301212904Sdim    BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
302212904Sdim                          C->getActions());
303193326Sed  else
304212904Sdim    BuildActions(C->getDefaultToolChain(), C->getArgs(), C->getActions());
305193326Sed
306193326Sed  if (CCCPrintActions) {
307193326Sed    PrintActions(*C);
308193326Sed    return C;
309193326Sed  }
310193326Sed
311193326Sed  BuildJobs(*C);
312193326Sed
313193326Sed  return C;
314193326Sed}
315193326Sed
316195341Sedint Driver::ExecuteCompilation(const Compilation &C) const {
317195341Sed  // Just print if -### was present.
318195341Sed  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
319195341Sed    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
320195341Sed    return 0;
321195341Sed  }
322195341Sed
323195341Sed  // If there were errors building the compilation, quit now.
324218893Sdim  if (getDiags().hasErrorOccurred())
325195341Sed    return 1;
326195341Sed
327195341Sed  const Command *FailingCommand = 0;
328195341Sed  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
329198092Srdivacky
330195341Sed  // Remove temp files.
331195341Sed  C.CleanupFileList(C.getTempFiles());
332195341Sed
333208600Srdivacky  // If the command succeeded, we are done.
334208600Srdivacky  if (Res == 0)
335208600Srdivacky    return Res;
336208600Srdivacky
337208600Srdivacky  // Otherwise, remove result files as well.
338208600Srdivacky  if (!C.getArgs().hasArg(options::OPT_save_temps))
339195341Sed    C.CleanupFileList(C.getResultFiles(), true);
340195341Sed
341195341Sed  // Print extra information about abnormal failures, if possible.
342208600Srdivacky  //
343208600Srdivacky  // This is ad-hoc, but we don't want to be excessively noisy. If the result
344208600Srdivacky  // status was 1, assume the command failed normally. In particular, if it was
345208600Srdivacky  // the compiler then assume it gave a reasonable error code. Failures in other
346208600Srdivacky  // tools are less common, and they generally have worse diagnostics, so always
347208600Srdivacky  // print the diagnostic there.
348208600Srdivacky  const Tool &FailingTool = FailingCommand->getCreator();
349195341Sed
350208600Srdivacky  if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
351208600Srdivacky    // FIXME: See FIXME above regarding result code interpretation.
352208600Srdivacky    if (Res < 0)
353208600Srdivacky      Diag(clang::diag::err_drv_command_signalled)
354208600Srdivacky        << FailingTool.getShortName() << -Res;
355208600Srdivacky    else
356208600Srdivacky      Diag(clang::diag::err_drv_command_failed)
357208600Srdivacky        << FailingTool.getShortName() << Res;
358195341Sed  }
359195341Sed
360195341Sed  return Res;
361195341Sed}
362195341Sed
363193326Sedvoid Driver::PrintOptions(const ArgList &Args) const {
364193326Sed  unsigned i = 0;
365198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
366193326Sed       it != ie; ++it, ++i) {
367193326Sed    Arg *A = *it;
368193326Sed    llvm::errs() << "Option " << i << " - "
369193326Sed                 << "Name: \"" << A->getOption().getName() << "\", "
370193326Sed                 << "Values: {";
371193326Sed    for (unsigned j = 0; j < A->getNumValues(); ++j) {
372193326Sed      if (j)
373193326Sed        llvm::errs() << ", ";
374193326Sed      llvm::errs() << '"' << A->getValue(Args, j) << '"';
375193326Sed    }
376193326Sed    llvm::errs() << "}\n";
377193326Sed  }
378193326Sed}
379193326Sed
380193326Sedvoid Driver::PrintHelp(bool ShowHidden) const {
381204643Srdivacky  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
382204643Srdivacky                      ShowHidden);
383193326Sed}
384193326Sed
385198092Srdivackyvoid Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
386198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
387198092Srdivacky  // know what the client would like to do.
388202879Srdivacky  OS << getClangFullVersion() << '\n';
389193326Sed  const ToolChain &TC = C.getDefaultToolChain();
390198092Srdivacky  OS << "Target: " << TC.getTripleString() << '\n';
391194613Sed
392194613Sed  // Print the threading model.
393194613Sed  //
394194613Sed  // FIXME: Implement correctly.
395198092Srdivacky  OS << "Thread model: " << "posix" << '\n';
396193326Sed}
397193326Sed
398208600Srdivacky/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
399208600Srdivacky/// option.
400208600Srdivackystatic void PrintDiagnosticCategories(llvm::raw_ostream &OS) {
401208600Srdivacky  for (unsigned i = 1; // Skip the empty category.
402218893Sdim       const char *CategoryName = DiagnosticIDs::getCategoryNameFromID(i); ++i)
403208600Srdivacky    OS << i << ',' << CategoryName << '\n';
404208600Srdivacky}
405208600Srdivacky
406193326Sedbool Driver::HandleImmediateArgs(const Compilation &C) {
407210299Sed  // The order these options are handled in gcc is all over the place, but we
408198092Srdivacky  // don't expect inconsistencies w.r.t. that to matter in practice.
409193326Sed
410218893Sdim  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
411218893Sdim    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
412218893Sdim    return false;
413218893Sdim  }
414218893Sdim
415193326Sed  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
416218893Sdim    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
417218893Sdim    // return an answer which matches our definition of __VERSION__.
418218893Sdim    //
419218893Sdim    // If we want to return a more correct answer some day, then we should
420218893Sdim    // introduce a non-pedantically GCC compatible mode to Clang in which we
421218893Sdim    // provide sensible definitions for -dumpversion, __VERSION__, etc.
422218893Sdim    llvm::outs() << "4.2.1\n";
423193326Sed    return false;
424193326Sed  }
425210299Sed
426208600Srdivacky  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
427208600Srdivacky    PrintDiagnosticCategories(llvm::outs());
428208600Srdivacky    return false;
429208600Srdivacky  }
430193326Sed
431198092Srdivacky  if (C.getArgs().hasArg(options::OPT__help) ||
432193326Sed      C.getArgs().hasArg(options::OPT__help_hidden)) {
433193326Sed    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
434193326Sed    return false;
435193326Sed  }
436193326Sed
437193326Sed  if (C.getArgs().hasArg(options::OPT__version)) {
438198092Srdivacky    // Follow gcc behavior and use stdout for --version and stderr for -v.
439198092Srdivacky    PrintVersion(C, llvm::outs());
440193326Sed    return false;
441193326Sed  }
442193326Sed
443198092Srdivacky  if (C.getArgs().hasArg(options::OPT_v) ||
444193326Sed      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
445198092Srdivacky    PrintVersion(C, llvm::errs());
446193326Sed    SuppressMissingInputWarning = true;
447193326Sed  }
448193326Sed
449193326Sed  const ToolChain &TC = C.getDefaultToolChain();
450193326Sed  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
451193326Sed    llvm::outs() << "programs: =";
452193326Sed    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
453193326Sed           ie = TC.getProgramPaths().end(); it != ie; ++it) {
454193326Sed      if (it != TC.getProgramPaths().begin())
455193326Sed        llvm::outs() << ':';
456193326Sed      llvm::outs() << *it;
457193326Sed    }
458193326Sed    llvm::outs() << "\n";
459193326Sed    llvm::outs() << "libraries: =";
460198092Srdivacky    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
461193326Sed           ie = TC.getFilePaths().end(); it != ie; ++it) {
462193326Sed      if (it != TC.getFilePaths().begin())
463193326Sed        llvm::outs() << ':';
464193326Sed      llvm::outs() << *it;
465193326Sed    }
466193326Sed    llvm::outs() << "\n";
467193326Sed    return false;
468193326Sed  }
469193326Sed
470198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
471198092Srdivacky  // know what the client would like to do.
472193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
473198092Srdivacky    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
474193326Sed    return false;
475193326Sed  }
476193326Sed
477193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
478198092Srdivacky    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
479193326Sed    return false;
480193326Sed  }
481193326Sed
482193326Sed  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
483198092Srdivacky    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
484193326Sed    return false;
485193326Sed  }
486193326Sed
487194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
488194613Sed    // FIXME: We need tool chain support for this.
489194613Sed    llvm::outs() << ".;\n";
490194613Sed
491194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
492194613Sed    default:
493194613Sed      break;
494198092Srdivacky
495194613Sed    case llvm::Triple::x86_64:
496194613Sed      llvm::outs() << "x86_64;@m64" << "\n";
497194613Sed      break;
498194613Sed
499194613Sed    case llvm::Triple::ppc64:
500194613Sed      llvm::outs() << "ppc64;@m64" << "\n";
501194613Sed      break;
502194613Sed    }
503194613Sed    return false;
504194613Sed  }
505194613Sed
506194613Sed  // FIXME: What is the difference between print-multi-directory and
507194613Sed  // print-multi-os-directory?
508194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
509194613Sed      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
510194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
511194613Sed    default:
512194613Sed    case llvm::Triple::x86:
513194613Sed    case llvm::Triple::ppc:
514194613Sed      llvm::outs() << "." << "\n";
515194613Sed      break;
516198092Srdivacky
517194613Sed    case llvm::Triple::x86_64:
518213492Sdim      llvm::outs() << "." << "\n";
519194613Sed      break;
520194613Sed
521194613Sed    case llvm::Triple::ppc64:
522194613Sed      llvm::outs() << "ppc64" << "\n";
523194613Sed      break;
524194613Sed    }
525194613Sed    return false;
526194613Sed  }
527194613Sed
528193326Sed  return true;
529193326Sed}
530193326Sed
531198092Srdivackystatic unsigned PrintActions1(const Compilation &C, Action *A,
532193326Sed                              std::map<Action*, unsigned> &Ids) {
533193326Sed  if (Ids.count(A))
534193326Sed    return Ids[A];
535198092Srdivacky
536193326Sed  std::string str;
537193326Sed  llvm::raw_string_ostream os(str);
538198092Srdivacky
539193326Sed  os << Action::getClassName(A->getKind()) << ", ";
540198092Srdivacky  if (InputAction *IA = dyn_cast<InputAction>(A)) {
541193326Sed    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
542193326Sed  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
543198092Srdivacky    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
544193326Sed                  C.getDefaultToolChain().getArchName()) << '"'
545193326Sed       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
546193326Sed  } else {
547193326Sed    os << "{";
548193326Sed    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
549193326Sed      os << PrintActions1(C, *it, Ids);
550193326Sed      ++it;
551193326Sed      if (it != ie)
552193326Sed        os << ", ";
553193326Sed    }
554193326Sed    os << "}";
555193326Sed  }
556193326Sed
557193326Sed  unsigned Id = Ids.size();
558193326Sed  Ids[A] = Id;
559198092Srdivacky  llvm::errs() << Id << ": " << os.str() << ", "
560193326Sed               << types::getTypeName(A->getType()) << "\n";
561193326Sed
562193326Sed  return Id;
563193326Sed}
564193326Sed
565193326Sedvoid Driver::PrintActions(const Compilation &C) const {
566193326Sed  std::map<Action*, unsigned> Ids;
567198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
568193326Sed         ie = C.getActions().end(); it != ie; ++it)
569193326Sed    PrintActions1(C, *it, Ids);
570193326Sed}
571193326Sed
572210299Sed/// \brief Check whether the given input tree contains any compilation (or
573210299Sed/// assembly) actions.
574210299Sedstatic bool ContainsCompileAction(const Action *A) {
575210299Sed  if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
576210299Sed    return true;
577210299Sed
578210299Sed  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
579210299Sed    if (ContainsCompileAction(*it))
580210299Sed      return true;
581210299Sed
582210299Sed  return false;
583210299Sed}
584210299Sed
585212904Sdimvoid Driver::BuildUniversalActions(const ToolChain &TC,
586221345Sdim                                   const DerivedArgList &Args,
587193326Sed                                   ActionList &Actions) const {
588198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
589198092Srdivacky  // Collect the list of architectures. Duplicates are allowed, but should only
590198092Srdivacky  // be handled once (in the order seen).
591193326Sed  llvm::StringSet<> ArchNames;
592193326Sed  llvm::SmallVector<const char *, 4> Archs;
593198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
594193326Sed       it != ie; ++it) {
595193326Sed    Arg *A = *it;
596193326Sed
597199512Srdivacky    if (A->getOption().matches(options::OPT_arch)) {
598198092Srdivacky      // Validate the option here; we don't save the type here because its
599198092Srdivacky      // particular spelling may participate in other driver choices.
600198092Srdivacky      llvm::Triple::ArchType Arch =
601198092Srdivacky        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
602198092Srdivacky      if (Arch == llvm::Triple::UnknownArch) {
603198092Srdivacky        Diag(clang::diag::err_drv_invalid_arch_name)
604198092Srdivacky          << A->getAsString(Args);
605198092Srdivacky        continue;
606198092Srdivacky      }
607193326Sed
608193326Sed      A->claim();
609198092Srdivacky      if (ArchNames.insert(A->getValue(Args)))
610198092Srdivacky        Archs.push_back(A->getValue(Args));
611193326Sed    }
612193326Sed  }
613193326Sed
614198092Srdivacky  // When there is no explicit arch for this platform, make sure we still bind
615198092Srdivacky  // the architecture (to the default) so that -Xarch_ is handled correctly.
616193326Sed  if (!Archs.size())
617193326Sed    Archs.push_back(0);
618193326Sed
619198092Srdivacky  // FIXME: We killed off some others but these aren't yet detected in a
620198092Srdivacky  // functional manner. If we added information to jobs about which "auxiliary"
621198092Srdivacky  // files they wrote then we could detect the conflict these cause downstream.
622193326Sed  if (Archs.size() > 1) {
623193326Sed    // No recovery needed, the point of this is just to prevent
624193326Sed    // overwriting the same files.
625193326Sed    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
626198092Srdivacky      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
627193326Sed        << A->getAsString(Args);
628193326Sed  }
629193326Sed
630193326Sed  ActionList SingleActions;
631212904Sdim  BuildActions(TC, Args, SingleActions);
632193326Sed
633210299Sed  // Add in arch bindings for every top level action, as well as lipo and
634210299Sed  // dsymutil steps if needed.
635193326Sed  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
636193326Sed    Action *Act = SingleActions[i];
637193326Sed
638198092Srdivacky    // Make sure we can lipo this kind of output. If not (and it is an actual
639198092Srdivacky    // output) then we disallow, since we can't create an output file with the
640198092Srdivacky    // right name without overwriting it. We could remove this oddity by just
641198092Srdivacky    // changing the output names to include the arch, which would also fix
642193326Sed    // -save-temps. Compatibility wins for now.
643193326Sed
644193326Sed    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
645193326Sed      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
646193326Sed        << types::getTypeName(Act->getType());
647193326Sed
648193326Sed    ActionList Inputs;
649205219Srdivacky    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
650193326Sed      Inputs.push_back(new BindArchAction(Act, Archs[i]));
651205219Srdivacky      if (i != 0)
652205219Srdivacky        Inputs.back()->setOwnsInputs(false);
653205219Srdivacky    }
654193326Sed
655198092Srdivacky    // Lipo if necessary, we do it this way because we need to set the arch flag
656198092Srdivacky    // so that -Xarch_ gets overwritten.
657193326Sed    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
658193326Sed      Actions.append(Inputs.begin(), Inputs.end());
659193326Sed    else
660193326Sed      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
661210299Sed
662210299Sed    // Add a 'dsymutil' step if necessary, when debug info is enabled and we
663210299Sed    // have a compile input. We need to run 'dsymutil' ourselves in such cases
664210299Sed    // because the debug info will refer to a temporary object file which is
665210299Sed    // will be removed at the end of the compilation process.
666210299Sed    if (Act->getType() == types::TY_Image) {
667210299Sed      Arg *A = Args.getLastArg(options::OPT_g_Group);
668210299Sed      if (A && !A->getOption().matches(options::OPT_g0) &&
669210299Sed          !A->getOption().matches(options::OPT_gstabs) &&
670210299Sed          ContainsCompileAction(Actions.back())) {
671210299Sed        ActionList Inputs;
672210299Sed        Inputs.push_back(Actions.back());
673210299Sed        Actions.pop_back();
674210299Sed
675210299Sed        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
676210299Sed      }
677210299Sed    }
678193326Sed  }
679193326Sed}
680193326Sed
681221345Sdimvoid Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args,
682212904Sdim                          ActionList &Actions) const {
683193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
684193326Sed  // Start by constructing the list of inputs and their types.
685193326Sed
686198092Srdivacky  // Track the current user specified (-x) input. We also explicitly track the
687198092Srdivacky  // argument used to set the type; we only want to claim the type when we
688198092Srdivacky  // actually use it, so we warn about unused -x arguments.
689193326Sed  types::ID InputType = types::TY_Nothing;
690193326Sed  Arg *InputTypeArg = 0;
691193326Sed
692193326Sed  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
693198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
694193326Sed       it != ie; ++it) {
695193326Sed    Arg *A = *it;
696193326Sed
697193326Sed    if (isa<InputOption>(A->getOption())) {
698193326Sed      const char *Value = A->getValue(Args);
699193326Sed      types::ID Ty = types::TY_INVALID;
700193326Sed
701193326Sed      // Infer the input type if necessary.
702193326Sed      if (InputType == types::TY_Nothing) {
703193326Sed        // If there was an explicit arg for this, claim it.
704193326Sed        if (InputTypeArg)
705193326Sed          InputTypeArg->claim();
706193326Sed
707193326Sed        // stdin must be handled specially.
708193326Sed        if (memcmp(Value, "-", 2) == 0) {
709198092Srdivacky          // If running with -E, treat as a C input (this changes the builtin
710198092Srdivacky          // macros, for example). This may be overridden by -ObjC below.
711193326Sed          //
712198092Srdivacky          // Otherwise emit an error but still use a valid type to avoid
713198092Srdivacky          // spurious errors (e.g., no inputs).
714221345Sdim          if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
715193326Sed            Diag(clang::diag::err_drv_unknown_stdin_type);
716193326Sed          Ty = types::TY_C;
717193326Sed        } else {
718221345Sdim          // Otherwise lookup by extension.
719221345Sdim          // Fallback is C if invoked as C preprocessor or Object otherwise.
720221345Sdim          // We use a host hook here because Darwin at least has its own
721198092Srdivacky          // idea of what .s is.
722193326Sed          if (const char *Ext = strrchr(Value, '.'))
723212904Sdim            Ty = TC.LookupTypeForExtension(Ext + 1);
724193326Sed
725221345Sdim          if (Ty == types::TY_INVALID) {
726221345Sdim            if (CCCIsCPP)
727221345Sdim              Ty = types::TY_C;
728221345Sdim            else
729221345Sdim              Ty = types::TY_Object;
730221345Sdim          }
731204643Srdivacky
732204643Srdivacky          // If the driver is invoked as C++ compiler (like clang++ or c++) it
733204643Srdivacky          // should autodetect some input files as C++ for g++ compatibility.
734204643Srdivacky          if (CCCIsCXX) {
735204643Srdivacky            types::ID OldTy = Ty;
736204643Srdivacky            Ty = types::lookupCXXTypeForCType(Ty);
737204643Srdivacky
738204643Srdivacky            if (Ty != OldTy)
739204643Srdivacky              Diag(clang::diag::warn_drv_treating_input_as_cxx)
740204643Srdivacky                << getTypeName(OldTy) << getTypeName(Ty);
741204643Srdivacky          }
742193326Sed        }
743193326Sed
744193326Sed        // -ObjC and -ObjC++ override the default language, but only for "source
745193326Sed        // files". We just treat everything that isn't a linker input as a
746193326Sed        // source file.
747198092Srdivacky        //
748193326Sed        // FIXME: Clean this up if we move the phase sequence into the type.
749193326Sed        if (Ty != types::TY_Object) {
750193326Sed          if (Args.hasArg(options::OPT_ObjC))
751193326Sed            Ty = types::TY_ObjC;
752193326Sed          else if (Args.hasArg(options::OPT_ObjCXX))
753193326Sed            Ty = types::TY_ObjCXX;
754193326Sed        }
755193326Sed      } else {
756193326Sed        assert(InputTypeArg && "InputType set w/o InputTypeArg");
757193326Sed        InputTypeArg->claim();
758193326Sed        Ty = InputType;
759193326Sed      }
760193326Sed
761203955Srdivacky      // Check that the file exists, if enabled.
762218893Sdim      if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
763218893Sdim        llvm::SmallString<64> Path(Value);
764218893Sdim        if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory))
765218893Sdim          if (llvm::sys::path::is_absolute(Path.str())) {
766218893Sdim            Path = WorkDir->getValue(Args);
767218893Sdim            llvm::sys::path::append(Path, Value);
768218893Sdim          }
769218893Sdim
770218893Sdim        bool exists = false;
771218893Sdim        if (/*error_code ec =*/llvm::sys::fs::exists(Value, exists) || !exists)
772218893Sdim          Diag(clang::diag::err_drv_no_such_file) << Path.str();
773218893Sdim        else
774218893Sdim          Inputs.push_back(std::make_pair(Ty, A));
775218893Sdim      } else
776193326Sed        Inputs.push_back(std::make_pair(Ty, A));
777193326Sed
778193326Sed    } else if (A->getOption().isLinkerInput()) {
779198092Srdivacky      // Just treat as object type, we could make a special type for this if
780198092Srdivacky      // necessary.
781193326Sed      Inputs.push_back(std::make_pair(types::TY_Object, A));
782193326Sed
783199512Srdivacky    } else if (A->getOption().matches(options::OPT_x)) {
784198092Srdivacky      InputTypeArg = A;
785193326Sed      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
786193326Sed
787193326Sed      // Follow gcc behavior and treat as linker input for invalid -x
788198092Srdivacky      // options. Its not clear why we shouldn't just revert to unknown; but
789218893Sdim      // this isn't very important, we might as well be bug compatible.
790193326Sed      if (!InputType) {
791193326Sed        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
792193326Sed        InputType = types::TY_Object;
793193326Sed      }
794193326Sed    }
795193326Sed  }
796193326Sed
797221345Sdim  if (CCCIsCPP && Inputs.empty()) {
798221345Sdim    // If called as standalone preprocessor, stdin is processed
799221345Sdim    // if no other input is present.
800221345Sdim    unsigned Index = Args.getBaseArgs().MakeIndex("-");
801221345Sdim    Arg *A = Opts->ParseOneArg(Args, Index);
802221345Sdim    A->claim();
803221345Sdim    Inputs.push_back(std::make_pair(types::TY_C, A));
804221345Sdim  }
805221345Sdim
806193326Sed  if (!SuppressMissingInputWarning && Inputs.empty()) {
807193326Sed    Diag(clang::diag::err_drv_no_input_files);
808193326Sed    return;
809193326Sed  }
810193326Sed
811198092Srdivacky  // Determine which compilation mode we are in. We look for options which
812198092Srdivacky  // affect the phase, starting with the earliest phases, and record which
813198092Srdivacky  // option we used to determine the final phase.
814193326Sed  Arg *FinalPhaseArg = 0;
815193326Sed  phases::ID FinalPhase;
816193326Sed
817193326Sed  // -{E,M,MM} only run the preprocessor.
818221345Sdim  if (CCCIsCPP ||
819221345Sdim      (FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
820218893Sdim      (FinalPhaseArg = Args.getLastArg(options::OPT_M, options::OPT_MM))) {
821193326Sed    FinalPhase = phases::Preprocess;
822198092Srdivacky
823198092Srdivacky    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
824193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
825203955Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_rewrite_objc)) ||
826193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
827193326Sed                                              options::OPT__analyze_auto)) ||
828198092Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
829193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
830193326Sed    FinalPhase = phases::Compile;
831193326Sed
832193326Sed    // -c only runs up to the assembler.
833193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
834193326Sed    FinalPhase = phases::Assemble;
835198092Srdivacky
836193326Sed    // Otherwise do everything.
837193326Sed  } else
838193326Sed    FinalPhase = phases::Link;
839193326Sed
840198092Srdivacky  // Reject -Z* at the top level, these options should never have been exposed
841198092Srdivacky  // by gcc.
842193326Sed  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
843193326Sed    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
844193326Sed
845193326Sed  // Construct the actions to perform.
846193326Sed  ActionList LinkerInputs;
847193326Sed  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
848193326Sed    types::ID InputType = Inputs[i].first;
849193326Sed    const Arg *InputArg = Inputs[i].second;
850193326Sed
851193326Sed    unsigned NumSteps = types::getNumCompilationPhases(InputType);
852193326Sed    assert(NumSteps && "Invalid number of steps!");
853193326Sed
854198092Srdivacky    // If the first step comes after the final phase we are doing as part of
855198092Srdivacky    // this compilation, warn the user about it.
856193326Sed    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
857193326Sed    if (InitialPhase > FinalPhase) {
858193326Sed      // Claim here to avoid the more general unused warning.
859193326Sed      InputArg->claim();
860198092Srdivacky
861221345Sdim      // Suppress all unused style warnings with -Qunused-arguments
862221345Sdim      if (Args.hasArg(options::OPT_Qunused_arguments))
863221345Sdim        continue;
864221345Sdim
865198092Srdivacky      // Special case '-E' warning on a previously preprocessed file to make
866198092Srdivacky      // more sense.
867198092Srdivacky      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
868198092Srdivacky          getPreprocessedType(InputType) == types::TY_INVALID)
869198092Srdivacky        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
870198092Srdivacky          << InputArg->getAsString(Args)
871198092Srdivacky          << FinalPhaseArg->getOption().getName();
872198092Srdivacky      else
873198092Srdivacky        Diag(clang::diag::warn_drv_input_file_unused)
874198092Srdivacky          << InputArg->getAsString(Args)
875198092Srdivacky          << getPhaseName(InitialPhase)
876198092Srdivacky          << FinalPhaseArg->getOption().getName();
877193326Sed      continue;
878193326Sed    }
879198092Srdivacky
880193326Sed    // Build the pipeline for this file.
881202879Srdivacky    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
882193326Sed    for (unsigned i = 0; i != NumSteps; ++i) {
883193326Sed      phases::ID Phase = types::getCompilationPhase(InputType, i);
884193326Sed
885193326Sed      // We are done if this step is past what the user requested.
886193326Sed      if (Phase > FinalPhase)
887193326Sed        break;
888193326Sed
889193326Sed      // Queue linker inputs.
890193326Sed      if (Phase == phases::Link) {
891193326Sed        assert(i + 1 == NumSteps && "linking must be final compilation step.");
892202879Srdivacky        LinkerInputs.push_back(Current.take());
893193326Sed        break;
894193326Sed      }
895193326Sed
896198092Srdivacky      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
897198092Srdivacky      // encode this in the steps because the intermediate type depends on
898198092Srdivacky      // arguments. Just special case here.
899193326Sed      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
900193326Sed        continue;
901193326Sed
902193326Sed      // Otherwise construct the appropriate action.
903202879Srdivacky      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
904193326Sed      if (Current->getType() == types::TY_Nothing)
905193326Sed        break;
906193326Sed    }
907193326Sed
908193326Sed    // If we ended with something, add to the output list.
909193326Sed    if (Current)
910202879Srdivacky      Actions.push_back(Current.take());
911193326Sed  }
912193326Sed
913193326Sed  // Add a link action if necessary.
914193326Sed  if (!LinkerInputs.empty())
915193326Sed    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
916201361Srdivacky
917201361Srdivacky  // If we are linking, claim any options which are obviously only used for
918201361Srdivacky  // compilation.
919201361Srdivacky  if (FinalPhase == phases::Link)
920201361Srdivacky    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
921193326Sed}
922193326Sed
923193326SedAction *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
924193326Sed                                     Action *Input) const {
925193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
926193326Sed  // Build the appropriate action.
927193326Sed  switch (Phase) {
928193326Sed  case phases::Link: assert(0 && "link action invalid here.");
929193326Sed  case phases::Preprocess: {
930193326Sed    types::ID OutputTy;
931193326Sed    // -{M, MM} alter the output type.
932218893Sdim    if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
933193326Sed      OutputTy = types::TY_Dependencies;
934193326Sed    } else {
935193326Sed      OutputTy = types::getPreprocessedType(Input->getType());
936193326Sed      assert(OutputTy != types::TY_INVALID &&
937193326Sed             "Cannot preprocess this input type!");
938193326Sed    }
939193326Sed    return new PreprocessJobAction(Input, OutputTy);
940193326Sed  }
941193326Sed  case phases::Precompile:
942198092Srdivacky    return new PrecompileJobAction(Input, types::TY_PCH);
943193326Sed  case phases::Compile: {
944201361Srdivacky    bool HasO4 = false;
945201361Srdivacky    if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
946201361Srdivacky      HasO4 = A->getOption().matches(options::OPT_O4);
947201361Srdivacky
948193326Sed    if (Args.hasArg(options::OPT_fsyntax_only)) {
949193326Sed      return new CompileJobAction(Input, types::TY_Nothing);
950203955Srdivacky    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
951203955Srdivacky      return new CompileJobAction(Input, types::TY_RewrittenObjC);
952193326Sed    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
953193326Sed      return new AnalyzeJobAction(Input, types::TY_Plist);
954198092Srdivacky    } else if (Args.hasArg(options::OPT_emit_ast)) {
955198092Srdivacky      return new CompileJobAction(Input, types::TY_AST);
956193326Sed    } else if (Args.hasArg(options::OPT_emit_llvm) ||
957221345Sdim               Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false) ||
958221345Sdim               HasO4) {
959198092Srdivacky      types::ID Output =
960210299Sed        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
961193326Sed      return new CompileJobAction(Input, Output);
962193326Sed    } else {
963193326Sed      return new CompileJobAction(Input, types::TY_PP_Asm);
964193326Sed    }
965193326Sed  }
966193326Sed  case phases::Assemble:
967193326Sed    return new AssembleJobAction(Input, types::TY_Object);
968193326Sed  }
969193326Sed
970193326Sed  assert(0 && "invalid phase in ConstructPhaseAction");
971193326Sed  return 0;
972193326Sed}
973193326Sed
974193326Sedvoid Driver::BuildJobs(Compilation &C) const {
975193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
976193326Sed
977193326Sed  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
978193326Sed
979198092Srdivacky  // It is an error to provide a -o option if we are making multiple output
980198092Srdivacky  // files.
981193326Sed  if (FinalOutput) {
982193326Sed    unsigned NumOutputs = 0;
983198092Srdivacky    for (ActionList::const_iterator it = C.getActions().begin(),
984193326Sed           ie = C.getActions().end(); it != ie; ++it)
985193326Sed      if ((*it)->getType() != types::TY_Nothing)
986193326Sed        ++NumOutputs;
987198092Srdivacky
988193326Sed    if (NumOutputs > 1) {
989193326Sed      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
990193326Sed      FinalOutput = 0;
991193326Sed    }
992193326Sed  }
993193326Sed
994198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
995193326Sed         ie = C.getActions().end(); it != ie; ++it) {
996193326Sed    Action *A = *it;
997193326Sed
998198092Srdivacky    // If we are linking an image for multiple archs then the linker wants
999198092Srdivacky    // -arch_multiple and -final_output <final image name>. Unfortunately, this
1000198092Srdivacky    // doesn't fit in cleanly because we have to pass this information down.
1001193326Sed    //
1002198092Srdivacky    // FIXME: This is a hack; find a cleaner way to integrate this into the
1003198092Srdivacky    // process.
1004193326Sed    const char *LinkingOutput = 0;
1005193326Sed    if (isa<LipoJobAction>(A)) {
1006193326Sed      if (FinalOutput)
1007193326Sed        LinkingOutput = FinalOutput->getValue(C.getArgs());
1008193326Sed      else
1009193326Sed        LinkingOutput = DefaultImageName.c_str();
1010193326Sed    }
1011193326Sed
1012193326Sed    InputInfo II;
1013198092Srdivacky    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1014198092Srdivacky                       /*BoundArch*/0,
1015193326Sed                       /*AtTopLevel*/ true,
1016193326Sed                       /*LinkingOutput*/ LinkingOutput,
1017193326Sed                       II);
1018193326Sed  }
1019193326Sed
1020198092Srdivacky  // If the user passed -Qunused-arguments or there were errors, don't warn
1021198092Srdivacky  // about any unused arguments.
1022218893Sdim  if (Diags.hasErrorOccurred() ||
1023193326Sed      C.getArgs().hasArg(options::OPT_Qunused_arguments))
1024193326Sed    return;
1025193326Sed
1026193326Sed  // Claim -### here.
1027193326Sed  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1028198092Srdivacky
1029193326Sed  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1030193326Sed       it != ie; ++it) {
1031193326Sed    Arg *A = *it;
1032198092Srdivacky
1033193326Sed    // FIXME: It would be nice to be able to send the argument to the
1034198092Srdivacky    // Diagnostic, so that extra values, position, and so on could be printed.
1035193326Sed    if (!A->isClaimed()) {
1036193326Sed      if (A->getOption().hasNoArgumentUnused())
1037193326Sed        continue;
1038193326Sed
1039198092Srdivacky      // Suppress the warning automatically if this is just a flag, and it is an
1040198092Srdivacky      // instance of an argument we already claimed.
1041193326Sed      const Option &Opt = A->getOption();
1042193326Sed      if (isa<FlagOption>(Opt)) {
1043193326Sed        bool DuplicateClaimed = false;
1044193326Sed
1045199990Srdivacky        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1046199990Srdivacky               ie = C.getArgs().filtered_end(); it != ie; ++it) {
1047199990Srdivacky          if ((*it)->isClaimed()) {
1048193326Sed            DuplicateClaimed = true;
1049193326Sed            break;
1050193326Sed          }
1051193326Sed        }
1052193326Sed
1053193326Sed        if (DuplicateClaimed)
1054193326Sed          continue;
1055193326Sed      }
1056193326Sed
1057198092Srdivacky      Diag(clang::diag::warn_drv_unused_argument)
1058193326Sed        << A->getAsString(C.getArgs());
1059193326Sed    }
1060193326Sed  }
1061193326Sed}
1062193326Sed
1063203955Srdivackystatic const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1064203955Srdivacky                                    const JobAction *JA,
1065203955Srdivacky                                    const ActionList *&Inputs) {
1066203955Srdivacky  const Tool *ToolForJob = 0;
1067203955Srdivacky
1068203955Srdivacky  // See if we should look for a compiler with an integrated assembler. We match
1069203955Srdivacky  // bottom up, so what we are actually looking for is an assembler job with a
1070203955Srdivacky  // compiler input.
1071208600Srdivacky
1072208600Srdivacky  // FIXME: This doesn't belong here, but ideally we will support static soon
1073208600Srdivacky  // anyway.
1074208600Srdivacky  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
1075208600Srdivacky                    C.getArgs().hasArg(options::OPT_static) ||
1076208600Srdivacky                    C.getArgs().hasArg(options::OPT_fapple_kext));
1077221345Sdim  bool IsDarwin = TC->getTriple().getOS() == llvm::Triple::Darwin;
1078221345Sdim  bool IsIADefault = TC->IsIntegratedAssemblerDefault() &&
1079221345Sdim    !(HasStatic && IsDarwin);
1080208600Srdivacky  if (C.getArgs().hasFlag(options::OPT_integrated_as,
1081203955Srdivacky                         options::OPT_no_integrated_as,
1082208600Srdivacky                         IsIADefault) &&
1083203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1084203955Srdivacky      isa<AssembleJobAction>(JA) &&
1085203955Srdivacky      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1086221345Sdim    const Tool &Compiler = TC->SelectTool(
1087221345Sdim      C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
1088203955Srdivacky    if (Compiler.hasIntegratedAssembler()) {
1089203955Srdivacky      Inputs = &(*Inputs)[0]->getInputs();
1090203955Srdivacky      ToolForJob = &Compiler;
1091203955Srdivacky    }
1092203955Srdivacky  }
1093203955Srdivacky
1094203955Srdivacky  // Otherwise use the tool for the current job.
1095203955Srdivacky  if (!ToolForJob)
1096221345Sdim    ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
1097203955Srdivacky
1098203955Srdivacky  // See if we should use an integrated preprocessor. We do so when we have
1099203955Srdivacky  // exactly one input, since this is the only use case we care about
1100203955Srdivacky  // (irrelevant since we don't support combine yet).
1101203955Srdivacky  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1102203955Srdivacky      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1103203955Srdivacky      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1104203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1105203955Srdivacky      ToolForJob->hasIntegratedCPP())
1106203955Srdivacky    Inputs = &(*Inputs)[0]->getInputs();
1107203955Srdivacky
1108203955Srdivacky  return *ToolForJob;
1109203955Srdivacky}
1110203955Srdivacky
1111193326Sedvoid Driver::BuildJobsForAction(Compilation &C,
1112193326Sed                                const Action *A,
1113193326Sed                                const ToolChain *TC,
1114198092Srdivacky                                const char *BoundArch,
1115193326Sed                                bool AtTopLevel,
1116193326Sed                                const char *LinkingOutput,
1117193326Sed                                InputInfo &Result) const {
1118198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1119193326Sed
1120193326Sed  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1121198092Srdivacky    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1122198092Srdivacky    // just using Args was better?
1123193326Sed    const Arg &Input = IA->getInputArg();
1124193326Sed    Input.claim();
1125210299Sed    if (Input.getOption().matches(options::OPT_INPUT)) {
1126193326Sed      const char *Name = Input.getValue(C.getArgs());
1127193326Sed      Result = InputInfo(Name, A->getType(), Name);
1128193326Sed    } else
1129193326Sed      Result = InputInfo(&Input, A->getType(), "");
1130193326Sed    return;
1131193326Sed  }
1132193326Sed
1133193326Sed  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1134198092Srdivacky    const ToolChain *TC = &C.getDefaultToolChain();
1135198092Srdivacky
1136193326Sed    std::string Arch;
1137198092Srdivacky    if (BAA->getArchName())
1138198092Srdivacky      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1139198092Srdivacky
1140198092Srdivacky    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1141212904Sdim                       AtTopLevel, LinkingOutput, Result);
1142193326Sed    return;
1143193326Sed  }
1144193326Sed
1145203955Srdivacky  const ActionList *Inputs = &A->getInputs();
1146203955Srdivacky
1147193326Sed  const JobAction *JA = cast<JobAction>(A);
1148203955Srdivacky  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1149198092Srdivacky
1150193326Sed  // Only use pipes when there is exactly one input.
1151193326Sed  InputInfoList InputInfos;
1152193326Sed  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1153193326Sed       it != ie; ++it) {
1154210299Sed    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1155210299Sed    // temporary output names.
1156210299Sed    //
1157210299Sed    // FIXME: Clean this up.
1158210299Sed    bool SubJobAtTopLevel = false;
1159210299Sed    if (AtTopLevel && isa<DsymutilJobAction>(A))
1160210299Sed      SubJobAtTopLevel = true;
1161210299Sed
1162193326Sed    InputInfo II;
1163212904Sdim    BuildJobsForAction(C, *it, TC, BoundArch,
1164210299Sed                       SubJobAtTopLevel, LinkingOutput, II);
1165193326Sed    InputInfos.push_back(II);
1166193326Sed  }
1167193326Sed
1168193326Sed  // Always use the first input as the base input.
1169193326Sed  const char *BaseInput = InputInfos[0].getBaseInput();
1170193326Sed
1171210299Sed  // ... except dsymutil actions, which use their actual input as the base
1172210299Sed  // input.
1173210299Sed  if (JA->getType() == types::TY_dSYM)
1174210299Sed    BaseInput = InputInfos[0].getFilename();
1175210299Sed
1176212904Sdim  // Determine the place to write output to, if any.
1177193326Sed  if (JA->getType() == types::TY_Nothing) {
1178193326Sed    Result = InputInfo(A->getType(), BaseInput);
1179193326Sed  } else {
1180193326Sed    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1181193326Sed                       A->getType(), BaseInput);
1182193326Sed  }
1183193326Sed
1184193326Sed  if (CCCPrintBindings) {
1185193326Sed    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1186193326Sed                 << " - \"" << T.getName() << "\", inputs: [";
1187193326Sed    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1188193326Sed      llvm::errs() << InputInfos[i].getAsString();
1189193326Sed      if (i + 1 != e)
1190193326Sed        llvm::errs() << ", ";
1191193326Sed    }
1192193326Sed    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1193193326Sed  } else {
1194212904Sdim    T.ConstructJob(C, *JA, Result, InputInfos,
1195198092Srdivacky                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1196193326Sed  }
1197193326Sed}
1198193326Sed
1199198092Srdivackyconst char *Driver::GetNamedOutputPath(Compilation &C,
1200193326Sed                                       const JobAction &JA,
1201193326Sed                                       const char *BaseInput,
1202193326Sed                                       bool AtTopLevel) const {
1203193326Sed  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1204193326Sed  // Output to a user requested destination?
1205210299Sed  if (AtTopLevel && !isa<DsymutilJobAction>(JA)) {
1206193326Sed    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1207193326Sed      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1208193326Sed  }
1209193326Sed
1210212904Sdim  // Default to writing to stdout?
1211212904Sdim  if (AtTopLevel && isa<PreprocessJobAction>(JA))
1212212904Sdim    return "-";
1213212904Sdim
1214193326Sed  // Output to a temporary file?
1215193326Sed  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1216198092Srdivacky    std::string TmpName =
1217193326Sed      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1218193326Sed    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1219193326Sed  }
1220193326Sed
1221218893Sdim  llvm::SmallString<128> BasePath(BaseInput);
1222221345Sdim  llvm::StringRef BaseName;
1223193326Sed
1224221345Sdim  // Dsymutil actions should use the full path.
1225221345Sdim  if (isa<DsymutilJobAction>(JA))
1226221345Sdim    BaseName = BasePath;
1227221345Sdim  else
1228221345Sdim    BaseName = llvm::sys::path::filename(BasePath);
1229221345Sdim
1230193326Sed  // Determine what the derived output name should be.
1231193326Sed  const char *NamedOutput;
1232193326Sed  if (JA.getType() == types::TY_Image) {
1233193326Sed    NamedOutput = DefaultImageName.c_str();
1234193326Sed  } else {
1235193326Sed    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1236193326Sed    assert(Suffix && "All types used for output should have a suffix.");
1237193326Sed
1238193326Sed    std::string::size_type End = std::string::npos;
1239193326Sed    if (!types::appendSuffixForType(JA.getType()))
1240193326Sed      End = BaseName.rfind('.');
1241193326Sed    std::string Suffixed(BaseName.substr(0, End));
1242193326Sed    Suffixed += '.';
1243193326Sed    Suffixed += Suffix;
1244193326Sed    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1245193326Sed  }
1246193326Sed
1247198092Srdivacky  // As an annoying special case, PCH generation doesn't strip the pathname.
1248193326Sed  if (JA.getType() == types::TY_PCH) {
1249218893Sdim    llvm::sys::path::remove_filename(BasePath);
1250218893Sdim    if (BasePath.empty())
1251193326Sed      BasePath = NamedOutput;
1252193326Sed    else
1253218893Sdim      llvm::sys::path::append(BasePath, NamedOutput);
1254193326Sed    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1255193326Sed  } else {
1256193326Sed    return C.addResultFile(NamedOutput);
1257193326Sed  }
1258193326Sed}
1259193326Sed
1260198092Srdivackystd::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1261206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1262206084Srdivacky  // attempting to use this prefix when lokup up program paths.
1263218893Sdim  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1264218893Sdim       ie = PrefixDirs.end(); it != ie; ++it) {
1265221345Sdim    std::string Dir(*it);
1266221345Sdim    if (Dir.empty())
1267221345Sdim      continue;
1268221345Sdim    if (Dir[0] == '=')
1269221345Sdim      Dir = SysRoot + Dir.substr(1);
1270221345Sdim    llvm::sys::Path P(Dir);
1271206084Srdivacky    P.appendComponent(Name);
1272218893Sdim    bool Exists;
1273218893Sdim    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1274206084Srdivacky      return P.str();
1275206084Srdivacky  }
1276206084Srdivacky
1277193326Sed  const ToolChain::path_list &List = TC.getFilePaths();
1278198092Srdivacky  for (ToolChain::path_list::const_iterator
1279193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1280221345Sdim    std::string Dir(*it);
1281221345Sdim    if (Dir.empty())
1282221345Sdim      continue;
1283221345Sdim    if (Dir[0] == '=')
1284221345Sdim      Dir = SysRoot + Dir.substr(1);
1285221345Sdim    llvm::sys::Path P(Dir);
1286193326Sed    P.appendComponent(Name);
1287218893Sdim    bool Exists;
1288218893Sdim    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1289198092Srdivacky      return P.str();
1290193326Sed  }
1291193326Sed
1292198092Srdivacky  return Name;
1293193326Sed}
1294193326Sed
1295198092Srdivackystd::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1296198092Srdivacky                                   bool WantFile) const {
1297206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1298206084Srdivacky  // attempting to use this prefix when lokup up program paths.
1299218893Sdim  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1300218893Sdim       ie = PrefixDirs.end(); it != ie; ++it) {
1301218893Sdim    llvm::sys::Path P(*it);
1302206084Srdivacky    P.appendComponent(Name);
1303218893Sdim    bool Exists;
1304218893Sdim    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1305218893Sdim                 : P.canExecute())
1306206084Srdivacky      return P.str();
1307206084Srdivacky  }
1308206084Srdivacky
1309193326Sed  const ToolChain::path_list &List = TC.getProgramPaths();
1310198092Srdivacky  for (ToolChain::path_list::const_iterator
1311193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1312193326Sed    llvm::sys::Path P(*it);
1313193326Sed    P.appendComponent(Name);
1314218893Sdim    bool Exists;
1315218893Sdim    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1316218893Sdim                 : P.canExecute())
1317198092Srdivacky      return P.str();
1318193326Sed  }
1319193326Sed
1320193326Sed  // If all else failed, search the path.
1321193326Sed  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1322193326Sed  if (!P.empty())
1323198092Srdivacky    return P.str();
1324193326Sed
1325198092Srdivacky  return Name;
1326193326Sed}
1327193326Sed
1328193326Sedstd::string Driver::GetTemporaryPath(const char *Suffix) const {
1329198092Srdivacky  // FIXME: This is lame; sys::Path should provide this function (in particular,
1330198092Srdivacky  // it should know how to find the temporary files dir).
1331193326Sed  std::string Error;
1332193326Sed  const char *TmpDir = ::getenv("TMPDIR");
1333193326Sed  if (!TmpDir)
1334193326Sed    TmpDir = ::getenv("TEMP");
1335193326Sed  if (!TmpDir)
1336193326Sed    TmpDir = ::getenv("TMP");
1337193326Sed  if (!TmpDir)
1338193326Sed    TmpDir = "/tmp";
1339193326Sed  llvm::sys::Path P(TmpDir);
1340193326Sed  P.appendComponent("cc");
1341193326Sed  if (P.makeUnique(false, &Error)) {
1342193326Sed    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1343193326Sed    return "";
1344193326Sed  }
1345193326Sed
1346198092Srdivacky  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1347193326Sed  P.eraseFromDisk(false, 0);
1348193326Sed
1349193326Sed  P.appendSuffix(Suffix);
1350198092Srdivacky  return P.str();
1351193326Sed}
1352193326Sed
1353193326Sedconst HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1354193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1355221345Sdim  llvm::Triple Triple(llvm::Triple::normalize(TripleStr).c_str());
1356193326Sed
1357204793Srdivacky  // TCE is an osless target
1358204793Srdivacky  if (Triple.getArchName() == "tce")
1359210299Sed    return createTCEHostInfo(*this, Triple);
1360204793Srdivacky
1361193326Sed  switch (Triple.getOS()) {
1362198092Srdivacky  case llvm::Triple::AuroraUX:
1363198092Srdivacky    return createAuroraUXHostInfo(*this, Triple);
1364193326Sed  case llvm::Triple::Darwin:
1365193326Sed    return createDarwinHostInfo(*this, Triple);
1366193326Sed  case llvm::Triple::DragonFly:
1367193326Sed    return createDragonFlyHostInfo(*this, Triple);
1368195341Sed  case llvm::Triple::OpenBSD:
1369195341Sed    return createOpenBSDHostInfo(*this, Triple);
1370218893Sdim  case llvm::Triple::NetBSD:
1371218893Sdim    return createNetBSDHostInfo(*this, Triple);
1372193326Sed  case llvm::Triple::FreeBSD:
1373193326Sed    return createFreeBSDHostInfo(*this, Triple);
1374210299Sed  case llvm::Triple::Minix:
1375210299Sed    return createMinixHostInfo(*this, Triple);
1376193326Sed  case llvm::Triple::Linux:
1377193326Sed    return createLinuxHostInfo(*this, Triple);
1378212904Sdim  case llvm::Triple::Win32:
1379212904Sdim    return createWindowsHostInfo(*this, Triple);
1380212904Sdim  case llvm::Triple::MinGW32:
1381212904Sdim    return createMinGWHostInfo(*this, Triple);
1382193326Sed  default:
1383193326Sed    return createUnknownHostInfo(*this, Triple);
1384193326Sed  }
1385193326Sed}
1386193326Sed
1387193326Sedbool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1388198092Srdivacky                                    const llvm::Triple &Triple) const {
1389198092Srdivacky  // Check if user requested no clang, or clang doesn't understand this type (we
1390198092Srdivacky  // only handle single inputs for now).
1391198092Srdivacky  if (!CCCUseClang || JA.size() != 1 ||
1392193326Sed      !types::isAcceptedByClang((*JA.begin())->getType()))
1393193326Sed    return false;
1394193326Sed
1395193326Sed  // Otherwise make sure this is an action clang understands.
1396193326Sed  if (isa<PreprocessJobAction>(JA)) {
1397193326Sed    if (!CCCUseClangCPP) {
1398193326Sed      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1399193326Sed      return false;
1400193326Sed    }
1401193326Sed  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1402193326Sed    return false;
1403193326Sed
1404193326Sed  // Use clang for C++?
1405193326Sed  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1406193326Sed    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1407193326Sed    return false;
1408193326Sed  }
1409193326Sed
1410203955Srdivacky  // Always use clang for precompiling, AST generation, and rewriting,
1411203955Srdivacky  // regardless of archs.
1412210299Sed  if (isa<PrecompileJobAction>(JA) ||
1413210299Sed      types::isOnlyAcceptedByClang(JA.getType()))
1414193326Sed    return true;
1415193326Sed
1416198092Srdivacky  // Finally, don't use clang if this isn't one of the user specified archs to
1417198092Srdivacky  // build.
1418198092Srdivacky  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1419198092Srdivacky    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1420193326Sed    return false;
1421193326Sed  }
1422193326Sed
1423193326Sed  return true;
1424193326Sed}
1425193326Sed
1426198092Srdivacky/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1427198092Srdivacky/// grouped values as integers. Numbers which are not provided are set to 0.
1428193326Sed///
1429198092Srdivacky/// \return True if the entire string was parsed (9.2), or all groups were
1430198092Srdivacky/// parsed (10.3.5extrastuff).
1431198092Srdivackybool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1432193326Sed                               unsigned &Minor, unsigned &Micro,
1433193326Sed                               bool &HadExtra) {
1434193326Sed  HadExtra = false;
1435193326Sed
1436193326Sed  Major = Minor = Micro = 0;
1437198092Srdivacky  if (*Str == '\0')
1438193326Sed    return true;
1439193326Sed
1440193326Sed  char *End;
1441193326Sed  Major = (unsigned) strtol(Str, &End, 10);
1442193326Sed  if (*Str != '\0' && *End == '\0')
1443193326Sed    return true;
1444193326Sed  if (*End != '.')
1445193326Sed    return false;
1446198092Srdivacky
1447193326Sed  Str = End+1;
1448193326Sed  Minor = (unsigned) strtol(Str, &End, 10);
1449193326Sed  if (*Str != '\0' && *End == '\0')
1450193326Sed    return true;
1451193326Sed  if (*End != '.')
1452193326Sed    return false;
1453193326Sed
1454193326Sed  Str = End+1;
1455193326Sed  Micro = (unsigned) strtol(Str, &End, 10);
1456193326Sed  if (*Str != '\0' && *End == '\0')
1457193326Sed    return true;
1458193326Sed  if (Str == End)
1459193326Sed    return false;
1460193326Sed  HadExtra = true;
1461193326Sed  return true;
1462193326Sed}
1463