Driver.cpp revision be21cd0f07726045367861d3882d18ef30f6a30c
1//===--- Driver.cpp - Clang GCC Compatible Driver -----------------------*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Driver/Driver.h"
11
12#include "clang/Driver/Action.h"
13#include "clang/Driver/Arg.h"
14#include "clang/Driver/ArgList.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/DriverDiagnostic.h"
17#include "clang/Driver/HostInfo.h"
18#include "clang/Driver/Job.h"
19#include "clang/Driver/OptTable.h"
20#include "clang/Driver/Option.h"
21#include "clang/Driver/Options.h"
22#include "clang/Driver/Tool.h"
23#include "clang/Driver/ToolChain.h"
24#include "clang/Driver/Types.h"
25
26#include "clang/Basic/Version.h"
27
28#include "llvm/ADT/StringSet.h"
29#include "llvm/ADT/OwningPtr.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/System/Path.h"
33#include "llvm/System/Program.h"
34
35#include "InputInfo.h"
36
37#include <map>
38
39using namespace clang::driver;
40using namespace clang;
41
42// Used to set values for "production" clang, for releases.
43// #define USE_PRODUCTION_CLANG
44
45Driver::Driver(llvm::StringRef _Name, llvm::StringRef _Dir,
46               llvm::StringRef _DefaultHostTriple,
47               llvm::StringRef _DefaultImageName,
48               bool IsProduction, bool CXXIsProduction,
49               Diagnostic &_Diags)
50  : Opts(createDriverOptTable()), Diags(_Diags),
51    Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
52    DefaultImageName(_DefaultImageName),
53    DriverTitle("clang \"gcc-compatible\" driver"),
54    Host(0),
55    CCCGenericGCCName("gcc"), CCPrintOptionsFilename(0), CCCIsCXX(false),
56    CCCEcho(false), CCCPrintBindings(false), CCPrintOptions(false),
57    CheckInputsExist(true), CCCUseClang(true), CCCUseClangCXX(true),
58    CCCUseClangCPP(true), CCCUsePCH(true), SuppressMissingInputWarning(false) {
59  if (IsProduction) {
60    // In a "production" build, only use clang on architectures we expect to
61    // work, and don't use clang C++.
62    //
63    // During development its more convenient to always have the driver use
64    // clang, but we don't want users to be confused when things don't work, or
65    // to file bugs for things we don't support.
66    CCCClangArchs.insert(llvm::Triple::x86);
67    CCCClangArchs.insert(llvm::Triple::x86_64);
68    CCCClangArchs.insert(llvm::Triple::arm);
69
70    if (!CXXIsProduction)
71      CCCUseClangCXX = false;
72  }
73
74  // Compute the path to the resource directory.
75  llvm::sys::Path P(Dir);
76  P.eraseComponent(); // Remove /bin from foo/bin
77  P.appendComponent("lib");
78  P.appendComponent("clang");
79  P.appendComponent(CLANG_VERSION_STRING);
80  ResourceDir = P.str();
81}
82
83Driver::~Driver() {
84  delete Opts;
85  delete Host;
86}
87
88InputArgList *Driver::ParseArgStrings(const char **ArgBegin,
89                                      const char **ArgEnd) {
90  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
91  unsigned MissingArgIndex, MissingArgCount;
92  InputArgList *Args = getOpts().ParseArgs(ArgBegin, ArgEnd,
93                                           MissingArgIndex, MissingArgCount);
94
95  // Check for missing argument error.
96  if (MissingArgCount)
97    Diag(clang::diag::err_drv_missing_argument)
98      << Args->getArgString(MissingArgIndex) << MissingArgCount;
99
100  // Check for unsupported options.
101  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
102       it != ie; ++it) {
103    Arg *A = *it;
104    if (A->getOption().isUnsupported()) {
105      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
106      continue;
107    }
108  }
109
110  return Args;
111}
112
113DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
114  DerivedArgList *DAL = new DerivedArgList(Args);
115
116  for (ArgList::const_iterator it = Args.begin(),
117         ie = Args.end(); it != ie; ++it)
118    DAL->append(*it);
119
120  return DAL;
121}
122
123Compilation *Driver::BuildCompilation(int argc, const char **argv) {
124  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
125
126  // FIXME: Handle environment options which effect driver behavior, somewhere
127  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
128  // CC_PRINT_OPTIONS.
129
130  // FIXME: What are we going to do with -V and -b?
131
132  // FIXME: This stuff needs to go into the Compilation, not the driver.
133  bool CCCPrintOptions = false, CCCPrintActions = false;
134
135  const char **Start = argv + 1, **End = argv + argc;
136  const char *HostTriple = DefaultHostTriple.c_str();
137
138  InputArgList *Args = ParseArgStrings(Start, End);
139
140  // -no-canonical-prefixes is used very early in main.
141  Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
142
143  // Extract -ccc args.
144  //
145  // FIXME: We need to figure out where this behavior should live. Most of it
146  // should be outside in the client; the parts that aren't should have proper
147  // options, either by introducing new ones or by overloading gcc ones like -V
148  // or -b.
149  CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options);
150  CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
151  CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
152  CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX;
153  CCCEcho = Args->hasArg(options::OPT_ccc_echo);
154  if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
155    CCCGenericGCCName = A->getValue(*Args);
156  CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx,
157                                 options::OPT_ccc_no_clang_cxx,
158                                 CCCUseClangCXX);
159  CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
160                            options::OPT_ccc_pch_is_pth);
161  CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang);
162  CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp);
163  if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) {
164    llvm::StringRef Cur = A->getValue(*Args);
165
166    CCCClangArchs.clear();
167    while (!Cur.empty()) {
168      std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
169
170      if (!Split.first.empty()) {
171        llvm::Triple::ArchType Arch =
172          llvm::Triple(Split.first, "", "").getArch();
173
174        if (Arch == llvm::Triple::UnknownArch)
175          Diag(clang::diag::err_drv_invalid_arch_name) << Split.first;
176
177        CCCClangArchs.insert(Arch);
178      }
179
180      Cur = Split.second;
181    }
182  }
183  if (const Arg *A = Args->getLastArg(options::OPT_ccc_host_triple))
184    HostTriple = A->getValue(*Args);
185  if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
186    Dir = A->getValue(*Args);
187  if (const Arg *A = Args->getLastArg(options::OPT_B))
188    PrefixDir = A->getValue(*Args);
189
190  Host = GetHostInfo(HostTriple);
191
192  // Perform the default argument translations.
193  DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
194
195  // The compilation takes ownership of Args.
196  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args,
197                                   TranslatedArgs);
198
199  // FIXME: This behavior shouldn't be here.
200  if (CCCPrintOptions) {
201    PrintOptions(C->getInputArgs());
202    return C;
203  }
204
205  if (!HandleImmediateArgs(*C))
206    return C;
207
208  // Construct the list of abstract actions to perform for this compilation. We
209  // avoid passing a Compilation here simply to enforce the abstraction that
210  // pipelining is not host or toolchain dependent (other than the driver driver
211  // test).
212  if (Host->useDriverDriver())
213    BuildUniversalActions(C->getArgs(), C->getActions());
214  else
215    BuildActions(C->getArgs(), C->getActions());
216
217  if (CCCPrintActions) {
218    PrintActions(*C);
219    return C;
220  }
221
222  BuildJobs(*C);
223
224  return C;
225}
226
227int Driver::ExecuteCompilation(const Compilation &C) const {
228  // Just print if -### was present.
229  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
230    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
231    return 0;
232  }
233
234  // If there were errors building the compilation, quit now.
235  if (getDiags().getNumErrors())
236    return 1;
237
238  const Command *FailingCommand = 0;
239  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
240
241  // Remove temp files.
242  C.CleanupFileList(C.getTempFiles());
243
244  // If the command succeeded, we are done.
245  if (Res == 0)
246    return Res;
247
248  // Otherwise, remove result files as well.
249  if (!C.getArgs().hasArg(options::OPT_save_temps))
250    C.CleanupFileList(C.getResultFiles(), true);
251
252  // Print extra information about abnormal failures, if possible.
253  //
254  // This is ad-hoc, but we don't want to be excessively noisy. If the result
255  // status was 1, assume the command failed normally. In particular, if it was
256  // the compiler then assume it gave a reasonable error code. Failures in other
257  // tools are less common, and they generally have worse diagnostics, so always
258  // print the diagnostic there.
259  const Tool &FailingTool = FailingCommand->getCreator();
260
261  if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
262    // FIXME: See FIXME above regarding result code interpretation.
263    if (Res < 0)
264      Diag(clang::diag::err_drv_command_signalled)
265        << FailingTool.getShortName() << -Res;
266    else
267      Diag(clang::diag::err_drv_command_failed)
268        << FailingTool.getShortName() << Res;
269  }
270
271  return Res;
272}
273
274void Driver::PrintOptions(const ArgList &Args) const {
275  unsigned i = 0;
276  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
277       it != ie; ++it, ++i) {
278    Arg *A = *it;
279    llvm::errs() << "Option " << i << " - "
280                 << "Name: \"" << A->getOption().getName() << "\", "
281                 << "Values: {";
282    for (unsigned j = 0; j < A->getNumValues(); ++j) {
283      if (j)
284        llvm::errs() << ", ";
285      llvm::errs() << '"' << A->getValue(Args, j) << '"';
286    }
287    llvm::errs() << "}\n";
288  }
289}
290
291void Driver::PrintHelp(bool ShowHidden) const {
292  getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
293                      ShowHidden);
294}
295
296void Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
297  // FIXME: The following handlers should use a callback mechanism, we don't
298  // know what the client would like to do.
299  OS << getClangFullVersion() << '\n';
300  const ToolChain &TC = C.getDefaultToolChain();
301  OS << "Target: " << TC.getTripleString() << '\n';
302
303  // Print the threading model.
304  //
305  // FIXME: Implement correctly.
306  OS << "Thread model: " << "posix" << '\n';
307}
308
309/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
310/// option.
311static void PrintDiagnosticCategories(llvm::raw_ostream &OS) {
312  for (unsigned i = 1; // Skip the empty category.
313       const char *CategoryName = Diagnostic::getCategoryNameFromID(i); ++i)
314    OS << i << ',' << CategoryName << '\n';
315}
316
317bool Driver::HandleImmediateArgs(const Compilation &C) {
318  // The order these options are handled in gcc is all over the place, but we
319  // don't expect inconsistencies w.r.t. that to matter in practice.
320
321  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
322    llvm::outs() << CLANG_VERSION_STRING "\n";
323    return false;
324  }
325
326  if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
327    PrintDiagnosticCategories(llvm::outs());
328    return false;
329  }
330
331  if (C.getArgs().hasArg(options::OPT__help) ||
332      C.getArgs().hasArg(options::OPT__help_hidden)) {
333    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
334    return false;
335  }
336
337  if (C.getArgs().hasArg(options::OPT__version)) {
338    // Follow gcc behavior and use stdout for --version and stderr for -v.
339    PrintVersion(C, llvm::outs());
340    return false;
341  }
342
343  if (C.getArgs().hasArg(options::OPT_v) ||
344      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
345    PrintVersion(C, llvm::errs());
346    SuppressMissingInputWarning = true;
347  }
348
349  const ToolChain &TC = C.getDefaultToolChain();
350  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
351    llvm::outs() << "programs: =";
352    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
353           ie = TC.getProgramPaths().end(); it != ie; ++it) {
354      if (it != TC.getProgramPaths().begin())
355        llvm::outs() << ':';
356      llvm::outs() << *it;
357    }
358    llvm::outs() << "\n";
359    llvm::outs() << "libraries: =";
360    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
361           ie = TC.getFilePaths().end(); it != ie; ++it) {
362      if (it != TC.getFilePaths().begin())
363        llvm::outs() << ':';
364      llvm::outs() << *it;
365    }
366    llvm::outs() << "\n";
367    return false;
368  }
369
370  // FIXME: The following handlers should use a callback mechanism, we don't
371  // know what the client would like to do.
372  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
373    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
374    return false;
375  }
376
377  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
378    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
379    return false;
380  }
381
382  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
383    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
384    return false;
385  }
386
387  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
388    // FIXME: We need tool chain support for this.
389    llvm::outs() << ".;\n";
390
391    switch (C.getDefaultToolChain().getTriple().getArch()) {
392    default:
393      break;
394
395    case llvm::Triple::x86_64:
396      llvm::outs() << "x86_64;@m64" << "\n";
397      break;
398
399    case llvm::Triple::ppc64:
400      llvm::outs() << "ppc64;@m64" << "\n";
401      break;
402    }
403    return false;
404  }
405
406  // FIXME: What is the difference between print-multi-directory and
407  // print-multi-os-directory?
408  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
409      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
410    switch (C.getDefaultToolChain().getTriple().getArch()) {
411    default:
412    case llvm::Triple::x86:
413    case llvm::Triple::ppc:
414      llvm::outs() << "." << "\n";
415      break;
416
417    case llvm::Triple::x86_64:
418      llvm::outs() << "x86_64" << "\n";
419      break;
420
421    case llvm::Triple::ppc64:
422      llvm::outs() << "ppc64" << "\n";
423      break;
424    }
425    return false;
426  }
427
428  return true;
429}
430
431static unsigned PrintActions1(const Compilation &C, Action *A,
432                              std::map<Action*, unsigned> &Ids) {
433  if (Ids.count(A))
434    return Ids[A];
435
436  std::string str;
437  llvm::raw_string_ostream os(str);
438
439  os << Action::getClassName(A->getKind()) << ", ";
440  if (InputAction *IA = dyn_cast<InputAction>(A)) {
441    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
442  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
443    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
444                  C.getDefaultToolChain().getArchName()) << '"'
445       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
446  } else {
447    os << "{";
448    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
449      os << PrintActions1(C, *it, Ids);
450      ++it;
451      if (it != ie)
452        os << ", ";
453    }
454    os << "}";
455  }
456
457  unsigned Id = Ids.size();
458  Ids[A] = Id;
459  llvm::errs() << Id << ": " << os.str() << ", "
460               << types::getTypeName(A->getType()) << "\n";
461
462  return Id;
463}
464
465void Driver::PrintActions(const Compilation &C) const {
466  std::map<Action*, unsigned> Ids;
467  for (ActionList::const_iterator it = C.getActions().begin(),
468         ie = C.getActions().end(); it != ie; ++it)
469    PrintActions1(C, *it, Ids);
470}
471
472void Driver::BuildUniversalActions(const ArgList &Args,
473                                   ActionList &Actions) const {
474  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
475  // Collect the list of architectures. Duplicates are allowed, but should only
476  // be handled once (in the order seen).
477  llvm::StringSet<> ArchNames;
478  llvm::SmallVector<const char *, 4> Archs;
479  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
480       it != ie; ++it) {
481    Arg *A = *it;
482
483    if (A->getOption().matches(options::OPT_arch)) {
484      // Validate the option here; we don't save the type here because its
485      // particular spelling may participate in other driver choices.
486      llvm::Triple::ArchType Arch =
487        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
488      if (Arch == llvm::Triple::UnknownArch) {
489        Diag(clang::diag::err_drv_invalid_arch_name)
490          << A->getAsString(Args);
491        continue;
492      }
493
494      A->claim();
495      if (ArchNames.insert(A->getValue(Args)))
496        Archs.push_back(A->getValue(Args));
497    }
498  }
499
500  // When there is no explicit arch for this platform, make sure we still bind
501  // the architecture (to the default) so that -Xarch_ is handled correctly.
502  if (!Archs.size())
503    Archs.push_back(0);
504
505  // FIXME: We killed off some others but these aren't yet detected in a
506  // functional manner. If we added information to jobs about which "auxiliary"
507  // files they wrote then we could detect the conflict these cause downstream.
508  if (Archs.size() > 1) {
509    // No recovery needed, the point of this is just to prevent
510    // overwriting the same files.
511    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
512      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
513        << A->getAsString(Args);
514  }
515
516  ActionList SingleActions;
517  BuildActions(Args, SingleActions);
518
519  // Add in arch bindings for every top level action, as well as lipo and
520  // dsymutil steps if needed.
521  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
522    Action *Act = SingleActions[i];
523
524    // Make sure we can lipo this kind of output. If not (and it is an actual
525    // output) then we disallow, since we can't create an output file with the
526    // right name without overwriting it. We could remove this oddity by just
527    // changing the output names to include the arch, which would also fix
528    // -save-temps. Compatibility wins for now.
529
530    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
531      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
532        << types::getTypeName(Act->getType());
533
534    ActionList Inputs;
535    for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
536      Inputs.push_back(new BindArchAction(Act, Archs[i]));
537      if (i != 0)
538        Inputs.back()->setOwnsInputs(false);
539    }
540
541    // Lipo if necessary, we do it this way because we need to set the arch flag
542    // so that -Xarch_ gets overwritten.
543    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
544      Actions.append(Inputs.begin(), Inputs.end());
545    else
546      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
547
548    // Add a 'dsymutil' step if necessary.
549    if (Act->getType() == types::TY_Image) {
550      Arg *A = Args.getLastArg(options::OPT_g_Group);
551      if (A && !A->getOption().matches(options::OPT_g0) &&
552          !A->getOption().matches(options::OPT_gstabs)) {
553        ActionList Inputs;
554        Inputs.push_back(Actions.back());
555        Actions.pop_back();
556
557        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
558      }
559    }
560  }
561}
562
563void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
564  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
565  // Start by constructing the list of inputs and their types.
566
567  // Track the current user specified (-x) input. We also explicitly track the
568  // argument used to set the type; we only want to claim the type when we
569  // actually use it, so we warn about unused -x arguments.
570  types::ID InputType = types::TY_Nothing;
571  Arg *InputTypeArg = 0;
572
573  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
574  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
575       it != ie; ++it) {
576    Arg *A = *it;
577
578    if (isa<InputOption>(A->getOption())) {
579      const char *Value = A->getValue(Args);
580      types::ID Ty = types::TY_INVALID;
581
582      // Infer the input type if necessary.
583      if (InputType == types::TY_Nothing) {
584        // If there was an explicit arg for this, claim it.
585        if (InputTypeArg)
586          InputTypeArg->claim();
587
588        // stdin must be handled specially.
589        if (memcmp(Value, "-", 2) == 0) {
590          // If running with -E, treat as a C input (this changes the builtin
591          // macros, for example). This may be overridden by -ObjC below.
592          //
593          // Otherwise emit an error but still use a valid type to avoid
594          // spurious errors (e.g., no inputs).
595          if (!Args.hasArgNoClaim(options::OPT_E))
596            Diag(clang::diag::err_drv_unknown_stdin_type);
597          Ty = types::TY_C;
598        } else {
599          // Otherwise lookup by extension, and fallback to ObjectType if not
600          // found. We use a host hook here because Darwin at least has its own
601          // idea of what .s is.
602          if (const char *Ext = strrchr(Value, '.'))
603            Ty = Host->lookupTypeForExtension(Ext + 1);
604
605          if (Ty == types::TY_INVALID)
606            Ty = types::TY_Object;
607
608          // If the driver is invoked as C++ compiler (like clang++ or c++) it
609          // should autodetect some input files as C++ for g++ compatibility.
610          if (CCCIsCXX) {
611            types::ID OldTy = Ty;
612            Ty = types::lookupCXXTypeForCType(Ty);
613
614            if (Ty != OldTy)
615              Diag(clang::diag::warn_drv_treating_input_as_cxx)
616                << getTypeName(OldTy) << getTypeName(Ty);
617          }
618        }
619
620        // -ObjC and -ObjC++ override the default language, but only for "source
621        // files". We just treat everything that isn't a linker input as a
622        // source file.
623        //
624        // FIXME: Clean this up if we move the phase sequence into the type.
625        if (Ty != types::TY_Object) {
626          if (Args.hasArg(options::OPT_ObjC))
627            Ty = types::TY_ObjC;
628          else if (Args.hasArg(options::OPT_ObjCXX))
629            Ty = types::TY_ObjCXX;
630        }
631      } else {
632        assert(InputTypeArg && "InputType set w/o InputTypeArg");
633        InputTypeArg->claim();
634        Ty = InputType;
635      }
636
637      // Check that the file exists, if enabled.
638      if (CheckInputsExist && memcmp(Value, "-", 2) != 0 &&
639          !llvm::sys::Path(Value).exists())
640        Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
641      else
642        Inputs.push_back(std::make_pair(Ty, A));
643
644    } else if (A->getOption().isLinkerInput()) {
645      // Just treat as object type, we could make a special type for this if
646      // necessary.
647      Inputs.push_back(std::make_pair(types::TY_Object, A));
648
649    } else if (A->getOption().matches(options::OPT_x)) {
650      InputTypeArg = A;
651      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
652
653      // Follow gcc behavior and treat as linker input for invalid -x
654      // options. Its not clear why we shouldn't just revert to unknown; but
655      // this isn't very important, we might as well be bug comatible.
656      if (!InputType) {
657        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
658        InputType = types::TY_Object;
659      }
660    }
661  }
662
663  if (!SuppressMissingInputWarning && Inputs.empty()) {
664    Diag(clang::diag::err_drv_no_input_files);
665    return;
666  }
667
668  // Determine which compilation mode we are in. We look for options which
669  // affect the phase, starting with the earliest phases, and record which
670  // option we used to determine the final phase.
671  Arg *FinalPhaseArg = 0;
672  phases::ID FinalPhase;
673
674  // -{E,M,MM} only run the preprocessor.
675  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
676      (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
677      (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
678    FinalPhase = phases::Preprocess;
679
680    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
681  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
682             (FinalPhaseArg = Args.getLastArg(options::OPT_rewrite_objc)) ||
683             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
684                                              options::OPT__analyze_auto)) ||
685             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
686             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
687    FinalPhase = phases::Compile;
688
689    // -c only runs up to the assembler.
690  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
691    FinalPhase = phases::Assemble;
692
693    // Otherwise do everything.
694  } else
695    FinalPhase = phases::Link;
696
697  // Reject -Z* at the top level, these options should never have been exposed
698  // by gcc.
699  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
700    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
701
702  // Construct the actions to perform.
703  ActionList LinkerInputs;
704  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
705    types::ID InputType = Inputs[i].first;
706    const Arg *InputArg = Inputs[i].second;
707
708    unsigned NumSteps = types::getNumCompilationPhases(InputType);
709    assert(NumSteps && "Invalid number of steps!");
710
711    // If the first step comes after the final phase we are doing as part of
712    // this compilation, warn the user about it.
713    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
714    if (InitialPhase > FinalPhase) {
715      // Claim here to avoid the more general unused warning.
716      InputArg->claim();
717
718      // Special case '-E' warning on a previously preprocessed file to make
719      // more sense.
720      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
721          getPreprocessedType(InputType) == types::TY_INVALID)
722        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
723          << InputArg->getAsString(Args)
724          << FinalPhaseArg->getOption().getName();
725      else
726        Diag(clang::diag::warn_drv_input_file_unused)
727          << InputArg->getAsString(Args)
728          << getPhaseName(InitialPhase)
729          << FinalPhaseArg->getOption().getName();
730      continue;
731    }
732
733    // Build the pipeline for this file.
734    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
735    for (unsigned i = 0; i != NumSteps; ++i) {
736      phases::ID Phase = types::getCompilationPhase(InputType, i);
737
738      // We are done if this step is past what the user requested.
739      if (Phase > FinalPhase)
740        break;
741
742      // Queue linker inputs.
743      if (Phase == phases::Link) {
744        assert(i + 1 == NumSteps && "linking must be final compilation step.");
745        LinkerInputs.push_back(Current.take());
746        break;
747      }
748
749      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
750      // encode this in the steps because the intermediate type depends on
751      // arguments. Just special case here.
752      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
753        continue;
754
755      // Otherwise construct the appropriate action.
756      Current.reset(ConstructPhaseAction(Args, Phase, Current.take()));
757      if (Current->getType() == types::TY_Nothing)
758        break;
759    }
760
761    // If we ended with something, add to the output list.
762    if (Current)
763      Actions.push_back(Current.take());
764  }
765
766  // Add a link action if necessary.
767  if (!LinkerInputs.empty())
768    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
769
770  // If we are linking, claim any options which are obviously only used for
771  // compilation.
772  if (FinalPhase == phases::Link)
773    Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
774}
775
776Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
777                                     Action *Input) const {
778  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
779  // Build the appropriate action.
780  switch (Phase) {
781  case phases::Link: assert(0 && "link action invalid here.");
782  case phases::Preprocess: {
783    types::ID OutputTy;
784    // -{M, MM} alter the output type.
785    if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
786      OutputTy = types::TY_Dependencies;
787    } else {
788      OutputTy = types::getPreprocessedType(Input->getType());
789      assert(OutputTy != types::TY_INVALID &&
790             "Cannot preprocess this input type!");
791    }
792    return new PreprocessJobAction(Input, OutputTy);
793  }
794  case phases::Precompile:
795    return new PrecompileJobAction(Input, types::TY_PCH);
796  case phases::Compile: {
797    bool HasO4 = false;
798    if (const Arg *A = Args.getLastArg(options::OPT_O_Group))
799      HasO4 = A->getOption().matches(options::OPT_O4);
800
801    if (Args.hasArg(options::OPT_fsyntax_only)) {
802      return new CompileJobAction(Input, types::TY_Nothing);
803    } else if (Args.hasArg(options::OPT_rewrite_objc)) {
804      return new CompileJobAction(Input, types::TY_RewrittenObjC);
805    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
806      return new AnalyzeJobAction(Input, types::TY_Plist);
807    } else if (Args.hasArg(options::OPT_emit_ast)) {
808      return new CompileJobAction(Input, types::TY_AST);
809    } else if (Args.hasArg(options::OPT_emit_llvm) ||
810               Args.hasArg(options::OPT_flto) || HasO4) {
811      types::ID Output =
812        Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
813      return new CompileJobAction(Input, Output);
814    } else {
815      return new CompileJobAction(Input, types::TY_PP_Asm);
816    }
817  }
818  case phases::Assemble:
819    return new AssembleJobAction(Input, types::TY_Object);
820  }
821
822  assert(0 && "invalid phase in ConstructPhaseAction");
823  return 0;
824}
825
826void Driver::BuildJobs(Compilation &C) const {
827  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
828  bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
829  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
830
831  // FIXME: Pipes are forcibly disabled until we support executing them.
832  if (!CCCPrintBindings)
833    UsePipes = false;
834
835  // -save-temps inhibits pipes.
836  if (SaveTemps && UsePipes)
837    Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
838
839  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
840
841  // It is an error to provide a -o option if we are making multiple output
842  // files.
843  if (FinalOutput) {
844    unsigned NumOutputs = 0;
845    for (ActionList::const_iterator it = C.getActions().begin(),
846           ie = C.getActions().end(); it != ie; ++it)
847      if ((*it)->getType() != types::TY_Nothing)
848        ++NumOutputs;
849
850    if (NumOutputs > 1) {
851      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
852      FinalOutput = 0;
853    }
854  }
855
856  for (ActionList::const_iterator it = C.getActions().begin(),
857         ie = C.getActions().end(); it != ie; ++it) {
858    Action *A = *it;
859
860    // If we are linking an image for multiple archs then the linker wants
861    // -arch_multiple and -final_output <final image name>. Unfortunately, this
862    // doesn't fit in cleanly because we have to pass this information down.
863    //
864    // FIXME: This is a hack; find a cleaner way to integrate this into the
865    // process.
866    const char *LinkingOutput = 0;
867    if (isa<LipoJobAction>(A)) {
868      if (FinalOutput)
869        LinkingOutput = FinalOutput->getValue(C.getArgs());
870      else
871        LinkingOutput = DefaultImageName.c_str();
872    }
873
874    InputInfo II;
875    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
876                       /*BoundArch*/0,
877                       /*CanAcceptPipe*/ true,
878                       /*AtTopLevel*/ true,
879                       /*LinkingOutput*/ LinkingOutput,
880                       II);
881  }
882
883  // If the user passed -Qunused-arguments or there were errors, don't warn
884  // about any unused arguments.
885  if (Diags.getNumErrors() ||
886      C.getArgs().hasArg(options::OPT_Qunused_arguments))
887    return;
888
889  // Claim -### here.
890  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
891
892  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
893       it != ie; ++it) {
894    Arg *A = *it;
895
896    // FIXME: It would be nice to be able to send the argument to the
897    // Diagnostic, so that extra values, position, and so on could be printed.
898    if (!A->isClaimed()) {
899      if (A->getOption().hasNoArgumentUnused())
900        continue;
901
902      // Suppress the warning automatically if this is just a flag, and it is an
903      // instance of an argument we already claimed.
904      const Option &Opt = A->getOption();
905      if (isa<FlagOption>(Opt)) {
906        bool DuplicateClaimed = false;
907
908        for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
909               ie = C.getArgs().filtered_end(); it != ie; ++it) {
910          if ((*it)->isClaimed()) {
911            DuplicateClaimed = true;
912            break;
913          }
914        }
915
916        if (DuplicateClaimed)
917          continue;
918      }
919
920      Diag(clang::diag::warn_drv_unused_argument)
921        << A->getAsString(C.getArgs());
922    }
923  }
924}
925
926static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC,
927                                    const JobAction *JA,
928                                    const ActionList *&Inputs) {
929  const Tool *ToolForJob = 0;
930
931  // See if we should look for a compiler with an integrated assembler. We match
932  // bottom up, so what we are actually looking for is an assembler job with a
933  // compiler input.
934
935  // FIXME: This doesn't belong here, but ideally we will support static soon
936  // anyway.
937  bool HasStatic = (C.getArgs().hasArg(options::OPT_mkernel) ||
938                    C.getArgs().hasArg(options::OPT_static) ||
939                    C.getArgs().hasArg(options::OPT_fapple_kext));
940  bool IsIADefault = (TC->IsIntegratedAssemblerDefault() && !HasStatic);
941  if (C.getArgs().hasFlag(options::OPT_integrated_as,
942                         options::OPT_no_integrated_as,
943                         IsIADefault) &&
944      !C.getArgs().hasArg(options::OPT_save_temps) &&
945      isa<AssembleJobAction>(JA) &&
946      Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
947    const Tool &Compiler = TC->SelectTool(C,cast<JobAction>(**Inputs->begin()));
948    if (Compiler.hasIntegratedAssembler()) {
949      Inputs = &(*Inputs)[0]->getInputs();
950      ToolForJob = &Compiler;
951    }
952  }
953
954  // Otherwise use the tool for the current job.
955  if (!ToolForJob)
956    ToolForJob = &TC->SelectTool(C, *JA);
957
958  // See if we should use an integrated preprocessor. We do so when we have
959  // exactly one input, since this is the only use case we care about
960  // (irrelevant since we don't support combine yet).
961  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
962      !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
963      !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
964      !C.getArgs().hasArg(options::OPT_save_temps) &&
965      ToolForJob->hasIntegratedCPP())
966    Inputs = &(*Inputs)[0]->getInputs();
967
968  return *ToolForJob;
969}
970
971void Driver::BuildJobsForAction(Compilation &C,
972                                const Action *A,
973                                const ToolChain *TC,
974                                const char *BoundArch,
975                                bool CanAcceptPipe,
976                                bool AtTopLevel,
977                                const char *LinkingOutput,
978                                InputInfo &Result) const {
979  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
980
981  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
982  // FIXME: Pipes are forcibly disabled until we support executing them.
983  if (!CCCPrintBindings)
984    UsePipes = false;
985
986  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
987    // FIXME: It would be nice to not claim this here; maybe the old scheme of
988    // just using Args was better?
989    const Arg &Input = IA->getInputArg();
990    Input.claim();
991    if (Input.getOption().matches(options::OPT_INPUT)) {
992      const char *Name = Input.getValue(C.getArgs());
993      Result = InputInfo(Name, A->getType(), Name);
994    } else
995      Result = InputInfo(&Input, A->getType(), "");
996    return;
997  }
998
999  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1000    const ToolChain *TC = &C.getDefaultToolChain();
1001
1002    std::string Arch;
1003    if (BAA->getArchName())
1004      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1005
1006    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1007                       CanAcceptPipe, AtTopLevel, LinkingOutput, Result);
1008    return;
1009  }
1010
1011  const ActionList *Inputs = &A->getInputs();
1012
1013  const JobAction *JA = cast<JobAction>(A);
1014  const Tool &T = SelectToolForJob(C, TC, JA, Inputs);
1015
1016  // Only use pipes when there is exactly one input.
1017  bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
1018  InputInfoList InputInfos;
1019  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1020       it != ie; ++it) {
1021    // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1022    // temporary output names.
1023    //
1024    // FIXME: Clean this up.
1025    bool SubJobAtTopLevel = false;
1026    if (AtTopLevel && isa<DsymutilJobAction>(A))
1027      SubJobAtTopLevel = true;
1028
1029    InputInfo II;
1030    BuildJobsForAction(C, *it, TC, BoundArch, TryToUsePipeInput,
1031                       SubJobAtTopLevel, LinkingOutput, II);
1032    InputInfos.push_back(II);
1033  }
1034
1035  // Determine if we should output to a pipe.
1036  bool OutputToPipe = false;
1037  if (CanAcceptPipe && T.canPipeOutput()) {
1038    // Some actions default to writing to a pipe if they are the top level phase
1039    // and there was no user override.
1040    //
1041    // FIXME: Is there a better way to handle this?
1042    if (AtTopLevel) {
1043      if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
1044        OutputToPipe = true;
1045    } else if (UsePipes)
1046      OutputToPipe = true;
1047  }
1048
1049  // Figure out where to put the job (pipes).
1050  Job *Dest = &C.getJobs();
1051  if (InputInfos[0].isPipe()) {
1052    assert(TryToUsePipeInput && "Unrequested pipe!");
1053    assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
1054    Dest = &InputInfos[0].getPipe();
1055  }
1056
1057  // Always use the first input as the base input.
1058  const char *BaseInput = InputInfos[0].getBaseInput();
1059
1060  // ... except dsymutil actions, which use their actual input as the base
1061  // input.
1062  if (JA->getType() == types::TY_dSYM)
1063    BaseInput = InputInfos[0].getFilename();
1064
1065  // Determine the place to write output to (nothing, pipe, or filename) and
1066  // where to put the new job.
1067  if (JA->getType() == types::TY_Nothing) {
1068    Result = InputInfo(A->getType(), BaseInput);
1069  } else if (OutputToPipe) {
1070    // Append to current piped job or create a new one as appropriate.
1071    PipedJob *PJ = dyn_cast<PipedJob>(Dest);
1072    if (!PJ) {
1073      PJ = new PipedJob();
1074      // FIXME: Temporary hack so that -ccc-print-bindings work until we have
1075      // pipe support. Please remove later.
1076      if (!CCCPrintBindings)
1077        cast<JobList>(Dest)->addJob(PJ);
1078      Dest = PJ;
1079    }
1080    Result = InputInfo(PJ, A->getType(), BaseInput);
1081  } else {
1082    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1083                       A->getType(), BaseInput);
1084  }
1085
1086  if (CCCPrintBindings) {
1087    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1088                 << " - \"" << T.getName() << "\", inputs: [";
1089    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1090      llvm::errs() << InputInfos[i].getAsString();
1091      if (i + 1 != e)
1092        llvm::errs() << ", ";
1093    }
1094    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1095  } else {
1096    T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
1097                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1098  }
1099}
1100
1101const char *Driver::GetNamedOutputPath(Compilation &C,
1102                                       const JobAction &JA,
1103                                       const char *BaseInput,
1104                                       bool AtTopLevel) const {
1105  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1106  // Output to a user requested destination?
1107  if (AtTopLevel && !isa<DsymutilJobAction>(JA)) {
1108    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1109      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1110  }
1111
1112  // Output to a temporary file?
1113  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1114    std::string TmpName =
1115      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1116    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1117  }
1118
1119  llvm::sys::Path BasePath(BaseInput);
1120  std::string BaseName(BasePath.getLast());
1121
1122  // Determine what the derived output name should be.
1123  const char *NamedOutput;
1124  if (JA.getType() == types::TY_Image) {
1125    NamedOutput = DefaultImageName.c_str();
1126  } else {
1127    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1128    assert(Suffix && "All types used for output should have a suffix.");
1129
1130    std::string::size_type End = std::string::npos;
1131    if (!types::appendSuffixForType(JA.getType()))
1132      End = BaseName.rfind('.');
1133    std::string Suffixed(BaseName.substr(0, End));
1134    Suffixed += '.';
1135    Suffixed += Suffix;
1136    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1137  }
1138
1139  // As an annoying special case, PCH generation doesn't strip the pathname.
1140  if (JA.getType() == types::TY_PCH) {
1141    BasePath.eraseComponent();
1142    if (BasePath.isEmpty())
1143      BasePath = NamedOutput;
1144    else
1145      BasePath.appendComponent(NamedOutput);
1146    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1147  } else {
1148    return C.addResultFile(NamedOutput);
1149  }
1150}
1151
1152std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1153  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1154  // attempting to use this prefix when lokup up program paths.
1155  if (!PrefixDir.empty()) {
1156    llvm::sys::Path P(PrefixDir);
1157    P.appendComponent(Name);
1158    if (P.exists())
1159      return P.str();
1160  }
1161
1162  const ToolChain::path_list &List = TC.getFilePaths();
1163  for (ToolChain::path_list::const_iterator
1164         it = List.begin(), ie = List.end(); it != ie; ++it) {
1165    llvm::sys::Path P(*it);
1166    P.appendComponent(Name);
1167    if (P.exists())
1168      return P.str();
1169  }
1170
1171  return Name;
1172}
1173
1174std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1175                                   bool WantFile) const {
1176  // Respect a limited subset of the '-Bprefix' functionality in GCC by
1177  // attempting to use this prefix when lokup up program paths.
1178  if (!PrefixDir.empty()) {
1179    llvm::sys::Path P(PrefixDir);
1180    P.appendComponent(Name);
1181    if (WantFile ? P.exists() : P.canExecute())
1182      return P.str();
1183  }
1184
1185  const ToolChain::path_list &List = TC.getProgramPaths();
1186  for (ToolChain::path_list::const_iterator
1187         it = List.begin(), ie = List.end(); it != ie; ++it) {
1188    llvm::sys::Path P(*it);
1189    P.appendComponent(Name);
1190    if (WantFile ? P.exists() : P.canExecute())
1191      return P.str();
1192  }
1193
1194  // If all else failed, search the path.
1195  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1196  if (!P.empty())
1197    return P.str();
1198
1199  return Name;
1200}
1201
1202std::string Driver::GetTemporaryPath(const char *Suffix) const {
1203  // FIXME: This is lame; sys::Path should provide this function (in particular,
1204  // it should know how to find the temporary files dir).
1205  std::string Error;
1206  const char *TmpDir = ::getenv("TMPDIR");
1207  if (!TmpDir)
1208    TmpDir = ::getenv("TEMP");
1209  if (!TmpDir)
1210    TmpDir = ::getenv("TMP");
1211  if (!TmpDir)
1212    TmpDir = "/tmp";
1213  llvm::sys::Path P(TmpDir);
1214  P.appendComponent("cc");
1215  if (P.makeUnique(false, &Error)) {
1216    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1217    return "";
1218  }
1219
1220  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1221  P.eraseFromDisk(false, 0);
1222
1223  P.appendSuffix(Suffix);
1224  return P.str();
1225}
1226
1227const HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1228  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1229  llvm::Triple Triple(TripleStr);
1230
1231  // TCE is an osless target
1232  if (Triple.getArchName() == "tce")
1233    return createTCEHostInfo(*this, Triple);
1234
1235  switch (Triple.getOS()) {
1236  case llvm::Triple::AuroraUX:
1237    return createAuroraUXHostInfo(*this, Triple);
1238  case llvm::Triple::Darwin:
1239    return createDarwinHostInfo(*this, Triple);
1240  case llvm::Triple::DragonFly:
1241    return createDragonFlyHostInfo(*this, Triple);
1242  case llvm::Triple::OpenBSD:
1243    return createOpenBSDHostInfo(*this, Triple);
1244  case llvm::Triple::FreeBSD:
1245    return createFreeBSDHostInfo(*this, Triple);
1246  case llvm::Triple::Linux:
1247    return createLinuxHostInfo(*this, Triple);
1248  default:
1249    return createUnknownHostInfo(*this, Triple);
1250  }
1251}
1252
1253bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1254                                    const llvm::Triple &Triple) const {
1255  // Check if user requested no clang, or clang doesn't understand this type (we
1256  // only handle single inputs for now).
1257  if (!CCCUseClang || JA.size() != 1 ||
1258      !types::isAcceptedByClang((*JA.begin())->getType()))
1259    return false;
1260
1261  // Otherwise make sure this is an action clang understands.
1262  if (isa<PreprocessJobAction>(JA)) {
1263    if (!CCCUseClangCPP) {
1264      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1265      return false;
1266    }
1267  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1268    return false;
1269
1270  // Use clang for C++?
1271  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1272    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1273    return false;
1274  }
1275
1276  // Always use clang for precompiling, AST generation, and rewriting,
1277  // regardless of archs.
1278  if (isa<PrecompileJobAction>(JA) ||
1279      types::isOnlyAcceptedByClang(JA.getType()))
1280    return true;
1281
1282  // Finally, don't use clang if this isn't one of the user specified archs to
1283  // build.
1284  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1285    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1286    return false;
1287  }
1288
1289  return true;
1290}
1291
1292/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1293/// grouped values as integers. Numbers which are not provided are set to 0.
1294///
1295/// \return True if the entire string was parsed (9.2), or all groups were
1296/// parsed (10.3.5extrastuff).
1297bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1298                               unsigned &Minor, unsigned &Micro,
1299                               bool &HadExtra) {
1300  HadExtra = false;
1301
1302  Major = Minor = Micro = 0;
1303  if (*Str == '\0')
1304    return true;
1305
1306  char *End;
1307  Major = (unsigned) strtol(Str, &End, 10);
1308  if (*Str != '\0' && *End == '\0')
1309    return true;
1310  if (*End != '.')
1311    return false;
1312
1313  Str = End+1;
1314  Minor = (unsigned) strtol(Str, &End, 10);
1315  if (*Str != '\0' && *End == '\0')
1316    return true;
1317  if (*End != '.')
1318    return false;
1319
1320  Str = End+1;
1321  Micro = (unsigned) strtol(Str, &End, 10);
1322  if (*Str != '\0' && *End == '\0')
1323    return true;
1324  if (Str == End)
1325    return false;
1326  HadExtra = true;
1327  return true;
1328}
1329