Driver.cpp revision 224145
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
49223017SdimDriver::Driver(llvm::StringRef ClangExecutable,
50223017Sdim               llvm::StringRef DefaultHostTriple,
51223017Sdim               llvm::StringRef DefaultImageName,
52206084Srdivacky               bool IsProduction, bool CXXIsProduction,
53223017Sdim               Diagnostic &Diags)
54223017Sdim  : Opts(createDriverOptTable()), Diags(Diags),
55223017Sdim    ClangExecutable(ClangExecutable), UseStdLib(true),
56223017Sdim    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) {
401223017Sdim  // Skip the empty category.
402223017Sdim  for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
403223017Sdim       i != max; ++i)
404223017Sdim    OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
405208600Srdivacky}
406208600Srdivacky
407193326Sedbool Driver::HandleImmediateArgs(const Compilation &C) {
408210299Sed  // The order these options are handled in gcc is all over the place, but we
409198092Srdivacky  // don't expect inconsistencies w.r.t. that to matter in practice.
410193326Sed
411218893Sdim  if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
412218893Sdim    llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
413218893Sdim    return false;
414218893Sdim  }
415218893Sdim
416193326Sed  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
417218893Sdim    // Since -dumpversion is only implemented for pedantic GCC compatibility, we
418218893Sdim    // return an answer which matches our definition of __VERSION__.
419218893Sdim    //
420218893Sdim    // If we want to return a more correct answer some day, then we should
421218893Sdim    // introduce a non-pedantically GCC compatible mode to Clang in which we
422218893Sdim    // provide sensible definitions for -dumpversion, __VERSION__, etc.
423218893Sdim    llvm::outs() << "4.2.1\n";
424193326Sed    return false;
425193326Sed  }
426210299Sed
427208600Srdivacky  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
428208600Srdivacky    PrintDiagnosticCategories(llvm::outs());
429208600Srdivacky    return false;
430208600Srdivacky  }
431193326Sed
432198092Srdivacky  if (C.getArgs().hasArg(options::OPT__help) ||
433193326Sed      C.getArgs().hasArg(options::OPT__help_hidden)) {
434193326Sed    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
435193326Sed    return false;
436193326Sed  }
437193326Sed
438193326Sed  if (C.getArgs().hasArg(options::OPT__version)) {
439198092Srdivacky    // Follow gcc behavior and use stdout for --version and stderr for -v.
440198092Srdivacky    PrintVersion(C, llvm::outs());
441193326Sed    return false;
442193326Sed  }
443193326Sed
444198092Srdivacky  if (C.getArgs().hasArg(options::OPT_v) ||
445193326Sed      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
446198092Srdivacky    PrintVersion(C, llvm::errs());
447193326Sed    SuppressMissingInputWarning = true;
448193326Sed  }
449193326Sed
450193326Sed  const ToolChain &TC = C.getDefaultToolChain();
451193326Sed  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
452193326Sed    llvm::outs() << "programs: =";
453193326Sed    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
454193326Sed           ie = TC.getProgramPaths().end(); it != ie; ++it) {
455193326Sed      if (it != TC.getProgramPaths().begin())
456193326Sed        llvm::outs() << ':';
457193326Sed      llvm::outs() << *it;
458193326Sed    }
459193326Sed    llvm::outs() << "\n";
460193326Sed    llvm::outs() << "libraries: =";
461224145Sdim
462224145Sdim    std::string sysroot;
463224145Sdim    if (Arg *A = C.getArgs().getLastArg(options::OPT__sysroot_EQ))
464224145Sdim      sysroot = A->getValue(C.getArgs());
465224145Sdim
466198092Srdivacky    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
467193326Sed           ie = TC.getFilePaths().end(); it != ie; ++it) {
468193326Sed      if (it != TC.getFilePaths().begin())
469193326Sed        llvm::outs() << ':';
470224145Sdim      const char *path = it->c_str();
471224145Sdim      if (path[0] == '=')
472224145Sdim        llvm::outs() << sysroot << path + 1;
473224145Sdim      else
474224145Sdim        llvm::outs() << path;
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
582223017Sdim/// \brief Check whether the given input tree contains any compilation or
583223017Sdim/// assembly actions.
584223017Sdimstatic bool ContainsCompileOrAssembleAction(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)
589223017Sdim    if (ContainsCompileOrAssembleAction(*it))
590210299Sed      return true;
591210299Sed
592210299Sed  return false;
593210299Sed}
594210299Sed
595212904Sdimvoid Driver::BuildUniversalActions(const ToolChain &TC,
596221345Sdim                                   const DerivedArgList &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) &&
680223017Sdim          ContainsCompileOrAssembleAction(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
691221345Sdimvoid Driver::BuildActions(const ToolChain &TC, const DerivedArgList &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).
724221345Sdim          if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP)
725193326Sed            Diag(clang::diag::err_drv_unknown_stdin_type);
726193326Sed          Ty = types::TY_C;
727193326Sed        } else {
728221345Sdim          // Otherwise lookup by extension.
729221345Sdim          // Fallback is C if invoked as C preprocessor or Object otherwise.
730221345Sdim          // We use a host hook here because Darwin at least has its own
731198092Srdivacky          // idea of what .s is.
732193326Sed          if (const char *Ext = strrchr(Value, '.'))
733212904Sdim            Ty = TC.LookupTypeForExtension(Ext + 1);
734193326Sed
735221345Sdim          if (Ty == types::TY_INVALID) {
736221345Sdim            if (CCCIsCPP)
737221345Sdim              Ty = types::TY_C;
738221345Sdim            else
739221345Sdim              Ty = types::TY_Object;
740221345Sdim          }
741204643Srdivacky
742204643Srdivacky          // If the driver is invoked as C++ compiler (like clang++ or c++) it
743204643Srdivacky          // should autodetect some input files as C++ for g++ compatibility.
744204643Srdivacky          if (CCCIsCXX) {
745204643Srdivacky            types::ID OldTy = Ty;
746204643Srdivacky            Ty = types::lookupCXXTypeForCType(Ty);
747204643Srdivacky
748204643Srdivacky            if (Ty != OldTy)
749204643Srdivacky              Diag(clang::diag::warn_drv_treating_input_as_cxx)
750204643Srdivacky                << getTypeName(OldTy) << getTypeName(Ty);
751204643Srdivacky          }
752193326Sed        }
753193326Sed
754193326Sed        // -ObjC and -ObjC++ override the default language, but only for "source
755193326Sed        // files". We just treat everything that isn't a linker input as a
756193326Sed        // source file.
757198092Srdivacky        //
758193326Sed        // FIXME: Clean this up if we move the phase sequence into the type.
759193326Sed        if (Ty != types::TY_Object) {
760193326Sed          if (Args.hasArg(options::OPT_ObjC))
761193326Sed            Ty = types::TY_ObjC;
762193326Sed          else if (Args.hasArg(options::OPT_ObjCXX))
763193326Sed            Ty = types::TY_ObjCXX;
764193326Sed        }
765193326Sed      } else {
766193326Sed        assert(InputTypeArg && "InputType set w/o InputTypeArg");
767193326Sed        InputTypeArg->claim();
768193326Sed        Ty = InputType;
769193326Sed      }
770193326Sed
771203955Srdivacky      // Check that the file exists, if enabled.
772218893Sdim      if (CheckInputsExist && memcmp(Value, "-", 2) != 0) {
773218893Sdim        llvm::SmallString<64> Path(Value);
774218893Sdim        if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory))
775218893Sdim          if (llvm::sys::path::is_absolute(Path.str())) {
776218893Sdim            Path = WorkDir->getValue(Args);
777218893Sdim            llvm::sys::path::append(Path, Value);
778218893Sdim          }
779218893Sdim
780218893Sdim        bool exists = false;
781218893Sdim        if (/*error_code ec =*/llvm::sys::fs::exists(Value, exists) || !exists)
782218893Sdim          Diag(clang::diag::err_drv_no_such_file) << Path.str();
783218893Sdim        else
784218893Sdim          Inputs.push_back(std::make_pair(Ty, A));
785218893Sdim      } else
786193326Sed        Inputs.push_back(std::make_pair(Ty, A));
787193326Sed
788193326Sed    } else if (A->getOption().isLinkerInput()) {
789198092Srdivacky      // Just treat as object type, we could make a special type for this if
790198092Srdivacky      // necessary.
791193326Sed      Inputs.push_back(std::make_pair(types::TY_Object, A));
792193326Sed
793199512Srdivacky    } else if (A->getOption().matches(options::OPT_x)) {
794198092Srdivacky      InputTypeArg = A;
795193326Sed      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
796193326Sed
797193326Sed      // Follow gcc behavior and treat as linker input for invalid -x
798198092Srdivacky      // options. Its not clear why we shouldn't just revert to unknown; but
799218893Sdim      // this isn't very important, we might as well be bug compatible.
800193326Sed      if (!InputType) {
801193326Sed        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
802193326Sed        InputType = types::TY_Object;
803193326Sed      }
804193326Sed    }
805193326Sed  }
806193326Sed
807221345Sdim  if (CCCIsCPP && Inputs.empty()) {
808221345Sdim    // If called as standalone preprocessor, stdin is processed
809221345Sdim    // if no other input is present.
810221345Sdim    unsigned Index = Args.getBaseArgs().MakeIndex("-");
811221345Sdim    Arg *A = Opts->ParseOneArg(Args, Index);
812221345Sdim    A->claim();
813221345Sdim    Inputs.push_back(std::make_pair(types::TY_C, A));
814221345Sdim  }
815221345Sdim
816193326Sed  if (!SuppressMissingInputWarning && Inputs.empty()) {
817193326Sed    Diag(clang::diag::err_drv_no_input_files);
818193326Sed    return;
819193326Sed  }
820193326Sed
821198092Srdivacky  // Determine which compilation mode we are in. We look for options which
822198092Srdivacky  // affect the phase, starting with the earliest phases, and record which
823198092Srdivacky  // option we used to determine the final phase.
824193326Sed  Arg *FinalPhaseArg = 0;
825193326Sed  phases::ID FinalPhase;
826193326Sed
827193326Sed  // -{E,M,MM} only run the preprocessor.
828221345Sdim  if (CCCIsCPP ||
829221345Sdim      (FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
830218893Sdim      (FinalPhaseArg = Args.getLastArg(options::OPT_M, options::OPT_MM))) {
831193326Sed    FinalPhase = phases::Preprocess;
832198092Srdivacky
833198092Srdivacky    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
834193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
835203955Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_rewrite_objc)) ||
836193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
837193326Sed                                              options::OPT__analyze_auto)) ||
838198092Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
839193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
840193326Sed    FinalPhase = phases::Compile;
841193326Sed
842193326Sed    // -c only runs up to the assembler.
843193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
844193326Sed    FinalPhase = phases::Assemble;
845198092Srdivacky
846193326Sed    // Otherwise do everything.
847193326Sed  } else
848193326Sed    FinalPhase = phases::Link;
849193326Sed
850198092Srdivacky  // Reject -Z* at the top level, these options should never have been exposed
851198092Srdivacky  // by gcc.
852193326Sed  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
853193326Sed    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
854193326Sed
855193326Sed  // Construct the actions to perform.
856193326Sed  ActionList LinkerInputs;
857193326Sed  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
858193326Sed    types::ID InputType = Inputs[i].first;
859193326Sed    const Arg *InputArg = Inputs[i].second;
860193326Sed
861193326Sed    unsigned NumSteps = types::getNumCompilationPhases(InputType);
862193326Sed    assert(NumSteps && "Invalid number of steps!");
863193326Sed
864198092Srdivacky    // If the first step comes after the final phase we are doing as part of
865198092Srdivacky    // this compilation, warn the user about it.
866193326Sed    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
867193326Sed    if (InitialPhase > FinalPhase) {
868193326Sed      // Claim here to avoid the more general unused warning.
869193326Sed      InputArg->claim();
870198092Srdivacky
871221345Sdim      // Suppress all unused style warnings with -Qunused-arguments
872221345Sdim      if (Args.hasArg(options::OPT_Qunused_arguments))
873221345Sdim        continue;
874221345Sdim
875198092Srdivacky      // Special case '-E' warning on a previously preprocessed file to make
876198092Srdivacky      // more sense.
877198092Srdivacky      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
878198092Srdivacky          getPreprocessedType(InputType) == types::TY_INVALID)
879198092Srdivacky        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
880198092Srdivacky          << InputArg->getAsString(Args)
881198092Srdivacky          << FinalPhaseArg->getOption().getName();
882198092Srdivacky      else
883198092Srdivacky        Diag(clang::diag::warn_drv_input_file_unused)
884198092Srdivacky          << InputArg->getAsString(Args)
885198092Srdivacky          << getPhaseName(InitialPhase)
886198092Srdivacky          << FinalPhaseArg->getOption().getName();
887193326Sed      continue;
888193326Sed    }
889198092Srdivacky
890193326Sed    // Build the pipeline for this file.
891202879Srdivacky    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
892193326Sed    for (unsigned i = 0; i != NumSteps; ++i) {
893193326Sed      phases::ID Phase = types::getCompilationPhase(InputType, i);
894193326Sed
895193326Sed      // We are done if this step is past what the user requested.
896193326Sed      if (Phase > FinalPhase)
897193326Sed        break;
898193326Sed
899193326Sed      // Queue linker inputs.
900193326Sed      if (Phase == phases::Link) {
901193326Sed        assert(i + 1 == NumSteps && "linking must be final compilation step.");
902202879Srdivacky        LinkerInputs.push_back(Current.take());
903193326Sed        break;
904193326Sed      }
905193326Sed
906198092Srdivacky      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
907198092Srdivacky      // encode this in the steps because the intermediate type depends on
908198092Srdivacky      // arguments. Just special case here.
909193326Sed      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
910193326Sed        continue;
911193326Sed
912193326Sed      // Otherwise construct the appropriate action.
913202879Srdivacky      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
914193326Sed      if (Current->getType() == types::TY_Nothing)
915193326Sed        break;
916193326Sed    }
917193326Sed
918193326Sed    // If we ended with something, add to the output list.
919193326Sed    if (Current)
920202879Srdivacky      Actions.push_back(Current.take());
921193326Sed  }
922193326Sed
923193326Sed  // Add a link action if necessary.
924193326Sed  if (!LinkerInputs.empty())
925193326Sed    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
926201361Srdivacky
927201361Srdivacky  // If we are linking, claim any options which are obviously only used for
928201361Srdivacky  // compilation.
929201361Srdivacky  if (FinalPhase == phases::Link)
930201361Srdivacky    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
931193326Sed}
932193326Sed
933193326SedAction *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
934193326Sed                                     Action *Input) const {
935193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
936193326Sed  // Build the appropriate action.
937193326Sed  switch (Phase) {
938193326Sed  case phases::Link: assert(0 && "link action invalid here.");
939193326Sed  case phases::Preprocess: {
940193326Sed    types::ID OutputTy;
941193326Sed    // -{M, MM} alter the output type.
942218893Sdim    if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
943193326Sed      OutputTy = types::TY_Dependencies;
944193326Sed    } else {
945193326Sed      OutputTy = types::getPreprocessedType(Input->getType());
946193326Sed      assert(OutputTy != types::TY_INVALID &&
947193326Sed             "Cannot preprocess this input type!");
948193326Sed    }
949193326Sed    return new PreprocessJobAction(Input, OutputTy);
950193326Sed  }
951193326Sed  case phases::Precompile:
952198092Srdivacky    return new PrecompileJobAction(Input, types::TY_PCH);
953193326Sed  case phases::Compile: {
954193326Sed    if (Args.hasArg(options::OPT_fsyntax_only)) {
955193326Sed      return new CompileJobAction(Input, types::TY_Nothing);
956203955Srdivacky    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
957203955Srdivacky      return new CompileJobAction(Input, types::TY_RewrittenObjC);
958193326Sed    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
959193326Sed      return new AnalyzeJobAction(Input, types::TY_Plist);
960198092Srdivacky    } else if (Args.hasArg(options::OPT_emit_ast)) {
961198092Srdivacky      return new CompileJobAction(Input, types::TY_AST);
962224145Sdim    } else if (IsUsingLTO(Args)) {
963198092Srdivacky      types::ID Output =
964210299Sed        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
965193326Sed      return new CompileJobAction(Input, Output);
966193326Sed    } else {
967193326Sed      return new CompileJobAction(Input, types::TY_PP_Asm);
968193326Sed    }
969193326Sed  }
970193326Sed  case phases::Assemble:
971193326Sed    return new AssembleJobAction(Input, types::TY_Object);
972193326Sed  }
973193326Sed
974193326Sed  assert(0 && "invalid phase in ConstructPhaseAction");
975193326Sed  return 0;
976193326Sed}
977193326Sed
978224145Sdimbool Driver::IsUsingLTO(const ArgList &Args) const {
979224145Sdim  // Check for -emit-llvm or -flto.
980224145Sdim  if (Args.hasArg(options::OPT_emit_llvm) ||
981224145Sdim      Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
982224145Sdim    return true;
983224145Sdim
984224145Sdim  // Check for -O4.
985224145Sdim  if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
986224145Sdim      return A->getOption().matches(options::OPT_O4);
987224145Sdim
988224145Sdim  return false;
989224145Sdim}
990224145Sdim
991193326Sedvoid Driver::BuildJobs(Compilation &C) const {
992193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
993193326Sed
994193326Sed  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
995193326Sed
996198092Srdivacky  // It is an error to provide a -o option if we are making multiple output
997198092Srdivacky  // files.
998193326Sed  if (FinalOutput) {
999193326Sed    unsigned NumOutputs = 0;
1000198092Srdivacky    for (ActionList::const_iterator it = C.getActions().begin(),
1001193326Sed           ie = C.getActions().end(); it != ie; ++it)
1002193326Sed      if ((*it)->getType() != types::TY_Nothing)
1003193326Sed        ++NumOutputs;
1004198092Srdivacky
1005193326Sed    if (NumOutputs > 1) {
1006193326Sed      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1007193326Sed      FinalOutput = 0;
1008193326Sed    }
1009193326Sed  }
1010193326Sed
1011198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
1012193326Sed         ie = C.getActions().end(); it != ie; ++it) {
1013193326Sed    Action *A = *it;
1014193326Sed
1015198092Srdivacky    // If we are linking an image for multiple archs then the linker wants
1016198092Srdivacky    // -arch_multiple and -final_output <final image name>. Unfortunately, this
1017198092Srdivacky    // doesn't fit in cleanly because we have to pass this information down.
1018193326Sed    //
1019198092Srdivacky    // FIXME: This is a hack; find a cleaner way to integrate this into the
1020198092Srdivacky    // process.
1021193326Sed    const char *LinkingOutput = 0;
1022193326Sed    if (isa<LipoJobAction>(A)) {
1023193326Sed      if (FinalOutput)
1024193326Sed        LinkingOutput = FinalOutput->getValue(C.getArgs());
1025193326Sed      else
1026193326Sed        LinkingOutput = DefaultImageName.c_str();
1027193326Sed    }
1028193326Sed
1029193326Sed    InputInfo II;
1030198092Srdivacky    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1031198092Srdivacky                       /*BoundArch*/0,
1032193326Sed                       /*AtTopLevel*/ true,
1033193326Sed                       /*LinkingOutput*/ LinkingOutput,
1034193326Sed                       II);
1035193326Sed  }
1036193326Sed
1037198092Srdivacky  // If the user passed -Qunused-arguments or there were errors, don't warn
1038198092Srdivacky  // about any unused arguments.
1039218893Sdim  if (Diags.hasErrorOccurred() ||
1040193326Sed      C.getArgs().hasArg(options::OPT_Qunused_arguments))
1041193326Sed    return;
1042193326Sed
1043193326Sed  // Claim -### here.
1044193326Sed  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1045198092Srdivacky
1046193326Sed  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
1047193326Sed       it != ie; ++it) {
1048193326Sed    Arg *A = *it;
1049198092Srdivacky
1050193326Sed    // FIXME: It would be nice to be able to send the argument to the
1051198092Srdivacky    // Diagnostic, so that extra values, position, and so on could be printed.
1052193326Sed    if (!A->isClaimed()) {
1053193326Sed      if (A->getOption().hasNoArgumentUnused())
1054193326Sed        continue;
1055193326Sed
1056198092Srdivacky      // Suppress the warning automatically if this is just a flag, and it is an
1057198092Srdivacky      // instance of an argument we already claimed.
1058193326Sed      const Option &Opt = A->getOption();
1059193326Sed      if (isa<FlagOption>(Opt)) {
1060193326Sed        bool DuplicateClaimed = false;
1061193326Sed
1062199990Srdivacky        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1063199990Srdivacky               ie = C.getArgs().filtered_end(); it != ie; ++it) {
1064199990Srdivacky          if ((*it)->isClaimed()) {
1065193326Sed            DuplicateClaimed = true;
1066193326Sed            break;
1067193326Sed          }
1068193326Sed        }
1069193326Sed
1070193326Sed        if (DuplicateClaimed)
1071193326Sed          continue;
1072193326Sed      }
1073193326Sed
1074198092Srdivacky      Diag(clang::diag::warn_drv_unused_argument)
1075193326Sed        << A->getAsString(C.getArgs());
1076193326Sed    }
1077193326Sed  }
1078193326Sed}
1079193326Sed
1080203955Srdivackystatic const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
1081203955Srdivacky                                    const JobAction *JA,
1082203955Srdivacky                                    const ActionList *&Inputs) {
1083203955Srdivacky  const Tool *ToolForJob = 0;
1084203955Srdivacky
1085203955Srdivacky  // See if we should look for a compiler with an integrated assembler. We match
1086203955Srdivacky  // bottom up, so what we are actually looking for is an assembler job with a
1087203955Srdivacky  // compiler input.
1088208600Srdivacky
1089208600Srdivacky  // FIXME: This doesn't belong here, but ideally we will support static soon
1090208600Srdivacky  // anyway.
1091208600Srdivacky  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
1092208600Srdivacky                    C.getArgs().hasArg(options::OPT_static) ||
1093208600Srdivacky                    C.getArgs().hasArg(options::OPT_fapple_kext));
1094221345Sdim  bool IsDarwin = TC->getTriple().getOS() == llvm::Triple::Darwin;
1095221345Sdim  bool IsIADefault = TC->IsIntegratedAssemblerDefault() &&
1096221345Sdim    !(HasStatic && IsDarwin);
1097208600Srdivacky  if (C.getArgs().hasFlag(options::OPT_integrated_as,
1098203955Srdivacky                         options::OPT_no_integrated_as,
1099208600Srdivacky                         IsIADefault) &&
1100203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1101203955Srdivacky      isa<AssembleJobAction>(JA) &&
1102203955Srdivacky      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
1103221345Sdim    const Tool &Compiler = TC->SelectTool(
1104221345Sdim      C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs());
1105203955Srdivacky    if (Compiler.hasIntegratedAssembler()) {
1106203955Srdivacky      Inputs = &(*Inputs)[0]->getInputs();
1107203955Srdivacky      ToolForJob = &Compiler;
1108203955Srdivacky    }
1109203955Srdivacky  }
1110203955Srdivacky
1111203955Srdivacky  // Otherwise use the tool for the current job.
1112203955Srdivacky  if (!ToolForJob)
1113221345Sdim    ToolForJob = &TC->SelectTool(C, *JA, *Inputs);
1114203955Srdivacky
1115203955Srdivacky  // See if we should use an integrated preprocessor. We do so when we have
1116203955Srdivacky  // exactly one input, since this is the only use case we care about
1117203955Srdivacky  // (irrelevant since we don't support combine yet).
1118203955Srdivacky  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1119203955Srdivacky      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1120203955Srdivacky      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1121203955Srdivacky      !C.getArgs().hasArg(options::OPT_save_temps) &&
1122203955Srdivacky      ToolForJob->hasIntegratedCPP())
1123203955Srdivacky    Inputs = &(*Inputs)[0]->getInputs();
1124203955Srdivacky
1125203955Srdivacky  return *ToolForJob;
1126203955Srdivacky}
1127203955Srdivacky
1128193326Sedvoid Driver::BuildJobsForAction(Compilation &C,
1129193326Sed                                const Action *A,
1130193326Sed                                const ToolChain *TC,
1131198092Srdivacky                                const char *BoundArch,
1132193326Sed                                bool AtTopLevel,
1133193326Sed                                const char *LinkingOutput,
1134193326Sed                                InputInfo &Result) const {
1135198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1136193326Sed
1137193326Sed  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1138198092Srdivacky    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1139198092Srdivacky    // just using Args was better?
1140193326Sed    const Arg &Input = IA->getInputArg();
1141193326Sed    Input.claim();
1142210299Sed    if (Input.getOption().matches(options::OPT_INPUT)) {
1143193326Sed      const char *Name = Input.getValue(C.getArgs());
1144193326Sed      Result = InputInfo(Name, A->getType(), Name);
1145193326Sed    } else
1146193326Sed      Result = InputInfo(&Input, A->getType(), "");
1147193326Sed    return;
1148193326Sed  }
1149193326Sed
1150193326Sed  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1151198092Srdivacky    const ToolChain *TC = &C.getDefaultToolChain();
1152198092Srdivacky
1153193326Sed    std::string Arch;
1154198092Srdivacky    if (BAA->getArchName())
1155198092Srdivacky      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1156198092Srdivacky
1157198092Srdivacky    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1158212904Sdim                       AtTopLevel, LinkingOutput, Result);
1159193326Sed    return;
1160193326Sed  }
1161193326Sed
1162203955Srdivacky  const ActionList *Inputs = &A->getInputs();
1163203955Srdivacky
1164193326Sed  const JobAction *JA = cast<JobAction>(A);
1165203955Srdivacky  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1166198092Srdivacky
1167193326Sed  // Only use pipes when there is exactly one input.
1168193326Sed  InputInfoList InputInfos;
1169193326Sed  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1170193326Sed       it != ie; ++it) {
1171210299Sed    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1172210299Sed    // temporary output names.
1173210299Sed    //
1174210299Sed    // FIXME: Clean this up.
1175210299Sed    bool SubJobAtTopLevel = false;
1176210299Sed    if (AtTopLevel && isa<DsymutilJobAction>(A))
1177210299Sed      SubJobAtTopLevel = true;
1178210299Sed
1179193326Sed    InputInfo II;
1180212904Sdim    BuildJobsForAction(C, *it, TC, BoundArch,
1181210299Sed                       SubJobAtTopLevel, LinkingOutput, II);
1182193326Sed    InputInfos.push_back(II);
1183193326Sed  }
1184193326Sed
1185193326Sed  // Always use the first input as the base input.
1186193326Sed  const char *BaseInput = InputInfos[0].getBaseInput();
1187193326Sed
1188210299Sed  // ... except dsymutil actions, which use their actual input as the base
1189210299Sed  // input.
1190210299Sed  if (JA->getType() == types::TY_dSYM)
1191210299Sed    BaseInput = InputInfos[0].getFilename();
1192210299Sed
1193212904Sdim  // Determine the place to write output to, if any.
1194193326Sed  if (JA->getType() == types::TY_Nothing) {
1195193326Sed    Result = InputInfo(A->getType(), BaseInput);
1196193326Sed  } else {
1197193326Sed    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1198193326Sed                       A->getType(), BaseInput);
1199193326Sed  }
1200193326Sed
1201193326Sed  if (CCCPrintBindings) {
1202193326Sed    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1203193326Sed                 << " - \"" << T.getName() << "\", inputs: [";
1204193326Sed    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1205193326Sed      llvm::errs() << InputInfos[i].getAsString();
1206193326Sed      if (i + 1 != e)
1207193326Sed        llvm::errs() << ", ";
1208193326Sed    }
1209193326Sed    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1210193326Sed  } else {
1211212904Sdim    T.ConstructJob(C, *JA, Result, InputInfos,
1212198092Srdivacky                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1213193326Sed  }
1214193326Sed}
1215193326Sed
1216198092Srdivackyconst char *Driver::GetNamedOutputPath(Compilation &C,
1217193326Sed                                       const JobAction &JA,
1218193326Sed                                       const char *BaseInput,
1219193326Sed                                       bool AtTopLevel) const {
1220193326Sed  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1221193326Sed  // Output to a user requested destination?
1222210299Sed  if (AtTopLevel && !isa<DsymutilJobAction>(JA)) {
1223193326Sed    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1224193326Sed      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1225193326Sed  }
1226193326Sed
1227212904Sdim  // Default to writing to stdout?
1228212904Sdim  if (AtTopLevel && isa<PreprocessJobAction>(JA))
1229212904Sdim    return "-";
1230212904Sdim
1231193326Sed  // Output to a temporary file?
1232193326Sed  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1233198092Srdivacky    std::string TmpName =
1234193326Sed      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1235193326Sed    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1236193326Sed  }
1237193326Sed
1238218893Sdim  llvm::SmallString<128> BasePath(BaseInput);
1239221345Sdim  llvm::StringRef BaseName;
1240193326Sed
1241221345Sdim  // Dsymutil actions should use the full path.
1242221345Sdim  if (isa<DsymutilJobAction>(JA))
1243221345Sdim    BaseName = BasePath;
1244221345Sdim  else
1245221345Sdim    BaseName = llvm::sys::path::filename(BasePath);
1246221345Sdim
1247193326Sed  // Determine what the derived output name should be.
1248193326Sed  const char *NamedOutput;
1249193326Sed  if (JA.getType() == types::TY_Image) {
1250193326Sed    NamedOutput = DefaultImageName.c_str();
1251193326Sed  } else {
1252193326Sed    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1253193326Sed    assert(Suffix && "All types used for output should have a suffix.");
1254193326Sed
1255193326Sed    std::string::size_type End = std::string::npos;
1256193326Sed    if (!types::appendSuffixForType(JA.getType()))
1257193326Sed      End = BaseName.rfind('.');
1258193326Sed    std::string Suffixed(BaseName.substr(0, End));
1259193326Sed    Suffixed += '.';
1260193326Sed    Suffixed += Suffix;
1261193326Sed    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1262193326Sed  }
1263193326Sed
1264224145Sdim  // If we're saving temps and the temp filename conflicts with the input
1265224145Sdim  // filename, then avoid overwriting input file.
1266224145Sdim  if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
1267224145Sdim    NamedOutput == BaseName) {
1268224145Sdim    std::string TmpName =
1269224145Sdim      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1270224145Sdim    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1271224145Sdim  }
1272224145Sdim
1273198092Srdivacky  // As an annoying special case, PCH generation doesn't strip the pathname.
1274193326Sed  if (JA.getType() == types::TY_PCH) {
1275218893Sdim    llvm::sys::path::remove_filename(BasePath);
1276218893Sdim    if (BasePath.empty())
1277193326Sed      BasePath = NamedOutput;
1278193326Sed    else
1279218893Sdim      llvm::sys::path::append(BasePath, NamedOutput);
1280193326Sed    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1281193326Sed  } else {
1282193326Sed    return C.addResultFile(NamedOutput);
1283193326Sed  }
1284193326Sed}
1285193326Sed
1286198092Srdivackystd::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1287206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1288206084Srdivacky  // attempting to use this prefix when lokup up program paths.
1289218893Sdim  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1290218893Sdim       ie = PrefixDirs.end(); it != ie; ++it) {
1291221345Sdim    std::string Dir(*it);
1292221345Sdim    if (Dir.empty())
1293221345Sdim      continue;
1294221345Sdim    if (Dir[0] == '=')
1295221345Sdim      Dir = SysRoot + Dir.substr(1);
1296221345Sdim    llvm::sys::Path P(Dir);
1297206084Srdivacky    P.appendComponent(Name);
1298218893Sdim    bool Exists;
1299218893Sdim    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1300206084Srdivacky      return P.str();
1301206084Srdivacky  }
1302206084Srdivacky
1303193326Sed  const ToolChain::path_list &List = TC.getFilePaths();
1304198092Srdivacky  for (ToolChain::path_list::const_iterator
1305193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1306221345Sdim    std::string Dir(*it);
1307221345Sdim    if (Dir.empty())
1308221345Sdim      continue;
1309221345Sdim    if (Dir[0] == '=')
1310221345Sdim      Dir = SysRoot + Dir.substr(1);
1311221345Sdim    llvm::sys::Path P(Dir);
1312193326Sed    P.appendComponent(Name);
1313218893Sdim    bool Exists;
1314218893Sdim    if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
1315198092Srdivacky      return P.str();
1316193326Sed  }
1317193326Sed
1318198092Srdivacky  return Name;
1319193326Sed}
1320193326Sed
1321198092Srdivackystd::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1322198092Srdivacky                                   bool WantFile) const {
1323206084Srdivacky  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1324206084Srdivacky  // attempting to use this prefix when lokup up program paths.
1325218893Sdim  for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1326218893Sdim       ie = PrefixDirs.end(); it != ie; ++it) {
1327218893Sdim    llvm::sys::Path P(*it);
1328206084Srdivacky    P.appendComponent(Name);
1329218893Sdim    bool Exists;
1330218893Sdim    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1331218893Sdim                 : P.canExecute())
1332206084Srdivacky      return P.str();
1333206084Srdivacky  }
1334206084Srdivacky
1335193326Sed  const ToolChain::path_list &List = TC.getProgramPaths();
1336198092Srdivacky  for (ToolChain::path_list::const_iterator
1337193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1338193326Sed    llvm::sys::Path P(*it);
1339193326Sed    P.appendComponent(Name);
1340218893Sdim    bool Exists;
1341218893Sdim    if (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists
1342218893Sdim                 : P.canExecute())
1343198092Srdivacky      return P.str();
1344193326Sed  }
1345193326Sed
1346193326Sed  // If all else failed, search the path.
1347193326Sed  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1348193326Sed  if (!P.empty())
1349198092Srdivacky    return P.str();
1350193326Sed
1351198092Srdivacky  return Name;
1352193326Sed}
1353193326Sed
1354193326Sedstd::string Driver::GetTemporaryPath(const char *Suffix) const {
1355198092Srdivacky  // FIXME: This is lame; sys::Path should provide this function (in particular,
1356198092Srdivacky  // it should know how to find the temporary files dir).
1357193326Sed  std::string Error;
1358193326Sed  const char *TmpDir = ::getenv("TMPDIR");
1359193326Sed  if (!TmpDir)
1360193326Sed    TmpDir = ::getenv("TEMP");
1361193326Sed  if (!TmpDir)
1362193326Sed    TmpDir = ::getenv("TMP");
1363193326Sed  if (!TmpDir)
1364193326Sed    TmpDir = "/tmp";
1365193326Sed  llvm::sys::Path P(TmpDir);
1366193326Sed  P.appendComponent("cc");
1367193326Sed  if (P.makeUnique(false, &Error)) {
1368193326Sed    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1369193326Sed    return "";
1370193326Sed  }
1371193326Sed
1372198092Srdivacky  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1373193326Sed  P.eraseFromDisk(false, 0);
1374193326Sed
1375193326Sed  P.appendSuffix(Suffix);
1376198092Srdivacky  return P.str();
1377193326Sed}
1378193326Sed
1379193326Sedconst HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1380193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1381221345Sdim  llvm::Triple Triple(llvm::Triple::normalize(TripleStr).c_str());
1382193326Sed
1383204793Srdivacky  // TCE is an osless target
1384204793Srdivacky  if (Triple.getArchName() == "tce")
1385210299Sed    return createTCEHostInfo(*this, Triple);
1386204793Srdivacky
1387193326Sed  switch (Triple.getOS()) {
1388198092Srdivacky  case llvm::Triple::AuroraUX:
1389198092Srdivacky    return createAuroraUXHostInfo(*this, Triple);
1390193326Sed  case llvm::Triple::Darwin:
1391193326Sed    return createDarwinHostInfo(*this, Triple);
1392193326Sed  case llvm::Triple::DragonFly:
1393193326Sed    return createDragonFlyHostInfo(*this, Triple);
1394195341Sed  case llvm::Triple::OpenBSD:
1395195341Sed    return createOpenBSDHostInfo(*this, Triple);
1396218893Sdim  case llvm::Triple::NetBSD:
1397218893Sdim    return createNetBSDHostInfo(*this, Triple);
1398193326Sed  case llvm::Triple::FreeBSD:
1399193326Sed    return createFreeBSDHostInfo(*this, Triple);
1400210299Sed  case llvm::Triple::Minix:
1401210299Sed    return createMinixHostInfo(*this, Triple);
1402193326Sed  case llvm::Triple::Linux:
1403193326Sed    return createLinuxHostInfo(*this, Triple);
1404212904Sdim  case llvm::Triple::Win32:
1405212904Sdim    return createWindowsHostInfo(*this, Triple);
1406212904Sdim  case llvm::Triple::MinGW32:
1407212904Sdim    return createMinGWHostInfo(*this, Triple);
1408193326Sed  default:
1409193326Sed    return createUnknownHostInfo(*this, Triple);
1410193326Sed  }
1411193326Sed}
1412193326Sed
1413193326Sedbool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1414198092Srdivacky                                    const llvm::Triple &Triple) const {
1415198092Srdivacky  // Check if user requested no clang, or clang doesn't understand this type (we
1416198092Srdivacky  // only handle single inputs for now).
1417198092Srdivacky  if (!CCCUseClang || JA.size() != 1 ||
1418193326Sed      !types::isAcceptedByClang((*JA.begin())->getType()))
1419193326Sed    return false;
1420193326Sed
1421193326Sed  // Otherwise make sure this is an action clang understands.
1422193326Sed  if (isa<PreprocessJobAction>(JA)) {
1423193326Sed    if (!CCCUseClangCPP) {
1424193326Sed      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1425193326Sed      return false;
1426193326Sed    }
1427193326Sed  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1428193326Sed    return false;
1429193326Sed
1430193326Sed  // Use clang for C++?
1431193326Sed  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1432193326Sed    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1433193326Sed    return false;
1434193326Sed  }
1435193326Sed
1436203955Srdivacky  // Always use clang for precompiling, AST generation, and rewriting,
1437203955Srdivacky  // regardless of archs.
1438210299Sed  if (isa<PrecompileJobAction>(JA) ||
1439210299Sed      types::isOnlyAcceptedByClang(JA.getType()))
1440193326Sed    return true;
1441193326Sed
1442198092Srdivacky  // Finally, don't use clang if this isn't one of the user specified archs to
1443198092Srdivacky  // build.
1444198092Srdivacky  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1445198092Srdivacky    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1446193326Sed    return false;
1447193326Sed  }
1448193326Sed
1449193326Sed  return true;
1450193326Sed}
1451193326Sed
1452198092Srdivacky/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1453198092Srdivacky/// grouped values as integers. Numbers which are not provided are set to 0.
1454193326Sed///
1455198092Srdivacky/// \return True if the entire string was parsed (9.2), or all groups were
1456198092Srdivacky/// parsed (10.3.5extrastuff).
1457198092Srdivackybool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1458193326Sed                               unsigned &Minor, unsigned &Micro,
1459193326Sed                               bool &HadExtra) {
1460193326Sed  HadExtra = false;
1461193326Sed
1462193326Sed  Major = Minor = Micro = 0;
1463198092Srdivacky  if (*Str == '\0')
1464193326Sed    return true;
1465193326Sed
1466193326Sed  char *End;
1467193326Sed  Major = (unsigned) strtol(Str, &End, 10);
1468193326Sed  if (*Str != '\0' && *End == '\0')
1469193326Sed    return true;
1470193326Sed  if (*End != '.')
1471193326Sed    return false;
1472198092Srdivacky
1473193326Sed  Str = End+1;
1474193326Sed  Minor = (unsigned) strtol(Str, &End, 10);
1475193326Sed  if (*Str != '\0' && *End == '\0')
1476193326Sed    return true;
1477193326Sed  if (*End != '.')
1478193326Sed    return false;
1479193326Sed
1480193326Sed  Str = End+1;
1481193326Sed  Micro = (unsigned) strtol(Str, &End, 10);
1482193326Sed  if (*Str != '\0' && *End == '\0')
1483193326Sed    return true;
1484193326Sed  if (Str == End)
1485193326Sed    return false;
1486193326Sed  HadExtra = true;
1487193326Sed  return true;
1488193326Sed}
1489