Driver.cpp revision 201361
1193326Sed//===--- 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
10193326Sed#include "clang/Driver/Driver.h"
11193326Sed
12193326Sed#include "clang/Driver/Action.h"
13193326Sed#include "clang/Driver/Arg.h"
14193326Sed#include "clang/Driver/ArgList.h"
15193326Sed#include "clang/Driver/Compilation.h"
16193326Sed#include "clang/Driver/DriverDiagnostic.h"
17193326Sed#include "clang/Driver/HostInfo.h"
18193326Sed#include "clang/Driver/Job.h"
19199512Srdivacky#include "clang/Driver/OptTable.h"
20193326Sed#include "clang/Driver/Option.h"
21193326Sed#include "clang/Driver/Options.h"
22193326Sed#include "clang/Driver/Tool.h"
23193326Sed#include "clang/Driver/ToolChain.h"
24193326Sed#include "clang/Driver/Types.h"
25193326Sed
26193326Sed#include "clang/Basic/Version.h"
27193326Sed
28193326Sed#include "llvm/ADT/StringSet.h"
29193326Sed#include "llvm/Support/PrettyStackTrace.h"
30193326Sed#include "llvm/Support/raw_ostream.h"
31193326Sed#include "llvm/System/Path.h"
32193326Sed#include "llvm/System/Program.h"
33193326Sed
34193326Sed#include "InputInfo.h"
35193326Sed
36193326Sed#include <map>
37193326Sed
38193326Sedusing namespace clang::driver;
39193326Sedusing namespace clang;
40193326Sed
41198092Srdivacky// Used to set values for "production" clang, for releases.
42198092Srdivacky// #define USE_PRODUCTION_CLANG
43198092Srdivacky
44200583SrdivackyDriver::Driver(llvm::StringRef _Name, llvm::StringRef _Dir,
45200583Srdivacky               llvm::StringRef _DefaultHostTriple,
46200583Srdivacky               llvm::StringRef _DefaultImageName,
47198092Srdivacky               bool IsProduction, Diagnostic &_Diags)
48199512Srdivacky  : Opts(createDriverOptTable()), Diags(_Diags),
49193326Sed    Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
50193326Sed    DefaultImageName(_DefaultImageName),
51193326Sed    Host(0),
52193326Sed    CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
53198092Srdivacky    CCCGenericGCCName("gcc"), CCCUseClang(true),
54198092Srdivacky    CCCUseClangCXX(true), CCCUseClangCPP(true), CCCUsePCH(true),
55198092Srdivacky    SuppressMissingInputWarning(false) {
56198092Srdivacky  if (IsProduction) {
57198092Srdivacky    // In a "production" build, only use clang on architectures we expect to
58198092Srdivacky    // work, and don't use clang C++.
59198092Srdivacky    //
60198092Srdivacky    // During development its more convenient to always have the driver use
61198092Srdivacky    // clang, but we don't want users to be confused when things don't work, or
62198092Srdivacky    // to file bugs for things we don't support.
63198092Srdivacky    CCCClangArchs.insert(llvm::Triple::x86);
64198092Srdivacky    CCCClangArchs.insert(llvm::Triple::x86_64);
65198092Srdivacky    CCCClangArchs.insert(llvm::Triple::arm);
66198092Srdivacky
67198092Srdivacky    CCCUseClangCXX = false;
68198092Srdivacky  }
69193326Sed}
70193326Sed
71193326SedDriver::~Driver() {
72193326Sed  delete Opts;
73193326Sed  delete Host;
74193326Sed}
75193326Sed
76198092SrdivackyInputArgList *Driver::ParseArgStrings(const char **ArgBegin,
77193326Sed                                      const char **ArgEnd) {
78193326Sed  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
79199512Srdivacky  unsigned MissingArgIndex, MissingArgCount;
80199512Srdivacky  InputArgList *Args = getOpts().ParseArgs(ArgBegin, ArgEnd,
81199512Srdivacky                                           MissingArgIndex, MissingArgCount);
82198092Srdivacky
83199512Srdivacky  // Check for missing argument error.
84199512Srdivacky  if (MissingArgCount)
85199512Srdivacky    Diag(clang::diag::err_drv_missing_argument)
86199512Srdivacky      << Args->getArgString(MissingArgIndex) << MissingArgCount;
87193326Sed
88199512Srdivacky  // Check for unsupported options.
89199512Srdivacky  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
90199512Srdivacky       it != ie; ++it) {
91199512Srdivacky    Arg *A = *it;
92193326Sed    if (A->getOption().isUnsupported()) {
93193326Sed      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
94193326Sed      continue;
95193326Sed    }
96193326Sed  }
97193326Sed
98193326Sed  return Args;
99193326Sed}
100193326Sed
101193326SedCompilation *Driver::BuildCompilation(int argc, const char **argv) {
102193326Sed  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
103193326Sed
104198092Srdivacky  // FIXME: Handle environment options which effect driver behavior, somewhere
105198092Srdivacky  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
106198092Srdivacky  // CC_PRINT_OPTIONS.
107193326Sed
108193326Sed  // FIXME: What are we going to do with -V and -b?
109193326Sed
110198092Srdivacky  // FIXME: This stuff needs to go into the Compilation, not the driver.
111193326Sed  bool CCCPrintOptions = false, CCCPrintActions = false;
112193326Sed
113193326Sed  const char **Start = argv + 1, **End = argv + argc;
114193326Sed  const char *HostTriple = DefaultHostTriple.c_str();
115193326Sed
116200583Srdivacky  InputArgList *Args = ParseArgStrings(Start, End);
117200583Srdivacky
118200583Srdivacky  // -no-canonical-prefixes is used very early in main.
119200583Srdivacky  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
120200583Srdivacky
121200583Srdivacky  // Extract -ccc args.
122193326Sed  //
123198092Srdivacky  // FIXME: We need to figure out where this behavior should live. Most of it
124198092Srdivacky  // should be outside in the client; the parts that aren't should have proper
125198092Srdivacky  // options, either by introducing new ones or by overloading gcc ones like -V
126198092Srdivacky  // or -b.
127200583Srdivacky  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
128200583Srdivacky  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
129200583Srdivacky  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
130200583Srdivacky  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
131200583Srdivacky  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
132200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
133200583Srdivacky    CCCGenericGCCName = A->getValue(*Args);
134200583Srdivacky  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
135200583Srdivacky                                 options::OPT_ccc_no_clang_cxx,
136200583Srdivacky                                 CCCUseClangCXX);
137200583Srdivacky  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
138200583Srdivacky                            options::OPT_ccc_pch_is_pth);
139200583Srdivacky  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
140200583Srdivacky  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
141200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
142200583Srdivacky    llvm::StringRef Cur = A->getValue(*Args);
143198092Srdivacky
144200583Srdivacky    CCCClangArchs.clear();
145200583Srdivacky    while (!Cur.empty()) {
146200583Srdivacky      std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
147198092Srdivacky
148200583Srdivacky      if (!Split.first.empty()) {
149200583Srdivacky        llvm::Triple::ArchType Arch =
150200583Srdivacky          llvm::Triple(Split.first, "", "").getArch();
151193326Sed
152200583Srdivacky        if (Arch == llvm::Triple::UnknownArch) {
153200583Srdivacky          Diag(clang::diag::err_drv_invalid_arch_name) << Arch;
154200583Srdivacky          continue;
155193326Sed        }
156198092Srdivacky
157200583Srdivacky        CCCClangArchs.insert(Arch);
158193326Sed      }
159193326Sed
160200583Srdivacky      Cur = Split.second;
161193326Sed    }
162193326Sed  }
163200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple))
164200583Srdivacky    HostTriple = A->getValue(*Args);
165200583Srdivacky  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
166200583Srdivacky    Dir = A->getValue(*Args);
167193326Sed
168193326Sed  Host = GetHostInfo(HostTriple);
169193326Sed
170193326Sed  // The compilation takes ownership of Args.
171198092Srdivacky  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args);
172193326Sed
173193326Sed  // FIXME: This behavior shouldn't be here.
174193326Sed  if (CCCPrintOptions) {
175193326Sed    PrintOptions(C->getArgs());
176193326Sed    return C;
177193326Sed  }
178193326Sed
179193326Sed  if (!HandleImmediateArgs(*C))
180193326Sed    return C;
181193326Sed
182198092Srdivacky  // Construct the list of abstract actions to perform for this compilation. We
183198092Srdivacky  // avoid passing a Compilation here simply to enforce the abstraction that
184198092Srdivacky  // pipelining is not host or toolchain dependent (other than the driver driver
185198092Srdivacky  // test).
186193326Sed  if (Host->useDriverDriver())
187193326Sed    BuildUniversalActions(C->getArgs(), C->getActions());
188193326Sed  else
189193326Sed    BuildActions(C->getArgs(), C->getActions());
190193326Sed
191193326Sed  if (CCCPrintActions) {
192193326Sed    PrintActions(*C);
193193326Sed    return C;
194193326Sed  }
195193326Sed
196193326Sed  BuildJobs(*C);
197193326Sed
198193326Sed  return C;
199193326Sed}
200193326Sed
201195341Sedint Driver::ExecuteCompilation(const Compilation &C) const {
202195341Sed  // Just print if -### was present.
203195341Sed  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
204195341Sed    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
205195341Sed    return 0;
206195341Sed  }
207195341Sed
208195341Sed  // If there were errors building the compilation, quit now.
209195341Sed  if (getDiags().getNumErrors())
210195341Sed    return 1;
211195341Sed
212195341Sed  const Command *FailingCommand = 0;
213195341Sed  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
214198092Srdivacky
215195341Sed  // Remove temp files.
216195341Sed  C.CleanupFileList(C.getTempFiles());
217195341Sed
218195341Sed  // If the compilation failed, remove result files as well.
219195341Sed  if (Res != 0 && !C.getArgs().hasArg(options::OPT_save_temps))
220195341Sed    C.CleanupFileList(C.getResultFiles(), true);
221195341Sed
222195341Sed  // Print extra information about abnormal failures, if possible.
223195341Sed  if (Res) {
224195341Sed    // This is ad-hoc, but we don't want to be excessively noisy. If the result
225195341Sed    // status was 1, assume the command failed normally. In particular, if it
226195341Sed    // was the compiler then assume it gave a reasonable error code. Failures in
227195341Sed    // other tools are less common, and they generally have worse diagnostics,
228195341Sed    // so always print the diagnostic there.
229195341Sed    const Action &Source = FailingCommand->getSource();
230195341Sed    bool IsFriendlyTool = (isa<PreprocessJobAction>(Source) ||
231195341Sed                           isa<PrecompileJobAction>(Source) ||
232195341Sed                           isa<AnalyzeJobAction>(Source) ||
233195341Sed                           isa<CompileJobAction>(Source));
234195341Sed
235195341Sed    if (!IsFriendlyTool || Res != 1) {
236195341Sed      // FIXME: See FIXME above regarding result code interpretation.
237195341Sed      if (Res < 0)
238198092Srdivacky        Diag(clang::diag::err_drv_command_signalled)
239195341Sed          << Source.getClassName() << -Res;
240195341Sed      else
241198092Srdivacky        Diag(clang::diag::err_drv_command_failed)
242195341Sed          << Source.getClassName() << Res;
243195341Sed    }
244195341Sed  }
245195341Sed
246195341Sed  return Res;
247195341Sed}
248195341Sed
249193326Sedvoid Driver::PrintOptions(const ArgList &Args) const {
250193326Sed  unsigned i = 0;
251198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
252193326Sed       it != ie; ++it, ++i) {
253193326Sed    Arg *A = *it;
254193326Sed    llvm::errs() << "Option " << i << " - "
255193326Sed                 << "Name: \"" << A->getOption().getName() << "\", "
256193326Sed                 << "Values: {";
257193326Sed    for (unsigned j = 0; j < A->getNumValues(); ++j) {
258193326Sed      if (j)
259193326Sed        llvm::errs() << ", ";
260193326Sed      llvm::errs() << '"' << A->getValue(Args, j) << '"';
261193326Sed    }
262193326Sed    llvm::errs() << "}\n";
263193326Sed  }
264193326Sed}
265193326Sed
266200583Srdivacky// FIXME: Move -ccc options to real options in the .td file (or eliminate), and
267200583Srdivacky// then move to using OptTable::PrintHelp.
268193326Sedvoid Driver::PrintHelp(bool ShowHidden) const {
269200583Srdivacky  getOpts().PrintHelp(llvm::outs(), Name.c_str(),
270200583Srdivacky                      "clang \"gcc-compatible\" driver", ShowHidden);
271193326Sed}
272193326Sed
273198092Srdivackyvoid Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
274198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
275198092Srdivacky  // know what the client would like to do.
276198092Srdivacky#ifdef CLANG_VENDOR
277198092Srdivacky  OS << CLANG_VENDOR;
278193326Sed#endif
279198092Srdivacky  OS << "clang version " CLANG_VERSION_STRING " ("
280198092Srdivacky     << getClangSubversionPath();
281198092Srdivacky  if (unsigned Revision = getClangSubversionRevision())
282198092Srdivacky    OS << " " << Revision;
283198092Srdivacky  OS << ")" << '\n';
284193326Sed
285193326Sed  const ToolChain &TC = C.getDefaultToolChain();
286198092Srdivacky  OS << "Target: " << TC.getTripleString() << '\n';
287194613Sed
288194613Sed  // Print the threading model.
289194613Sed  //
290194613Sed  // FIXME: Implement correctly.
291198092Srdivacky  OS << "Thread model: " << "posix" << '\n';
292193326Sed}
293193326Sed
294193326Sedbool Driver::HandleImmediateArgs(const Compilation &C) {
295198092Srdivacky  // The order these options are handled in in gcc is all over the place, but we
296198092Srdivacky  // don't expect inconsistencies w.r.t. that to matter in practice.
297193326Sed
298193326Sed  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
299193326Sed    llvm::outs() << CLANG_VERSION_STRING "\n";
300193326Sed    return false;
301193326Sed  }
302193326Sed
303198092Srdivacky  if (C.getArgs().hasArg(options::OPT__help) ||
304193326Sed      C.getArgs().hasArg(options::OPT__help_hidden)) {
305193326Sed    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
306193326Sed    return false;
307193326Sed  }
308193326Sed
309193326Sed  if (C.getArgs().hasArg(options::OPT__version)) {
310198092Srdivacky    // Follow gcc behavior and use stdout for --version and stderr for -v.
311198092Srdivacky    PrintVersion(C, llvm::outs());
312193326Sed    return false;
313193326Sed  }
314193326Sed
315198092Srdivacky  if (C.getArgs().hasArg(options::OPT_v) ||
316193326Sed      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
317198092Srdivacky    PrintVersion(C, llvm::errs());
318193326Sed    SuppressMissingInputWarning = true;
319193326Sed  }
320193326Sed
321193326Sed  const ToolChain &TC = C.getDefaultToolChain();
322193326Sed  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
323193326Sed    llvm::outs() << "programs: =";
324193326Sed    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
325193326Sed           ie = TC.getProgramPaths().end(); it != ie; ++it) {
326193326Sed      if (it != TC.getProgramPaths().begin())
327193326Sed        llvm::outs() << ':';
328193326Sed      llvm::outs() << *it;
329193326Sed    }
330193326Sed    llvm::outs() << "\n";
331193326Sed    llvm::outs() << "libraries: =";
332198092Srdivacky    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
333193326Sed           ie = TC.getFilePaths().end(); it != ie; ++it) {
334193326Sed      if (it != TC.getFilePaths().begin())
335193326Sed        llvm::outs() << ':';
336193326Sed      llvm::outs() << *it;
337193326Sed    }
338193326Sed    llvm::outs() << "\n";
339193326Sed    return false;
340193326Sed  }
341193326Sed
342198092Srdivacky  // FIXME: The following handlers should use a callback mechanism, we don't
343198092Srdivacky  // know what the client would like to do.
344193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
345198092Srdivacky    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
346193326Sed    return false;
347193326Sed  }
348193326Sed
349193326Sed  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
350198092Srdivacky    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
351193326Sed    return false;
352193326Sed  }
353193326Sed
354193326Sed  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
355198092Srdivacky    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
356193326Sed    return false;
357193326Sed  }
358193326Sed
359194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
360194613Sed    // FIXME: We need tool chain support for this.
361194613Sed    llvm::outs() << ".;\n";
362194613Sed
363194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
364194613Sed    default:
365194613Sed      break;
366198092Srdivacky
367194613Sed    case llvm::Triple::x86_64:
368194613Sed      llvm::outs() << "x86_64;@m64" << "\n";
369194613Sed      break;
370194613Sed
371194613Sed    case llvm::Triple::ppc64:
372194613Sed      llvm::outs() << "ppc64;@m64" << "\n";
373194613Sed      break;
374194613Sed    }
375194613Sed    return false;
376194613Sed  }
377194613Sed
378194613Sed  // FIXME: What is the difference between print-multi-directory and
379194613Sed  // print-multi-os-directory?
380194613Sed  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
381194613Sed      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
382194613Sed    switch (C.getDefaultToolChain().getTriple().getArch()) {
383194613Sed    default:
384194613Sed    case llvm::Triple::x86:
385194613Sed    case llvm::Triple::ppc:
386194613Sed      llvm::outs() << "." << "\n";
387194613Sed      break;
388198092Srdivacky
389194613Sed    case llvm::Triple::x86_64:
390194613Sed      llvm::outs() << "x86_64" << "\n";
391194613Sed      break;
392194613Sed
393194613Sed    case llvm::Triple::ppc64:
394194613Sed      llvm::outs() << "ppc64" << "\n";
395194613Sed      break;
396194613Sed    }
397194613Sed    return false;
398194613Sed  }
399194613Sed
400193326Sed  return true;
401193326Sed}
402193326Sed
403198092Srdivackystatic unsigned PrintActions1(const Compilation &C, Action *A,
404193326Sed                              std::map<Action*, unsigned> &Ids) {
405193326Sed  if (Ids.count(A))
406193326Sed    return Ids[A];
407198092Srdivacky
408193326Sed  std::string str;
409193326Sed  llvm::raw_string_ostream os(str);
410198092Srdivacky
411193326Sed  os << Action::getClassName(A->getKind()) << ", ";
412198092Srdivacky  if (InputAction *IA = dyn_cast<InputAction>(A)) {
413193326Sed    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
414193326Sed  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
415198092Srdivacky    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
416193326Sed                  C.getDefaultToolChain().getArchName()) << '"'
417193326Sed       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
418193326Sed  } else {
419193326Sed    os << "{";
420193326Sed    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
421193326Sed      os << PrintActions1(C, *it, Ids);
422193326Sed      ++it;
423193326Sed      if (it != ie)
424193326Sed        os << ", ";
425193326Sed    }
426193326Sed    os << "}";
427193326Sed  }
428193326Sed
429193326Sed  unsigned Id = Ids.size();
430193326Sed  Ids[A] = Id;
431198092Srdivacky  llvm::errs() << Id << ": " << os.str() << ", "
432193326Sed               << types::getTypeName(A->getType()) << "\n";
433193326Sed
434193326Sed  return Id;
435193326Sed}
436193326Sed
437193326Sedvoid Driver::PrintActions(const Compilation &C) const {
438193326Sed  std::map<Action*, unsigned> Ids;
439198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
440193326Sed         ie = C.getActions().end(); it != ie; ++it)
441193326Sed    PrintActions1(C, *it, Ids);
442193326Sed}
443193326Sed
444198092Srdivackyvoid Driver::BuildUniversalActions(const ArgList &Args,
445193326Sed                                   ActionList &Actions) const {
446198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
447198092Srdivacky  // Collect the list of architectures. Duplicates are allowed, but should only
448198092Srdivacky  // be handled once (in the order seen).
449193326Sed  llvm::StringSet<> ArchNames;
450193326Sed  llvm::SmallVector<const char *, 4> Archs;
451198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
452193326Sed       it != ie; ++it) {
453193326Sed    Arg *A = *it;
454193326Sed
455199512Srdivacky    if (A->getOption().matches(options::OPT_arch)) {
456198092Srdivacky      // Validate the option here; we don't save the type here because its
457198092Srdivacky      // particular spelling may participate in other driver choices.
458198092Srdivacky      llvm::Triple::ArchType Arch =
459198092Srdivacky        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
460198092Srdivacky      if (Arch == llvm::Triple::UnknownArch) {
461198092Srdivacky        Diag(clang::diag::err_drv_invalid_arch_name)
462198092Srdivacky          << A->getAsString(Args);
463198092Srdivacky        continue;
464198092Srdivacky      }
465193326Sed
466193326Sed      A->claim();
467198092Srdivacky      if (ArchNames.insert(A->getValue(Args)))
468198092Srdivacky        Archs.push_back(A->getValue(Args));
469193326Sed    }
470193326Sed  }
471193326Sed
472198092Srdivacky  // When there is no explicit arch for this platform, make sure we still bind
473198092Srdivacky  // the architecture (to the default) so that -Xarch_ is handled correctly.
474193326Sed  if (!Archs.size())
475193326Sed    Archs.push_back(0);
476193326Sed
477198092Srdivacky  // FIXME: We killed off some others but these aren't yet detected in a
478198092Srdivacky  // functional manner. If we added information to jobs about which "auxiliary"
479198092Srdivacky  // files they wrote then we could detect the conflict these cause downstream.
480193326Sed  if (Archs.size() > 1) {
481193326Sed    // No recovery needed, the point of this is just to prevent
482193326Sed    // overwriting the same files.
483193326Sed    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
484198092Srdivacky      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
485193326Sed        << A->getAsString(Args);
486193326Sed  }
487193326Sed
488193326Sed  ActionList SingleActions;
489193326Sed  BuildActions(Args, SingleActions);
490193326Sed
491198092Srdivacky  // Add in arch binding and lipo (if necessary) for every top level action.
492193326Sed  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
493193326Sed    Action *Act = SingleActions[i];
494193326Sed
495198092Srdivacky    // Make sure we can lipo this kind of output. If not (and it is an actual
496198092Srdivacky    // output) then we disallow, since we can't create an output file with the
497198092Srdivacky    // right name without overwriting it. We could remove this oddity by just
498198092Srdivacky    // changing the output names to include the arch, which would also fix
499193326Sed    // -save-temps. Compatibility wins for now.
500193326Sed
501193326Sed    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
502193326Sed      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
503193326Sed        << types::getTypeName(Act->getType());
504193326Sed
505193326Sed    ActionList Inputs;
506193326Sed    for (unsigned i = 0, e = Archs.size(); i != e; ++i)
507193326Sed      Inputs.push_back(new BindArchAction(Act, Archs[i]));
508193326Sed
509198092Srdivacky    // Lipo if necessary, we do it this way because we need to set the arch flag
510198092Srdivacky    // so that -Xarch_ gets overwritten.
511193326Sed    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
512193326Sed      Actions.append(Inputs.begin(), Inputs.end());
513193326Sed    else
514193326Sed      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
515193326Sed  }
516193326Sed}
517193326Sed
518193326Sedvoid Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
519193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
520193326Sed  // Start by constructing the list of inputs and their types.
521193326Sed
522198092Srdivacky  // Track the current user specified (-x) input. We also explicitly track the
523198092Srdivacky  // argument used to set the type; we only want to claim the type when we
524198092Srdivacky  // actually use it, so we warn about unused -x arguments.
525193326Sed  types::ID InputType = types::TY_Nothing;
526193326Sed  Arg *InputTypeArg = 0;
527193326Sed
528193326Sed  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
529198092Srdivacky  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
530193326Sed       it != ie; ++it) {
531193326Sed    Arg *A = *it;
532193326Sed
533193326Sed    if (isa<InputOption>(A->getOption())) {
534193326Sed      const char *Value = A->getValue(Args);
535193326Sed      types::ID Ty = types::TY_INVALID;
536193326Sed
537193326Sed      // Infer the input type if necessary.
538193326Sed      if (InputType == types::TY_Nothing) {
539193326Sed        // If there was an explicit arg for this, claim it.
540193326Sed        if (InputTypeArg)
541193326Sed          InputTypeArg->claim();
542193326Sed
543193326Sed        // stdin must be handled specially.
544193326Sed        if (memcmp(Value, "-", 2) == 0) {
545198092Srdivacky          // If running with -E, treat as a C input (this changes the builtin
546198092Srdivacky          // macros, for example). This may be overridden by -ObjC below.
547193326Sed          //
548198092Srdivacky          // Otherwise emit an error but still use a valid type to avoid
549198092Srdivacky          // spurious errors (e.g., no inputs).
550199512Srdivacky          if (!Args.hasArgNoClaim(options::OPT_E))
551193326Sed            Diag(clang::diag::err_drv_unknown_stdin_type);
552193326Sed          Ty = types::TY_C;
553193326Sed        } else {
554198092Srdivacky          // Otherwise lookup by extension, and fallback to ObjectType if not
555198092Srdivacky          // found. We use a host hook here because Darwin at least has its own
556198092Srdivacky          // idea of what .s is.
557193326Sed          if (const char *Ext = strrchr(Value, '.'))
558193326Sed            Ty = Host->lookupTypeForExtension(Ext + 1);
559193326Sed
560193326Sed          if (Ty == types::TY_INVALID)
561193326Sed            Ty = types::TY_Object;
562193326Sed        }
563193326Sed
564193326Sed        // -ObjC and -ObjC++ override the default language, but only for "source
565193326Sed        // files". We just treat everything that isn't a linker input as a
566193326Sed        // source file.
567198092Srdivacky        //
568193326Sed        // FIXME: Clean this up if we move the phase sequence into the type.
569193326Sed        if (Ty != types::TY_Object) {
570193326Sed          if (Args.hasArg(options::OPT_ObjC))
571193326Sed            Ty = types::TY_ObjC;
572193326Sed          else if (Args.hasArg(options::OPT_ObjCXX))
573193326Sed            Ty = types::TY_ObjCXX;
574193326Sed        }
575193326Sed      } else {
576193326Sed        assert(InputTypeArg && "InputType set w/o InputTypeArg");
577193326Sed        InputTypeArg->claim();
578193326Sed        Ty = InputType;
579193326Sed      }
580193326Sed
581198092Srdivacky      // Check that the file exists. It isn't clear this is worth doing, since
582198092Srdivacky      // the tool presumably does this anyway, and this just adds an extra stat
583198092Srdivacky      // to the equation, but this is gcc compatible.
584193326Sed      if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
585193326Sed        Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
586193326Sed      else
587193326Sed        Inputs.push_back(std::make_pair(Ty, A));
588193326Sed
589193326Sed    } else if (A->getOption().isLinkerInput()) {
590198092Srdivacky      // Just treat as object type, we could make a special type for this if
591198092Srdivacky      // necessary.
592193326Sed      Inputs.push_back(std::make_pair(types::TY_Object, A));
593193326Sed
594199512Srdivacky    } else if (A->getOption().matches(options::OPT_x)) {
595198092Srdivacky      InputTypeArg = A;
596193326Sed      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
597193326Sed
598193326Sed      // Follow gcc behavior and treat as linker input for invalid -x
599198092Srdivacky      // options. Its not clear why we shouldn't just revert to unknown; but
600198092Srdivacky      // this isn't very important, we might as well be bug comatible.
601193326Sed      if (!InputType) {
602193326Sed        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
603193326Sed        InputType = types::TY_Object;
604193326Sed      }
605193326Sed    }
606193326Sed  }
607193326Sed
608193326Sed  if (!SuppressMissingInputWarning && Inputs.empty()) {
609193326Sed    Diag(clang::diag::err_drv_no_input_files);
610193326Sed    return;
611193326Sed  }
612193326Sed
613198092Srdivacky  // Determine which compilation mode we are in. We look for options which
614198092Srdivacky  // affect the phase, starting with the earliest phases, and record which
615198092Srdivacky  // option we used to determine the final phase.
616193326Sed  Arg *FinalPhaseArg = 0;
617193326Sed  phases::ID FinalPhase;
618193326Sed
619193326Sed  // -{E,M,MM} only run the preprocessor.
620193326Sed  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
621193326Sed      (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
622193326Sed      (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
623193326Sed    FinalPhase = phases::Preprocess;
624198092Srdivacky
625198092Srdivacky    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
626193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
627193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
628193326Sed                                              options::OPT__analyze_auto)) ||
629198092Srdivacky             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
630193326Sed             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
631193326Sed    FinalPhase = phases::Compile;
632193326Sed
633193326Sed    // -c only runs up to the assembler.
634193326Sed  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
635193326Sed    FinalPhase = phases::Assemble;
636198092Srdivacky
637193326Sed    // Otherwise do everything.
638193326Sed  } else
639193326Sed    FinalPhase = phases::Link;
640193326Sed
641198092Srdivacky  // Reject -Z* at the top level, these options should never have been exposed
642198092Srdivacky  // by gcc.
643193326Sed  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
644193326Sed    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
645193326Sed
646193326Sed  // Construct the actions to perform.
647193326Sed  ActionList LinkerInputs;
648193326Sed  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
649193326Sed    types::ID InputType = Inputs[i].first;
650193326Sed    const Arg *InputArg = Inputs[i].second;
651193326Sed
652193326Sed    unsigned NumSteps = types::getNumCompilationPhases(InputType);
653193326Sed    assert(NumSteps && "Invalid number of steps!");
654193326Sed
655198092Srdivacky    // If the first step comes after the final phase we are doing as part of
656198092Srdivacky    // this compilation, warn the user about it.
657193326Sed    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
658193326Sed    if (InitialPhase > FinalPhase) {
659193326Sed      // Claim here to avoid the more general unused warning.
660193326Sed      InputArg->claim();
661198092Srdivacky
662198092Srdivacky      // Special case '-E' warning on a previously preprocessed file to make
663198092Srdivacky      // more sense.
664198092Srdivacky      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
665198092Srdivacky          getPreprocessedType(InputType) == types::TY_INVALID)
666198092Srdivacky        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
667198092Srdivacky          << InputArg->getAsString(Args)
668198092Srdivacky          << FinalPhaseArg->getOption().getName();
669198092Srdivacky      else
670198092Srdivacky        Diag(clang::diag::warn_drv_input_file_unused)
671198092Srdivacky          << InputArg->getAsString(Args)
672198092Srdivacky          << getPhaseName(InitialPhase)
673198092Srdivacky          << FinalPhaseArg->getOption().getName();
674193326Sed      continue;
675193326Sed    }
676198092Srdivacky
677193326Sed    // Build the pipeline for this file.
678193326Sed    Action *Current = new InputAction(*InputArg, InputType);
679193326Sed    for (unsigned i = 0; i != NumSteps; ++i) {
680193326Sed      phases::ID Phase = types::getCompilationPhase(InputType, i);
681193326Sed
682193326Sed      // We are done if this step is past what the user requested.
683193326Sed      if (Phase > FinalPhase)
684193326Sed        break;
685193326Sed
686193326Sed      // Queue linker inputs.
687193326Sed      if (Phase == phases::Link) {
688193326Sed        assert(i + 1 == NumSteps && "linking must be final compilation step.");
689193326Sed        LinkerInputs.push_back(Current);
690193326Sed        Current = 0;
691193326Sed        break;
692193326Sed      }
693193326Sed
694198092Srdivacky      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
695198092Srdivacky      // encode this in the steps because the intermediate type depends on
696198092Srdivacky      // arguments. Just special case here.
697193326Sed      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
698193326Sed        continue;
699193326Sed
700193326Sed      // Otherwise construct the appropriate action.
701193326Sed      Current = ConstructPhaseAction(Args, Phase, Current);
702193326Sed      if (Current->getType() == types::TY_Nothing)
703193326Sed        break;
704193326Sed    }
705193326Sed
706193326Sed    // If we ended with something, add to the output list.
707193326Sed    if (Current)
708193326Sed      Actions.push_back(Current);
709193326Sed  }
710193326Sed
711193326Sed  // Add a link action if necessary.
712193326Sed  if (!LinkerInputs.empty())
713193326Sed    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
714201361Srdivacky
715201361Srdivacky  // If we are linking, claim any options which are obviously only used for
716201361Srdivacky  // compilation.
717201361Srdivacky  if (FinalPhase == phases::Link)
718201361Srdivacky    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
719193326Sed}
720193326Sed
721193326SedAction *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
722193326Sed                                     Action *Input) const {
723193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
724193326Sed  // Build the appropriate action.
725193326Sed  switch (Phase) {
726193326Sed  case phases::Link: assert(0 && "link action invalid here.");
727193326Sed  case phases::Preprocess: {
728193326Sed    types::ID OutputTy;
729193326Sed    // -{M, MM} alter the output type.
730193326Sed    if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
731193326Sed      OutputTy = types::TY_Dependencies;
732193326Sed    } else {
733193326Sed      OutputTy = types::getPreprocessedType(Input->getType());
734193326Sed      assert(OutputTy != types::TY_INVALID &&
735193326Sed             "Cannot preprocess this input type!");
736193326Sed    }
737193326Sed    return new PreprocessJobAction(Input, OutputTy);
738193326Sed  }
739193326Sed  case phases::Precompile:
740198092Srdivacky    return new PrecompileJobAction(Input, types::TY_PCH);
741193326Sed  case phases::Compile: {
742201361Srdivacky    bool HasO4 = false;
743201361Srdivacky    if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
744201361Srdivacky      HasO4 = A->getOption().matches(options::OPT_O4);
745201361Srdivacky
746193326Sed    if (Args.hasArg(options::OPT_fsyntax_only)) {
747193326Sed      return new CompileJobAction(Input, types::TY_Nothing);
748193326Sed    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
749193326Sed      return new AnalyzeJobAction(Input, types::TY_Plist);
750198092Srdivacky    } else if (Args.hasArg(options::OPT_emit_ast)) {
751198092Srdivacky      return new CompileJobAction(Input, types::TY_AST);
752193326Sed    } else if (Args.hasArg(options::OPT_emit_llvm) ||
753201361Srdivacky               Args.hasArg(options::OPT_flto) || HasO4) {
754198092Srdivacky      types::ID Output =
755193326Sed        Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
756193326Sed      return new CompileJobAction(Input, Output);
757193326Sed    } else {
758193326Sed      return new CompileJobAction(Input, types::TY_PP_Asm);
759193326Sed    }
760193326Sed  }
761193326Sed  case phases::Assemble:
762193326Sed    return new AssembleJobAction(Input, types::TY_Object);
763193326Sed  }
764193326Sed
765193326Sed  assert(0 && "invalid phase in ConstructPhaseAction");
766193326Sed  return 0;
767193326Sed}
768193326Sed
769193326Sedvoid Driver::BuildJobs(Compilation &C) const {
770193326Sed  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
771193326Sed  bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
772193326Sed  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
773193326Sed
774198092Srdivacky  // FIXME: Pipes are forcibly disabled until we support executing them.
775193326Sed  if (!CCCPrintBindings)
776193326Sed    UsePipes = false;
777198092Srdivacky
778193326Sed  // -save-temps inhibits pipes.
779201361Srdivacky  if (SaveTemps && UsePipes)
780193326Sed    Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
781193326Sed
782193326Sed  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
783193326Sed
784198092Srdivacky  // It is an error to provide a -o option if we are making multiple output
785198092Srdivacky  // files.
786193326Sed  if (FinalOutput) {
787193326Sed    unsigned NumOutputs = 0;
788198092Srdivacky    for (ActionList::const_iterator it = C.getActions().begin(),
789193326Sed           ie = C.getActions().end(); it != ie; ++it)
790193326Sed      if ((*it)->getType() != types::TY_Nothing)
791193326Sed        ++NumOutputs;
792198092Srdivacky
793193326Sed    if (NumOutputs > 1) {
794193326Sed      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
795193326Sed      FinalOutput = 0;
796193326Sed    }
797193326Sed  }
798193326Sed
799198092Srdivacky  for (ActionList::const_iterator it = C.getActions().begin(),
800193326Sed         ie = C.getActions().end(); it != ie; ++it) {
801193326Sed    Action *A = *it;
802193326Sed
803198092Srdivacky    // If we are linking an image for multiple archs then the linker wants
804198092Srdivacky    // -arch_multiple and -final_output <final image name>. Unfortunately, this
805198092Srdivacky    // doesn't fit in cleanly because we have to pass this information down.
806193326Sed    //
807198092Srdivacky    // FIXME: This is a hack; find a cleaner way to integrate this into the
808198092Srdivacky    // process.
809193326Sed    const char *LinkingOutput = 0;
810193326Sed    if (isa<LipoJobAction>(A)) {
811193326Sed      if (FinalOutput)
812193326Sed        LinkingOutput = FinalOutput->getValue(C.getArgs());
813193326Sed      else
814193326Sed        LinkingOutput = DefaultImageName.c_str();
815193326Sed    }
816193326Sed
817193326Sed    InputInfo II;
818198092Srdivacky    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
819198092Srdivacky                       /*BoundArch*/0,
820193326Sed                       /*CanAcceptPipe*/ true,
821193326Sed                       /*AtTopLevel*/ true,
822193326Sed                       /*LinkingOutput*/ LinkingOutput,
823193326Sed                       II);
824193326Sed  }
825193326Sed
826198092Srdivacky  // If the user passed -Qunused-arguments or there were errors, don't warn
827198092Srdivacky  // about any unused arguments.
828198092Srdivacky  if (Diags.getNumErrors() ||
829193326Sed      C.getArgs().hasArg(options::OPT_Qunused_arguments))
830193326Sed    return;
831193326Sed
832193326Sed  // Claim -### here.
833193326Sed  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
834198092Srdivacky
835193326Sed  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
836193326Sed       it != ie; ++it) {
837193326Sed    Arg *A = *it;
838198092Srdivacky
839193326Sed    // FIXME: It would be nice to be able to send the argument to the
840198092Srdivacky    // Diagnostic, so that extra values, position, and so on could be printed.
841193326Sed    if (!A->isClaimed()) {
842193326Sed      if (A->getOption().hasNoArgumentUnused())
843193326Sed        continue;
844193326Sed
845198092Srdivacky      // Suppress the warning automatically if this is just a flag, and it is an
846198092Srdivacky      // instance of an argument we already claimed.
847193326Sed      const Option &Opt = A->getOption();
848193326Sed      if (isa<FlagOption>(Opt)) {
849193326Sed        bool DuplicateClaimed = false;
850193326Sed
851199990Srdivacky        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
852199990Srdivacky               ie = C.getArgs().filtered_end(); it != ie; ++it) {
853199990Srdivacky          if ((*it)->isClaimed()) {
854193326Sed            DuplicateClaimed = true;
855193326Sed            break;
856193326Sed          }
857193326Sed        }
858193326Sed
859193326Sed        if (DuplicateClaimed)
860193326Sed          continue;
861193326Sed      }
862193326Sed
863198092Srdivacky      Diag(clang::diag::warn_drv_unused_argument)
864193326Sed        << A->getAsString(C.getArgs());
865193326Sed    }
866193326Sed  }
867193326Sed}
868193326Sed
869193326Sedvoid Driver::BuildJobsForAction(Compilation &C,
870193326Sed                                const Action *A,
871193326Sed                                const ToolChain *TC,
872198092Srdivacky                                const char *BoundArch,
873193326Sed                                bool CanAcceptPipe,
874193326Sed                                bool AtTopLevel,
875193326Sed                                const char *LinkingOutput,
876193326Sed                                InputInfo &Result) const {
877198092Srdivacky  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
878193326Sed
879193326Sed  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
880198092Srdivacky  // FIXME: Pipes are forcibly disabled until we support executing them.
881193326Sed  if (!CCCPrintBindings)
882193326Sed    UsePipes = false;
883193326Sed
884193326Sed  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
885198092Srdivacky    // FIXME: It would be nice to not claim this here; maybe the old scheme of
886198092Srdivacky    // just using Args was better?
887193326Sed    const Arg &Input = IA->getInputArg();
888193326Sed    Input.claim();
889193326Sed    if (isa<PositionalArg>(Input)) {
890193326Sed      const char *Name = Input.getValue(C.getArgs());
891193326Sed      Result = InputInfo(Name, A->getType(), Name);
892193326Sed    } else
893193326Sed      Result = InputInfo(&Input, A->getType(), "");
894193326Sed    return;
895193326Sed  }
896193326Sed
897193326Sed  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
898198092Srdivacky    const ToolChain *TC = &C.getDefaultToolChain();
899198092Srdivacky
900193326Sed    std::string Arch;
901198092Srdivacky    if (BAA->getArchName())
902198092Srdivacky      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
903198092Srdivacky
904198092Srdivacky    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
905198092Srdivacky                       CanAcceptPipe, AtTopLevel, LinkingOutput, Result);
906193326Sed    return;
907193326Sed  }
908193326Sed
909193326Sed  const JobAction *JA = cast<JobAction>(A);
910193326Sed  const Tool &T = TC->SelectTool(C, *JA);
911198092Srdivacky
912198092Srdivacky  // See if we should use an integrated preprocessor. We do so when we have
913198092Srdivacky  // exactly one input, since this is the only use case we care about
914198092Srdivacky  // (irrelevant since we don't support combine yet).
915193326Sed  const ActionList *Inputs = &A->getInputs();
916193326Sed  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
917193326Sed    if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
918193326Sed        !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
919193326Sed        !C.getArgs().hasArg(options::OPT_save_temps) &&
920193326Sed        T.hasIntegratedCPP()) {
921193326Sed      Inputs = &(*Inputs)[0]->getInputs();
922193326Sed    }
923193326Sed  }
924193326Sed
925193326Sed  // Only use pipes when there is exactly one input.
926193326Sed  bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
927193326Sed  InputInfoList InputInfos;
928193326Sed  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
929193326Sed       it != ie; ++it) {
930193326Sed    InputInfo II;
931198092Srdivacky    BuildJobsForAction(C, *it, TC, BoundArch, TryToUsePipeInput,
932198092Srdivacky                       /*AtTopLevel*/false, LinkingOutput, II);
933193326Sed    InputInfos.push_back(II);
934193326Sed  }
935193326Sed
936193326Sed  // Determine if we should output to a pipe.
937193326Sed  bool OutputToPipe = false;
938193326Sed  if (CanAcceptPipe && T.canPipeOutput()) {
939198092Srdivacky    // Some actions default to writing to a pipe if they are the top level phase
940198092Srdivacky    // and there was no user override.
941193326Sed    //
942193326Sed    // FIXME: Is there a better way to handle this?
943193326Sed    if (AtTopLevel) {
944193326Sed      if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
945193326Sed        OutputToPipe = true;
946193326Sed    } else if (UsePipes)
947193326Sed      OutputToPipe = true;
948193326Sed  }
949193326Sed
950193326Sed  // Figure out where to put the job (pipes).
951193326Sed  Job *Dest = &C.getJobs();
952193326Sed  if (InputInfos[0].isPipe()) {
953193326Sed    assert(TryToUsePipeInput && "Unrequested pipe!");
954193326Sed    assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
955193326Sed    Dest = &InputInfos[0].getPipe();
956193326Sed  }
957193326Sed
958193326Sed  // Always use the first input as the base input.
959193326Sed  const char *BaseInput = InputInfos[0].getBaseInput();
960193326Sed
961198092Srdivacky  // Determine the place to write output to (nothing, pipe, or filename) and
962198092Srdivacky  // where to put the new job.
963193326Sed  if (JA->getType() == types::TY_Nothing) {
964193326Sed    Result = InputInfo(A->getType(), BaseInput);
965193326Sed  } else if (OutputToPipe) {
966193326Sed    // Append to current piped job or create a new one as appropriate.
967193326Sed    PipedJob *PJ = dyn_cast<PipedJob>(Dest);
968193326Sed    if (!PJ) {
969193326Sed      PJ = new PipedJob();
970198092Srdivacky      // FIXME: Temporary hack so that -ccc-print-bindings work until we have
971198092Srdivacky      // pipe support. Please remove later.
972193326Sed      if (!CCCPrintBindings)
973193326Sed        cast<JobList>(Dest)->addJob(PJ);
974193326Sed      Dest = PJ;
975193326Sed    }
976193326Sed    Result = InputInfo(PJ, A->getType(), BaseInput);
977193326Sed  } else {
978193326Sed    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
979193326Sed                       A->getType(), BaseInput);
980193326Sed  }
981193326Sed
982193326Sed  if (CCCPrintBindings) {
983193326Sed    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
984193326Sed                 << " - \"" << T.getName() << "\", inputs: [";
985193326Sed    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
986193326Sed      llvm::errs() << InputInfos[i].getAsString();
987193326Sed      if (i + 1 != e)
988193326Sed        llvm::errs() << ", ";
989193326Sed    }
990193326Sed    llvm::errs() << "], output: " << Result.getAsString() << "\n";
991193326Sed  } else {
992198092Srdivacky    T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
993198092Srdivacky                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
994193326Sed  }
995193326Sed}
996193326Sed
997198092Srdivackyconst char *Driver::GetNamedOutputPath(Compilation &C,
998193326Sed                                       const JobAction &JA,
999193326Sed                                       const char *BaseInput,
1000193326Sed                                       bool AtTopLevel) const {
1001193326Sed  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1002193326Sed  // Output to a user requested destination?
1003193326Sed  if (AtTopLevel) {
1004193326Sed    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1005193326Sed      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1006193326Sed  }
1007193326Sed
1008193326Sed  // Output to a temporary file?
1009193326Sed  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1010198092Srdivacky    std::string TmpName =
1011193326Sed      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1012193326Sed    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1013193326Sed  }
1014193326Sed
1015193326Sed  llvm::sys::Path BasePath(BaseInput);
1016193326Sed  std::string BaseName(BasePath.getLast());
1017193326Sed
1018193326Sed  // Determine what the derived output name should be.
1019193326Sed  const char *NamedOutput;
1020193326Sed  if (JA.getType() == types::TY_Image) {
1021193326Sed    NamedOutput = DefaultImageName.c_str();
1022193326Sed  } else {
1023193326Sed    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1024193326Sed    assert(Suffix && "All types used for output should have a suffix.");
1025193326Sed
1026193326Sed    std::string::size_type End = std::string::npos;
1027193326Sed    if (!types::appendSuffixForType(JA.getType()))
1028193326Sed      End = BaseName.rfind('.');
1029193326Sed    std::string Suffixed(BaseName.substr(0, End));
1030193326Sed    Suffixed += '.';
1031193326Sed    Suffixed += Suffix;
1032193326Sed    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1033193326Sed  }
1034193326Sed
1035198092Srdivacky  // As an annoying special case, PCH generation doesn't strip the pathname.
1036193326Sed  if (JA.getType() == types::TY_PCH) {
1037193326Sed    BasePath.eraseComponent();
1038193326Sed    if (BasePath.isEmpty())
1039193326Sed      BasePath = NamedOutput;
1040193326Sed    else
1041193326Sed      BasePath.appendComponent(NamedOutput);
1042193326Sed    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1043193326Sed  } else {
1044193326Sed    return C.addResultFile(NamedOutput);
1045193326Sed  }
1046193326Sed}
1047193326Sed
1048198092Srdivackystd::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1049193326Sed  const ToolChain::path_list &List = TC.getFilePaths();
1050198092Srdivacky  for (ToolChain::path_list::const_iterator
1051193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1052193326Sed    llvm::sys::Path P(*it);
1053193326Sed    P.appendComponent(Name);
1054193326Sed    if (P.exists())
1055198092Srdivacky      return P.str();
1056193326Sed  }
1057193326Sed
1058198092Srdivacky  return Name;
1059193326Sed}
1060193326Sed
1061198092Srdivackystd::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1062198092Srdivacky                                   bool WantFile) const {
1063193326Sed  const ToolChain::path_list &List = TC.getProgramPaths();
1064198092Srdivacky  for (ToolChain::path_list::const_iterator
1065193326Sed         it = List.begin(), ie = List.end(); it != ie; ++it) {
1066193326Sed    llvm::sys::Path P(*it);
1067193326Sed    P.appendComponent(Name);
1068193326Sed    if (WantFile ? P.exists() : P.canExecute())
1069198092Srdivacky      return P.str();
1070193326Sed  }
1071193326Sed
1072193326Sed  // If all else failed, search the path.
1073193326Sed  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1074193326Sed  if (!P.empty())
1075198092Srdivacky    return P.str();
1076193326Sed
1077198092Srdivacky  return Name;
1078193326Sed}
1079193326Sed
1080193326Sedstd::string Driver::GetTemporaryPath(const char *Suffix) const {
1081198092Srdivacky  // FIXME: This is lame; sys::Path should provide this function (in particular,
1082198092Srdivacky  // it should know how to find the temporary files dir).
1083193326Sed  std::string Error;
1084193326Sed  const char *TmpDir = ::getenv("TMPDIR");
1085193326Sed  if (!TmpDir)
1086193326Sed    TmpDir = ::getenv("TEMP");
1087193326Sed  if (!TmpDir)
1088193326Sed    TmpDir = ::getenv("TMP");
1089193326Sed  if (!TmpDir)
1090193326Sed    TmpDir = "/tmp";
1091193326Sed  llvm::sys::Path P(TmpDir);
1092193326Sed  P.appendComponent("cc");
1093193326Sed  if (P.makeUnique(false, &Error)) {
1094193326Sed    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1095193326Sed    return "";
1096193326Sed  }
1097193326Sed
1098198092Srdivacky  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1099193326Sed  P.eraseFromDisk(false, 0);
1100193326Sed
1101193326Sed  P.appendSuffix(Suffix);
1102198092Srdivacky  return P.str();
1103193326Sed}
1104193326Sed
1105193326Sedconst HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1106193326Sed  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1107193326Sed  llvm::Triple Triple(TripleStr);
1108193326Sed
1109193326Sed  switch (Triple.getOS()) {
1110198092Srdivacky  case llvm::Triple::AuroraUX:
1111198092Srdivacky    return createAuroraUXHostInfo(*this, Triple);
1112193326Sed  case llvm::Triple::Darwin:
1113193326Sed    return createDarwinHostInfo(*this, Triple);
1114193326Sed  case llvm::Triple::DragonFly:
1115193326Sed    return createDragonFlyHostInfo(*this, Triple);
1116195341Sed  case llvm::Triple::OpenBSD:
1117195341Sed    return createOpenBSDHostInfo(*this, Triple);
1118193326Sed  case llvm::Triple::FreeBSD:
1119193326Sed    return createFreeBSDHostInfo(*this, Triple);
1120193326Sed  case llvm::Triple::Linux:
1121193326Sed    return createLinuxHostInfo(*this, Triple);
1122193326Sed  default:
1123193326Sed    return createUnknownHostInfo(*this, Triple);
1124193326Sed  }
1125193326Sed}
1126193326Sed
1127193326Sedbool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1128198092Srdivacky                                    const llvm::Triple &Triple) const {
1129198092Srdivacky  // Check if user requested no clang, or clang doesn't understand this type (we
1130198092Srdivacky  // only handle single inputs for now).
1131198092Srdivacky  if (!CCCUseClang || JA.size() != 1 ||
1132193326Sed      !types::isAcceptedByClang((*JA.begin())->getType()))
1133193326Sed    return false;
1134193326Sed
1135193326Sed  // Otherwise make sure this is an action clang understands.
1136193326Sed  if (isa<PreprocessJobAction>(JA)) {
1137193326Sed    if (!CCCUseClangCPP) {
1138193326Sed      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1139193326Sed      return false;
1140193326Sed    }
1141193326Sed  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1142193326Sed    return false;
1143193326Sed
1144193326Sed  // Use clang for C++?
1145193326Sed  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1146193326Sed    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1147193326Sed    return false;
1148193326Sed  }
1149193326Sed
1150198092Srdivacky  // Always use clang for precompiling and AST generation, regardless of archs.
1151198092Srdivacky  if (isa<PrecompileJobAction>(JA) || JA.getType() == types::TY_AST)
1152193326Sed    return true;
1153193326Sed
1154198092Srdivacky  // Finally, don't use clang if this isn't one of the user specified archs to
1155198092Srdivacky  // build.
1156198092Srdivacky  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1157198092Srdivacky    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1158193326Sed    return false;
1159193326Sed  }
1160193326Sed
1161193326Sed  return true;
1162193326Sed}
1163193326Sed
1164198092Srdivacky/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1165198092Srdivacky/// grouped values as integers. Numbers which are not provided are set to 0.
1166193326Sed///
1167198092Srdivacky/// \return True if the entire string was parsed (9.2), or all groups were
1168198092Srdivacky/// parsed (10.3.5extrastuff).
1169198092Srdivackybool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1170193326Sed                               unsigned &Minor, unsigned &Micro,
1171193326Sed                               bool &HadExtra) {
1172193326Sed  HadExtra = false;
1173193326Sed
1174193326Sed  Major = Minor = Micro = 0;
1175198092Srdivacky  if (*Str == '\0')
1176193326Sed    return true;
1177193326Sed
1178193326Sed  char *End;
1179193326Sed  Major = (unsigned) strtol(Str, &End, 10);
1180193326Sed  if (*Str != '\0' && *End == '\0')
1181193326Sed    return true;
1182193326Sed  if (*End != '.')
1183193326Sed    return false;
1184198092Srdivacky
1185193326Sed  Str = End+1;
1186193326Sed  Minor = (unsigned) strtol(Str, &End, 10);
1187193326Sed  if (*Str != '\0' && *End == '\0')
1188193326Sed    return true;
1189193326Sed  if (*End != '.')
1190193326Sed    return false;
1191193326Sed
1192193326Sed  Str = End+1;
1193193326Sed  Micro = (unsigned) strtol(Str, &End, 10);
1194193326Sed  if (*Str != '\0' && *End == '\0')
1195193326Sed    return true;
1196193326Sed  if (Str == End)
1197193326Sed    return false;
1198193326Sed  HadExtra = true;
1199193326Sed  return true;
1200193326Sed}
1201