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