Driver.cpp revision b8d1191fdeb4eec9bc5cf9bf4b027add0fb467b3
12a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===--- Driver.cpp - Clang GCC Compatible Driver -----------------------*-===//
22a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//
32a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//                     The LLVM Compiler Infrastructure
42a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//
52a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source
62a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// License. See LICENSE.TXT for details.
7a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)//
8a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)//===----------------------------------------------------------------------===//
9a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)
10a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)#include "clang/Driver/Driver.h"
112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Action.h"
132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Arg.h"
142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/ArgList.h"
152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Compilation.h"
162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/DriverDiagnostic.h"
172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/HostInfo.h"
182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Job.h"
192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Option.h"
20a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Driver/Options.h"
212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Tool.h"
222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/ToolChain.h"
232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Driver/Types.h"
242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
25a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)#include "clang/Basic/Version.h"
262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/ADT/StringSet.h"
282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/Support/PrettyStackTrace.h"
292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/Support/raw_ostream.h"
302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/System/Path.h"
312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/System/Program.h"
32a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)
332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "InputInfo.h"
342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
357dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch#include <map>
362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
37eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochusing namespace clang::driver;
382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)using namespace clang;
39c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
40c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)// Used to set values for "production" clang, for releases.
412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// #define USE_PRODUCTION_CLANG
422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)Driver::Driver(const char *_Name, const char *_Dir,
442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)               const char *_DefaultHostTriple,
452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)               const char *_DefaultImageName,
46c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch               bool IsProduction, Diagnostic &_Diags)
472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  : Opts(new OptTable()), Diags(_Diags),
482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    DefaultImageName(_DefaultImageName),
502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Host(0),
512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    CCCGenericGCCName("gcc"), CCCUseClang(true),
53a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    CCCUseClangCXX(true), CCCUseClangCPP(true), CCCUsePCH(true),
542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    SuppressMissingInputWarning(false) {
55a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  if (IsProduction) {
56a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    // In a "production" build, only use clang on architectures we expect to
572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // work, and don't use clang C++.
582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    //
59a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    // During development its more convenient to always have the driver use
60a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    // clang, but we don't want users to be confused when things don't work, or
61a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    // to file bugs for things we don't support.
62a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::x86);
632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::x86_64);
64a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    CCCClangArchs.insert(llvm::Triple::arm);
65a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)
66a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    CCCUseClangCXX = false;
67a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  }
68effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch}
69a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)
70a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)Driver::~Driver() {
712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  delete Opts;
722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  delete Host;
732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)InputArgList *Driver::ParseArgStrings(const char **ArgBegin,
762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                      const char **ArgEnd) {
772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: Handle '@' args (or at least error on them).
812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned Index = 0, End = ArgEnd - ArgBegin;
832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  while (Index < End) {
84c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    // gcc's handling of empty arguments doesn't make sense, but this is not a
852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // common use case. :)
86c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    //
872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // We just ignore them here (note that other things may still take them as
882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // arguments).
892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (Args->getArgString(Index)[0] == '\0') {
902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ++Index;
912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      continue;
922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    unsigned Prev = Index;
95a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)    Arg *A = getOpts().ParseOneArg(*Args, Index);
962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    assert(Index > Prev && "Parser failed to consume argument.");
972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Check for missing argument error.
99c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    if (!A) {
1002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      assert(Index >= End && "Unexpected parser error.");
1012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Diag(clang::diag::err_drv_missing_argument)
1022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        << Args->getArgString(Prev)
1032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        << (Index - Prev - 1);
1042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
1052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
1062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
107c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    if (A->getOption().isUnsupported()) {
1082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
1092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      continue;
1102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
1112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Args->append(A);
112a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  }
113a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
114a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  return Args;
115a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
116a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
117a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)Compilation *Driver::BuildCompilation(int argc, const char **argv) {
118a93a17c8d99d686bd4a1511e5504e5e6cc9fcadfTorne (Richard Coles)  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
1192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: Handle environment options which effect driver behavior, somewhere
121a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // (client?). GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH,
122a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // CC_PRINT_OPTIONS.
1232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: What are we going to do with -V and -b?
1252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: This stuff needs to go into the Compilation, not the driver.
1272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  bool CCCPrintOptions = false, CCCPrintActions = false;
1282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const char **Start = argv + 1, **End = argv + argc;
1302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const char *HostTriple = DefaultHostTriple.c_str();
1312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Read -ccc args.
1332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //
1342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: We need to figure out where this behavior should live. Most of it
1352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // should be outside in the client; the parts that aren't should have proper
1362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // options, either by introducing new ones or by overloading gcc ones like -V
1372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // or -b.
1382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
1392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    const char *Opt = *Start + 5;
1402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (!strcmp(Opt, "print-options")) {
1422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCPrintOptions = true;
1432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "print-phases")) {
1442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCPrintActions = true;
1452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "print-bindings")) {
1462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCPrintBindings = true;
1472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "cxx")) {
1482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCIsCXX = true;
1492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "echo")) {
1502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCEcho = true;
1512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "gcc-name")) {
1532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
1542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCGenericGCCName = *++Start;
1552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "clang-cxx")) {
1572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCUseClangCXX = true;
1582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "no-clang-cxx")) {
1592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCUseClangCXX = false;
1602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "pch-is-pch")) {
1612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCUsePCH = true;
1622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "pch-is-pth")) {
1632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCUsePCH = false;
164868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    } else if (!strcmp(Opt, "no-clang")) {
165868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      CCCUseClang = false;
1662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "no-clang-cpp")) {
1672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCUseClangCPP = false;
1682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "clang-archs")) {
1692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
1702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      llvm::StringRef Cur = *++Start;
1712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CCCClangArchs.clear();
1732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      while (!Cur.empty()) {
1742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        std::pair<llvm::StringRef, llvm::StringRef> Split = Cur.split(',');
1752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        if (!Split.first.empty()) {
1772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          llvm::Triple::ArchType Arch =
1782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)            llvm::Triple(Split.first, "", "").getArch();
1792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          if (Arch == llvm::Triple::UnknownArch) {
1817dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch            // FIXME: Error handling.
1822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)            llvm::errs() << "invalid arch name: " << Split.first << "\n";
1832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)            exit(1);
1842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          }
1852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          CCCClangArchs.insert(Arch);
1872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        }
1882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        Cur = Split.second;
1902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      }
1912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "host-triple")) {
1922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
1932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      HostTriple = *++Start;
1942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (!strcmp(Opt, "install-dir")) {
1962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
1972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Dir = *++Start;
198eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
199eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    } else {
200eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      // FIXME: Error handling.
201eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch      llvm::errs() << "invalid option: " << *Start << "\n";
2022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      exit(1);
2032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
2042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
2052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InputArgList *Args = ParseArgStrings(Start, End);
2072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Host = GetHostInfo(HostTriple);
209eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
210eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // The compilation takes ownership of Args.
211eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  Compilation *C = new Compilation(*this, *Host->CreateToolChain(*Args), Args);
212eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
213eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  // FIXME: This behavior shouldn't be here.
214eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  if (CCCPrintOptions) {
215eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    PrintOptions(C->getArgs());
216eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    return C;
217eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  }
218eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
2192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (!HandleImmediateArgs(*C))
2202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return C;
2212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Construct the list of abstract actions to perform for this compilation. We
2232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // avoid passing a Compilation here simply to enforce the abstraction that
2242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // pipelining is not host or toolchain dependent (other than the driver driver
2252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // test).
2262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Host->useDriverDriver())
2272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    BuildUniversalActions(C->getArgs(), C->getActions());
2282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  else
2292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    BuildActions(C->getArgs(), C->getActions());
2302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (CCCPrintActions) {
2322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    PrintActions(*C);
2332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return C;
2342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
2352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  BuildJobs(*C);
2372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return C;
2392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)int Driver::ExecuteCompilation(const Compilation &C) const {
2422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Just print if -### was present.
2437dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
2442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    C.PrintJob(llvm::errs(), C.getJobs(), "\n", true);
2452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 0;
2462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
2472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // If there were errors building the compilation, quit now.
2492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (getDiags().getNumErrors())
2502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 1;
2512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const Command *FailingCommand = 0;
2532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  int Res = C.ExecuteJob(C.getJobs(), FailingCommand);
2542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Remove temp files.
2562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  C.CleanupFileList(C.getTempFiles());
2572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // If the compilation failed, remove result files as well.
2592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Res != 0 && !C.getArgs().hasArg(options::OPT_save_temps))
2602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    C.CleanupFileList(C.getResultFiles(), true);
2612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Print extra information about abnormal failures, if possible.
2632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Res) {
264868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // This is ad-hoc, but we don't want to be excessively noisy. If the result
265868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // status was 1, assume the command failed normally. In particular, if it
266868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // was the compiler then assume it gave a reasonable error code. Failures in
267868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // other tools are less common, and they generally have worse diagnostics,
268868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // so always print the diagnostic there.
269868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    const Action &Source = FailingCommand->getSource();
270868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    bool IsFriendlyTool = (isa<PreprocessJobAction>(Source) ||
271868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)                           isa<PrecompileJobAction>(Source) ||
272868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)                           isa<AnalyzeJobAction>(Source) ||
2732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                           isa<CompileJobAction>(Source));
2742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
275868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    if (!IsFriendlyTool || Res != 1) {
276868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      // FIXME: See FIXME above regarding result code interpretation.
277868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      if (Res < 0)
2782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        Diag(clang::diag::err_drv_command_signalled)
2792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          << Source.getClassName() << -Res;
2802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      else
2812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        Diag(clang::diag::err_drv_command_failed)
2822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          << Source.getClassName() << Res;
2832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
2842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
2852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Res;
2872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void Driver::PrintOptions(const ArgList &Args) const {
2902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned i = 0;
2912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
2922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)       it != ie; ++it, ++i) {
2932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Arg *A = *it;
2942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    llvm::errs() << "Option " << i << " - "
2952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                 << "Name: \"" << A->getOption().getName() << "\", "
2962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                 << "Values: {";
2972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    for (unsigned j = 0; j < A->getNumValues(); ++j) {
2982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (j)
2992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        llvm::errs() << ", ";
3002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      llvm::errs() << '"' << A->getValue(Args, j) << '"';
3012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
3022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    llvm::errs() << "}\n";
3032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
3042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
3052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)static std::string getOptionHelpName(const OptTable &Opts, options::ID Id) {
3072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  std::string Name = Opts.getOptionName(Id);
3082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Add metavar, if used.
3102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  switch (Opts.getOptionKind(Id)) {
3112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
3122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    assert(0 && "Invalid option with help text.");
3132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Option::MultiArgClass: case Option::JoinedAndSeparateClass:
3152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    assert(0 && "Cannot print metavar for this kind of option.");
3162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Option::FlagClass:
3182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
3192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Option::SeparateClass: case Option::JoinedOrSeparateClass:
321eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    Name += ' ';
322eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // FALLTHROUGH
3232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Option::JoinedClass: case Option::CommaJoinedClass:
3242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Name += Opts.getOptionMetaVar(Id);
3252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
3262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
3272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Name;
3292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
330eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch
331eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochvoid Driver::PrintHelp(bool ShowHidden) const {
3322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::raw_ostream &OS = llvm::outs();
3332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OS << "OVERVIEW: clang \"gcc-compatible\" driver\n";
3352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OS << '\n';
3362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OS << "USAGE: " << Name << " [options] <input files>\n";
3372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OS << '\n';
3382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OS << "OPTIONS:\n";
3392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Render help text into (option, help) pairs.
3412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  std::vector< std::pair<std::string, const char*> > OptionHelp;
3422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
343eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) {
3442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    options::ID Id = (options::ID) i;
3452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (const char *Text = getOpts().getOptionHelpText(Id))
3462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id),
3472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                          Text));
3482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
3492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (ShowHidden) {
3512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("\nDRIVER OPTIONS:",""));
3522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-cxx",
3532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        "Act as a C++ driver"));
3542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-gcc-name",
3552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        "Name for native GCC compiler"));
3562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-clang-cxx",
3572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        "Enable the clang compiler for C++"));
3582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-no-clang-cxx",
3592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        "Disable the clang compiler for C++"));
3602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-no-clang",
3612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        "Disable the clang compiler"));
3622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-no-clang-cpp",
3632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        "Disable the clang preprocessor"));
3642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-clang-archs",
3652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        "Comma separate list of architectures "
3662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                        "to use the clang compiler for"));
3672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-pch-is-pch",
3682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                     "Use lazy PCH for precompiled headers"));
3692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-pch-is-pth",
3702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                         "Use pretokenized headers for precompiled headers"));
3712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("\nDEBUG/DEVELOPMENT OPTIONS:",""));
3732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-host-triple",
3742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                       "Simulate running on the given target"));
3752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-install-dir",
3762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                               "Simulate installation in the given directory"));
3772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OptionHelp.push_back(std::make_pair("-ccc-print-options",
378eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                                        "Dump parsed command line arguments"));
379eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    OptionHelp.push_back(std::make_pair("-ccc-print-phases",
380eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                                        "Dump list of actions to perform"));
381eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    OptionHelp.push_back(std::make_pair("-ccc-print-bindings",
382eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch                                        "Show bindings of tools to actions"));
383eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    OptionHelp.push_back(std::make_pair("CCC_ADD_ARGS",
3842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                               "(ENVIRONMENT VARIABLE) Comma separated list of "
3852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                               "arguments to prepend to the command line"));
3862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
3872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Find the maximum option length.
3892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned OptionFieldWidth = 0;
3902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
391868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // Skip titles.
3922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (!OptionHelp[i].second)
3932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      continue;
3942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
395868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    // Limit the amount of padding we are willing to give up for alignment.
3962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    unsigned Length = OptionHelp[i].first.size();
3972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (Length <= 23)
398868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      OptionFieldWidth = std::max(OptionFieldWidth, Length);
3992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
4002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
4022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    const std::string &Option = OptionHelp[i].first;
4032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OS << "  " << Option;
4042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j)
4052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      OS << ' ';
406868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    OS << ' ' << OptionHelp[i].second << '\n';
407868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  }
408868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
409868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  OS.flush();
410868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)}
411868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
4122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void Driver::PrintVersion(const Compilation &C, llvm::raw_ostream &OS) const {
4132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: The following handlers should use a callback mechanism, we don't
4142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // know what the client would like to do.
4152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OS << "clang version " CLANG_VERSION_STRING " ("
4162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)     << getClangSubversionPath();
4172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (unsigned Revision = getClangSubversionRevision())
4182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OS << " " << Revision;
4192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OS << ")" << '\n';
420
421  const ToolChain &TC = C.getDefaultToolChain();
422  OS << "Target: " << TC.getTripleString() << '\n';
423
424  // Print the threading model.
425  //
426  // FIXME: Implement correctly.
427  OS << "Thread model: " << "posix" << '\n';
428}
429
430bool Driver::HandleImmediateArgs(const Compilation &C) {
431  // The order these options are handled in in gcc is all over the place, but we
432  // don't expect inconsistencies w.r.t. that to matter in practice.
433
434  if (C.getArgs().hasArg(options::OPT_dumpversion)) {
435    llvm::outs() << CLANG_VERSION_STRING "\n";
436    return false;
437  }
438
439  if (C.getArgs().hasArg(options::OPT__help) ||
440      C.getArgs().hasArg(options::OPT__help_hidden)) {
441    PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
442    return false;
443  }
444
445  if (C.getArgs().hasArg(options::OPT__version)) {
446    // Follow gcc behavior and use stdout for --version and stderr for -v.
447    PrintVersion(C, llvm::outs());
448    return false;
449  }
450
451  if (C.getArgs().hasArg(options::OPT_v) ||
452      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
453    PrintVersion(C, llvm::errs());
454    SuppressMissingInputWarning = true;
455  }
456
457  const ToolChain &TC = C.getDefaultToolChain();
458  if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
459    llvm::outs() << "programs: =";
460    for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
461           ie = TC.getProgramPaths().end(); it != ie; ++it) {
462      if (it != TC.getProgramPaths().begin())
463        llvm::outs() << ':';
464      llvm::outs() << *it;
465    }
466    llvm::outs() << "\n";
467    llvm::outs() << "libraries: =";
468    for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
469           ie = TC.getFilePaths().end(); it != ie; ++it) {
470      if (it != TC.getFilePaths().begin())
471        llvm::outs() << ':';
472      llvm::outs() << *it;
473    }
474    llvm::outs() << "\n";
475    return false;
476  }
477
478  // FIXME: The following handlers should use a callback mechanism, we don't
479  // know what the client would like to do.
480  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
481    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n";
482    return false;
483  }
484
485  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
486    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n";
487    return false;
488  }
489
490  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
491    llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
492    return false;
493  }
494
495  if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
496    // FIXME: We need tool chain support for this.
497    llvm::outs() << ".;\n";
498
499    switch (C.getDefaultToolChain().getTriple().getArch()) {
500    default:
501      break;
502
503    case llvm::Triple::x86_64:
504      llvm::outs() << "x86_64;@m64" << "\n";
505      break;
506
507    case llvm::Triple::ppc64:
508      llvm::outs() << "ppc64;@m64" << "\n";
509      break;
510    }
511    return false;
512  }
513
514  // FIXME: What is the difference between print-multi-directory and
515  // print-multi-os-directory?
516  if (C.getArgs().hasArg(options::OPT_print_multi_directory) ||
517      C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
518    switch (C.getDefaultToolChain().getTriple().getArch()) {
519    default:
520    case llvm::Triple::x86:
521    case llvm::Triple::ppc:
522      llvm::outs() << "." << "\n";
523      break;
524
525    case llvm::Triple::x86_64:
526      llvm::outs() << "x86_64" << "\n";
527      break;
528
529    case llvm::Triple::ppc64:
530      llvm::outs() << "ppc64" << "\n";
531      break;
532    }
533    return false;
534  }
535
536  return true;
537}
538
539static unsigned PrintActions1(const Compilation &C, Action *A,
540                              std::map<Action*, unsigned> &Ids) {
541  if (Ids.count(A))
542    return Ids[A];
543
544  std::string str;
545  llvm::raw_string_ostream os(str);
546
547  os << Action::getClassName(A->getKind()) << ", ";
548  if (InputAction *IA = dyn_cast<InputAction>(A)) {
549    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
550  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
551    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
552                  C.getDefaultToolChain().getArchName()) << '"'
553       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
554  } else {
555    os << "{";
556    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
557      os << PrintActions1(C, *it, Ids);
558      ++it;
559      if (it != ie)
560        os << ", ";
561    }
562    os << "}";
563  }
564
565  unsigned Id = Ids.size();
566  Ids[A] = Id;
567  llvm::errs() << Id << ": " << os.str() << ", "
568               << types::getTypeName(A->getType()) << "\n";
569
570  return Id;
571}
572
573void Driver::PrintActions(const Compilation &C) const {
574  std::map<Action*, unsigned> Ids;
575  for (ActionList::const_iterator it = C.getActions().begin(),
576         ie = C.getActions().end(); it != ie; ++it)
577    PrintActions1(C, *it, Ids);
578}
579
580void Driver::BuildUniversalActions(const ArgList &Args,
581                                   ActionList &Actions) const {
582  llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
583  // Collect the list of architectures. Duplicates are allowed, but should only
584  // be handled once (in the order seen).
585  llvm::StringSet<> ArchNames;
586  llvm::SmallVector<const char *, 4> Archs;
587  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
588       it != ie; ++it) {
589    Arg *A = *it;
590
591    if (A->getOption().getId() == options::OPT_arch) {
592      // Validate the option here; we don't save the type here because its
593      // particular spelling may participate in other driver choices.
594      llvm::Triple::ArchType Arch =
595        llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
596      if (Arch == llvm::Triple::UnknownArch) {
597        Diag(clang::diag::err_drv_invalid_arch_name)
598          << A->getAsString(Args);
599        continue;
600      }
601
602      A->claim();
603      if (ArchNames.insert(A->getValue(Args)))
604        Archs.push_back(A->getValue(Args));
605    }
606  }
607
608  // When there is no explicit arch for this platform, make sure we still bind
609  // the architecture (to the default) so that -Xarch_ is handled correctly.
610  if (!Archs.size())
611    Archs.push_back(0);
612
613  // FIXME: We killed off some others but these aren't yet detected in a
614  // functional manner. If we added information to jobs about which "auxiliary"
615  // files they wrote then we could detect the conflict these cause downstream.
616  if (Archs.size() > 1) {
617    // No recovery needed, the point of this is just to prevent
618    // overwriting the same files.
619    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
620      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
621        << A->getAsString(Args);
622  }
623
624  ActionList SingleActions;
625  BuildActions(Args, SingleActions);
626
627  // Add in arch binding and lipo (if necessary) for every top level action.
628  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
629    Action *Act = SingleActions[i];
630
631    // Make sure we can lipo this kind of output. If not (and it is an actual
632    // output) then we disallow, since we can't create an output file with the
633    // right name without overwriting it. We could remove this oddity by just
634    // changing the output names to include the arch, which would also fix
635    // -save-temps. Compatibility wins for now.
636
637    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
638      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
639        << types::getTypeName(Act->getType());
640
641    ActionList Inputs;
642    for (unsigned i = 0, e = Archs.size(); i != e; ++i)
643      Inputs.push_back(new BindArchAction(Act, Archs[i]));
644
645    // Lipo if necessary, we do it this way because we need to set the arch flag
646    // so that -Xarch_ gets overwritten.
647    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
648      Actions.append(Inputs.begin(), Inputs.end());
649    else
650      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
651  }
652}
653
654void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
655  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
656  // Start by constructing the list of inputs and their types.
657
658  // Track the current user specified (-x) input. We also explicitly track the
659  // argument used to set the type; we only want to claim the type when we
660  // actually use it, so we warn about unused -x arguments.
661  types::ID InputType = types::TY_Nothing;
662  Arg *InputTypeArg = 0;
663
664  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
665  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
666       it != ie; ++it) {
667    Arg *A = *it;
668
669    if (isa<InputOption>(A->getOption())) {
670      const char *Value = A->getValue(Args);
671      types::ID Ty = types::TY_INVALID;
672
673      // Infer the input type if necessary.
674      if (InputType == types::TY_Nothing) {
675        // If there was an explicit arg for this, claim it.
676        if (InputTypeArg)
677          InputTypeArg->claim();
678
679        // stdin must be handled specially.
680        if (memcmp(Value, "-", 2) == 0) {
681          // If running with -E, treat as a C input (this changes the builtin
682          // macros, for example). This may be overridden by -ObjC below.
683          //
684          // Otherwise emit an error but still use a valid type to avoid
685          // spurious errors (e.g., no inputs).
686          if (!Args.hasArg(options::OPT_E, false))
687            Diag(clang::diag::err_drv_unknown_stdin_type);
688          Ty = types::TY_C;
689        } else {
690          // Otherwise lookup by extension, and fallback to ObjectType if not
691          // found. We use a host hook here because Darwin at least has its own
692          // idea of what .s is.
693          if (const char *Ext = strrchr(Value, '.'))
694            Ty = Host->lookupTypeForExtension(Ext + 1);
695
696          if (Ty == types::TY_INVALID)
697            Ty = types::TY_Object;
698        }
699
700        // -ObjC and -ObjC++ override the default language, but only for "source
701        // files". We just treat everything that isn't a linker input as a
702        // source file.
703        //
704        // FIXME: Clean this up if we move the phase sequence into the type.
705        if (Ty != types::TY_Object) {
706          if (Args.hasArg(options::OPT_ObjC))
707            Ty = types::TY_ObjC;
708          else if (Args.hasArg(options::OPT_ObjCXX))
709            Ty = types::TY_ObjCXX;
710        }
711      } else {
712        assert(InputTypeArg && "InputType set w/o InputTypeArg");
713        InputTypeArg->claim();
714        Ty = InputType;
715      }
716
717      // Check that the file exists. It isn't clear this is worth doing, since
718      // the tool presumably does this anyway, and this just adds an extra stat
719      // to the equation, but this is gcc compatible.
720      if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
721        Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
722      else
723        Inputs.push_back(std::make_pair(Ty, A));
724
725    } else if (A->getOption().isLinkerInput()) {
726      // Just treat as object type, we could make a special type for this if
727      // necessary.
728      Inputs.push_back(std::make_pair(types::TY_Object, A));
729
730    } else if (A->getOption().getId() == options::OPT_x) {
731      InputTypeArg = A;
732      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
733
734      // Follow gcc behavior and treat as linker input for invalid -x
735      // options. Its not clear why we shouldn't just revert to unknown; but
736      // this isn't very important, we might as well be bug comatible.
737      if (!InputType) {
738        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
739        InputType = types::TY_Object;
740      }
741    }
742  }
743
744  if (!SuppressMissingInputWarning && Inputs.empty()) {
745    Diag(clang::diag::err_drv_no_input_files);
746    return;
747  }
748
749  // Determine which compilation mode we are in. We look for options which
750  // affect the phase, starting with the earliest phases, and record which
751  // option we used to determine the final phase.
752  Arg *FinalPhaseArg = 0;
753  phases::ID FinalPhase;
754
755  // -{E,M,MM} only run the preprocessor.
756  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
757      (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
758      (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
759    FinalPhase = phases::Preprocess;
760
761    // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
762  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
763             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze,
764                                              options::OPT__analyze_auto)) ||
765             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_ast)) ||
766             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
767    FinalPhase = phases::Compile;
768
769    // -c only runs up to the assembler.
770  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
771    FinalPhase = phases::Assemble;
772
773    // Otherwise do everything.
774  } else
775    FinalPhase = phases::Link;
776
777  // Reject -Z* at the top level, these options should never have been exposed
778  // by gcc.
779  if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
780    Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
781
782  // Construct the actions to perform.
783  ActionList LinkerInputs;
784  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
785    types::ID InputType = Inputs[i].first;
786    const Arg *InputArg = Inputs[i].second;
787
788    unsigned NumSteps = types::getNumCompilationPhases(InputType);
789    assert(NumSteps && "Invalid number of steps!");
790
791    // If the first step comes after the final phase we are doing as part of
792    // this compilation, warn the user about it.
793    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
794    if (InitialPhase > FinalPhase) {
795      // Claim here to avoid the more general unused warning.
796      InputArg->claim();
797
798      // Special case '-E' warning on a previously preprocessed file to make
799      // more sense.
800      if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess &&
801          getPreprocessedType(InputType) == types::TY_INVALID)
802        Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
803          << InputArg->getAsString(Args)
804          << FinalPhaseArg->getOption().getName();
805      else
806        Diag(clang::diag::warn_drv_input_file_unused)
807          << InputArg->getAsString(Args)
808          << getPhaseName(InitialPhase)
809          << FinalPhaseArg->getOption().getName();
810      continue;
811    }
812
813    // Build the pipeline for this file.
814    Action *Current = new InputAction(*InputArg, InputType);
815    for (unsigned i = 0; i != NumSteps; ++i) {
816      phases::ID Phase = types::getCompilationPhase(InputType, i);
817
818      // We are done if this step is past what the user requested.
819      if (Phase > FinalPhase)
820        break;
821
822      // Queue linker inputs.
823      if (Phase == phases::Link) {
824        assert(i + 1 == NumSteps && "linking must be final compilation step.");
825        LinkerInputs.push_back(Current);
826        Current = 0;
827        break;
828      }
829
830      // Some types skip the assembler phase (e.g., llvm-bc), but we can't
831      // encode this in the steps because the intermediate type depends on
832      // arguments. Just special case here.
833      if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
834        continue;
835
836      // Otherwise construct the appropriate action.
837      Current = ConstructPhaseAction(Args, Phase, Current);
838      if (Current->getType() == types::TY_Nothing)
839        break;
840    }
841
842    // If we ended with something, add to the output list.
843    if (Current)
844      Actions.push_back(Current);
845  }
846
847  // Add a link action if necessary.
848  if (!LinkerInputs.empty())
849    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
850}
851
852Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
853                                     Action *Input) const {
854  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
855  // Build the appropriate action.
856  switch (Phase) {
857  case phases::Link: assert(0 && "link action invalid here.");
858  case phases::Preprocess: {
859    types::ID OutputTy;
860    // -{M, MM} alter the output type.
861    if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
862      OutputTy = types::TY_Dependencies;
863    } else {
864      OutputTy = types::getPreprocessedType(Input->getType());
865      assert(OutputTy != types::TY_INVALID &&
866             "Cannot preprocess this input type!");
867    }
868    return new PreprocessJobAction(Input, OutputTy);
869  }
870  case phases::Precompile:
871    return new PrecompileJobAction(Input, types::TY_PCH);
872  case phases::Compile: {
873    if (Args.hasArg(options::OPT_fsyntax_only)) {
874      return new CompileJobAction(Input, types::TY_Nothing);
875    } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
876      return new AnalyzeJobAction(Input, types::TY_Plist);
877    } else if (Args.hasArg(options::OPT_emit_ast)) {
878      return new CompileJobAction(Input, types::TY_AST);
879    } else if (Args.hasArg(options::OPT_emit_llvm) ||
880               Args.hasArg(options::OPT_flto) ||
881               Args.hasArg(options::OPT_O4)) {
882      types::ID Output =
883        Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
884      return new CompileJobAction(Input, Output);
885    } else {
886      return new CompileJobAction(Input, types::TY_PP_Asm);
887    }
888  }
889  case phases::Assemble:
890    return new AssembleJobAction(Input, types::TY_Object);
891  }
892
893  assert(0 && "invalid phase in ConstructPhaseAction");
894  return 0;
895}
896
897void Driver::BuildJobs(Compilation &C) const {
898  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
899  bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
900  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
901
902  // FIXME: Pipes are forcibly disabled until we support executing them.
903  if (!CCCPrintBindings)
904    UsePipes = false;
905
906  // -save-temps inhibits pipes.
907  if (SaveTemps && UsePipes) {
908    Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
909    UsePipes = true;
910  }
911
912  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
913
914  // It is an error to provide a -o option if we are making multiple output
915  // files.
916  if (FinalOutput) {
917    unsigned NumOutputs = 0;
918    for (ActionList::const_iterator it = C.getActions().begin(),
919           ie = C.getActions().end(); it != ie; ++it)
920      if ((*it)->getType() != types::TY_Nothing)
921        ++NumOutputs;
922
923    if (NumOutputs > 1) {
924      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
925      FinalOutput = 0;
926    }
927  }
928
929  for (ActionList::const_iterator it = C.getActions().begin(),
930         ie = C.getActions().end(); it != ie; ++it) {
931    Action *A = *it;
932
933    // If we are linking an image for multiple archs then the linker wants
934    // -arch_multiple and -final_output <final image name>. Unfortunately, this
935    // doesn't fit in cleanly because we have to pass this information down.
936    //
937    // FIXME: This is a hack; find a cleaner way to integrate this into the
938    // process.
939    const char *LinkingOutput = 0;
940    if (isa<LipoJobAction>(A)) {
941      if (FinalOutput)
942        LinkingOutput = FinalOutput->getValue(C.getArgs());
943      else
944        LinkingOutput = DefaultImageName.c_str();
945    }
946
947    InputInfo II;
948    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
949                       /*BoundArch*/0,
950                       /*CanAcceptPipe*/ true,
951                       /*AtTopLevel*/ true,
952                       /*LinkingOutput*/ LinkingOutput,
953                       II);
954  }
955
956  // If the user passed -Qunused-arguments or there were errors, don't warn
957  // about any unused arguments.
958  if (Diags.getNumErrors() ||
959      C.getArgs().hasArg(options::OPT_Qunused_arguments))
960    return;
961
962  // Claim -### here.
963  (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
964
965  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
966       it != ie; ++it) {
967    Arg *A = *it;
968
969    // FIXME: It would be nice to be able to send the argument to the
970    // Diagnostic, so that extra values, position, and so on could be printed.
971    if (!A->isClaimed()) {
972      if (A->getOption().hasNoArgumentUnused())
973        continue;
974
975      // Suppress the warning automatically if this is just a flag, and it is an
976      // instance of an argument we already claimed.
977      const Option &Opt = A->getOption();
978      if (isa<FlagOption>(Opt)) {
979        bool DuplicateClaimed = false;
980
981        // FIXME: Use iterator.
982        for (ArgList::const_iterator it = C.getArgs().begin(),
983               ie = C.getArgs().end(); it != ie; ++it) {
984          if ((*it)->isClaimed() && (*it)->getOption().matches(Opt.getId())) {
985            DuplicateClaimed = true;
986            break;
987          }
988        }
989
990        if (DuplicateClaimed)
991          continue;
992      }
993
994      Diag(clang::diag::warn_drv_unused_argument)
995        << A->getAsString(C.getArgs());
996    }
997  }
998}
999
1000void Driver::BuildJobsForAction(Compilation &C,
1001                                const Action *A,
1002                                const ToolChain *TC,
1003                                const char *BoundArch,
1004                                bool CanAcceptPipe,
1005                                bool AtTopLevel,
1006                                const char *LinkingOutput,
1007                                InputInfo &Result) const {
1008  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1009
1010  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
1011  // FIXME: Pipes are forcibly disabled until we support executing them.
1012  if (!CCCPrintBindings)
1013    UsePipes = false;
1014
1015  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1016    // FIXME: It would be nice to not claim this here; maybe the old scheme of
1017    // just using Args was better?
1018    const Arg &Input = IA->getInputArg();
1019    Input.claim();
1020    if (isa<PositionalArg>(Input)) {
1021      const char *Name = Input.getValue(C.getArgs());
1022      Result = InputInfo(Name, A->getType(), Name);
1023    } else
1024      Result = InputInfo(&Input, A->getType(), "");
1025    return;
1026  }
1027
1028  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1029    const ToolChain *TC = &C.getDefaultToolChain();
1030
1031    std::string Arch;
1032    if (BAA->getArchName())
1033      TC = Host->CreateToolChain(C.getArgs(), BAA->getArchName());
1034
1035    BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1036                       CanAcceptPipe, AtTopLevel, LinkingOutput, Result);
1037    return;
1038  }
1039
1040  const JobAction *JA = cast<JobAction>(A);
1041  const Tool &T = TC->SelectTool(C, *JA);
1042
1043  // See if we should use an integrated preprocessor. We do so when we have
1044  // exactly one input, since this is the only use case we care about
1045  // (irrelevant since we don't support combine yet).
1046  bool UseIntegratedCPP = false;
1047  const ActionList *Inputs = &A->getInputs();
1048  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
1049    if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1050        !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1051        !C.getArgs().hasArg(options::OPT_save_temps) &&
1052        T.hasIntegratedCPP()) {
1053      UseIntegratedCPP = true;
1054      Inputs = &(*Inputs)[0]->getInputs();
1055    }
1056  }
1057
1058  // Only use pipes when there is exactly one input.
1059  bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
1060  InputInfoList InputInfos;
1061  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
1062       it != ie; ++it) {
1063    InputInfo II;
1064    BuildJobsForAction(C, *it, TC, BoundArch, TryToUsePipeInput,
1065                       /*AtTopLevel*/false, LinkingOutput, II);
1066    InputInfos.push_back(II);
1067  }
1068
1069  // Determine if we should output to a pipe.
1070  bool OutputToPipe = false;
1071  if (CanAcceptPipe && T.canPipeOutput()) {
1072    // Some actions default to writing to a pipe if they are the top level phase
1073    // and there was no user override.
1074    //
1075    // FIXME: Is there a better way to handle this?
1076    if (AtTopLevel) {
1077      if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
1078        OutputToPipe = true;
1079    } else if (UsePipes)
1080      OutputToPipe = true;
1081  }
1082
1083  // Figure out where to put the job (pipes).
1084  Job *Dest = &C.getJobs();
1085  if (InputInfos[0].isPipe()) {
1086    assert(TryToUsePipeInput && "Unrequested pipe!");
1087    assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
1088    Dest = &InputInfos[0].getPipe();
1089  }
1090
1091  // Always use the first input as the base input.
1092  const char *BaseInput = InputInfos[0].getBaseInput();
1093
1094  // Determine the place to write output to (nothing, pipe, or filename) and
1095  // where to put the new job.
1096  if (JA->getType() == types::TY_Nothing) {
1097    Result = InputInfo(A->getType(), BaseInput);
1098  } else if (OutputToPipe) {
1099    // Append to current piped job or create a new one as appropriate.
1100    PipedJob *PJ = dyn_cast<PipedJob>(Dest);
1101    if (!PJ) {
1102      PJ = new PipedJob();
1103      // FIXME: Temporary hack so that -ccc-print-bindings work until we have
1104      // pipe support. Please remove later.
1105      if (!CCCPrintBindings)
1106        cast<JobList>(Dest)->addJob(PJ);
1107      Dest = PJ;
1108    }
1109    Result = InputInfo(PJ, A->getType(), BaseInput);
1110  } else {
1111    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
1112                       A->getType(), BaseInput);
1113  }
1114
1115  if (CCCPrintBindings) {
1116    llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
1117                 << " - \"" << T.getName() << "\", inputs: [";
1118    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1119      llvm::errs() << InputInfos[i].getAsString();
1120      if (i + 1 != e)
1121        llvm::errs() << ", ";
1122    }
1123    llvm::errs() << "], output: " << Result.getAsString() << "\n";
1124  } else {
1125    T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
1126                   C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1127  }
1128}
1129
1130const char *Driver::GetNamedOutputPath(Compilation &C,
1131                                       const JobAction &JA,
1132                                       const char *BaseInput,
1133                                       bool AtTopLevel) const {
1134  llvm::PrettyStackTraceString CrashInfo("Computing output path");
1135  // Output to a user requested destination?
1136  if (AtTopLevel) {
1137    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1138      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
1139  }
1140
1141  // Output to a temporary file?
1142  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
1143    std::string TmpName =
1144      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
1145    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1146  }
1147
1148  llvm::sys::Path BasePath(BaseInput);
1149  std::string BaseName(BasePath.getLast());
1150
1151  // Determine what the derived output name should be.
1152  const char *NamedOutput;
1153  if (JA.getType() == types::TY_Image) {
1154    NamedOutput = DefaultImageName.c_str();
1155  } else {
1156    const char *Suffix = types::getTypeTempSuffix(JA.getType());
1157    assert(Suffix && "All types used for output should have a suffix.");
1158
1159    std::string::size_type End = std::string::npos;
1160    if (!types::appendSuffixForType(JA.getType()))
1161      End = BaseName.rfind('.');
1162    std::string Suffixed(BaseName.substr(0, End));
1163    Suffixed += '.';
1164    Suffixed += Suffix;
1165    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1166  }
1167
1168  // As an annoying special case, PCH generation doesn't strip the pathname.
1169  if (JA.getType() == types::TY_PCH) {
1170    BasePath.eraseComponent();
1171    if (BasePath.isEmpty())
1172      BasePath = NamedOutput;
1173    else
1174      BasePath.appendComponent(NamedOutput);
1175    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1176  } else {
1177    return C.addResultFile(NamedOutput);
1178  }
1179}
1180
1181std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1182  const ToolChain::path_list &List = TC.getFilePaths();
1183  for (ToolChain::path_list::const_iterator
1184         it = List.begin(), ie = List.end(); it != ie; ++it) {
1185    llvm::sys::Path P(*it);
1186    P.appendComponent(Name);
1187    if (P.exists())
1188      return P.str();
1189  }
1190
1191  return Name;
1192}
1193
1194std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
1195                                   bool WantFile) const {
1196  const ToolChain::path_list &List = TC.getProgramPaths();
1197  for (ToolChain::path_list::const_iterator
1198         it = List.begin(), ie = List.end(); it != ie; ++it) {
1199    llvm::sys::Path P(*it);
1200    P.appendComponent(Name);
1201    if (WantFile ? P.exists() : P.canExecute())
1202      return P.str();
1203  }
1204
1205  // If all else failed, search the path.
1206  llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
1207  if (!P.empty())
1208    return P.str();
1209
1210  return Name;
1211}
1212
1213std::string Driver::GetTemporaryPath(const char *Suffix) const {
1214  // FIXME: This is lame; sys::Path should provide this function (in particular,
1215  // it should know how to find the temporary files dir).
1216  std::string Error;
1217  const char *TmpDir = ::getenv("TMPDIR");
1218  if (!TmpDir)
1219    TmpDir = ::getenv("TEMP");
1220  if (!TmpDir)
1221    TmpDir = ::getenv("TMP");
1222  if (!TmpDir)
1223    TmpDir = "/tmp";
1224  llvm::sys::Path P(TmpDir);
1225  P.appendComponent("cc");
1226  if (P.makeUnique(false, &Error)) {
1227    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1228    return "";
1229  }
1230
1231  // FIXME: Grumble, makeUnique sometimes leaves the file around!?  PR3837.
1232  P.eraseFromDisk(false, 0);
1233
1234  P.appendSuffix(Suffix);
1235  return P.str();
1236}
1237
1238const HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
1239  llvm::PrettyStackTraceString CrashInfo("Constructing host");
1240  llvm::Triple Triple(TripleStr);
1241
1242  switch (Triple.getOS()) {
1243  case llvm::Triple::AuroraUX:
1244    return createAuroraUXHostInfo(*this, Triple);
1245  case llvm::Triple::Darwin:
1246    return createDarwinHostInfo(*this, Triple);
1247  case llvm::Triple::DragonFly:
1248    return createDragonFlyHostInfo(*this, Triple);
1249  case llvm::Triple::OpenBSD:
1250    return createOpenBSDHostInfo(*this, Triple);
1251  case llvm::Triple::FreeBSD:
1252    return createFreeBSDHostInfo(*this, Triple);
1253  case llvm::Triple::Linux:
1254    return createLinuxHostInfo(*this, Triple);
1255  default:
1256    return createUnknownHostInfo(*this, Triple);
1257  }
1258}
1259
1260bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
1261                                    const llvm::Triple &Triple) const {
1262  // Check if user requested no clang, or clang doesn't understand this type (we
1263  // only handle single inputs for now).
1264  if (!CCCUseClang || JA.size() != 1 ||
1265      !types::isAcceptedByClang((*JA.begin())->getType()))
1266    return false;
1267
1268  // Otherwise make sure this is an action clang understands.
1269  if (isa<PreprocessJobAction>(JA)) {
1270    if (!CCCUseClangCPP) {
1271      Diag(clang::diag::warn_drv_not_using_clang_cpp);
1272      return false;
1273    }
1274  } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1275    return false;
1276
1277  // Use clang for C++?
1278  if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1279    Diag(clang::diag::warn_drv_not_using_clang_cxx);
1280    return false;
1281  }
1282
1283  // Always use clang for precompiling and AST generation, regardless of archs.
1284  if (isa<PrecompileJobAction>(JA) || JA.getType() == types::TY_AST)
1285    return true;
1286
1287  // Finally, don't use clang if this isn't one of the user specified archs to
1288  // build.
1289  if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) {
1290    Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName();
1291    return false;
1292  }
1293
1294  return true;
1295}
1296
1297/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1298/// grouped values as integers. Numbers which are not provided are set to 0.
1299///
1300/// \return True if the entire string was parsed (9.2), or all groups were
1301/// parsed (10.3.5extrastuff).
1302bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1303                               unsigned &Minor, unsigned &Micro,
1304                               bool &HadExtra) {
1305  HadExtra = false;
1306
1307  Major = Minor = Micro = 0;
1308  if (*Str == '\0')
1309    return true;
1310
1311  char *End;
1312  Major = (unsigned) strtol(Str, &End, 10);
1313  if (*Str != '\0' && *End == '\0')
1314    return true;
1315  if (*End != '.')
1316    return false;
1317
1318  Str = End+1;
1319  Minor = (unsigned) strtol(Str, &End, 10);
1320  if (*Str != '\0' && *End == '\0')
1321    return true;
1322  if (*End != '.')
1323    return false;
1324
1325  Str = End+1;
1326  Micro = (unsigned) strtol(Str, &End, 10);
1327  if (*Str != '\0' && *End == '\0')
1328    return true;
1329  if (Str == End)
1330    return false;
1331  HadExtra = true;
1332  return true;
1333}
1334