clang API Documentation

Tools.cpp
Go to the documentation of this file.
00001 //===--- Tools.cpp - Tools Implementations --------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "Tools.h"
00011 
00012 #include "clang/Driver/Action.h"
00013 #include "clang/Driver/Arg.h"
00014 #include "clang/Driver/ArgList.h"
00015 #include "clang/Driver/Driver.h"
00016 #include "clang/Driver/DriverDiagnostic.h"
00017 #include "clang/Driver/Compilation.h"
00018 #include "clang/Driver/Job.h"
00019 #include "clang/Driver/ObjCRuntime.h"
00020 #include "clang/Driver/Option.h"
00021 #include "clang/Driver/Options.h"
00022 #include "clang/Driver/ToolChain.h"
00023 #include "clang/Driver/Util.h"
00024 
00025 #include "llvm/ADT/SmallString.h"
00026 #include "llvm/ADT/StringSwitch.h"
00027 #include "llvm/ADT/Twine.h"
00028 #include "llvm/Support/FileSystem.h"
00029 #include "llvm/Support/Format.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Support/Host.h"
00032 #include "llvm/Support/Process.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 
00035 #include "InputInfo.h"
00036 #include "ToolChains.h"
00037 
00038 using namespace clang::driver;
00039 using namespace clang::driver::tools;
00040 using namespace clang;
00041 
00042 /// CheckPreprocessingOptions - Perform some validation of preprocessing
00043 /// arguments that is shared with gcc.
00044 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
00045   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC))
00046     if (!Args.hasArg(options::OPT_E) && !D.CCCIsCPP)
00047       D.Diag(diag::err_drv_argument_only_allowed_with)
00048         << A->getAsString(Args) << "-E";
00049 }
00050 
00051 /// CheckCodeGenerationOptions - Perform some validation of code generation
00052 /// arguments that is shared with gcc.
00053 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
00054   // In gcc, only ARM checks this, but it seems reasonable to check universally.
00055   if (Args.hasArg(options::OPT_static))
00056     if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
00057                                        options::OPT_mdynamic_no_pic))
00058       D.Diag(diag::err_drv_argument_not_allowed_with)
00059         << A->getAsString(Args) << "-static";
00060 }
00061 
00062 // Quote target names for inclusion in GNU Make dependency files.
00063 // Only the characters '$', '#', ' ', '\t' are quoted.
00064 static void QuoteTarget(StringRef Target,
00065                         SmallVectorImpl<char> &Res) {
00066   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
00067     switch (Target[i]) {
00068     case ' ':
00069     case '\t':
00070       // Escape the preceding backslashes
00071       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
00072         Res.push_back('\\');
00073 
00074       // Escape the space/tab
00075       Res.push_back('\\');
00076       break;
00077     case '$':
00078       Res.push_back('$');
00079       break;
00080     case '#':
00081       Res.push_back('\\');
00082       break;
00083     default:
00084       break;
00085     }
00086 
00087     Res.push_back(Target[i]);
00088   }
00089 }
00090 
00091 static void addDirectoryList(const ArgList &Args,
00092                              ArgStringList &CmdArgs,
00093                              const char *ArgName,
00094                              const char *EnvVar) {
00095   const char *DirList = ::getenv(EnvVar);
00096   if (!DirList)
00097     return; // Nothing to do.
00098 
00099   StringRef Dirs(DirList);
00100   if (Dirs.empty()) // Empty string should not add '.'.
00101     return;
00102 
00103   StringRef::size_type Delim;
00104   while ((Delim = Dirs.find(llvm::sys::PathSeparator)) != StringRef::npos) {
00105     if (Delim == 0) { // Leading colon.
00106       CmdArgs.push_back(ArgName);
00107       CmdArgs.push_back(".");
00108     } else {
00109       CmdArgs.push_back(ArgName);
00110       CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
00111     }
00112     Dirs = Dirs.substr(Delim + 1);
00113   }
00114 
00115   if (Dirs.empty()) { // Trailing colon.
00116     CmdArgs.push_back(ArgName);
00117     CmdArgs.push_back(".");
00118   } else { // Add the last path.
00119     CmdArgs.push_back(ArgName);
00120     CmdArgs.push_back(Args.MakeArgString(Dirs));
00121   }
00122 }
00123 
00124 static void AddLinkerInputs(const ToolChain &TC,
00125                             const InputInfoList &Inputs, const ArgList &Args,
00126                             ArgStringList &CmdArgs) {
00127   const Driver &D = TC.getDriver();
00128 
00129   // Add extra linker input arguments which are not treated as inputs
00130   // (constructed via -Xarch_).
00131   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
00132 
00133   for (InputInfoList::const_iterator
00134          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
00135     const InputInfo &II = *it;
00136 
00137     if (!TC.HasNativeLLVMSupport()) {
00138       // Don't try to pass LLVM inputs unless we have native support.
00139       if (II.getType() == types::TY_LLVM_IR ||
00140           II.getType() == types::TY_LTO_IR ||
00141           II.getType() == types::TY_LLVM_BC ||
00142           II.getType() == types::TY_LTO_BC)
00143         D.Diag(diag::err_drv_no_linker_llvm_support)
00144           << TC.getTripleString();
00145     }
00146 
00147     // Add filenames immediately.
00148     if (II.isFilename()) {
00149       CmdArgs.push_back(II.getFilename());
00150       continue;
00151     }
00152 
00153     // Otherwise, this is a linker input argument.
00154     const Arg &A = II.getInputArg();
00155 
00156     // Handle reserved library options.
00157     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
00158       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
00159     } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
00160       TC.AddCCKextLibArgs(Args, CmdArgs);
00161     } else
00162       A.renderAsInput(Args, CmdArgs);
00163   }
00164 
00165   // LIBRARY_PATH - included following the user specified library paths.
00166   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
00167 }
00168 
00169 /// \brief Determine whether Objective-C automated reference counting is
00170 /// enabled.
00171 static bool isObjCAutoRefCount(const ArgList &Args) {
00172   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
00173 }
00174 
00175 /// \brief Determine whether we are linking the ObjC runtime.
00176 static bool isObjCRuntimeLinked(const ArgList &Args) {
00177   if (isObjCAutoRefCount(Args))
00178     return true;
00179   return Args.hasArg(options::OPT_fobjc_link_runtime);
00180 }
00181 
00182 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
00183                          ArgStringList &CmdArgs,
00184                          llvm::Triple Triple) {
00185   if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
00186         Args.hasArg(options::OPT_fprofile_generate) ||
00187         Args.hasArg(options::OPT_fcreate_profile) ||
00188         Args.hasArg(options::OPT_coverage)))
00189     return;
00190 
00191   // GCC links libgcov.a by adding -L<inst>/gcc/lib/gcc/<triple>/<ver> -lgcov to
00192   // the link line. We cannot do the same thing because unlike gcov there is a
00193   // libprofile_rt.so. We used to use the -l:libprofile_rt.a syntax, but that is
00194   // not supported by old linkers.
00195   std::string ProfileRT =
00196     std::string(TC.getDriver().Dir) + "/../lib/libprofile_rt.a";
00197 
00198   CmdArgs.push_back(Args.MakeArgString(ProfileRT));
00199 }
00200 
00201 void Clang::AddPreprocessingOptions(Compilation &C,
00202                                     const Driver &D,
00203                                     const ArgList &Args,
00204                                     ArgStringList &CmdArgs,
00205                                     const InputInfo &Output,
00206                                     const InputInfoList &Inputs) const {
00207   Arg *A;
00208 
00209   CheckPreprocessingOptions(D, Args);
00210 
00211   Args.AddLastArg(CmdArgs, options::OPT_C);
00212   Args.AddLastArg(CmdArgs, options::OPT_CC);
00213 
00214   // Handle dependency file generation.
00215   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
00216       (A = Args.getLastArg(options::OPT_MD)) ||
00217       (A = Args.getLastArg(options::OPT_MMD))) {
00218     // Determine the output location.
00219     const char *DepFile;
00220     if (Output.getType() == types::TY_Dependencies) {
00221       DepFile = Output.getFilename();
00222     } else if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
00223       DepFile = MF->getValue(Args);
00224       C.addFailureResultFile(DepFile);
00225     } else if (A->getOption().matches(options::OPT_M) ||
00226                A->getOption().matches(options::OPT_MM)) {
00227       DepFile = "-";
00228     } else {
00229       DepFile = darwin::CC1::getDependencyFileName(Args, Inputs);
00230       C.addFailureResultFile(DepFile);
00231     }
00232     CmdArgs.push_back("-dependency-file");
00233     CmdArgs.push_back(DepFile);
00234 
00235     // Add a default target if one wasn't specified.
00236     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
00237       const char *DepTarget;
00238 
00239       // If user provided -o, that is the dependency target, except
00240       // when we are only generating a dependency file.
00241       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
00242       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
00243         DepTarget = OutputOpt->getValue(Args);
00244       } else {
00245         // Otherwise derive from the base input.
00246         //
00247         // FIXME: This should use the computed output file location.
00248         SmallString<128> P(Inputs[0].getBaseInput());
00249         llvm::sys::path::replace_extension(P, "o");
00250         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
00251       }
00252 
00253       CmdArgs.push_back("-MT");
00254       SmallString<128> Quoted;
00255       QuoteTarget(DepTarget, Quoted);
00256       CmdArgs.push_back(Args.MakeArgString(Quoted));
00257     }
00258 
00259     if (A->getOption().matches(options::OPT_M) ||
00260         A->getOption().matches(options::OPT_MD))
00261       CmdArgs.push_back("-sys-header-deps");
00262   }
00263 
00264   if (Args.hasArg(options::OPT_MG)) {
00265     if (!A || A->getOption().matches(options::OPT_MD) ||
00266               A->getOption().matches(options::OPT_MMD))
00267       D.Diag(diag::err_drv_mg_requires_m_or_mm);
00268     CmdArgs.push_back("-MG");
00269   }
00270 
00271   Args.AddLastArg(CmdArgs, options::OPT_MP);
00272 
00273   // Convert all -MQ <target> args to -MT <quoted target>
00274   for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
00275                                              options::OPT_MQ),
00276          ie = Args.filtered_end(); it != ie; ++it) {
00277     const Arg *A = *it;
00278     A->claim();
00279 
00280     if (A->getOption().matches(options::OPT_MQ)) {
00281       CmdArgs.push_back("-MT");
00282       SmallString<128> Quoted;
00283       QuoteTarget(A->getValue(Args), Quoted);
00284       CmdArgs.push_back(Args.MakeArgString(Quoted));
00285 
00286     // -MT flag - no change
00287     } else {
00288       A->render(Args, CmdArgs);
00289     }
00290   }
00291 
00292   // Add -i* options, and automatically translate to
00293   // -include-pch/-include-pth for transparent PCH support. It's
00294   // wonky, but we include looking for .gch so we can support seamless
00295   // replacement into a build system already set up to be generating
00296   // .gch files.
00297   bool RenderedImplicitInclude = false;
00298   for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
00299          ie = Args.filtered_end(); it != ie; ++it) {
00300     const Arg *A = it;
00301 
00302     if (A->getOption().matches(options::OPT_include)) {
00303       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
00304       RenderedImplicitInclude = true;
00305 
00306       // Use PCH if the user requested it.
00307       bool UsePCH = D.CCCUsePCH;
00308 
00309       bool FoundPTH = false;
00310       bool FoundPCH = false;
00311       llvm::sys::Path P(A->getValue(Args));
00312       bool Exists;
00313       if (UsePCH) {
00314         P.appendSuffix("pch");
00315         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
00316           FoundPCH = true;
00317         else
00318           P.eraseSuffix();
00319       }
00320 
00321       if (!FoundPCH) {
00322         P.appendSuffix("pth");
00323         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists)
00324           FoundPTH = true;
00325         else
00326           P.eraseSuffix();
00327       }
00328 
00329       if (!FoundPCH && !FoundPTH) {
00330         P.appendSuffix("gch");
00331         if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) {
00332           FoundPCH = UsePCH;
00333           FoundPTH = !UsePCH;
00334         }
00335         else
00336           P.eraseSuffix();
00337       }
00338 
00339       if (FoundPCH || FoundPTH) {
00340         if (IsFirstImplicitInclude) {
00341           A->claim();
00342           if (UsePCH)
00343             CmdArgs.push_back("-include-pch");
00344           else
00345             CmdArgs.push_back("-include-pth");
00346           CmdArgs.push_back(Args.MakeArgString(P.str()));
00347           continue;
00348         } else {
00349           // Ignore the PCH if not first on command line and emit warning.
00350           D.Diag(diag::warn_drv_pch_not_first_include)
00351               << P.str() << A->getAsString(Args);
00352         }
00353       }
00354     }
00355 
00356     // Not translated, render as usual.
00357     A->claim();
00358     A->render(Args, CmdArgs);
00359   }
00360 
00361   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
00362   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
00363                   options::OPT_index_header_map);
00364 
00365   // Add -Wp, and -Xassembler if using the preprocessor.
00366 
00367   // FIXME: There is a very unfortunate problem here, some troubled
00368   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
00369   // really support that we would have to parse and then translate
00370   // those options. :(
00371   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
00372                        options::OPT_Xpreprocessor);
00373 
00374   // -I- is a deprecated GCC feature, reject it.
00375   if (Arg *A = Args.getLastArg(options::OPT_I_))
00376     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
00377 
00378   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
00379   // -isysroot to the CC1 invocation.
00380   StringRef sysroot = C.getSysRoot();
00381   if (sysroot != "") {
00382     if (!Args.hasArg(options::OPT_isysroot)) {
00383       CmdArgs.push_back("-isysroot");
00384       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
00385     }
00386   }
00387   
00388   // If a module path was provided, pass it along. Otherwise, use a temporary
00389   // directory.
00390   if (Arg *A = Args.getLastArg(options::OPT_fmodule_cache_path)) {
00391     A->claim();
00392     A->render(Args, CmdArgs);
00393   } else {
00394     SmallString<128> DefaultModuleCache;
00395     llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, 
00396                                            DefaultModuleCache);
00397     llvm::sys::path::append(DefaultModuleCache, "clang-module-cache");
00398     CmdArgs.push_back("-fmodule-cache-path");
00399     CmdArgs.push_back(Args.MakeArgString(DefaultModuleCache));
00400   }
00401   
00402   // Parse additional include paths from environment variables.
00403   // FIXME: We should probably sink the logic for handling these from the
00404   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
00405   // CPATH - included following the user specified includes (but prior to
00406   // builtin and standard includes).
00407   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
00408   // C_INCLUDE_PATH - system includes enabled when compiling C.
00409   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
00410   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
00411   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
00412   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
00413   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
00414   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
00415   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
00416 
00417   // Add C++ include arguments, if needed.
00418   if (types::isCXX(Inputs[0].getType()))
00419     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
00420 
00421   // Add system include arguments.
00422   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
00423 }
00424 
00425 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
00426 //
00427 // FIXME: tblgen this.
00428 static const char *getARMTargetCPU(const ArgList &Args,
00429                                    const llvm::Triple &Triple) {
00430   // FIXME: Warn on inconsistent use of -mcpu and -march.
00431 
00432   // If we have -mcpu=, use that.
00433   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
00434     return A->getValue(Args);
00435 
00436   StringRef MArch;
00437   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
00438     // Otherwise, if we have -march= choose the base CPU for that arch.
00439     MArch = A->getValue(Args);
00440   } else {
00441     // Otherwise, use the Arch from the triple.
00442     MArch = Triple.getArchName();
00443   }
00444 
00445   return llvm::StringSwitch<const char *>(MArch)
00446     .Cases("armv2", "armv2a","arm2")
00447     .Case("armv3", "arm6")
00448     .Case("armv3m", "arm7m")
00449     .Cases("armv4", "armv4t", "arm7tdmi")
00450     .Cases("armv5", "armv5t", "arm10tdmi")
00451     .Cases("armv5e", "armv5te", "arm1022e")
00452     .Case("armv5tej", "arm926ej-s")
00453     .Cases("armv6", "armv6k", "arm1136jf-s")
00454     .Case("armv6j", "arm1136j-s")
00455     .Cases("armv6z", "armv6zk", "arm1176jzf-s")
00456     .Case("armv6t2", "arm1156t2-s")
00457     .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
00458     .Cases("armv7r", "armv7-r", "cortex-r4")
00459     .Cases("armv7m", "armv7-m", "cortex-m3")
00460     .Case("ep9312", "ep9312")
00461     .Case("iwmmxt", "iwmmxt")
00462     .Case("xscale", "xscale")
00463     .Cases("armv6m", "armv6-m", "cortex-m0")
00464     // If all else failed, return the most base CPU LLVM supports.
00465     .Default("arm7tdmi");
00466 }
00467 
00468 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
00469 /// CPU.
00470 //
00471 // FIXME: This is redundant with -mcpu, why does LLVM use this.
00472 // FIXME: tblgen this, or kill it!
00473 static const char *getLLVMArchSuffixForARM(StringRef CPU) {
00474   return llvm::StringSwitch<const char *>(CPU)
00475     .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
00476     .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
00477     .Cases("arm920", "arm920t", "arm922t", "v4t")
00478     .Cases("arm940t", "ep9312","v4t")
00479     .Cases("arm10tdmi",  "arm1020t", "v5")
00480     .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
00481     .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
00482     .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
00483     .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
00484     .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
00485     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
00486     .Cases("cortex-a8", "cortex-a9", "v7")
00487     .Case("cortex-m3", "v7m")
00488     .Case("cortex-m4", "v7m")
00489     .Case("cortex-m0", "v6m")
00490     .Default("");
00491 }
00492 
00493 // FIXME: Move to target hook.
00494 static bool isSignedCharDefault(const llvm::Triple &Triple) {
00495   switch (Triple.getArch()) {
00496   default:
00497     return true;
00498 
00499   case llvm::Triple::arm:
00500   case llvm::Triple::ppc:
00501   case llvm::Triple::ppc64:
00502     if (Triple.isOSDarwin())
00503       return true;
00504     return false;
00505   }
00506 }
00507 
00508 // Handle -mfpu=.
00509 //
00510 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
00511 // frontend target.
00512 static void addFPUArgs(const Driver &D, const Arg *A, const ArgList &Args,
00513                        ArgStringList &CmdArgs) {
00514   StringRef FPU = A->getValue(Args);
00515 
00516   // Set the target features based on the FPU.
00517   if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
00518     // Disable any default FPU support.
00519     CmdArgs.push_back("-target-feature");
00520     CmdArgs.push_back("-vfp2");
00521     CmdArgs.push_back("-target-feature");
00522     CmdArgs.push_back("-vfp3");
00523     CmdArgs.push_back("-target-feature");
00524     CmdArgs.push_back("-neon");
00525   } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
00526     CmdArgs.push_back("-target-feature");
00527     CmdArgs.push_back("+vfp3");
00528     CmdArgs.push_back("-target-feature");
00529     CmdArgs.push_back("+d16");
00530     CmdArgs.push_back("-target-feature");
00531     CmdArgs.push_back("-neon");
00532   } else if (FPU == "vfp") {
00533     CmdArgs.push_back("-target-feature");
00534     CmdArgs.push_back("+vfp2");
00535     CmdArgs.push_back("-target-feature");
00536     CmdArgs.push_back("-neon");
00537   } else if (FPU == "vfp3" || FPU == "vfpv3") {
00538     CmdArgs.push_back("-target-feature");
00539     CmdArgs.push_back("+vfp3");
00540     CmdArgs.push_back("-target-feature");
00541     CmdArgs.push_back("-neon");
00542   } else if (FPU == "neon") {
00543     CmdArgs.push_back("-target-feature");
00544     CmdArgs.push_back("+neon");
00545   } else
00546     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
00547 }
00548 
00549 // Handle -mfpmath=.
00550 static void addFPMathArgs(const Driver &D, const Arg *A, const ArgList &Args,
00551                           ArgStringList &CmdArgs, StringRef CPU) {
00552   StringRef FPMath = A->getValue(Args);
00553   
00554   // Set the target features based on the FPMath.
00555   if (FPMath == "neon") {
00556     CmdArgs.push_back("-target-feature");
00557     CmdArgs.push_back("+neonfp");
00558     
00559     if (CPU != "cortex-a8" && CPU != "cortex-a9" && CPU != "cortex-a9-mp")    
00560       D.Diag(diag::err_drv_invalid_feature) << "-mfpmath=neon" << CPU;
00561     
00562   } else if (FPMath == "vfp" || FPMath == "vfp2" || FPMath == "vfp3" ||
00563              FPMath == "vfp4") {
00564     CmdArgs.push_back("-target-feature");
00565     CmdArgs.push_back("-neonfp");
00566 
00567     // FIXME: Add warnings when disabling a feature not present for a given CPU.    
00568   } else
00569     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
00570 }
00571 
00572 // Select the float ABI as determined by -msoft-float, -mhard-float, and
00573 // -mfloat-abi=.
00574 static StringRef getARMFloatABI(const Driver &D,
00575                                 const ArgList &Args,
00576                                 const llvm::Triple &Triple) {
00577   StringRef FloatABI;
00578   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
00579                                options::OPT_mhard_float,
00580                                options::OPT_mfloat_abi_EQ)) {
00581     if (A->getOption().matches(options::OPT_msoft_float))
00582       FloatABI = "soft";
00583     else if (A->getOption().matches(options::OPT_mhard_float))
00584       FloatABI = "hard";
00585     else {
00586       FloatABI = A->getValue(Args);
00587       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
00588         D.Diag(diag::err_drv_invalid_mfloat_abi)
00589           << A->getAsString(Args);
00590         FloatABI = "soft";
00591       }
00592     }
00593   }
00594 
00595   // If unspecified, choose the default based on the platform.
00596   if (FloatABI.empty()) {
00597     switch (Triple.getOS()) {
00598     case llvm::Triple::Darwin:
00599     case llvm::Triple::MacOSX:
00600     case llvm::Triple::IOS: {
00601       // Darwin defaults to "softfp" for v6 and v7.
00602       //
00603       // FIXME: Factor out an ARM class so we can cache the arch somewhere.
00604       StringRef ArchName =
00605         getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
00606       if (ArchName.startswith("v6") || ArchName.startswith("v7"))
00607         FloatABI = "softfp";
00608       else
00609         FloatABI = "soft";
00610       break;
00611     }
00612 
00613     case llvm::Triple::Linux: {
00614       if (Triple.getEnvironment() == llvm::Triple::GNUEABI) {
00615         FloatABI = "softfp";
00616         break;
00617       }
00618     }
00619     // fall through
00620 
00621     default:
00622       switch(Triple.getEnvironment()) {
00623       case llvm::Triple::GNUEABI:
00624         FloatABI = "softfp";
00625         break;
00626       case llvm::Triple::EABI:
00627         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
00628         FloatABI = "softfp";
00629         break;
00630       case llvm::Triple::ANDROIDEABI: {
00631         StringRef ArchName =
00632           getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
00633         if (ArchName.startswith("v7"))
00634           FloatABI = "softfp";
00635         else
00636           FloatABI = "soft";
00637         break;
00638       }
00639       default:
00640         // Assume "soft", but warn the user we are guessing.
00641         FloatABI = "soft";
00642         D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
00643         break;
00644       }
00645     }
00646   }
00647 
00648   return FloatABI;
00649 }
00650 
00651 
00652 void Clang::AddARMTargetArgs(const ArgList &Args,
00653                              ArgStringList &CmdArgs,
00654                              bool KernelOrKext) const {
00655   const Driver &D = getToolChain().getDriver();
00656   llvm::Triple Triple = getToolChain().getTriple();
00657 
00658   // Select the ABI to use.
00659   //
00660   // FIXME: Support -meabi.
00661   const char *ABIName = 0;
00662   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
00663     ABIName = A->getValue(Args);
00664   } else {
00665     // Select the default based on the platform.
00666     switch(Triple.getEnvironment()) {
00667     case llvm::Triple::ANDROIDEABI:
00668     case llvm::Triple::GNUEABI:
00669       ABIName = "aapcs-linux";
00670       break;
00671     case llvm::Triple::EABI:
00672       ABIName = "aapcs";
00673       break;
00674     default:
00675       ABIName = "apcs-gnu";
00676     }
00677   }
00678   CmdArgs.push_back("-target-abi");
00679   CmdArgs.push_back(ABIName);
00680 
00681   // Set the CPU based on -march= and -mcpu=.
00682   CmdArgs.push_back("-target-cpu");
00683   CmdArgs.push_back(getARMTargetCPU(Args, Triple));
00684 
00685   // Determine floating point ABI from the options & target defaults.
00686   StringRef FloatABI = getARMFloatABI(D, Args, Triple);
00687   if (FloatABI == "soft") {
00688     // Floating point operations and argument passing are soft.
00689     //
00690     // FIXME: This changes CPP defines, we need -target-soft-float.
00691     CmdArgs.push_back("-msoft-float");
00692     CmdArgs.push_back("-mfloat-abi");
00693     CmdArgs.push_back("soft");
00694   } else if (FloatABI == "softfp") {
00695     // Floating point operations are hard, but argument passing is soft.
00696     CmdArgs.push_back("-mfloat-abi");
00697     CmdArgs.push_back("soft");
00698   } else {
00699     // Floating point operations and argument passing are hard.
00700     assert(FloatABI == "hard" && "Invalid float abi!");
00701     CmdArgs.push_back("-mfloat-abi");
00702     CmdArgs.push_back("hard");
00703   }
00704 
00705   // Set appropriate target features for floating point mode.
00706   //
00707   // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
00708   // yet (it uses the -mfloat-abi and -msoft-float options above), and it is
00709   // stripped out by the ARM target.
00710 
00711   // Use software floating point operations?
00712   if (FloatABI == "soft") {
00713     CmdArgs.push_back("-target-feature");
00714     CmdArgs.push_back("+soft-float");
00715   }
00716 
00717   // Use software floating point argument passing?
00718   if (FloatABI != "hard") {
00719     CmdArgs.push_back("-target-feature");
00720     CmdArgs.push_back("+soft-float-abi");
00721   }
00722 
00723   // Honor -mfpu=.
00724   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
00725     addFPUArgs(D, A, Args, CmdArgs);
00726 
00727   // Honor -mfpmath=.
00728   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ))
00729     addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
00730 
00731   // Setting -msoft-float effectively disables NEON because of the GCC
00732   // implementation, although the same isn't true of VFP or VFP3.
00733   if (FloatABI == "soft") {
00734     CmdArgs.push_back("-target-feature");
00735     CmdArgs.push_back("-neon");
00736   }
00737 
00738   // Kernel code has more strict alignment requirements.
00739   if (KernelOrKext) {
00740     CmdArgs.push_back("-backend-option");
00741     CmdArgs.push_back("-arm-long-calls");
00742 
00743     CmdArgs.push_back("-backend-option");
00744     CmdArgs.push_back("-arm-strict-align");
00745 
00746     // The kext linker doesn't know how to deal with movw/movt.
00747     CmdArgs.push_back("-backend-option");
00748     CmdArgs.push_back("-arm-darwin-use-movt=0");
00749   }
00750 
00751   // Setting -mno-global-merge disables the codegen global merge pass. Setting 
00752   // -mglobal-merge has no effect as the pass is enabled by default.
00753   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
00754                                options::OPT_mno_global_merge)) {
00755     if (A->getOption().matches(options::OPT_mno_global_merge))
00756       CmdArgs.push_back("-mno-global-merge");
00757   }
00758 
00759   if (Args.hasArg(options::OPT_mno_implicit_float))
00760     CmdArgs.push_back("-no-implicit-float");
00761 }
00762 
00763 // Get default architecture.
00764 static const char* getMipsArchFromCPU(StringRef CPUName) {
00765   if (CPUName == "mips32" || CPUName == "mips32r2")
00766     return "mips";
00767 
00768   assert((CPUName == "mips64" || CPUName == "mips64r2") &&
00769          "Unexpected cpu name.");
00770 
00771   return "mips64";
00772 }
00773 
00774 // Check that ArchName is a known Mips architecture name.
00775 static bool checkMipsArchName(StringRef ArchName) {
00776   return ArchName == "mips" ||
00777          ArchName == "mipsel" ||
00778          ArchName == "mips64" ||
00779          ArchName == "mips64el";
00780 }
00781 
00782 // Get default target cpu.
00783 static const char* getMipsCPUFromArch(StringRef ArchName) {
00784   if (ArchName == "mips" || ArchName == "mipsel")
00785     return "mips32";
00786 
00787   assert((ArchName == "mips64" || ArchName == "mips64el") &&
00788          "Unexpected arch name.");
00789 
00790   return "mips64";
00791 }
00792 
00793 // Get default ABI.
00794 static const char* getMipsABIFromArch(StringRef ArchName) {
00795     if (ArchName == "mips" || ArchName == "mipsel")
00796       return "o32";
00797     
00798     assert((ArchName == "mips64" || ArchName == "mips64el") &&
00799            "Unexpected arch name.");
00800     return "n64";
00801 }
00802 
00803 // Get CPU and ABI names. They are not independent
00804 // so we have to calculate them together.
00805 static void getMipsCPUAndABI(const ArgList &Args,
00806                              const ToolChain &TC,
00807                              StringRef &CPUName,
00808                              StringRef &ABIName) {
00809   StringRef ArchName;
00810 
00811   // Select target cpu and architecture.
00812   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
00813     CPUName = A->getValue(Args);
00814     ArchName = getMipsArchFromCPU(CPUName);
00815   }
00816   else {
00817     ArchName = Args.MakeArgString(TC.getArchName());
00818     if (!checkMipsArchName(ArchName))
00819       TC.getDriver().Diag(diag::err_drv_invalid_arch_name) << ArchName;
00820     else
00821       CPUName = getMipsCPUFromArch(ArchName);
00822   }
00823  
00824   // Select the ABI to use.
00825   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
00826     ABIName = A->getValue(Args);
00827   else 
00828     ABIName = getMipsABIFromArch(ArchName);
00829 }
00830 
00831 void Clang::AddMIPSTargetArgs(const ArgList &Args,
00832                              ArgStringList &CmdArgs) const {
00833   const Driver &D = getToolChain().getDriver();
00834   StringRef CPUName;
00835   StringRef ABIName;
00836   getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
00837 
00838   CmdArgs.push_back("-target-cpu");
00839   CmdArgs.push_back(CPUName.data());
00840 
00841   CmdArgs.push_back("-target-abi");
00842   CmdArgs.push_back(ABIName.data());
00843 
00844   // Select the float ABI as determined by -msoft-float, -mhard-float,
00845   // and -mfloat-abi=.
00846   StringRef FloatABI;
00847   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
00848                                options::OPT_mhard_float,
00849                                options::OPT_mfloat_abi_EQ)) {
00850     if (A->getOption().matches(options::OPT_msoft_float))
00851       FloatABI = "soft";
00852     else if (A->getOption().matches(options::OPT_mhard_float))
00853       FloatABI = "hard";
00854     else {
00855       FloatABI = A->getValue(Args);
00856       if (FloatABI != "soft" && FloatABI != "single" && FloatABI != "hard") {
00857         D.Diag(diag::err_drv_invalid_mfloat_abi)
00858           << A->getAsString(Args);
00859         FloatABI = "hard";
00860       }
00861     }
00862   }
00863 
00864   // If unspecified, choose the default based on the platform.
00865   if (FloatABI.empty()) {
00866     // Assume "hard", because it's a default value used by gcc.
00867     // When we start to recognize specific target MIPS processors,
00868     // we will be able to select the default more correctly.
00869     FloatABI = "hard";
00870   }
00871 
00872   if (FloatABI == "soft") {
00873     // Floating point operations and argument passing are soft.
00874     CmdArgs.push_back("-msoft-float");
00875     CmdArgs.push_back("-mfloat-abi");
00876     CmdArgs.push_back("soft");
00877 
00878     // FIXME: Note, this is a hack. We need to pass the selected float
00879     // mode to the MipsTargetInfoBase to define appropriate macros there.
00880     // Now it is the only method.
00881     CmdArgs.push_back("-target-feature");
00882     CmdArgs.push_back("+soft-float");
00883   }
00884   else if (FloatABI == "single") {
00885     // Restrict the use of hardware floating-point
00886     // instructions to 32-bit operations.
00887     CmdArgs.push_back("-target-feature");
00888     CmdArgs.push_back("+single-float");
00889   }
00890   else {
00891     // Floating point operations and argument passing are hard.
00892     assert(FloatABI == "hard" && "Invalid float abi!");
00893     CmdArgs.push_back("-mfloat-abi");
00894     CmdArgs.push_back("hard");
00895   }
00896 }
00897 
00898 void Clang::AddSparcTargetArgs(const ArgList &Args,
00899                              ArgStringList &CmdArgs) const {
00900   const Driver &D = getToolChain().getDriver();
00901 
00902   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
00903     CmdArgs.push_back("-target-cpu");
00904     CmdArgs.push_back(A->getValue(Args));
00905   }
00906 
00907   // Select the float ABI as determined by -msoft-float, -mhard-float, and
00908   StringRef FloatABI;
00909   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
00910                                options::OPT_mhard_float)) {
00911     if (A->getOption().matches(options::OPT_msoft_float))
00912       FloatABI = "soft";
00913     else if (A->getOption().matches(options::OPT_mhard_float))
00914       FloatABI = "hard";
00915   }
00916 
00917   // If unspecified, choose the default based on the platform.
00918   if (FloatABI.empty()) {
00919     switch (getToolChain().getTriple().getOS()) {
00920     default:
00921       // Assume "soft", but warn the user we are guessing.
00922       FloatABI = "soft";
00923       D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
00924       break;
00925     }
00926   }
00927 
00928   if (FloatABI == "soft") {
00929     // Floating point operations and argument passing are soft.
00930     //
00931     // FIXME: This changes CPP defines, we need -target-soft-float.
00932     CmdArgs.push_back("-msoft-float");
00933     CmdArgs.push_back("-target-feature");
00934     CmdArgs.push_back("+soft-float");
00935   } else {
00936     assert(FloatABI == "hard" && "Invalid float abi!");
00937     CmdArgs.push_back("-mhard-float");
00938   }
00939 }
00940 
00941 void Clang::AddX86TargetArgs(const ArgList &Args,
00942                              ArgStringList &CmdArgs) const {
00943   if (!Args.hasFlag(options::OPT_mred_zone,
00944                     options::OPT_mno_red_zone,
00945                     true) ||
00946       Args.hasArg(options::OPT_mkernel) ||
00947       Args.hasArg(options::OPT_fapple_kext))
00948     CmdArgs.push_back("-disable-red-zone");
00949 
00950   if (Args.hasFlag(options::OPT_msoft_float,
00951                    options::OPT_mno_soft_float,
00952                    false))
00953     CmdArgs.push_back("-no-implicit-float");
00954 
00955   const char *CPUName = 0;
00956   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
00957     if (StringRef(A->getValue(Args)) == "native") {
00958       // FIXME: Reject attempts to use -march=native unless the target matches
00959       // the host.
00960       //
00961       // FIXME: We should also incorporate the detected target features for use
00962       // with -native.
00963       std::string CPU = llvm::sys::getHostCPUName();
00964       if (!CPU.empty() && CPU != "generic")
00965         CPUName = Args.MakeArgString(CPU);
00966     } else
00967       CPUName = A->getValue(Args);
00968   }
00969 
00970   // Select the default CPU if none was given (or detection failed).
00971   if (!CPUName) {
00972     // FIXME: Need target hooks.
00973     if (getToolChain().getTriple().isOSDarwin()) {
00974       if (getToolChain().getArch() == llvm::Triple::x86_64)
00975         CPUName = "core2";
00976       else if (getToolChain().getArch() == llvm::Triple::x86)
00977         CPUName = "yonah";
00978     } else if (getToolChain().getOS().startswith("haiku"))  {
00979       if (getToolChain().getArch() == llvm::Triple::x86_64)
00980         CPUName = "x86-64";
00981       else if (getToolChain().getArch() == llvm::Triple::x86)
00982         CPUName = "i586";
00983     } else if (getToolChain().getOS().startswith("openbsd"))  {
00984       if (getToolChain().getArch() == llvm::Triple::x86_64)
00985         CPUName = "x86-64";
00986       else if (getToolChain().getArch() == llvm::Triple::x86)
00987         CPUName = "i486";
00988     } else if (getToolChain().getOS().startswith("freebsd"))  {
00989       if (getToolChain().getArch() == llvm::Triple::x86_64)
00990         CPUName = "x86-64";
00991       else if (getToolChain().getArch() == llvm::Triple::x86)
00992         CPUName = "i486";
00993     } else if (getToolChain().getOS().startswith("netbsd"))  {
00994       if (getToolChain().getArch() == llvm::Triple::x86_64)
00995         CPUName = "x86-64";
00996       else if (getToolChain().getArch() == llvm::Triple::x86)
00997         CPUName = "i486";
00998     } else {
00999       if (getToolChain().getArch() == llvm::Triple::x86_64)
01000         CPUName = "x86-64";
01001       else if (getToolChain().getArch() == llvm::Triple::x86)
01002         CPUName = "pentium4";
01003     }
01004   }
01005 
01006   if (CPUName) {
01007     CmdArgs.push_back("-target-cpu");
01008     CmdArgs.push_back(CPUName);
01009   }
01010 
01011   // The required algorithm here is slightly strange: the options are applied
01012   // in order (so -mno-sse -msse2 disables SSE3), but any option that gets
01013   // directly overridden later is ignored (so "-mno-sse -msse2 -mno-sse2 -msse"
01014   // is equivalent to "-mno-sse2 -msse"). The -cc1 handling deals with the
01015   // former correctly, but not the latter; handle directly-overridden
01016   // attributes here.
01017   llvm::StringMap<unsigned> PrevFeature;
01018   std::vector<const char*> Features;
01019   for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
01020          ie = Args.filtered_end(); it != ie; ++it) {
01021     StringRef Name = (*it)->getOption().getName();
01022     (*it)->claim();
01023 
01024     // Skip over "-m".
01025     assert(Name.startswith("-m") && "Invalid feature name.");
01026     Name = Name.substr(2);
01027 
01028     bool IsNegative = Name.startswith("no-");
01029     if (IsNegative)
01030       Name = Name.substr(3);
01031 
01032     unsigned& Prev = PrevFeature[Name];
01033     if (Prev)
01034       Features[Prev - 1] = 0;
01035     Prev = Features.size() + 1;
01036     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
01037   }
01038   for (unsigned i = 0; i < Features.size(); i++) {
01039     if (Features[i]) {
01040       CmdArgs.push_back("-target-feature");
01041       CmdArgs.push_back(Features[i]);
01042     }
01043   }
01044 }
01045 
01046 static Arg* getLastHexagonArchArg (const ArgList &Args)
01047 {
01048   Arg * A = NULL;
01049 
01050   for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
01051        it != ie; ++it) {
01052     if ((*it)->getOption().matches(options::OPT_march_EQ) ||
01053         (*it)->getOption().matches(options::OPT_mcpu_EQ)) {
01054       A = *it;
01055       A->claim();
01056     }
01057     else if ((*it)->getOption().matches(options::OPT_m_Joined)){
01058       StringRef Value = (*it)->getValue(Args,0);
01059       if (Value.startswith("v")) {
01060         A = *it;
01061         A->claim();
01062       }
01063     }
01064   }
01065   return A;
01066 }
01067 
01068 static StringRef getHexagonTargetCPU(const ArgList &Args)
01069 {
01070   Arg *A;
01071   llvm::StringRef WhichHexagon;
01072 
01073   // Select the default CPU (v4) if none was given or detection failed.
01074   if ((A = getLastHexagonArchArg (Args))) {
01075     WhichHexagon = A->getValue(Args);
01076     if (WhichHexagon == "")
01077       return "v4";
01078     else
01079       return WhichHexagon;
01080   }
01081   else
01082     return "v4";
01083 }
01084 
01085 void Clang::AddHexagonTargetArgs(const ArgList &Args,
01086                                  ArgStringList &CmdArgs) const {
01087   llvm::Triple Triple = getToolChain().getTriple();
01088 
01089   CmdArgs.push_back("-target-cpu");
01090   CmdArgs.push_back(Args.MakeArgString("hexagon" + getHexagonTargetCPU(Args)));
01091   CmdArgs.push_back("-fno-signed-char");
01092   CmdArgs.push_back("-nobuiltininc");
01093 
01094   if (Args.hasArg(options::OPT_mqdsp6_compat))
01095     CmdArgs.push_back("-mqdsp6-compat");
01096 
01097   if (Arg *A = Args.getLastArg(options::OPT_G,
01098                                options::OPT_msmall_data_threshold_EQ)) {
01099     std::string SmallDataThreshold="-small-data-threshold=";
01100     SmallDataThreshold += A->getValue(Args);
01101     CmdArgs.push_back ("-mllvm");
01102     CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
01103     A->claim();
01104   }
01105 
01106   if (!Args.hasArg(options::OPT_fno_short_enums))
01107     CmdArgs.push_back("-fshort-enums");
01108   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
01109     CmdArgs.push_back ("-mllvm");
01110     CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
01111   }
01112   CmdArgs.push_back ("-mllvm");
01113   CmdArgs.push_back ("-machine-sink-split=0");
01114 }
01115 
01116 static bool
01117 shouldUseExceptionTablesForObjCExceptions(unsigned objcABIVersion,
01118                                           const llvm::Triple &Triple) {
01119   // We use the zero-cost exception tables for Objective-C if the non-fragile
01120   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
01121   // later.
01122 
01123   if (objcABIVersion >= 2)
01124     return true;
01125 
01126   if (!Triple.isOSDarwin())
01127     return false;
01128 
01129   return (!Triple.isMacOSXVersionLT(10,5) &&
01130           (Triple.getArch() == llvm::Triple::x86_64 ||
01131            Triple.getArch() == llvm::Triple::arm));
01132 }
01133 
01134 /// addExceptionArgs - Adds exception related arguments to the driver command
01135 /// arguments. There's a master flag, -fexceptions and also language specific
01136 /// flags to enable/disable C++ and Objective-C exceptions.
01137 /// This makes it possible to for example disable C++ exceptions but enable
01138 /// Objective-C exceptions.
01139 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
01140                              const llvm::Triple &Triple,
01141                              bool KernelOrKext,
01142                              unsigned objcABIVersion,
01143                              ArgStringList &CmdArgs) {
01144   if (KernelOrKext) {
01145     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
01146     // arguments now to avoid warnings about unused arguments.
01147     Args.ClaimAllArgs(options::OPT_fexceptions);
01148     Args.ClaimAllArgs(options::OPT_fno_exceptions);
01149     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
01150     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
01151     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
01152     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
01153     return;
01154   }
01155 
01156   // Exceptions are enabled by default.
01157   bool ExceptionsEnabled = true;
01158 
01159   // This keeps track of whether exceptions were explicitly turned on or off.
01160   bool DidHaveExplicitExceptionFlag = false;
01161 
01162   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
01163                                options::OPT_fno_exceptions)) {
01164     if (A->getOption().matches(options::OPT_fexceptions))
01165       ExceptionsEnabled = true;
01166     else
01167       ExceptionsEnabled = false;
01168 
01169     DidHaveExplicitExceptionFlag = true;
01170   }
01171 
01172   bool ShouldUseExceptionTables = false;
01173 
01174   // Exception tables and cleanups can be enabled with -fexceptions even if the
01175   // language itself doesn't support exceptions.
01176   if (ExceptionsEnabled && DidHaveExplicitExceptionFlag)
01177     ShouldUseExceptionTables = true;
01178 
01179   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
01180   // is not necessarily sensible, but follows GCC.
01181   if (types::isObjC(InputType) &&
01182       Args.hasFlag(options::OPT_fobjc_exceptions,
01183                    options::OPT_fno_objc_exceptions,
01184                    true)) {
01185     CmdArgs.push_back("-fobjc-exceptions");
01186 
01187     ShouldUseExceptionTables |=
01188       shouldUseExceptionTablesForObjCExceptions(objcABIVersion, Triple);
01189   }
01190 
01191   if (types::isCXX(InputType)) {
01192     bool CXXExceptionsEnabled = ExceptionsEnabled;
01193 
01194     if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
01195                                  options::OPT_fno_cxx_exceptions,
01196                                  options::OPT_fexceptions,
01197                                  options::OPT_fno_exceptions)) {
01198       if (A->getOption().matches(options::OPT_fcxx_exceptions))
01199         CXXExceptionsEnabled = true;
01200       else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
01201         CXXExceptionsEnabled = false;
01202     }
01203 
01204     if (CXXExceptionsEnabled) {
01205       CmdArgs.push_back("-fcxx-exceptions");
01206 
01207       ShouldUseExceptionTables = true;
01208     }
01209   }
01210 
01211   if (ShouldUseExceptionTables)
01212     CmdArgs.push_back("-fexceptions");
01213 }
01214 
01215 static bool ShouldDisableCFI(const ArgList &Args,
01216                              const ToolChain &TC) {
01217   bool Default = true;
01218   if (TC.getTriple().isOSDarwin()) {
01219     // The native darwin assembler doesn't support cfi directives, so
01220     // we disable them if we think the .s file will be passed to it.
01221     Default = Args.hasFlag(options::OPT_integrated_as,
01222          options::OPT_no_integrated_as,
01223          TC.IsIntegratedAssemblerDefault());
01224   }
01225   return !Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
01226            options::OPT_fno_dwarf2_cfi_asm,
01227            Default);
01228 }
01229 
01230 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
01231                                         const ToolChain &TC) {
01232   bool IsIADefault = TC.IsIntegratedAssemblerDefault();
01233   bool UseIntegratedAs = Args.hasFlag(options::OPT_integrated_as,
01234                                       options::OPT_no_integrated_as,
01235                                       IsIADefault);
01236   bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
01237                                         options::OPT_fno_dwarf_directory_asm,
01238                                         UseIntegratedAs);
01239   return !UseDwarfDirectory;
01240 }
01241 
01242 /// \brief Check whether the given input tree contains any compilation actions.
01243 static bool ContainsCompileAction(const Action *A) {
01244   if (isa<CompileJobAction>(A))
01245     return true;
01246 
01247   for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
01248     if (ContainsCompileAction(*it))
01249       return true;
01250 
01251   return false;
01252 }
01253 
01254 /// \brief Check if -relax-all should be passed to the internal assembler.
01255 /// This is done by default when compiling non-assembler source with -O0.
01256 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
01257   bool RelaxDefault = true;
01258 
01259   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
01260     RelaxDefault = A->getOption().matches(options::OPT_O0);
01261 
01262   if (RelaxDefault) {
01263     RelaxDefault = false;
01264     for (ActionList::const_iterator it = C.getActions().begin(),
01265            ie = C.getActions().end(); it != ie; ++it) {
01266       if (ContainsCompileAction(*it)) {
01267         RelaxDefault = true;
01268         break;
01269       }
01270     }
01271   }
01272 
01273   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
01274     RelaxDefault);
01275 }
01276 
01277 /// If AddressSanitizer is enabled, add appropriate linker flags (Linux).
01278 /// This needs to be called before we add the C run-time (malloc, etc).
01279 static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
01280                            ArgStringList &CmdArgs) {
01281   if (!Args.hasFlag(options::OPT_faddress_sanitizer,
01282                     options::OPT_fno_address_sanitizer, false))
01283     return;
01284   if(TC.getTriple().getEnvironment() == llvm::Triple::ANDROIDEABI) {
01285     if (!Args.hasArg(options::OPT_shared)) {
01286       // For an executable, we add a .preinit_array stub.
01287       CmdArgs.push_back("-u");
01288       CmdArgs.push_back("__asan_preinit");
01289       CmdArgs.push_back("-lasan");
01290     }
01291 
01292     CmdArgs.push_back("-lasan_preload");
01293     CmdArgs.push_back("-ldl");
01294   } else {
01295     if (!Args.hasArg(options::OPT_shared)) {
01296       // LibAsan is "libclang_rt.asan-<ArchName>.a" in the Linux library
01297       // resource directory.
01298       SmallString<128> LibAsan(TC.getDriver().ResourceDir);
01299       llvm::sys::path::append(LibAsan, "lib", "linux",
01300                               (Twine("libclang_rt.asan-") +
01301                                TC.getArchName() + ".a"));
01302       CmdArgs.push_back(Args.MakeArgString(LibAsan));
01303       CmdArgs.push_back("-lpthread");
01304       CmdArgs.push_back("-ldl");
01305       CmdArgs.push_back("-export-dynamic");
01306     }
01307   }
01308 }
01309 
01310 /// If ThreadSanitizer is enabled, add appropriate linker flags (Linux).
01311 /// This needs to be called before we add the C run-time (malloc, etc).
01312 static void addTsanRTLinux(const ToolChain &TC, const ArgList &Args,
01313                            ArgStringList &CmdArgs) {
01314   if (!Args.hasFlag(options::OPT_fthread_sanitizer,
01315                     options::OPT_fno_thread_sanitizer, false))
01316     return;
01317   if (!Args.hasArg(options::OPT_shared)) {
01318     // LibTsan is "libclang_rt.tsan-<ArchName>.a" in the Linux library
01319     // resource directory.
01320     SmallString<128> LibTsan(TC.getDriver().ResourceDir);
01321     llvm::sys::path::append(LibTsan, "lib", "linux",
01322                             (Twine("libclang_rt.tsan-") +
01323                              TC.getArchName() + ".a"));
01324     CmdArgs.push_back(Args.MakeArgString(LibTsan));
01325     CmdArgs.push_back("-lpthread");
01326     CmdArgs.push_back("-ldl");
01327     CmdArgs.push_back("-export-dynamic");
01328   }
01329 }
01330 
01331 static bool shouldUseFramePointer(const ArgList &Args,
01332                                   const llvm::Triple &Triple) {
01333   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
01334                                options::OPT_fomit_frame_pointer))
01335     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
01336 
01337   // Don't use a frame pointer on linux x86 and x86_64 if optimizing.
01338   if ((Triple.getArch() == llvm::Triple::x86_64 ||
01339        Triple.getArch() == llvm::Triple::x86) &&
01340       Triple.getOS() == llvm::Triple::Linux) {
01341     if (Arg *A = Args.getLastArg(options::OPT_O_Group))
01342       if (!A->getOption().matches(options::OPT_O0))
01343         return false;
01344   }
01345 
01346   return true;
01347 }
01348 
01349 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
01350                          const InputInfo &Output,
01351                          const InputInfoList &Inputs,
01352                          const ArgList &Args,
01353                          const char *LinkingOutput) const {
01354   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
01355                                   options::OPT_fapple_kext);
01356   const Driver &D = getToolChain().getDriver();
01357   ArgStringList CmdArgs;
01358 
01359   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
01360 
01361   // Invoke ourselves in -cc1 mode.
01362   //
01363   // FIXME: Implement custom jobs for internal actions.
01364   CmdArgs.push_back("-cc1");
01365 
01366   // Add the "effective" target triple.
01367   CmdArgs.push_back("-triple");
01368   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
01369   CmdArgs.push_back(Args.MakeArgString(TripleStr));
01370 
01371   // Select the appropriate action.
01372   bool IsRewriter = false;
01373   bool IsModernRewriter = false;
01374   
01375   if (isa<AnalyzeJobAction>(JA)) {
01376     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
01377     CmdArgs.push_back("-analyze");
01378   } else if (isa<MigrateJobAction>(JA)) {
01379     CmdArgs.push_back("-migrate");
01380   } else if (isa<PreprocessJobAction>(JA)) {
01381     if (Output.getType() == types::TY_Dependencies)
01382       CmdArgs.push_back("-Eonly");
01383     else
01384       CmdArgs.push_back("-E");
01385   } else if (isa<AssembleJobAction>(JA)) {
01386     CmdArgs.push_back("-emit-obj");
01387 
01388     if (UseRelaxAll(C, Args))
01389       CmdArgs.push_back("-mrelax-all");
01390 
01391     // When using an integrated assembler, translate -Wa, and -Xassembler
01392     // options.
01393     for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
01394                                                options::OPT_Xassembler),
01395            ie = Args.filtered_end(); it != ie; ++it) {
01396       const Arg *A = *it;
01397       A->claim();
01398 
01399       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
01400         StringRef Value = A->getValue(Args, i);
01401 
01402         if (Value == "-force_cpusubtype_ALL") {
01403           // Do nothing, this is the default and we don't support anything else.
01404         } else if (Value == "-L") {
01405           CmdArgs.push_back("-msave-temp-labels");
01406         } else if (Value == "--fatal-warnings") {
01407           CmdArgs.push_back("-mllvm");
01408           CmdArgs.push_back("-fatal-assembler-warnings");
01409         } else if (Value == "--noexecstack") {
01410           CmdArgs.push_back("-mnoexecstack");
01411         } else {
01412           D.Diag(diag::err_drv_unsupported_option_argument)
01413             << A->getOption().getName() << Value;
01414         }
01415       }
01416     }
01417 
01418     // Also ignore explicit -force_cpusubtype_ALL option.
01419     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
01420   } else if (isa<PrecompileJobAction>(JA)) {
01421     // Use PCH if the user requested it.
01422     bool UsePCH = D.CCCUsePCH;
01423 
01424     if (UsePCH)
01425       CmdArgs.push_back("-emit-pch");
01426     else
01427       CmdArgs.push_back("-emit-pth");
01428   } else {
01429     assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
01430 
01431     if (JA.getType() == types::TY_Nothing) {
01432       CmdArgs.push_back("-fsyntax-only");
01433     } else if (JA.getType() == types::TY_LLVM_IR ||
01434                JA.getType() == types::TY_LTO_IR) {
01435       CmdArgs.push_back("-emit-llvm");
01436     } else if (JA.getType() == types::TY_LLVM_BC ||
01437                JA.getType() == types::TY_LTO_BC) {
01438       CmdArgs.push_back("-emit-llvm-bc");
01439     } else if (JA.getType() == types::TY_PP_Asm) {
01440       CmdArgs.push_back("-S");
01441     } else if (JA.getType() == types::TY_AST) {
01442       CmdArgs.push_back("-emit-pch");
01443     } else if (JA.getType() == types::TY_RewrittenObjC) {
01444       CmdArgs.push_back("-rewrite-objc");
01445       IsModernRewriter = true;
01446     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
01447       CmdArgs.push_back("-rewrite-objc");
01448       IsRewriter = true;
01449     } else {
01450       assert(JA.getType() == types::TY_PP_Asm &&
01451              "Unexpected output type!");
01452     }
01453   }
01454 
01455   // The make clang go fast button.
01456   CmdArgs.push_back("-disable-free");
01457 
01458   // Disable the verification pass in -asserts builds.
01459 #ifdef NDEBUG
01460   CmdArgs.push_back("-disable-llvm-verifier");
01461 #endif
01462 
01463   // Set the main file name, so that debug info works even with
01464   // -save-temps.
01465   CmdArgs.push_back("-main-file-name");
01466   CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
01467 
01468   // Some flags which affect the language (via preprocessor
01469   // defines). See darwin::CC1::AddCPPArgs.
01470   if (Args.hasArg(options::OPT_static))
01471     CmdArgs.push_back("-static-define");
01472 
01473   if (isa<AnalyzeJobAction>(JA)) {
01474     // Enable region store model by default.
01475     CmdArgs.push_back("-analyzer-store=region");
01476 
01477     // Treat blocks as analysis entry points.
01478     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
01479 
01480     CmdArgs.push_back("-analyzer-eagerly-assume");
01481 
01482     CmdArgs.push_back("-analyzer-ipa=inlining");
01483 
01484     // Add default argument set.
01485     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
01486       CmdArgs.push_back("-analyzer-checker=core");
01487 
01488       if (getToolChain().getTriple().getOS() != llvm::Triple::Win32)
01489         CmdArgs.push_back("-analyzer-checker=unix");
01490 
01491       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
01492         CmdArgs.push_back("-analyzer-checker=osx");
01493       
01494       CmdArgs.push_back("-analyzer-checker=deadcode");
01495       
01496       // Enable the following experimental checkers for testing. 
01497       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
01498       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
01499       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
01500       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");      
01501       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
01502       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
01503     }
01504 
01505     // Set the output format. The default is plist, for (lame) historical
01506     // reasons.
01507     CmdArgs.push_back("-analyzer-output");
01508     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
01509       CmdArgs.push_back(A->getValue(Args));
01510     else
01511       CmdArgs.push_back("plist");
01512 
01513     // Disable the presentation of standard compiler warnings when
01514     // using --analyze.  We only want to show static analyzer diagnostics
01515     // or frontend errors.
01516     CmdArgs.push_back("-w");
01517 
01518     // Add -Xanalyzer arguments when running as analyzer.
01519     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
01520   }
01521 
01522   CheckCodeGenerationOptions(D, Args);
01523 
01524   // Perform argument translation for LLVM backend. This
01525   // takes some care in reconciling with llvm-gcc. The
01526   // issue is that llvm-gcc translates these options based on
01527   // the values in cc1, whereas we are processing based on
01528   // the driver arguments.
01529 
01530   // This comes from the default translation the driver + cc1
01531   // would do to enable flag_pic.
01532   //
01533   // FIXME: Centralize this code.
01534   Arg *LastPICArg = 0;
01535   for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I) {
01536     if ((*I)->getOption().matches(options::OPT_fPIC) ||
01537         (*I)->getOption().matches(options::OPT_fno_PIC) ||
01538         (*I)->getOption().matches(options::OPT_fpic) ||
01539         (*I)->getOption().matches(options::OPT_fno_pic) ||
01540         (*I)->getOption().matches(options::OPT_fPIE) ||
01541         (*I)->getOption().matches(options::OPT_fno_PIE) ||
01542         (*I)->getOption().matches(options::OPT_fpie) ||
01543         (*I)->getOption().matches(options::OPT_fno_pie)) {
01544       LastPICArg = *I;
01545       (*I)->claim();
01546     }
01547   }
01548   bool PICDisabled = false;
01549   bool PICEnabled = false;
01550   bool PICForPIE = false;
01551   if (LastPICArg) {
01552     PICForPIE = (LastPICArg->getOption().matches(options::OPT_fPIE) ||
01553                  LastPICArg->getOption().matches(options::OPT_fpie));
01554     PICEnabled = (PICForPIE ||
01555                   LastPICArg->getOption().matches(options::OPT_fPIC) ||
01556                   LastPICArg->getOption().matches(options::OPT_fpic));
01557     PICDisabled = !PICEnabled;
01558   }
01559   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
01560   // PIC or PIE options above, if these show up, PIC is disabled.
01561   if (Args.hasArg(options::OPT_mkernel))
01562     PICDisabled = true;
01563   if (Args.hasArg(options::OPT_static))
01564     PICDisabled = true;
01565   bool DynamicNoPIC = Args.hasArg(options::OPT_mdynamic_no_pic);
01566 
01567   // Select the relocation model.
01568   const char *Model = getToolChain().GetForcedPicModel();
01569   if (!Model) {
01570     if (DynamicNoPIC)
01571       Model = "dynamic-no-pic";
01572     else if (PICDisabled)
01573       Model = "static";
01574     else if (PICEnabled)
01575       Model = "pic";
01576     else
01577       Model = getToolChain().GetDefaultRelocationModel();
01578   }
01579   StringRef ModelStr = Model ? Model : "";
01580   if (Model && ModelStr != "pic") {
01581     CmdArgs.push_back("-mrelocation-model");
01582     CmdArgs.push_back(Model);
01583   }
01584 
01585   // Infer the __PIC__ and __PIE__ values.
01586   if (ModelStr == "pic" && PICForPIE) {
01587     CmdArgs.push_back("-pie-level");
01588     CmdArgs.push_back((LastPICArg &&
01589                        LastPICArg->getOption().matches(options::OPT_fPIE)) ?
01590                       "2" : "1");
01591   } else if (ModelStr == "pic" || ModelStr == "dynamic-no-pic") {
01592     CmdArgs.push_back("-pic-level");
01593     CmdArgs.push_back(((ModelStr != "dynamic-no-pic" && LastPICArg &&
01594                         LastPICArg->getOption().matches(options::OPT_fPIC)) ||
01595                        getToolChain().getTriple().isOSDarwin()) ? "2" : "1");
01596   }
01597 
01598   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
01599                     options::OPT_fno_merge_all_constants))
01600     CmdArgs.push_back("-fno-merge-all-constants");
01601 
01602   // LLVM Code Generator Options.
01603 
01604   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
01605     CmdArgs.push_back("-mregparm");
01606     CmdArgs.push_back(A->getValue(Args));
01607   }
01608 
01609   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
01610     CmdArgs.push_back("-mrtd");
01611 
01612   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
01613     CmdArgs.push_back("-mdisable-fp-elim");
01614   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
01615                     options::OPT_fno_zero_initialized_in_bss))
01616     CmdArgs.push_back("-mno-zero-initialized-in-bss");
01617   if (!Args.hasFlag(options::OPT_fstrict_aliasing,
01618                     options::OPT_fno_strict_aliasing,
01619                     getToolChain().IsStrictAliasingDefault()))
01620     CmdArgs.push_back("-relaxed-aliasing");
01621   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
01622                    false))
01623     CmdArgs.push_back("-fstrict-enums");
01624   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
01625                     options::OPT_fno_optimize_sibling_calls))
01626     CmdArgs.push_back("-mdisable-tail-calls");
01627 
01628   // Handle various floating point optimization flags, mapping them to the
01629   // appropriate LLVM code generation flags. The pattern for all of these is to
01630   // default off the codegen optimizations, and if any flag enables them and no
01631   // flag disables them after the flag enabling them, enable the codegen
01632   // optimization. This is complicated by several "umbrella" flags.
01633   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
01634                                options::OPT_ffinite_math_only,
01635                                options::OPT_fno_finite_math_only,
01636                                options::OPT_fhonor_infinities,
01637                                options::OPT_fno_honor_infinities))
01638     if (A->getOption().getID() != options::OPT_fno_finite_math_only &&
01639         A->getOption().getID() != options::OPT_fhonor_infinities)
01640       CmdArgs.push_back("-menable-no-infs");
01641   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
01642                                options::OPT_ffinite_math_only,
01643                                options::OPT_fno_finite_math_only,
01644                                options::OPT_fhonor_nans,
01645                                options::OPT_fno_honor_nans))
01646     if (A->getOption().getID() != options::OPT_fno_finite_math_only &&
01647         A->getOption().getID() != options::OPT_fhonor_nans)
01648       CmdArgs.push_back("-menable-no-nans");
01649 
01650   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
01651   bool MathErrno = getToolChain().IsMathErrnoDefault();
01652   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
01653                                options::OPT_fmath_errno,
01654                                options::OPT_fno_math_errno))
01655     MathErrno = A->getOption().getID() == options::OPT_fmath_errno;
01656   if (MathErrno)
01657     CmdArgs.push_back("-fmath-errno");
01658 
01659   // There are several flags which require disabling very specific
01660   // optimizations. Any of these being disabled forces us to turn off the
01661   // entire set of LLVM optimizations, so collect them through all the flag
01662   // madness.
01663   bool AssociativeMath = false;
01664   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
01665                                options::OPT_funsafe_math_optimizations,
01666                                options::OPT_fno_unsafe_math_optimizations,
01667                                options::OPT_fassociative_math,
01668                                options::OPT_fno_associative_math))
01669     if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
01670         A->getOption().getID() != options::OPT_fno_associative_math)
01671       AssociativeMath = true;
01672   bool ReciprocalMath = false;
01673   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
01674                                options::OPT_funsafe_math_optimizations,
01675                                options::OPT_fno_unsafe_math_optimizations,
01676                                options::OPT_freciprocal_math,
01677                                options::OPT_fno_reciprocal_math))
01678     if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
01679         A->getOption().getID() != options::OPT_fno_reciprocal_math)
01680       ReciprocalMath = true;
01681   bool SignedZeros = true;
01682   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
01683                                options::OPT_funsafe_math_optimizations,
01684                                options::OPT_fno_unsafe_math_optimizations,
01685                                options::OPT_fsigned_zeros,
01686                                options::OPT_fno_signed_zeros))
01687     if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
01688         A->getOption().getID() != options::OPT_fsigned_zeros)
01689       SignedZeros = false;
01690   bool TrappingMath = true;
01691   if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
01692                                options::OPT_funsafe_math_optimizations,
01693                                options::OPT_fno_unsafe_math_optimizations,
01694                                options::OPT_ftrapping_math,
01695                                options::OPT_fno_trapping_math))
01696     if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
01697         A->getOption().getID() != options::OPT_ftrapping_math)
01698       TrappingMath = false;
01699   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
01700       !TrappingMath)
01701     CmdArgs.push_back("-menable-unsafe-fp-math");
01702 
01703   // We separately look for the '-ffast-math' flag, and if we find it, tell the
01704   // frontend to provide the appropriate preprocessor macros. This is distinct
01705   // from enabling any optimizations as it induces a language change which must
01706   // survive serialization and deserialization, etc.
01707   if (Args.hasArg(options::OPT_ffast_math))
01708     CmdArgs.push_back("-ffast-math");
01709 
01710   // Decide whether to use verbose asm. Verbose assembly is the default on
01711   // toolchains which have the integrated assembler on by default.
01712   bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
01713   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
01714                    IsVerboseAsmDefault) ||
01715       Args.hasArg(options::OPT_dA))
01716     CmdArgs.push_back("-masm-verbose");
01717 
01718   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
01719     CmdArgs.push_back("-mdebug-pass");
01720     CmdArgs.push_back("Structure");
01721   }
01722   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
01723     CmdArgs.push_back("-mdebug-pass");
01724     CmdArgs.push_back("Arguments");
01725   }
01726 
01727   // Enable -mconstructor-aliases except on darwin, where we have to
01728   // work around a linker bug;  see <rdar://problem/7651567>.
01729   if (!getToolChain().getTriple().isOSDarwin())
01730     CmdArgs.push_back("-mconstructor-aliases");
01731 
01732   // Darwin's kernel doesn't support guard variables; just die if we
01733   // try to use them.
01734   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
01735     CmdArgs.push_back("-fforbid-guard-variables");
01736 
01737   if (Args.hasArg(options::OPT_mms_bitfields)) {
01738     CmdArgs.push_back("-mms-bitfields");
01739   }
01740 
01741   // This is a coarse approximation of what llvm-gcc actually does, both
01742   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
01743   // complicated ways.
01744   bool AsynchronousUnwindTables =
01745     Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
01746                  options::OPT_fno_asynchronous_unwind_tables,
01747                  getToolChain().IsUnwindTablesDefault() &&
01748                  !KernelOrKext);
01749   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
01750                    AsynchronousUnwindTables))
01751     CmdArgs.push_back("-munwind-tables");
01752 
01753   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
01754     CmdArgs.push_back("-mlimit-float-precision");
01755     CmdArgs.push_back(A->getValue(Args));
01756   }
01757 
01758   // FIXME: Handle -mtune=.
01759   (void) Args.hasArg(options::OPT_mtune_EQ);
01760 
01761   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
01762     CmdArgs.push_back("-mcode-model");
01763     CmdArgs.push_back(A->getValue(Args));
01764   }
01765 
01766   // Add target specific cpu and features flags.
01767   switch(getToolChain().getTriple().getArch()) {
01768   default:
01769     break;
01770 
01771   case llvm::Triple::arm:
01772   case llvm::Triple::thumb:
01773     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
01774     break;
01775 
01776   case llvm::Triple::mips:
01777   case llvm::Triple::mipsel:
01778   case llvm::Triple::mips64:
01779   case llvm::Triple::mips64el:
01780     AddMIPSTargetArgs(Args, CmdArgs);
01781     break;
01782 
01783   case llvm::Triple::sparc:
01784     AddSparcTargetArgs(Args, CmdArgs);
01785     break;
01786 
01787   case llvm::Triple::x86:
01788   case llvm::Triple::x86_64:
01789     AddX86TargetArgs(Args, CmdArgs);
01790     break;
01791 
01792   case llvm::Triple::hexagon:
01793     AddHexagonTargetArgs(Args, CmdArgs);
01794     break;
01795   }
01796 
01797 
01798 
01799   // Pass the linker version in use.
01800   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
01801     CmdArgs.push_back("-target-linker-version");
01802     CmdArgs.push_back(A->getValue(Args));
01803   }
01804 
01805   // -mno-omit-leaf-frame-pointer is the default on Darwin.
01806   if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
01807                    options::OPT_mno_omit_leaf_frame_pointer,
01808                    !getToolChain().getTriple().isOSDarwin()))
01809     CmdArgs.push_back("-momit-leaf-frame-pointer");
01810 
01811   // Explicitly error on some things we know we don't support and can't just
01812   // ignore.
01813   types::ID InputType = Inputs[0].getType();
01814   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
01815     Arg *Unsupported;
01816     if (types::isCXX(InputType) &&
01817         getToolChain().getTriple().isOSDarwin() &&
01818         getToolChain().getTriple().getArch() == llvm::Triple::x86) {
01819       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
01820           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
01821         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
01822           << Unsupported->getOption().getName();
01823     }
01824   }
01825 
01826   Args.AddAllArgs(CmdArgs, options::OPT_v);
01827   Args.AddLastArg(CmdArgs, options::OPT_H);
01828   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
01829     CmdArgs.push_back("-header-include-file");
01830     CmdArgs.push_back(D.CCPrintHeadersFilename ?
01831                       D.CCPrintHeadersFilename : "-");
01832   }
01833   Args.AddLastArg(CmdArgs, options::OPT_P);
01834   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
01835 
01836   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
01837     CmdArgs.push_back("-diagnostic-log-file");
01838     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
01839                       D.CCLogDiagnosticsFilename : "-");
01840   }
01841 
01842   // Special case debug options to only pass -g to clang. This is
01843   // wrong.
01844   Args.ClaimAllArgs(options::OPT_g_Group);
01845   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
01846     if (!A->getOption().matches(options::OPT_g0)) {
01847       CmdArgs.push_back("-g");
01848     }
01849   if (Args.hasArg(options::OPT_gline_tables_only))
01850     CmdArgs.push_back("-gline-tables-only");
01851 
01852   Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
01853   Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
01854 
01855   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
01856 
01857   if (Args.hasArg(options::OPT_ftest_coverage) ||
01858       Args.hasArg(options::OPT_coverage))
01859     CmdArgs.push_back("-femit-coverage-notes");
01860   if (Args.hasArg(options::OPT_fprofile_arcs) ||
01861       Args.hasArg(options::OPT_coverage))
01862     CmdArgs.push_back("-femit-coverage-data");
01863 
01864   if (C.getArgs().hasArg(options::OPT_c) ||
01865       C.getArgs().hasArg(options::OPT_S)) {
01866     if (Output.isFilename()) {
01867       CmdArgs.push_back("-coverage-file");
01868       CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
01869     }
01870   }
01871 
01872   // Pass options for controlling the default header search paths.
01873   if (Args.hasArg(options::OPT_nostdinc)) {
01874     CmdArgs.push_back("-nostdsysteminc");
01875     CmdArgs.push_back("-nobuiltininc");
01876   } else {
01877     if (Args.hasArg(options::OPT_nostdlibinc))
01878         CmdArgs.push_back("-nostdsysteminc");
01879     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
01880     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
01881   }
01882 
01883   // Pass the path to compiler resource files.
01884   CmdArgs.push_back("-resource-dir");
01885   CmdArgs.push_back(D.ResourceDir.c_str());
01886 
01887   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
01888 
01889   bool ARCMTEnabled = false;
01890   if (!Args.hasArg(options::OPT_fno_objc_arc)) {
01891     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
01892                                        options::OPT_ccc_arcmt_modify,
01893                                        options::OPT_ccc_arcmt_migrate)) {
01894       ARCMTEnabled = true;
01895       switch (A->getOption().getID()) {
01896       default:
01897         llvm_unreachable("missed a case");
01898       case options::OPT_ccc_arcmt_check:
01899         CmdArgs.push_back("-arcmt-check");
01900         break;
01901       case options::OPT_ccc_arcmt_modify:
01902         CmdArgs.push_back("-arcmt-modify");
01903         break;
01904       case options::OPT_ccc_arcmt_migrate:
01905         CmdArgs.push_back("-arcmt-migrate");
01906         CmdArgs.push_back("-mt-migrate-directory");
01907         CmdArgs.push_back(A->getValue(Args));
01908 
01909         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
01910         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
01911         break;
01912       }
01913     }
01914   }
01915 
01916   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
01917     if (ARCMTEnabled) {
01918       D.Diag(diag::err_drv_argument_not_allowed_with)
01919         << A->getAsString(Args) << "-ccc-arcmt-migrate";
01920     }
01921     CmdArgs.push_back("-mt-migrate-directory");
01922     CmdArgs.push_back(A->getValue(Args));
01923 
01924     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
01925                      options::OPT_objcmt_migrate_subscripting)) {
01926       // None specified, means enable them all.
01927       CmdArgs.push_back("-objcmt-migrate-literals");
01928       CmdArgs.push_back("-objcmt-migrate-subscripting");
01929     } else {
01930       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
01931       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
01932     }
01933   }
01934 
01935   // Add preprocessing options like -I, -D, etc. if we are using the
01936   // preprocessor.
01937   //
01938   // FIXME: Support -fpreprocessed
01939   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
01940     AddPreprocessingOptions(C, D, Args, CmdArgs, Output, Inputs);
01941 
01942   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
01943   // that "The compiler can only warn and ignore the option if not recognized".
01944   // When building with ccache, it will pass -D options to clang even on
01945   // preprocessed inputs and configure concludes that -fPIC is not supported.
01946   Args.ClaimAllArgs(options::OPT_D);
01947 
01948   // Manually translate -O to -O2 and -O4 to -O3; let clang reject
01949   // others.
01950   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
01951     if (A->getOption().matches(options::OPT_O4))
01952       CmdArgs.push_back("-O3");
01953     else if (A->getOption().matches(options::OPT_O) &&
01954              A->getValue(Args)[0] == '\0')
01955       CmdArgs.push_back("-O2");
01956     else
01957       A->render(Args, CmdArgs);
01958   }
01959 
01960   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
01961   Args.AddLastArg(CmdArgs, options::OPT_pedantic);
01962   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
01963   Args.AddLastArg(CmdArgs, options::OPT_w);
01964 
01965   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
01966   // (-ansi is equivalent to -std=c89).
01967   //
01968   // If a std is supplied, only add -trigraphs if it follows the
01969   // option.
01970   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
01971     if (Std->getOption().matches(options::OPT_ansi))
01972       if (types::isCXX(InputType))
01973         CmdArgs.push_back("-std=c++98");
01974       else
01975         CmdArgs.push_back("-std=c89");
01976     else
01977       Std->render(Args, CmdArgs);
01978 
01979     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
01980                                  options::OPT_trigraphs))
01981       if (A != Std)
01982         A->render(Args, CmdArgs);
01983   } else {
01984     // Honor -std-default.
01985     //
01986     // FIXME: Clang doesn't correctly handle -std= when the input language
01987     // doesn't match. For the time being just ignore this for C++ inputs;
01988     // eventually we want to do all the standard defaulting here instead of
01989     // splitting it between the driver and clang -cc1.
01990     if (!types::isCXX(InputType))
01991         Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
01992                                   "-std=", /*Joined=*/true);
01993     Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
01994   }
01995 
01996   // Map the bizarre '-Wwrite-strings' flag to a more sensible
01997   // '-fconst-strings'; this better indicates its actual behavior.
01998   if (Args.hasFlag(options::OPT_Wwrite_strings, options::OPT_Wno_write_strings,
01999                    false)) {
02000     // For perfect compatibility with GCC, we do this even in the presence of
02001     // '-w'. This flag names something other than a warning for GCC.
02002     CmdArgs.push_back("-fconst-strings");
02003   }
02004 
02005   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
02006   // during C++ compilation, which it is by default. GCC keeps this define even
02007   // in the presence of '-w', match this behavior bug-for-bug.
02008   if (types::isCXX(InputType) &&
02009       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
02010                    true)) {
02011     CmdArgs.push_back("-fdeprecated-macro");
02012   }
02013 
02014   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
02015   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
02016     if (Asm->getOption().matches(options::OPT_fasm))
02017       CmdArgs.push_back("-fgnu-keywords");
02018     else
02019       CmdArgs.push_back("-fno-gnu-keywords");
02020   }
02021 
02022   if (ShouldDisableCFI(Args, getToolChain()))
02023     CmdArgs.push_back("-fno-dwarf2-cfi-asm");
02024 
02025   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
02026     CmdArgs.push_back("-fno-dwarf-directory-asm");
02027 
02028   if (const char *pwd = ::getenv("PWD")) {
02029     // GCC also verifies that stat(pwd) and stat(".") have the same inode
02030     // number. Not doing those because stats are slow, but we could.
02031     if (llvm::sys::path::is_absolute(pwd)) {
02032       std::string CompDir = pwd;
02033       CmdArgs.push_back("-fdebug-compilation-dir");
02034       CmdArgs.push_back(Args.MakeArgString(CompDir));
02035     }
02036   }
02037 
02038   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
02039                                options::OPT_ftemplate_depth_EQ)) {
02040     CmdArgs.push_back("-ftemplate-depth");
02041     CmdArgs.push_back(A->getValue(Args));
02042   }
02043 
02044   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
02045     CmdArgs.push_back("-fconstexpr-depth");
02046     CmdArgs.push_back(A->getValue(Args));
02047   }
02048 
02049   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
02050                                options::OPT_Wlarge_by_value_copy_def)) {
02051     if (A->getNumValues()) {
02052       StringRef bytes = A->getValue(Args);
02053       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
02054     } else
02055       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
02056   }
02057 
02058   if (Arg *A = Args.getLastArg(options::OPT_fbounds_checking,
02059                                options::OPT_fbounds_checking_EQ)) {
02060     if (A->getNumValues()) {
02061       StringRef val = A->getValue(Args);
02062       CmdArgs.push_back(Args.MakeArgString("-fbounds-checking=" + val));
02063     } else
02064       CmdArgs.push_back("-fbounds-checking=1");
02065   }
02066 
02067   if (Args.hasArg(options::OPT__relocatable_pch))
02068     CmdArgs.push_back("-relocatable-pch");
02069 
02070   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
02071     CmdArgs.push_back("-fconstant-string-class");
02072     CmdArgs.push_back(A->getValue(Args));
02073   }
02074 
02075   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
02076     CmdArgs.push_back("-ftabstop");
02077     CmdArgs.push_back(A->getValue(Args));
02078   }
02079 
02080   CmdArgs.push_back("-ferror-limit");
02081   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
02082     CmdArgs.push_back(A->getValue(Args));
02083   else
02084     CmdArgs.push_back("19");
02085 
02086   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
02087     CmdArgs.push_back("-fmacro-backtrace-limit");
02088     CmdArgs.push_back(A->getValue(Args));
02089   }
02090 
02091   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
02092     CmdArgs.push_back("-ftemplate-backtrace-limit");
02093     CmdArgs.push_back(A->getValue(Args));
02094   }
02095 
02096   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
02097     CmdArgs.push_back("-fconstexpr-backtrace-limit");
02098     CmdArgs.push_back(A->getValue(Args));
02099   }
02100 
02101   // Pass -fmessage-length=.
02102   CmdArgs.push_back("-fmessage-length");
02103   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
02104     CmdArgs.push_back(A->getValue(Args));
02105   } else {
02106     // If -fmessage-length=N was not specified, determine whether this is a
02107     // terminal and, if so, implicitly define -fmessage-length appropriately.
02108     unsigned N = llvm::sys::Process::StandardErrColumns();
02109     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
02110   }
02111 
02112   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ)) {
02113     CmdArgs.push_back("-fvisibility");
02114     CmdArgs.push_back(A->getValue(Args));
02115   }
02116 
02117   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
02118 
02119   // -fhosted is default.
02120   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
02121       KernelOrKext)
02122     CmdArgs.push_back("-ffreestanding");
02123 
02124   // Forward -f (flag) options which we can pass directly.
02125   Args.AddLastArg(CmdArgs, options::OPT_fcatch_undefined_behavior);
02126   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
02127   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
02128   Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
02129   Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info);
02130   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
02131   Args.AddLastArg(CmdArgs, options::OPT_faltivec);
02132 
02133   // Report and error for -faltivec on anything other then PowerPC.
02134   if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
02135     if (!(getToolChain().getTriple().getArch() == llvm::Triple::ppc ||
02136           getToolChain().getTriple().getArch() == llvm::Triple::ppc64))
02137       D.Diag(diag::err_drv_argument_only_allowed_with)
02138         << A->getAsString(Args) << "ppc/ppc64";
02139 
02140   if (getToolChain().SupportsProfiling())
02141     Args.AddLastArg(CmdArgs, options::OPT_pg);
02142 
02143   if (Args.hasFlag(options::OPT_faddress_sanitizer,
02144                    options::OPT_fno_address_sanitizer, false))
02145     CmdArgs.push_back("-faddress-sanitizer");
02146 
02147   if (Args.hasFlag(options::OPT_fthread_sanitizer,
02148                    options::OPT_fno_thread_sanitizer, false))
02149     CmdArgs.push_back("-fthread-sanitizer");
02150 
02151   // -flax-vector-conversions is default.
02152   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
02153                     options::OPT_fno_lax_vector_conversions))
02154     CmdArgs.push_back("-fno-lax-vector-conversions");
02155 
02156   if (Args.getLastArg(options::OPT_fapple_kext))
02157     CmdArgs.push_back("-fapple-kext");
02158 
02159   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
02160   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
02161   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
02162   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
02163   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
02164 
02165   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
02166     CmdArgs.push_back("-ftrapv-handler");
02167     CmdArgs.push_back(A->getValue(Args));
02168   }
02169 
02170   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
02171 
02172   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
02173   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
02174   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
02175                                options::OPT_fno_wrapv)) {
02176     if (A->getOption().matches(options::OPT_fwrapv))
02177       CmdArgs.push_back("-fwrapv");
02178   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
02179                                       options::OPT_fno_strict_overflow)) {
02180     if (A->getOption().matches(options::OPT_fno_strict_overflow))
02181       CmdArgs.push_back("-fwrapv");
02182   }
02183   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
02184   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops);
02185 
02186   Args.AddLastArg(CmdArgs, options::OPT_pthread);
02187 
02188   // -stack-protector=0 is default.
02189   unsigned StackProtectorLevel = 0;
02190   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
02191                                options::OPT_fstack_protector_all,
02192                                options::OPT_fstack_protector)) {
02193     if (A->getOption().matches(options::OPT_fstack_protector))
02194       StackProtectorLevel = 1;
02195     else if (A->getOption().matches(options::OPT_fstack_protector_all))
02196       StackProtectorLevel = 2;
02197   } else {
02198     StackProtectorLevel =
02199       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
02200   }
02201   if (StackProtectorLevel) {
02202     CmdArgs.push_back("-stack-protector");
02203     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
02204   }
02205 
02206   // Translate -mstackrealign
02207   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
02208                    false)) {
02209     CmdArgs.push_back("-backend-option");
02210     CmdArgs.push_back("-force-align-stack");
02211   }
02212   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
02213                    false)) {
02214     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
02215   }
02216 
02217   if (Args.hasArg(options::OPT_mstack_alignment)) {
02218     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
02219     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
02220   }
02221 
02222   // Forward -f options with positive and negative forms; we translate
02223   // these by hand.
02224 
02225   if (Args.hasArg(options::OPT_mkernel)) {
02226     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
02227       CmdArgs.push_back("-fapple-kext");
02228     if (!Args.hasArg(options::OPT_fbuiltin))
02229       CmdArgs.push_back("-fno-builtin");
02230     Args.ClaimAllArgs(options::OPT_fno_builtin);
02231   }
02232   // -fbuiltin is default.
02233   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
02234     CmdArgs.push_back("-fno-builtin");
02235 
02236   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
02237                     options::OPT_fno_assume_sane_operator_new))
02238     CmdArgs.push_back("-fno-assume-sane-operator-new");
02239 
02240   // -fblocks=0 is default.
02241   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
02242                    getToolChain().IsBlocksDefault()) ||
02243         (Args.hasArg(options::OPT_fgnu_runtime) &&
02244          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
02245          !Args.hasArg(options::OPT_fno_blocks))) {
02246     CmdArgs.push_back("-fblocks");
02247 
02248     if (!Args.hasArg(options::OPT_fgnu_runtime) && 
02249         !getToolChain().hasBlocksRuntime())
02250       CmdArgs.push_back("-fblocks-runtime-optional");
02251   }
02252 
02253   // -fmodules enables modules (off by default). However, for C++/Objective-C++,
02254   // users must also pass -fcxx-modules. The latter flag will disappear once the
02255   // modules implementation is solid for C++/Objective-C++ programs as well.
02256   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
02257     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 
02258                                      options::OPT_fno_cxx_modules, 
02259                                      false);
02260     if (AllowedInCXX || !types::isCXX(InputType))
02261       CmdArgs.push_back("-fmodules");
02262   }
02263 
02264   // -faccess-control is default.
02265   if (Args.hasFlag(options::OPT_fno_access_control,
02266                    options::OPT_faccess_control,
02267                    false))
02268     CmdArgs.push_back("-fno-access-control");
02269 
02270   // -felide-constructors is the default.
02271   if (Args.hasFlag(options::OPT_fno_elide_constructors,
02272                    options::OPT_felide_constructors,
02273                    false))
02274     CmdArgs.push_back("-fno-elide-constructors");
02275 
02276   // -frtti is default.
02277   if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
02278       KernelOrKext)
02279     CmdArgs.push_back("-fno-rtti");
02280 
02281   // -fshort-enums=0 is default for all architectures except Hexagon.
02282   if (Args.hasFlag(options::OPT_fshort_enums,
02283                    options::OPT_fno_short_enums,
02284                    getToolChain().getTriple().getArch() ==
02285                    llvm::Triple::hexagon))
02286     CmdArgs.push_back("-fshort-enums");
02287 
02288   // -fsigned-char is default.
02289   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
02290                     isSignedCharDefault(getToolChain().getTriple())))
02291     CmdArgs.push_back("-fno-signed-char");
02292 
02293   // -fthreadsafe-static is default.
02294   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
02295                     options::OPT_fno_threadsafe_statics))
02296     CmdArgs.push_back("-fno-threadsafe-statics");
02297 
02298   // -fuse-cxa-atexit is default.
02299   if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
02300                     options::OPT_fno_use_cxa_atexit,
02301                    getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
02302                   getToolChain().getTriple().getOS() != llvm::Triple::MinGW32 &&
02303               getToolChain().getTriple().getArch() != llvm::Triple::hexagon) ||
02304       KernelOrKext)
02305     CmdArgs.push_back("-fno-use-cxa-atexit");
02306 
02307   // -fms-extensions=0 is default.
02308   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
02309                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
02310     CmdArgs.push_back("-fms-extensions");
02311 
02312   // -fms-compatibility=0 is default.
02313   if (Args.hasFlag(options::OPT_fms_compatibility, 
02314                    options::OPT_fno_ms_compatibility,
02315                    (getToolChain().getTriple().getOS() == llvm::Triple::Win32 &&
02316                     Args.hasFlag(options::OPT_fms_extensions, 
02317                                  options::OPT_fno_ms_extensions,
02318                                  true))))
02319     CmdArgs.push_back("-fms-compatibility");
02320 
02321   // -fmsc-version=1300 is default.
02322   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
02323                    getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
02324       Args.hasArg(options::OPT_fmsc_version)) {
02325     StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
02326     if (msc_ver.empty())
02327       CmdArgs.push_back("-fmsc-version=1300");
02328     else
02329       CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
02330   }
02331 
02332 
02333   // -fborland-extensions=0 is default.
02334   if (Args.hasFlag(options::OPT_fborland_extensions,
02335                    options::OPT_fno_borland_extensions, false))
02336     CmdArgs.push_back("-fborland-extensions");
02337 
02338   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
02339   // needs it.
02340   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
02341                    options::OPT_fno_delayed_template_parsing,
02342                    getToolChain().getTriple().getOS() == llvm::Triple::Win32))
02343     CmdArgs.push_back("-fdelayed-template-parsing");
02344 
02345   // -fgnu-keywords default varies depending on language; only pass if
02346   // specified.
02347   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
02348                                options::OPT_fno_gnu_keywords))
02349     A->render(Args, CmdArgs);
02350 
02351   if (Args.hasFlag(options::OPT_fgnu89_inline,
02352                    options::OPT_fno_gnu89_inline,
02353                    false))
02354     CmdArgs.push_back("-fgnu89-inline");
02355 
02356   if (Args.hasArg(options::OPT_fno_inline))
02357     CmdArgs.push_back("-fno-inline");
02358 
02359   if (Args.hasArg(options::OPT_fno_inline_functions))
02360     CmdArgs.push_back("-fno-inline-functions");
02361 
02362   // -fobjc-nonfragile-abi=0 is default.
02363   ObjCRuntime objCRuntime;
02364   unsigned objcABIVersion = 0;
02365   bool NeXTRuntimeIsDefault
02366     = (IsRewriter || IsModernRewriter ||
02367        getToolChain().getTriple().isOSDarwin());
02368   if (Args.hasFlag(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
02369                    NeXTRuntimeIsDefault)) {
02370     objCRuntime.setKind(ObjCRuntime::NeXT);
02371   } else {
02372     CmdArgs.push_back("-fgnu-runtime");
02373     objCRuntime.setKind(ObjCRuntime::GNU);
02374   }
02375   getToolChain().configureObjCRuntime(objCRuntime);
02376   if (objCRuntime.HasARC)
02377     CmdArgs.push_back("-fobjc-runtime-has-arc");
02378   if (objCRuntime.HasWeak)
02379     CmdArgs.push_back("-fobjc-runtime-has-weak");
02380   if (objCRuntime.HasTerminate)
02381     CmdArgs.push_back("-fobjc-runtime-has-terminate");
02382 
02383   // Compute the Objective-C ABI "version" to use. Version numbers are
02384   // slightly confusing for historical reasons:
02385   //   1 - Traditional "fragile" ABI
02386   //   2 - Non-fragile ABI, version 1
02387   //   3 - Non-fragile ABI, version 2
02388   objcABIVersion = 1;
02389   // If -fobjc-abi-version= is present, use that to set the version.
02390   if (Arg *A = Args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
02391     if (StringRef(A->getValue(Args)) == "1")
02392       objcABIVersion = 1;
02393     else if (StringRef(A->getValue(Args)) == "2")
02394       objcABIVersion = 2;
02395     else if (StringRef(A->getValue(Args)) == "3")
02396       objcABIVersion = 3;
02397     else
02398       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
02399   } else {
02400     // Otherwise, determine if we are using the non-fragile ABI.
02401     bool NonFragileABIIsDefault = 
02402       (IsModernRewriter || 
02403        (!IsRewriter && getToolChain().IsObjCNonFragileABIDefault()));
02404     if (Args.hasFlag(options::OPT_fobjc_nonfragile_abi,
02405                      options::OPT_fno_objc_nonfragile_abi,
02406                      NonFragileABIIsDefault)) {
02407       // Determine the non-fragile ABI version to use.
02408 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
02409       unsigned NonFragileABIVersion = 1;
02410 #else
02411       unsigned NonFragileABIVersion = 2;
02412 #endif
02413 
02414       if (Arg *A = Args.getLastArg(
02415             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
02416         if (StringRef(A->getValue(Args)) == "1")
02417           NonFragileABIVersion = 1;
02418         else if (StringRef(A->getValue(Args)) == "2")
02419           NonFragileABIVersion = 2;
02420         else
02421           D.Diag(diag::err_drv_clang_unsupported)
02422             << A->getAsString(Args);
02423       }
02424 
02425       objcABIVersion = 1 + NonFragileABIVersion;
02426     } else {
02427       objcABIVersion = 1;
02428     }
02429   }
02430 
02431   if (objcABIVersion == 1) {
02432     CmdArgs.push_back("-fobjc-fragile-abi");
02433   } else {
02434     // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
02435     // legacy is the default.
02436     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
02437                       options::OPT_fno_objc_legacy_dispatch,
02438                       getToolChain().IsObjCLegacyDispatchDefault())) {
02439       if (getToolChain().UseObjCMixedDispatch())
02440         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
02441       else
02442         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
02443     }
02444   }
02445 
02446   // -fobjc-default-synthesize-properties=1 is default. This only has an effect
02447   // if the nonfragile objc abi is used.
02448   if (getToolChain().IsObjCDefaultSynthPropertiesDefault()) {
02449     CmdArgs.push_back("-fobjc-default-synthesize-properties");
02450   }
02451 
02452   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
02453   // NOTE: This logic is duplicated in ToolChains.cpp.
02454   bool ARC = isObjCAutoRefCount(Args);
02455   if (ARC) {
02456     if (!getToolChain().SupportsObjCARC())
02457       D.Diag(diag::err_arc_unsupported);
02458 
02459     CmdArgs.push_back("-fobjc-arc");
02460 
02461     // FIXME: It seems like this entire block, and several around it should be
02462     // wrapped in isObjC, but for now we just use it here as this is where it
02463     // was being used previously.
02464     if (types::isCXX(InputType) && types::isObjC(InputType)) {
02465       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
02466         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
02467       else
02468         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
02469     }
02470 
02471     // Allow the user to enable full exceptions code emission.
02472     // We define off for Objective-CC, on for Objective-C++.
02473     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
02474                      options::OPT_fno_objc_arc_exceptions,
02475                      /*default*/ types::isCXX(InputType)))
02476       CmdArgs.push_back("-fobjc-arc-exceptions");
02477   }
02478 
02479   // -fobjc-infer-related-result-type is the default, except in the Objective-C
02480   // rewriter.
02481   if (IsRewriter || IsModernRewriter)
02482     CmdArgs.push_back("-fno-objc-infer-related-result-type");
02483 
02484   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
02485   // takes precedence.
02486   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
02487   if (!GCArg)
02488     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
02489   if (GCArg) {
02490     if (ARC) {
02491       D.Diag(diag::err_drv_objc_gc_arr)
02492         << GCArg->getAsString(Args);
02493     } else if (getToolChain().SupportsObjCGC()) {
02494       GCArg->render(Args, CmdArgs);
02495     } else {
02496       // FIXME: We should move this to a hard error.
02497       D.Diag(diag::warn_drv_objc_gc_unsupported)
02498         << GCArg->getAsString(Args);
02499     }
02500   }
02501 
02502   // Add exception args.
02503   addExceptionArgs(Args, InputType, getToolChain().getTriple(),
02504                    KernelOrKext, objcABIVersion, CmdArgs);
02505 
02506   if (getToolChain().UseSjLjExceptions())
02507     CmdArgs.push_back("-fsjlj-exceptions");
02508 
02509   // C++ "sane" operator new.
02510   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
02511                     options::OPT_fno_assume_sane_operator_new))
02512     CmdArgs.push_back("-fno-assume-sane-operator-new");
02513 
02514   // -fconstant-cfstrings is default, and may be subject to argument translation
02515   // on Darwin.
02516   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
02517                     options::OPT_fno_constant_cfstrings) ||
02518       !Args.hasFlag(options::OPT_mconstant_cfstrings,
02519                     options::OPT_mno_constant_cfstrings))
02520     CmdArgs.push_back("-fno-constant-cfstrings");
02521 
02522   // -fshort-wchar default varies depending on platform; only
02523   // pass if specified.
02524   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
02525     A->render(Args, CmdArgs);
02526 
02527   // -fno-pascal-strings is default, only pass non-default. If the tool chain
02528   // happened to translate to -mpascal-strings, we want to back translate here.
02529   //
02530   // FIXME: This is gross; that translation should be pulled from the
02531   // tool chain.
02532   if (Args.hasFlag(options::OPT_fpascal_strings,
02533                    options::OPT_fno_pascal_strings,
02534                    false) ||
02535       Args.hasFlag(options::OPT_mpascal_strings,
02536                    options::OPT_mno_pascal_strings,
02537                    false))
02538     CmdArgs.push_back("-fpascal-strings");
02539 
02540   // Honor -fpack-struct= and -fpack-struct, if given. Note that
02541   // -fno-pack-struct doesn't apply to -fpack-struct=.
02542   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
02543     std::string PackStructStr = "-fpack-struct=";
02544     PackStructStr += A->getValue(Args);
02545     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
02546   } else if (Args.hasFlag(options::OPT_fpack_struct,
02547                           options::OPT_fno_pack_struct, false)) {
02548     CmdArgs.push_back("-fpack-struct=1");
02549   }
02550 
02551   if (Args.hasArg(options::OPT_mkernel) ||
02552       Args.hasArg(options::OPT_fapple_kext)) {
02553     if (!Args.hasArg(options::OPT_fcommon))
02554       CmdArgs.push_back("-fno-common");
02555     Args.ClaimAllArgs(options::OPT_fno_common);
02556   }
02557 
02558   // -fcommon is default, only pass non-default.
02559   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
02560     CmdArgs.push_back("-fno-common");
02561 
02562   // -fsigned-bitfields is default, and clang doesn't yet support
02563   // -funsigned-bitfields.
02564   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
02565                     options::OPT_funsigned_bitfields))
02566     D.Diag(diag::warn_drv_clang_unsupported)
02567       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
02568 
02569   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
02570   if (!Args.hasFlag(options::OPT_ffor_scope,
02571                     options::OPT_fno_for_scope))
02572     D.Diag(diag::err_drv_clang_unsupported)
02573       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
02574 
02575   // -fcaret-diagnostics is default.
02576   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
02577                     options::OPT_fno_caret_diagnostics, true))
02578     CmdArgs.push_back("-fno-caret-diagnostics");
02579 
02580   // -fdiagnostics-fixit-info is default, only pass non-default.
02581   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
02582                     options::OPT_fno_diagnostics_fixit_info))
02583     CmdArgs.push_back("-fno-diagnostics-fixit-info");
02584 
02585   // Enable -fdiagnostics-show-option by default.
02586   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
02587                    options::OPT_fno_diagnostics_show_option))
02588     CmdArgs.push_back("-fdiagnostics-show-option");
02589 
02590   if (const Arg *A =
02591         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
02592     CmdArgs.push_back("-fdiagnostics-show-category");
02593     CmdArgs.push_back(A->getValue(Args));
02594   }
02595 
02596   if (const Arg *A =
02597         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
02598     CmdArgs.push_back("-fdiagnostics-format");
02599     CmdArgs.push_back(A->getValue(Args));
02600   }
02601 
02602   if (Arg *A = Args.getLastArg(
02603       options::OPT_fdiagnostics_show_note_include_stack,
02604       options::OPT_fno_diagnostics_show_note_include_stack)) {
02605     if (A->getOption().matches(
02606         options::OPT_fdiagnostics_show_note_include_stack))
02607       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
02608     else
02609       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
02610   }
02611 
02612   // Color diagnostics are the default, unless the terminal doesn't support
02613   // them.
02614   if (Args.hasFlag(options::OPT_fcolor_diagnostics,
02615                    options::OPT_fno_color_diagnostics,
02616                    llvm::sys::Process::StandardErrHasColors()))
02617     CmdArgs.push_back("-fcolor-diagnostics");
02618 
02619   if (!Args.hasFlag(options::OPT_fshow_source_location,
02620                     options::OPT_fno_show_source_location))
02621     CmdArgs.push_back("-fno-show-source-location");
02622 
02623   if (!Args.hasFlag(options::OPT_fshow_column,
02624                     options::OPT_fno_show_column,
02625                     true))
02626     CmdArgs.push_back("-fno-show-column");
02627 
02628   if (!Args.hasFlag(options::OPT_fspell_checking,
02629                     options::OPT_fno_spell_checking))
02630     CmdArgs.push_back("-fno-spell-checking");
02631 
02632 
02633   // Silently ignore -fasm-blocks for now.
02634   (void) Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
02635                       false);
02636 
02637   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
02638     A->render(Args, CmdArgs);
02639 
02640   // -fdollars-in-identifiers default varies depending on platform and
02641   // language; only pass if specified.
02642   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
02643                                options::OPT_fno_dollars_in_identifiers)) {
02644     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
02645       CmdArgs.push_back("-fdollars-in-identifiers");
02646     else
02647       CmdArgs.push_back("-fno-dollars-in-identifiers");
02648   }
02649 
02650   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
02651   // practical purposes.
02652   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
02653                                options::OPT_fno_unit_at_a_time)) {
02654     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
02655       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
02656   }
02657 
02658   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
02659                    options::OPT_fno_apple_pragma_pack, false))
02660     CmdArgs.push_back("-fapple-pragma-pack");
02661 
02662   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
02663   //
02664   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
02665 #if 0
02666   if (getToolChain().getTriple().isOSDarwin() &&
02667       (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
02668        getToolChain().getTriple().getArch() == llvm::Triple::thumb)) {
02669     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
02670       CmdArgs.push_back("-fno-builtin-strcat");
02671     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
02672       CmdArgs.push_back("-fno-builtin-strcpy");
02673   }
02674 #endif
02675 
02676   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
02677   if (Arg *A = Args.getLastArg(options::OPT_traditional,
02678                                options::OPT_traditional_cpp)) {
02679     if (isa<PreprocessJobAction>(JA))
02680       CmdArgs.push_back("-traditional-cpp");
02681     else
02682       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
02683   }
02684 
02685   Args.AddLastArg(CmdArgs, options::OPT_dM);
02686   Args.AddLastArg(CmdArgs, options::OPT_dD);
02687   
02688   // Handle serialized diagnostics.
02689   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
02690     CmdArgs.push_back("-serialize-diagnostic-file");
02691     CmdArgs.push_back(Args.MakeArgString(A->getValue(Args)));
02692   }
02693 
02694   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
02695   // parser.
02696   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
02697   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
02698          ie = Args.filtered_end(); it != ie; ++it) {
02699     (*it)->claim();
02700 
02701     // We translate this by hand to the -cc1 argument, since nightly test uses
02702     // it and developers have been trained to spell it with -mllvm.
02703     if (StringRef((*it)->getValue(Args, 0)) == "-disable-llvm-optzns")
02704       CmdArgs.push_back("-disable-llvm-optzns");
02705     else
02706       (*it)->render(Args, CmdArgs);
02707   }
02708 
02709   if (Output.getType() == types::TY_Dependencies) {
02710     // Handled with other dependency code.
02711   } else if (Output.isFilename()) {
02712     CmdArgs.push_back("-o");
02713     CmdArgs.push_back(Output.getFilename());
02714   } else {
02715     assert(Output.isNothing() && "Invalid output.");
02716   }
02717 
02718   for (InputInfoList::const_iterator
02719          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
02720     const InputInfo &II = *it;
02721     CmdArgs.push_back("-x");
02722     CmdArgs.push_back(types::getTypeName(II.getType()));
02723     if (II.isFilename())
02724       CmdArgs.push_back(II.getFilename());
02725     else
02726       II.getInputArg().renderAsInput(Args, CmdArgs);
02727   }
02728 
02729   Args.AddAllArgs(CmdArgs, options::OPT_undef);
02730 
02731   const char *Exec = getToolChain().getDriver().getClangProgramPath();
02732 
02733   // Optionally embed the -cc1 level arguments into the debug info, for build
02734   // analysis.
02735   if (getToolChain().UseDwarfDebugFlags()) {
02736     ArgStringList OriginalArgs;
02737     for (ArgList::const_iterator it = Args.begin(),
02738            ie = Args.end(); it != ie; ++it)
02739       (*it)->render(Args, OriginalArgs);
02740 
02741     SmallString<256> Flags;
02742     Flags += Exec;
02743     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
02744       Flags += " ";
02745       Flags += OriginalArgs[i];
02746     }
02747     CmdArgs.push_back("-dwarf-debug-flags");
02748     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
02749   }
02750 
02751   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
02752 
02753   if (Arg *A = Args.getLastArg(options::OPT_pg))
02754     if (Args.hasArg(options::OPT_fomit_frame_pointer))
02755       D.Diag(diag::err_drv_argument_not_allowed_with)
02756         << "-fomit-frame-pointer" << A->getAsString(Args);
02757 
02758   // Claim some arguments which clang supports automatically.
02759 
02760   // -fpch-preprocess is used with gcc to add a special marker in the output to
02761   // include the PCH file. Clang's PTH solution is completely transparent, so we
02762   // do not need to deal with it at all.
02763   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
02764 
02765   // Claim some arguments which clang doesn't support, but we don't
02766   // care to warn the user about.
02767   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
02768   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
02769 
02770   // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c
02771   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
02772   Args.ClaimAllArgs(options::OPT_emit_llvm);
02773 }
02774 
02775 void ClangAs::AddARMTargetArgs(const ArgList &Args,
02776                                ArgStringList &CmdArgs) const {
02777   const Driver &D = getToolChain().getDriver();
02778   llvm::Triple Triple = getToolChain().getTriple();
02779 
02780   // Set the CPU based on -march= and -mcpu=.
02781   CmdArgs.push_back("-target-cpu");
02782   CmdArgs.push_back(getARMTargetCPU(Args, Triple));
02783 
02784   // Honor -mfpu=.
02785   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
02786     addFPUArgs(D, A, Args, CmdArgs);
02787 
02788   // Honor -mfpmath=.
02789   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ))
02790     addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
02791 }
02792 
02793 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
02794                            const InputInfo &Output,
02795                            const InputInfoList &Inputs,
02796                            const ArgList &Args,
02797                            const char *LinkingOutput) const {
02798   ArgStringList CmdArgs;
02799 
02800   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
02801   const InputInfo &Input = Inputs[0];
02802 
02803   // Don't warn about "clang -w -c foo.s"
02804   Args.ClaimAllArgs(options::OPT_w);
02805   // and "clang -emit-llvm -c foo.s"
02806   Args.ClaimAllArgs(options::OPT_emit_llvm);
02807   // and "clang -use-gold-plugin -c foo.s"
02808   Args.ClaimAllArgs(options::OPT_use_gold_plugin);
02809 
02810   // Invoke ourselves in -cc1as mode.
02811   //
02812   // FIXME: Implement custom jobs for internal actions.
02813   CmdArgs.push_back("-cc1as");
02814 
02815   // Add the "effective" target triple.
02816   CmdArgs.push_back("-triple");
02817   std::string TripleStr = 
02818     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
02819   CmdArgs.push_back(Args.MakeArgString(TripleStr));
02820 
02821   // Set the output mode, we currently only expect to be used as a real
02822   // assembler.
02823   CmdArgs.push_back("-filetype");
02824   CmdArgs.push_back("obj");
02825 
02826   if (UseRelaxAll(C, Args))
02827     CmdArgs.push_back("-relax-all");
02828 
02829   // Add target specific cpu and features flags.
02830   switch(getToolChain().getTriple().getArch()) {
02831   default:
02832     break;
02833 
02834   case llvm::Triple::arm:
02835   case llvm::Triple::thumb:
02836     AddARMTargetArgs(Args, CmdArgs);
02837     break;
02838   }
02839 
02840   // Ignore explicit -force_cpusubtype_ALL option.
02841   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
02842 
02843   // Determine the original source input.
02844   const Action *SourceAction = &JA;
02845   while (SourceAction->getKind() != Action::InputClass) {
02846     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
02847     SourceAction = SourceAction->getInputs()[0];
02848   }
02849 
02850   // Forward -g, assuming we are dealing with an actual assembly file.
02851   if (SourceAction->getType() == types::TY_Asm ||
02852       SourceAction->getType() == types::TY_PP_Asm) {
02853     Args.ClaimAllArgs(options::OPT_g_Group);
02854     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
02855       if (!A->getOption().matches(options::OPT_g0))
02856         CmdArgs.push_back("-g");
02857   }
02858 
02859   // Optionally embed the -cc1as level arguments into the debug info, for build
02860   // analysis.
02861   if (getToolChain().UseDwarfDebugFlags()) {
02862     ArgStringList OriginalArgs;
02863     for (ArgList::const_iterator it = Args.begin(),
02864            ie = Args.end(); it != ie; ++it)
02865       (*it)->render(Args, OriginalArgs);
02866 
02867     SmallString<256> Flags;
02868     const char *Exec = getToolChain().getDriver().getClangProgramPath();
02869     Flags += Exec;
02870     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
02871       Flags += " ";
02872       Flags += OriginalArgs[i];
02873     }
02874     CmdArgs.push_back("-dwarf-debug-flags");
02875     CmdArgs.push_back(Args.MakeArgString(Flags.str()));
02876   }
02877 
02878   // FIXME: Add -static support, once we have it.
02879 
02880   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
02881                        options::OPT_Xassembler);
02882   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
02883 
02884   assert(Output.isFilename() && "Unexpected lipo output.");
02885   CmdArgs.push_back("-o");
02886   CmdArgs.push_back(Output.getFilename());
02887 
02888   assert(Input.isFilename() && "Invalid input.");
02889   CmdArgs.push_back(Input.getFilename());
02890 
02891   const char *Exec = getToolChain().getDriver().getClangProgramPath();
02892   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
02893 }
02894 
02895 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
02896                                const InputInfo &Output,
02897                                const InputInfoList &Inputs,
02898                                const ArgList &Args,
02899                                const char *LinkingOutput) const {
02900   const Driver &D = getToolChain().getDriver();
02901   ArgStringList CmdArgs;
02902 
02903   for (ArgList::const_iterator
02904          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
02905     Arg *A = *it;
02906     if (A->getOption().hasForwardToGCC()) {
02907       // Don't forward any -g arguments to assembly steps.
02908       if (isa<AssembleJobAction>(JA) &&
02909           A->getOption().matches(options::OPT_g_Group))
02910         continue;
02911 
02912       // It is unfortunate that we have to claim here, as this means
02913       // we will basically never report anything interesting for
02914       // platforms using a generic gcc, even if we are just using gcc
02915       // to get to the assembler.
02916       A->claim();
02917       A->render(Args, CmdArgs);
02918     }
02919   }
02920 
02921   RenderExtraToolArgs(JA, CmdArgs);
02922 
02923   // If using a driver driver, force the arch.
02924   const std::string &Arch = getToolChain().getArchName();
02925   if (getToolChain().getTriple().isOSDarwin()) {
02926     CmdArgs.push_back("-arch");
02927 
02928     // FIXME: Remove these special cases.
02929     if (Arch == "powerpc")
02930       CmdArgs.push_back("ppc");
02931     else if (Arch == "powerpc64")
02932       CmdArgs.push_back("ppc64");
02933     else
02934       CmdArgs.push_back(Args.MakeArgString(Arch));
02935   }
02936 
02937   // Try to force gcc to match the tool chain we want, if we recognize
02938   // the arch.
02939   //
02940   // FIXME: The triple class should directly provide the information we want
02941   // here.
02942   if (Arch == "i386" || Arch == "powerpc")
02943     CmdArgs.push_back("-m32");
02944   else if (Arch == "x86_64" || Arch == "powerpc64")
02945     CmdArgs.push_back("-m64");
02946 
02947   if (Output.isFilename()) {
02948     CmdArgs.push_back("-o");
02949     CmdArgs.push_back(Output.getFilename());
02950   } else {
02951     assert(Output.isNothing() && "Unexpected output");
02952     CmdArgs.push_back("-fsyntax-only");
02953   }
02954 
02955   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
02956                        options::OPT_Xassembler);
02957 
02958   // Only pass -x if gcc will understand it; otherwise hope gcc
02959   // understands the suffix correctly. The main use case this would go
02960   // wrong in is for linker inputs if they happened to have an odd
02961   // suffix; really the only way to get this to happen is a command
02962   // like '-x foobar a.c' which will treat a.c like a linker input.
02963   //
02964   // FIXME: For the linker case specifically, can we safely convert
02965   // inputs into '-Wl,' options?
02966   for (InputInfoList::const_iterator
02967          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
02968     const InputInfo &II = *it;
02969 
02970     // Don't try to pass LLVM or AST inputs to a generic gcc.
02971     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
02972         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
02973       D.Diag(diag::err_drv_no_linker_llvm_support)
02974         << getToolChain().getTripleString();
02975     else if (II.getType() == types::TY_AST)
02976       D.Diag(diag::err_drv_no_ast_support)
02977         << getToolChain().getTripleString();
02978 
02979     if (types::canTypeBeUserSpecified(II.getType())) {
02980       CmdArgs.push_back("-x");
02981       CmdArgs.push_back(types::getTypeName(II.getType()));
02982     }
02983 
02984     if (II.isFilename())
02985       CmdArgs.push_back(II.getFilename());
02986     else {
02987       const Arg &A = II.getInputArg();
02988 
02989       // Reverse translate some rewritten options.
02990       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
02991         CmdArgs.push_back("-lstdc++");
02992         continue;
02993       }
02994 
02995       // Don't render as input, we need gcc to do the translations.
02996       A.render(Args, CmdArgs);
02997     }
02998   }
02999 
03000   const std::string customGCCName = D.getCCCGenericGCCName();
03001   const char *GCCName;
03002   if (!customGCCName.empty())
03003     GCCName = customGCCName.c_str();
03004   else if (D.CCCIsCXX) {
03005     GCCName = "g++";
03006   } else
03007     GCCName = "gcc";
03008 
03009   const char *Exec =
03010     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
03011   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
03012 }
03013 
03014 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
03015                                           ArgStringList &CmdArgs) const {
03016   CmdArgs.push_back("-E");
03017 }
03018 
03019 void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
03020                                           ArgStringList &CmdArgs) const {
03021   // The type is good enough.
03022 }
03023 
03024 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
03025                                        ArgStringList &CmdArgs) const {
03026   const Driver &D = getToolChain().getDriver();
03027 
03028   // If -flto, etc. are present then make sure not to force assembly output.
03029   if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
03030       JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
03031     CmdArgs.push_back("-c");
03032   else {
03033     if (JA.getType() != types::TY_PP_Asm)
03034       D.Diag(diag::err_drv_invalid_gcc_output_type)
03035         << getTypeName(JA.getType());
03036 
03037     CmdArgs.push_back("-S");
03038   }
03039 }
03040 
03041 void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
03042                                         ArgStringList &CmdArgs) const {
03043   CmdArgs.push_back("-c");
03044 }
03045 
03046 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
03047                                     ArgStringList &CmdArgs) const {
03048   // The types are (hopefully) good enough.
03049 }
03050 
03051 // Hexagon tools start.
03052 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
03053                                         ArgStringList &CmdArgs) const {
03054 
03055 }
03056 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
03057                                const InputInfo &Output,
03058                                const InputInfoList &Inputs,
03059                                const ArgList &Args,
03060                                const char *LinkingOutput) const {
03061 
03062   const Driver &D = getToolChain().getDriver();
03063   ArgStringList CmdArgs;
03064 
03065   std::string MarchString = "-march=";
03066   MarchString += getHexagonTargetCPU(Args);
03067   CmdArgs.push_back(Args.MakeArgString(MarchString));
03068 
03069   RenderExtraToolArgs(JA, CmdArgs);
03070 
03071   if (Output.isFilename()) {
03072     CmdArgs.push_back("-o");
03073     CmdArgs.push_back(Output.getFilename());
03074   } else {
03075     assert(Output.isNothing() && "Unexpected output");
03076     CmdArgs.push_back("-fsyntax-only");
03077   }
03078 
03079 
03080   // Only pass -x if gcc will understand it; otherwise hope gcc
03081   // understands the suffix correctly. The main use case this would go
03082   // wrong in is for linker inputs if they happened to have an odd
03083   // suffix; really the only way to get this to happen is a command
03084   // like '-x foobar a.c' which will treat a.c like a linker input.
03085   //
03086   // FIXME: For the linker case specifically, can we safely convert
03087   // inputs into '-Wl,' options?
03088   for (InputInfoList::const_iterator
03089          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
03090     const InputInfo &II = *it;
03091 
03092     // Don't try to pass LLVM or AST inputs to a generic gcc.
03093     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
03094         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
03095       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
03096         << getToolChain().getTripleString();
03097     else if (II.getType() == types::TY_AST)
03098       D.Diag(clang::diag::err_drv_no_ast_support)
03099         << getToolChain().getTripleString();
03100 
03101     if (II.isFilename())
03102       CmdArgs.push_back(II.getFilename());
03103     else
03104       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
03105       II.getInputArg().render(Args, CmdArgs);
03106   }
03107 
03108   const char *GCCName = "hexagon-as";
03109   const char *Exec =
03110     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
03111   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
03112 
03113 }
03114 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
03115                                     ArgStringList &CmdArgs) const {
03116   // The types are (hopefully) good enough.
03117 }
03118 
03119 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
03120                                const InputInfo &Output,
03121                                const InputInfoList &Inputs,
03122                                const ArgList &Args,
03123                                const char *LinkingOutput) const {
03124 
03125   const Driver &D = getToolChain().getDriver();
03126   ArgStringList CmdArgs;
03127 
03128   for (ArgList::const_iterator
03129          it = Args.begin(), ie = Args.end(); it != ie; ++it) {
03130     Arg *A = *it;
03131     if (A->getOption().hasForwardToGCC()) {
03132       // Don't forward any -g arguments to assembly steps.
03133       if (isa<AssembleJobAction>(JA) &&
03134           A->getOption().matches(options::OPT_g_Group))
03135         continue;
03136 
03137       // It is unfortunate that we have to claim here, as this means
03138       // we will basically never report anything interesting for
03139       // platforms using a generic gcc, even if we are just using gcc
03140       // to get to the assembler.
03141       A->claim();
03142       A->render(Args, CmdArgs);
03143     }
03144   }
03145 
03146   RenderExtraToolArgs(JA, CmdArgs);
03147 
03148   // Add Arch Information
03149   Arg *A;
03150   if ((A = getLastHexagonArchArg(Args))) {
03151     if (A->getOption().matches(options::OPT_m_Joined))
03152       A->render(Args, CmdArgs);
03153     else
03154       CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)));
03155   }
03156   else {
03157     CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)));
03158   }
03159 
03160   CmdArgs.push_back("-mqdsp6-compat");
03161 
03162   const char *GCCName;
03163   if (C.getDriver().CCCIsCXX)
03164     GCCName = "hexagon-g++";
03165   else
03166     GCCName = "hexagon-gcc";
03167   const char *Exec =
03168     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
03169 
03170   if (Output.isFilename()) {
03171     CmdArgs.push_back("-o");
03172     CmdArgs.push_back(Output.getFilename());
03173   }
03174 
03175   for (InputInfoList::const_iterator
03176          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
03177     const InputInfo &II = *it;
03178 
03179     // Don't try to pass LLVM or AST inputs to a generic gcc.
03180     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
03181         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
03182       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
03183         << getToolChain().getTripleString();
03184     else if (II.getType() == types::TY_AST)
03185       D.Diag(clang::diag::err_drv_no_ast_support)
03186         << getToolChain().getTripleString();
03187 
03188     if (II.isFilename())
03189       CmdArgs.push_back(II.getFilename());
03190     else
03191       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
03192       II.getInputArg().render(Args, CmdArgs);
03193   }
03194   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
03195 
03196 }
03197 // Hexagon tools end.
03198 
03199 
03200 const char *darwin::CC1::getCC1Name(types::ID Type) const {
03201   switch (Type) {
03202   default:
03203     llvm_unreachable("Unexpected type for Darwin CC1 tool.");
03204   case types::TY_Asm:
03205   case types::TY_C: case types::TY_CHeader:
03206   case types::TY_PP_C: case types::TY_PP_CHeader:
03207     return "cc1";
03208   case types::TY_ObjC: case types::TY_ObjCHeader:
03209   case types::TY_PP_ObjC: case types::TY_PP_ObjC_Alias:
03210   case types::TY_PP_ObjCHeader:
03211     return "cc1obj";
03212   case types::TY_CXX: case types::TY_CXXHeader:
03213   case types::TY_PP_CXX: case types::TY_PP_CXXHeader:
03214     return "cc1plus";
03215   case types::TY_ObjCXX: case types::TY_ObjCXXHeader:
03216   case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXX_Alias:
03217   case types::TY_PP_ObjCXXHeader:
03218     return "cc1objplus";
03219   }
03220 }
03221 
03222 void darwin::CC1::anchor() {}
03223 
03224 const char *darwin::CC1::getBaseInputName(const ArgList &Args,
03225                                           const InputInfoList &Inputs) {
03226   return Args.MakeArgString(
03227     llvm::sys::path::filename(Inputs[0].getBaseInput()));
03228 }
03229 
03230 const char *darwin::CC1::getBaseInputStem(const ArgList &Args,
03231                                           const InputInfoList &Inputs) {
03232   const char *Str = getBaseInputName(Args, Inputs);
03233 
03234   if (const char *End = strrchr(Str, '.'))
03235     return Args.MakeArgString(std::string(Str, End));
03236 
03237   return Str;
03238 }
03239 
03240 const char *
03241 darwin::CC1::getDependencyFileName(const ArgList &Args,
03242                                    const InputInfoList &Inputs) {
03243   // FIXME: Think about this more.
03244   std::string Res;
03245 
03246   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
03247     std::string Str(OutputOpt->getValue(Args));
03248     Res = Str.substr(0, Str.rfind('.'));
03249   } else {
03250     Res = darwin::CC1::getBaseInputStem(Args, Inputs);
03251   }
03252   return Args.MakeArgString(Res + ".d");
03253 }
03254 
03255 void darwin::CC1::RemoveCC1UnsupportedArgs(ArgStringList &CmdArgs) const {
03256   for (ArgStringList::iterator it = CmdArgs.begin(), ie = CmdArgs.end();
03257        it != ie;) {
03258 
03259     StringRef Option = *it;
03260     bool RemoveOption = false;
03261 
03262     // Erase both -fmodule-cache-path and its argument.
03263     if (Option.equals("-fmodule-cache-path") && it+2 != ie) {
03264       it = CmdArgs.erase(it, it+2);
03265       ie = CmdArgs.end();
03266       continue;
03267     }
03268 
03269     // Remove unsupported -f options.
03270     if (Option.startswith("-f")) {
03271       // Remove -f/-fno- to reduce the number of cases.
03272       if (Option.startswith("-fno-"))
03273         Option = Option.substr(5);
03274       else
03275         Option = Option.substr(2);
03276       RemoveOption = llvm::StringSwitch<bool>(Option)
03277         .Case("altivec", true)
03278         .Case("modules", true)
03279         .Case("diagnostics-show-note-include-stack", true)
03280         .Default(false);
03281     }
03282 
03283     // Handle machine specific options.
03284     if (Option.startswith("-m")) {
03285       RemoveOption = llvm::StringSwitch<bool>(Option)
03286         .Case("-mthumb", true)
03287         .Case("-mno-thumb", true)
03288         .Case("-mno-fused-madd", true)
03289         .Case("-mlong-branch", true)
03290         .Case("-mlongcall", true)
03291         .Case("-mcpu=G4", true)
03292         .Case("-mcpu=G5", true)
03293         .Default(false);
03294     }
03295     
03296     // Handle warning options.
03297     if (Option.startswith("-W")) {
03298       // Remove -W/-Wno- to reduce the number of cases.
03299       if (Option.startswith("-Wno-"))
03300         Option = Option.substr(5);
03301       else
03302         Option = Option.substr(2);
03303       
03304       RemoveOption = llvm::StringSwitch<bool>(Option)
03305         .Case("address-of-temporary", true)
03306         .Case("ambiguous-member-template", true)
03307         .Case("analyzer-incompatible-plugin", true)
03308         .Case("array-bounds", true)
03309         .Case("array-bounds-pointer-arithmetic", true)
03310         .Case("bind-to-temporary-copy", true)
03311         .Case("bitwise-op-parentheses", true)
03312         .Case("bool-conversions", true)
03313         .Case("builtin-macro-redefined", true)
03314         .Case("c++-hex-floats", true)
03315         .Case("c++0x-compat", true)
03316         .Case("c++0x-extensions", true)
03317         .Case("c++0x-narrowing", true)
03318         .Case("c++11-compat", true)
03319         .Case("c++11-extensions", true)
03320         .Case("c++11-narrowing", true)
03321         .Case("conditional-uninitialized", true)
03322         .Case("constant-conversion", true)
03323         .Case("conversion-null", true)
03324         .Case("CFString-literal", true)
03325         .Case("constant-logical-operand", true)
03326         .Case("custom-atomic-properties", true)
03327         .Case("default-arg-special-member", true)
03328         .Case("delegating-ctor-cycles", true)
03329         .Case("delete-non-virtual-dtor", true)
03330         .Case("deprecated-implementations", true)
03331         .Case("deprecated-writable-strings", true)
03332         .Case("distributed-object-modifiers", true)
03333         .Case("duplicate-method-arg", true)
03334         .Case("dynamic-class-memaccess", true)
03335         .Case("enum-compare", true)
03336         .Case("exit-time-destructors", true)
03337         .Case("gnu", true)
03338         .Case("gnu-designator", true)
03339         .Case("header-hygiene", true)
03340         .Case("idiomatic-parentheses", true)
03341         .Case("ignored-qualifiers", true)
03342         .Case("implicit-atomic-properties", true)
03343         .Case("incompatible-pointer-types", true)
03344         .Case("incomplete-implementation", true)
03345         .Case("initializer-overrides", true)
03346         .Case("invalid-noreturn", true)
03347         .Case("invalid-token-paste", true)
03348         .Case("language-extension-token", true)
03349         .Case("literal-conversion", true)
03350         .Case("literal-range", true)
03351         .Case("local-type-template-args", true)
03352         .Case("logical-op-parentheses", true)
03353         .Case("method-signatures", true)
03354         .Case("microsoft", true)
03355         .Case("mismatched-tags", true)
03356         .Case("missing-method-return-type", true)
03357         .Case("non-pod-varargs", true)
03358         .Case("nonfragile-abi2", true)
03359         .Case("null-arithmetic", true)
03360         .Case("null-dereference", true)
03361         .Case("out-of-line-declaration", true)
03362         .Case("overriding-method-mismatch", true)
03363         .Case("readonly-setter-attrs", true)
03364         .Case("return-stack-address", true)
03365         .Case("self-assign", true)
03366         .Case("semicolon-before-method-body", true)
03367         .Case("sentinel", true)
03368         .Case("shift-overflow", true)
03369         .Case("shift-sign-overflow", true)
03370         .Case("sign-conversion", true)
03371         .Case("sizeof-array-argument", true)
03372         .Case("sizeof-pointer-memaccess", true)
03373         .Case("string-compare", true)
03374         .Case("super-class-method-mismatch", true)
03375         .Case("tautological-compare", true)
03376         .Case("typedef-redefinition", true)
03377         .Case("typename-missing", true)
03378         .Case("undefined-reinterpret-cast", true)
03379         .Case("unknown-warning-option", true)
03380         .Case("unnamed-type-template-args", true)
03381         .Case("unneeded-internal-declaration", true)
03382         .Case("unneeded-member-function", true)
03383         .Case("unused-comparison", true)
03384         .Case("unused-exception-parameter", true)
03385         .Case("unused-member-function", true)
03386         .Case("unused-result", true)
03387         .Case("vector-conversions", true)
03388         .Case("vla", true)
03389         .Case("used-but-marked-unused", true)
03390         .Case("weak-vtables", true)
03391         .Default(false);
03392     } // if (Option.startswith("-W"))
03393     if (RemoveOption) {
03394       it = CmdArgs.erase(it);
03395       ie = CmdArgs.end();
03396     } else {
03397       ++it;
03398     }
03399   }
03400 }
03401 
03402 void darwin::CC1::AddCC1Args(const ArgList &Args,
03403                              ArgStringList &CmdArgs) const {
03404   const Driver &D = getToolChain().getDriver();
03405 
03406   CheckCodeGenerationOptions(D, Args);
03407 
03408   // Derived from cc1 spec.
03409   if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) &&
03410       !Args.hasArg(options::OPT_mdynamic_no_pic))
03411     CmdArgs.push_back("-fPIC");
03412 
03413   if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
03414       getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
03415     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
03416       CmdArgs.push_back("-fno-builtin-strcat");
03417     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
03418       CmdArgs.push_back("-fno-builtin-strcpy");
03419   }
03420 
03421   if (Args.hasArg(options::OPT_g_Flag) &&
03422       !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols))
03423     CmdArgs.push_back("-feliminate-unused-debug-symbols");
03424 }
03425 
03426 void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
03427                                     const InputInfoList &Inputs,
03428                                     const ArgStringList &OutputArgs) const {
03429   const Driver &D = getToolChain().getDriver();
03430 
03431   // Derived from cc1_options spec.
03432   if (Args.hasArg(options::OPT_fast) ||
03433       Args.hasArg(options::OPT_fastf) ||
03434       Args.hasArg(options::OPT_fastcp))
03435     CmdArgs.push_back("-O3");
03436 
03437   if (Arg *A = Args.getLastArg(options::OPT_pg))
03438     if (Args.hasArg(options::OPT_fomit_frame_pointer))
03439       D.Diag(diag::err_drv_argument_not_allowed_with)
03440         << A->getAsString(Args) << "-fomit-frame-pointer";
03441 
03442   AddCC1Args(Args, CmdArgs);
03443 
03444   if (!Args.hasArg(options::OPT_Q))
03445     CmdArgs.push_back("-quiet");
03446 
03447   CmdArgs.push_back("-dumpbase");
03448   CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs));
03449 
03450   Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
03451 
03452   Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
03453   Args.AddAllArgs(CmdArgs, options::OPT_a_Group);
03454 
03455   // FIXME: The goal is to use the user provided -o if that is our
03456   // final output, otherwise to drive from the original input
03457   // name. Find a clean way to go about this.
03458   if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
03459       Args.hasArg(options::OPT_o)) {
03460     Arg *OutputOpt = Args.getLastArg(options::OPT_o);
03461     CmdArgs.push_back("-auxbase-strip");
03462     CmdArgs.push_back(OutputOpt->getValue(Args));
03463   } else {
03464     CmdArgs.push_back("-auxbase");
03465     CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs));
03466   }
03467 
03468   Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
03469 
03470   Args.AddAllArgs(CmdArgs, options::OPT_O);
03471   // FIXME: -Wall is getting some special treatment. Investigate.
03472   Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
03473   Args.AddLastArg(CmdArgs, options::OPT_w);
03474   Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
03475                   options::OPT_trigraphs);
03476   if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
03477     // Honor -std-default.
03478     Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
03479                               "-std=", /*Joined=*/true);
03480   }
03481 
03482   if (Args.hasArg(options::OPT_v))
03483     CmdArgs.push_back("-version");
03484   if (Args.hasArg(options::OPT_pg) &&
03485       getToolChain().SupportsProfiling())
03486     CmdArgs.push_back("-p");
03487   Args.AddLastArg(CmdArgs, options::OPT_p);
03488 
03489   // The driver treats -fsyntax-only specially.
03490   if (getToolChain().getTriple().getArch() == llvm::Triple::arm ||
03491       getToolChain().getTriple().getArch() == llvm::Triple::thumb) {
03492     // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are
03493     // used to inhibit the default -fno-builtin-str{cat,cpy}.
03494     //
03495     // FIXME: Should we grow a better way to deal with "removing" args?
03496     for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group,
03497                                                options::OPT_fsyntax_only),
03498            ie = Args.filtered_end(); it != ie; ++it) {
03499       if (!(*it)->getOption().matches(options::OPT_fbuiltin_strcat) &&
03500           !(*it)->getOption().matches(options::OPT_fbuiltin_strcpy)) {
03501         (*it)->claim();
03502         (*it)->render(Args, CmdArgs);
03503       }
03504     }
03505   } else
03506     Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
03507 
03508   // Claim Clang only -f options, they aren't worth warning about.
03509   Args.ClaimAllArgs(options::OPT_f_clang_Group);
03510 
03511   Args.AddAllArgs(CmdArgs, options::OPT_undef);
03512   if (Args.hasArg(options::OPT_Qn))
03513     CmdArgs.push_back("-fno-ident");
03514 
03515   // FIXME: This isn't correct.
03516   //Args.AddLastArg(CmdArgs, options::OPT__help)
03517   //Args.AddLastArg(CmdArgs, options::OPT__targetHelp)
03518 
03519   CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
03520 
03521   // FIXME: Still don't get what is happening here. Investigate.
03522   Args.AddAllArgs(CmdArgs, options::OPT__param);
03523 
03524   if (Args.hasArg(options::OPT_fmudflap) ||
03525       Args.hasArg(options::OPT_fmudflapth)) {
03526     CmdArgs.push_back("-fno-builtin");
03527     CmdArgs.push_back("-fno-merge-constants");
03528   }
03529 
03530   if (Args.hasArg(options::OPT_coverage)) {
03531     CmdArgs.push_back("-fprofile-arcs");
03532     CmdArgs.push_back("-ftest-coverage");
03533   }
03534 
03535   if (types::isCXX(Inputs[0].getType()))
03536     CmdArgs.push_back("-D__private_extern__=extern");
03537 }
03538 
03539 void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs,
03540                                     const InputInfoList &Inputs,
03541                                     const ArgStringList &OutputArgs) const {
03542   // Derived from cpp_options
03543   AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
03544 
03545   CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
03546 
03547   AddCC1Args(Args, CmdArgs);
03548 
03549   // NOTE: The code below has some commonality with cpp_options, but
03550   // in classic gcc style ends up sending things in different
03551   // orders. This may be a good merge candidate once we drop pedantic
03552   // compatibility.
03553 
03554   Args.AddAllArgs(CmdArgs, options::OPT_m_Group);
03555   Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi,
03556                   options::OPT_trigraphs);
03557   if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
03558     // Honor -std-default.
03559     Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
03560                               "-std=", /*Joined=*/true);
03561   }
03562   Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group);
03563   Args.AddLastArg(CmdArgs, options::OPT_w);
03564 
03565   // The driver treats -fsyntax-only specially.
03566   Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only);
03567 
03568   // Claim Clang only -f options, they aren't worth warning about.
03569   Args.ClaimAllArgs(options::OPT_f_clang_Group);
03570 
03571   if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) &&
03572       !Args.hasArg(options::OPT_fno_working_directory))
03573     CmdArgs.push_back("-fworking-directory");
03574 
03575   Args.AddAllArgs(CmdArgs, options::OPT_O);
03576   Args.AddAllArgs(CmdArgs, options::OPT_undef);
03577   if (Args.hasArg(options::OPT_save_temps))
03578     CmdArgs.push_back("-fpch-preprocess");
03579 }
03580 
03581 void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args,
03582                                           ArgStringList &CmdArgs,
03583                                           const InputInfoList &Inputs) const {
03584   const Driver &D = getToolChain().getDriver();
03585 
03586   CheckPreprocessingOptions(D, Args);
03587 
03588   // Derived from cpp_unique_options.
03589   // -{C,CC} only with -E is checked in CheckPreprocessingOptions().
03590   Args.AddLastArg(CmdArgs, options::OPT_C);
03591   Args.AddLastArg(CmdArgs, options::OPT_CC);
03592   if (!Args.hasArg(options::OPT_Q))
03593     CmdArgs.push_back("-quiet");
03594   Args.AddAllArgs(CmdArgs, options::OPT_nostdinc);
03595   Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx);
03596   Args.AddLastArg(CmdArgs, options::OPT_v);
03597   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F);
03598   Args.AddLastArg(CmdArgs, options::OPT_P);
03599 
03600   // FIXME: Handle %I properly.
03601   if (getToolChain().getArchName() == "x86_64") {
03602     CmdArgs.push_back("-imultilib");
03603     CmdArgs.push_back("x86_64");
03604   }
03605 
03606   if (Args.hasArg(options::OPT_MD)) {
03607     CmdArgs.push_back("-MD");
03608     CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
03609   }
03610 
03611   if (Args.hasArg(options::OPT_MMD)) {
03612     CmdArgs.push_back("-MMD");
03613     CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs));
03614   }
03615 
03616   Args.AddLastArg(CmdArgs, options::OPT_M);
03617   Args.AddLastArg(CmdArgs, options::OPT_MM);
03618   Args.AddAllArgs(CmdArgs, options::OPT_MF);
03619   Args.AddLastArg(CmdArgs, options::OPT_MG);
03620   Args.AddLastArg(CmdArgs, options::OPT_MP);
03621   Args.AddAllArgs(CmdArgs, options::OPT_MQ);
03622   Args.AddAllArgs(CmdArgs, options::OPT_MT);
03623   if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) &&
03624       (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) {
03625     if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
03626       CmdArgs.push_back("-MQ");
03627       CmdArgs.push_back(OutputOpt->getValue(Args));
03628     }
03629   }
03630 
03631   Args.AddLastArg(CmdArgs, options::OPT_remap);
03632   if (Args.hasArg(options::OPT_g3))
03633     CmdArgs.push_back("-dD");
03634   Args.AddLastArg(CmdArgs, options::OPT_H);
03635 
03636   AddCPPArgs(Args, CmdArgs);
03637 
03638   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A);
03639   Args.AddAllArgs(CmdArgs, options::OPT_i_Group);
03640 
03641   for (InputInfoList::const_iterator
03642          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
03643     const InputInfo &II = *it;
03644 
03645     CmdArgs.push_back(II.getFilename());
03646   }
03647 
03648   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
03649                        options::OPT_Xpreprocessor);
03650 
03651   if (Args.hasArg(options::OPT_fmudflap)) {
03652     CmdArgs.push_back("-D_MUDFLAP");
03653     CmdArgs.push_back("-include");
03654     CmdArgs.push_back("mf-runtime.h");
03655   }
03656 
03657   if (Args.hasArg(options::OPT_fmudflapth)) {
03658     CmdArgs.push_back("-D_MUDFLAP");
03659     CmdArgs.push_back("-D_MUDFLAPTH");
03660     CmdArgs.push_back("-include");
03661     CmdArgs.push_back("mf-runtime.h");
03662   }
03663 }
03664 
03665 void darwin::CC1::AddCPPArgs(const ArgList &Args,
03666                              ArgStringList &CmdArgs) const {
03667   // Derived from cpp spec.
03668 
03669   if (Args.hasArg(options::OPT_static)) {
03670     // The gcc spec is broken here, it refers to dynamic but
03671     // that has been translated. Start by being bug compatible.
03672 
03673     // if (!Args.hasArg(arglist.parser.dynamicOption))
03674     CmdArgs.push_back("-D__STATIC__");
03675   } else
03676     CmdArgs.push_back("-D__DYNAMIC__");
03677 
03678   if (Args.hasArg(options::OPT_pthread))
03679     CmdArgs.push_back("-D_REENTRANT");
03680 }
03681 
03682 void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA,
03683                                       const InputInfo &Output,
03684                                       const InputInfoList &Inputs,
03685                                       const ArgList &Args,
03686                                       const char *LinkingOutput) const {
03687   ArgStringList CmdArgs;
03688 
03689   assert(Inputs.size() == 1 && "Unexpected number of inputs!");
03690 
03691   CmdArgs.push_back("-E");
03692 
03693   if (Args.hasArg(options::OPT_traditional) ||
03694       Args.hasArg(options::OPT_traditional_cpp))
03695     CmdArgs.push_back("-traditional-cpp");
03696 
03697   ArgStringList OutputArgs;
03698   assert(Output.isFilename() && "Unexpected CC1 output.");
03699   OutputArgs.push_back("-o");
03700   OutputArgs.push_back(Output.getFilename());
03701 
03702   if (Args.hasArg(options::OPT_E) || getToolChain().getDriver().CCCIsCPP) {
03703     AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
03704   } else {
03705     AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
03706     CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
03707   }
03708 
03709   Args.AddAllArgs(CmdArgs, options::OPT_d_Group);
03710 
03711   RemoveCC1UnsupportedArgs(CmdArgs);
03712 
03713   const char *CC1Name = getCC1Name(Inputs[0].getType());
03714   const char *Exec =
03715     Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
03716   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
03717 }
03718 
03719 void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA,
03720                                    const InputInfo &Output,
03721                                    const InputInfoList &Inputs,
03722                                    const ArgList &Args,
03723                                    const char *LinkingOutput) const {
03724   const Driver &D = getToolChain().getDriver();
03725   ArgStringList CmdArgs;
03726 
03727   assert(Inputs.size() == 1 && "Unexpected number of inputs!");
03728 
03729   // Silence warning about unused --serialize-diagnostics
03730   Args.ClaimAllArgs(options::OPT__serialize_diags);
03731 
03732   types::ID InputType = Inputs[0].getType();
03733   if (const Arg *A = Args.getLastArg(options::OPT_traditional))
03734     D.Diag(diag::err_drv_argument_only_allowed_with)
03735       << A->getAsString(Args) << "-E";
03736 
03737   if (JA.getType() == types::TY_LLVM_IR ||
03738       JA.getType() == types::TY_LTO_IR)
03739     CmdArgs.push_back("-emit-llvm");
03740   else if (JA.getType() == types::TY_LLVM_BC ||
03741            JA.getType() == types::TY_LTO_BC)
03742     CmdArgs.push_back("-emit-llvm-bc");
03743   else if (Output.getType() == types::TY_AST)
03744     D.Diag(diag::err_drv_no_ast_support)
03745       << getToolChain().getTripleString();
03746   else if (JA.getType() != types::TY_PP_Asm &&
03747            JA.getType() != types::TY_PCH)
03748     D.Diag(diag::err_drv_invalid_gcc_output_type)
03749       << getTypeName(JA.getType());
03750 
03751   ArgStringList OutputArgs;
03752   if (Output.getType() != types::TY_PCH) {
03753     OutputArgs.push_back("-o");
03754     if (Output.isNothing())
03755       OutputArgs.push_back("/dev/null");
03756     else
03757       OutputArgs.push_back(Output.getFilename());
03758   }
03759 
03760   // There is no need for this level of compatibility, but it makes
03761   // diffing easier.
03762   bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) ||
03763                           Args.hasArg(options::OPT_S));
03764 
03765   if (types::getPreprocessedType(InputType) != types::TY_INVALID) {
03766     AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs);
03767     if (OutputArgsEarly) {
03768       AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
03769     } else {
03770       AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
03771       CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
03772     }
03773   } else {
03774     CmdArgs.push_back("-fpreprocessed");
03775 
03776     for (InputInfoList::const_iterator
03777            it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
03778       const InputInfo &II = *it;
03779 
03780       // Reject AST inputs.
03781       if (II.getType() == types::TY_AST) {
03782         D.Diag(diag::err_drv_no_ast_support)
03783           << getToolChain().getTripleString();
03784         return;
03785       }
03786 
03787       CmdArgs.push_back(II.getFilename());
03788     }
03789 
03790     if (OutputArgsEarly) {
03791       AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs);
03792     } else {
03793       AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList());
03794       CmdArgs.append(OutputArgs.begin(), OutputArgs.end());
03795     }
03796   }
03797 
03798   if (Output.getType() == types::TY_PCH) {
03799     assert(Output.isFilename() && "Invalid PCH output.");
03800 
03801     CmdArgs.push_back("-o");
03802     // NOTE: gcc uses a temp .s file for this, but there doesn't seem
03803     // to be a good reason.
03804     const char *TmpPath = C.getArgs().MakeArgString(
03805       D.GetTemporaryPath("cc", "s"));
03806     C.addTempFile(TmpPath);
03807     CmdArgs.push_back(TmpPath);
03808 
03809     // If we're emitting a pch file with the last 4 characters of ".pth"
03810     // and falling back to llvm-gcc we want to use ".gch" instead.
03811     std::string OutputFile(Output.getFilename());
03812     size_t loc = OutputFile.rfind(".pth");
03813     if (loc != std::string::npos)
03814       OutputFile.replace(loc, 4, ".gch");
03815     const char *Tmp = C.getArgs().MakeArgString("--output-pch="+OutputFile);
03816     CmdArgs.push_back(Tmp);
03817   }
03818 
03819   RemoveCC1UnsupportedArgs(CmdArgs);
03820 
03821   const char *CC1Name = getCC1Name(Inputs[0].getType());
03822   const char *Exec =
03823     Args.MakeArgString(getToolChain().GetProgramPath(CC1Name));
03824   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
03825 }
03826 
03827 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
03828                                     const InputInfo &Output,
03829                                     const InputInfoList &Inputs,
03830                                     const ArgList &Args,
03831                                     const char *LinkingOutput) const {
03832   ArgStringList CmdArgs;
03833 
03834   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
03835   const InputInfo &Input = Inputs[0];
03836 
03837   // Determine the original source input.
03838   const Action *SourceAction = &JA;
03839   while (SourceAction->getKind() != Action::InputClass) {
03840     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
03841     SourceAction = SourceAction->getInputs()[0];
03842   }
03843 
03844   // Forward -g, assuming we are dealing with an actual assembly file.
03845   if (SourceAction->getType() == types::TY_Asm ||
03846       SourceAction->getType() == types::TY_PP_Asm) {
03847     if (Args.hasArg(options::OPT_gstabs))
03848       CmdArgs.push_back("--gstabs");
03849     else if (Args.hasArg(options::OPT_g_Group))
03850       CmdArgs.push_back("-g");
03851   }
03852 
03853   // Derived from asm spec.
03854   AddDarwinArch(Args, CmdArgs);
03855 
03856   // Use -force_cpusubtype_ALL on x86 by default.
03857   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 ||
03858       getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
03859       Args.hasArg(options::OPT_force__cpusubtype__ALL))
03860     CmdArgs.push_back("-force_cpusubtype_ALL");
03861 
03862   if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 &&
03863       (Args.hasArg(options::OPT_mkernel) ||
03864        Args.hasArg(options::OPT_static) ||
03865        Args.hasArg(options::OPT_fapple_kext)))
03866     CmdArgs.push_back("-static");
03867 
03868   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
03869                        options::OPT_Xassembler);
03870 
03871   assert(Output.isFilename() && "Unexpected lipo output.");
03872   CmdArgs.push_back("-o");
03873   CmdArgs.push_back(Output.getFilename());
03874 
03875   assert(Input.isFilename() && "Invalid input.");
03876   CmdArgs.push_back(Input.getFilename());
03877 
03878   // asm_final spec is empty.
03879 
03880   const char *Exec =
03881     Args.MakeArgString(getToolChain().GetProgramPath("as"));
03882   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
03883 }
03884 
03885 void darwin::DarwinTool::anchor() {}
03886 
03887 void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
03888                                        ArgStringList &CmdArgs) const {
03889   StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
03890 
03891   // Derived from darwin_arch spec.
03892   CmdArgs.push_back("-arch");
03893   CmdArgs.push_back(Args.MakeArgString(ArchName));
03894 
03895   // FIXME: Is this needed anymore?
03896   if (ArchName == "arm")
03897     CmdArgs.push_back("-force_cpusubtype_ALL");
03898 }
03899 
03900 void darwin::Link::AddLinkArgs(Compilation &C,
03901                                const ArgList &Args,
03902                                ArgStringList &CmdArgs) const {
03903   const Driver &D = getToolChain().getDriver();
03904   const toolchains::Darwin &DarwinTC = getDarwinToolChain();
03905 
03906   unsigned Version[3] = { 0, 0, 0 };
03907   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
03908     bool HadExtra;
03909     if (!Driver::GetReleaseVersion(A->getValue(Args), Version[0],
03910                                    Version[1], Version[2], HadExtra) ||
03911         HadExtra)
03912       D.Diag(diag::err_drv_invalid_version_number)
03913         << A->getAsString(Args);
03914   }
03915 
03916   // Newer linkers support -demangle, pass it if supported and not disabled by
03917   // the user.
03918   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) {
03919     // Don't pass -demangle to ld_classic.
03920     //
03921     // FIXME: This is a temporary workaround, ld should be handling this.
03922     bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
03923                           Args.hasArg(options::OPT_static));
03924     if (getToolChain().getArch() == llvm::Triple::x86) {
03925       for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
03926                                                  options::OPT_Wl_COMMA),
03927              ie = Args.filtered_end(); it != ie; ++it) {
03928         const Arg *A = *it;
03929         for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
03930           if (StringRef(A->getValue(Args, i)) == "-kext")
03931             UsesLdClassic = true;
03932       }
03933     }
03934     if (!UsesLdClassic)
03935       CmdArgs.push_back("-demangle");
03936   }
03937 
03938   // If we are using LTO, then automatically create a temporary file path for
03939   // the linker to use, so that it's lifetime will extend past a possible
03940   // dsymutil step.
03941   if (Version[0] >= 116 && D.IsUsingLTO(Args)) {
03942     const char *TmpPath = C.getArgs().MakeArgString(
03943       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
03944     C.addTempFile(TmpPath);
03945     CmdArgs.push_back("-object_path_lto");
03946     CmdArgs.push_back(TmpPath);
03947   }
03948 
03949   // Derived from the "link" spec.
03950   Args.AddAllArgs(CmdArgs, options::OPT_static);
03951   if (!Args.hasArg(options::OPT_static))
03952     CmdArgs.push_back("-dynamic");
03953   if (Args.hasArg(options::OPT_fgnu_runtime)) {
03954     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
03955     // here. How do we wish to handle such things?
03956   }
03957 
03958   if (!Args.hasArg(options::OPT_dynamiclib)) {
03959     AddDarwinArch(Args, CmdArgs);
03960     // FIXME: Why do this only on this path?
03961     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
03962 
03963     Args.AddLastArg(CmdArgs, options::OPT_bundle);
03964     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
03965     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
03966 
03967     Arg *A;
03968     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
03969         (A = Args.getLastArg(options::OPT_current__version)) ||
03970         (A = Args.getLastArg(options::OPT_install__name)))
03971       D.Diag(diag::err_drv_argument_only_allowed_with)
03972         << A->getAsString(Args) << "-dynamiclib";
03973 
03974     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
03975     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
03976     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
03977   } else {
03978     CmdArgs.push_back("-dylib");
03979 
03980     Arg *A;
03981     if ((A = Args.getLastArg(options::OPT_bundle)) ||
03982         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
03983         (A = Args.getLastArg(options::OPT_client__name)) ||
03984         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
03985         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
03986         (A = Args.getLastArg(options::OPT_private__bundle)))
03987       D.Diag(diag::err_drv_argument_not_allowed_with)
03988         << A->getAsString(Args) << "-dynamiclib";
03989 
03990     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
03991                               "-dylib_compatibility_version");
03992     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
03993                               "-dylib_current_version");
03994 
03995     AddDarwinArch(Args, CmdArgs);
03996 
03997     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
03998                               "-dylib_install_name");
03999   }
04000 
04001   Args.AddLastArg(CmdArgs, options::OPT_all__load);
04002   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
04003   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
04004   if (DarwinTC.isTargetIPhoneOS())
04005     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
04006   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
04007   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
04008   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
04009   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
04010   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
04011   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
04012   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
04013   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
04014   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
04015   Args.AddAllArgs(CmdArgs, options::OPT_init);
04016 
04017   // Add the deployment target.
04018   VersionTuple TargetVersion = DarwinTC.getTargetVersion();
04019 
04020   // If we had an explicit -mios-simulator-version-min argument, honor that,
04021   // otherwise use the traditional deployment targets. We can't just check the
04022   // is-sim attribute because existing code follows this path, and the linker
04023   // may not handle the argument.
04024   //
04025   // FIXME: We may be able to remove this, once we can verify no one depends on
04026   // it.
04027   if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
04028     CmdArgs.push_back("-ios_simulator_version_min");
04029   else if (DarwinTC.isTargetIPhoneOS())
04030     CmdArgs.push_back("-iphoneos_version_min");
04031   else
04032     CmdArgs.push_back("-macosx_version_min");
04033   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
04034 
04035   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
04036   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
04037   Args.AddLastArg(CmdArgs, options::OPT_single__module);
04038   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
04039   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
04040 
04041   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
04042                                      options::OPT_fno_pie,
04043                                      options::OPT_fno_PIE)) {
04044     if (A->getOption().matches(options::OPT_fpie) ||
04045         A->getOption().matches(options::OPT_fPIE))
04046       CmdArgs.push_back("-pie");
04047     else
04048       CmdArgs.push_back("-no_pie");
04049   }
04050 
04051   Args.AddLastArg(CmdArgs, options::OPT_prebind);
04052   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
04053   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
04054   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
04055   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
04056   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
04057   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
04058   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
04059   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
04060   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
04061   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
04062   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
04063   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
04064   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
04065   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
04066   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
04067 
04068   // Give --sysroot= preference, over the Apple specific behavior to also use
04069   // --isysroot as the syslibroot.
04070   StringRef sysroot = C.getSysRoot();
04071   if (sysroot != "") {
04072     CmdArgs.push_back("-syslibroot");
04073     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
04074   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
04075     CmdArgs.push_back("-syslibroot");
04076     CmdArgs.push_back(A->getValue(Args));
04077   }
04078 
04079   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
04080   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
04081   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
04082   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
04083   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
04084   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
04085   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
04086   Args.AddAllArgs(CmdArgs, options::OPT_y);
04087   Args.AddLastArg(CmdArgs, options::OPT_w);
04088   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
04089   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
04090   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
04091   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
04092   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
04093   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
04094   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
04095   Args.AddLastArg(CmdArgs, options::OPT_whyload);
04096   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
04097   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
04098   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
04099   Args.AddLastArg(CmdArgs, options::OPT_Mach);
04100 }
04101 
04102 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
04103                                 const InputInfo &Output,
04104                                 const InputInfoList &Inputs,
04105                                 const ArgList &Args,
04106                                 const char *LinkingOutput) const {
04107   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
04108 
04109   // The logic here is derived from gcc's behavior; most of which
04110   // comes from specs (starting with link_command). Consult gcc for
04111   // more information.
04112   ArgStringList CmdArgs;
04113 
04114   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
04115   if (Args.hasArg(options::OPT_ccc_arcmt_check,
04116                   options::OPT_ccc_arcmt_migrate)) {
04117     for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I)
04118       (*I)->claim();
04119     const char *Exec =
04120       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
04121     CmdArgs.push_back(Output.getFilename());
04122     C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04123     return;
04124   }
04125 
04126   // I'm not sure why this particular decomposition exists in gcc, but
04127   // we follow suite for ease of comparison.
04128   AddLinkArgs(C, Args, CmdArgs);
04129 
04130   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
04131   Args.AddAllArgs(CmdArgs, options::OPT_s);
04132   Args.AddAllArgs(CmdArgs, options::OPT_t);
04133   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
04134   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
04135   Args.AddLastArg(CmdArgs, options::OPT_e);
04136   Args.AddAllArgs(CmdArgs, options::OPT_m_Separate);
04137   Args.AddAllArgs(CmdArgs, options::OPT_r);
04138 
04139   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
04140   // members of static archive libraries which implement Objective-C classes or
04141   // categories.
04142   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
04143     CmdArgs.push_back("-ObjC");
04144 
04145   CmdArgs.push_back("-o");
04146   CmdArgs.push_back(Output.getFilename());
04147 
04148   if (!Args.hasArg(options::OPT_nostdlib) &&
04149       !Args.hasArg(options::OPT_nostartfiles)) {
04150     // Derived from startfile spec.
04151     if (Args.hasArg(options::OPT_dynamiclib)) {
04152       // Derived from darwin_dylib1 spec.
04153       if (getDarwinToolChain().isTargetIOSSimulator()) {
04154         // The simulator doesn't have a versioned crt1 file.
04155         CmdArgs.push_back("-ldylib1.o");
04156       } else if (getDarwinToolChain().isTargetIPhoneOS()) {
04157         if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
04158           CmdArgs.push_back("-ldylib1.o");
04159       } else {
04160         if (getDarwinToolChain().isMacosxVersionLT(10, 5))
04161           CmdArgs.push_back("-ldylib1.o");
04162         else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
04163           CmdArgs.push_back("-ldylib1.10.5.o");
04164       }
04165     } else {
04166       if (Args.hasArg(options::OPT_bundle)) {
04167         if (!Args.hasArg(options::OPT_static)) {
04168           // Derived from darwin_bundle1 spec.
04169           if (getDarwinToolChain().isTargetIOSSimulator()) {
04170             // The simulator doesn't have a versioned crt1 file.
04171             CmdArgs.push_back("-lbundle1.o");
04172           } else if (getDarwinToolChain().isTargetIPhoneOS()) {
04173             if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
04174               CmdArgs.push_back("-lbundle1.o");
04175           } else {
04176             if (getDarwinToolChain().isMacosxVersionLT(10, 6))
04177               CmdArgs.push_back("-lbundle1.o");
04178           }
04179         }
04180       } else {
04181         if (Args.hasArg(options::OPT_pg) &&
04182             getToolChain().SupportsProfiling()) {
04183           if (Args.hasArg(options::OPT_static) ||
04184               Args.hasArg(options::OPT_object) ||
04185               Args.hasArg(options::OPT_preload)) {
04186             CmdArgs.push_back("-lgcrt0.o");
04187           } else {
04188             CmdArgs.push_back("-lgcrt1.o");
04189 
04190             // darwin_crt2 spec is empty.
04191           }
04192         } else {
04193           if (Args.hasArg(options::OPT_static) ||
04194               Args.hasArg(options::OPT_object) ||
04195               Args.hasArg(options::OPT_preload)) {
04196             CmdArgs.push_back("-lcrt0.o");
04197           } else {
04198             // Derived from darwin_crt1 spec.
04199             if (getDarwinToolChain().isTargetIOSSimulator()) {
04200               // The simulator doesn't have a versioned crt1 file.
04201               CmdArgs.push_back("-lcrt1.o");
04202             } else if (getDarwinToolChain().isTargetIPhoneOS()) {
04203               if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
04204                 CmdArgs.push_back("-lcrt1.o");
04205               else
04206                 CmdArgs.push_back("-lcrt1.3.1.o");
04207             } else {
04208               if (getDarwinToolChain().isMacosxVersionLT(10, 5))
04209                 CmdArgs.push_back("-lcrt1.o");
04210               else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
04211                 CmdArgs.push_back("-lcrt1.10.5.o");
04212               else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
04213                 CmdArgs.push_back("-lcrt1.10.6.o");
04214 
04215               // darwin_crt2 spec is empty.
04216             }
04217           }
04218         }
04219       }
04220     }
04221 
04222     if (!getDarwinToolChain().isTargetIPhoneOS() &&
04223         Args.hasArg(options::OPT_shared_libgcc) &&
04224         getDarwinToolChain().isMacosxVersionLT(10, 5)) {
04225       const char *Str =
04226         Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
04227       CmdArgs.push_back(Str);
04228     }
04229   }
04230 
04231   Args.AddAllArgs(CmdArgs, options::OPT_L);
04232 
04233   // If we're building a dynamic lib with -faddress-sanitizer, unresolved
04234   // symbols may appear. Mark all of them as dynamic_lookup.
04235   // Linking executables is handled in lib/Driver/ToolChains.cpp.
04236   if (Args.hasFlag(options::OPT_faddress_sanitizer,
04237                    options::OPT_fno_address_sanitizer, false)) {
04238     if (Args.hasArg(options::OPT_dynamiclib) ||
04239         Args.hasArg(options::OPT_bundle)) {
04240       CmdArgs.push_back("-undefined");
04241       CmdArgs.push_back("dynamic_lookup");
04242     }
04243   }
04244 
04245   if (Args.hasArg(options::OPT_fopenmp))
04246     // This is more complicated in gcc...
04247     CmdArgs.push_back("-lgomp");
04248 
04249   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
04250   
04251   if (isObjCRuntimeLinked(Args) &&
04252       !Args.hasArg(options::OPT_nostdlib) &&
04253       !Args.hasArg(options::OPT_nodefaultlibs)) {
04254     // Avoid linking compatibility stubs on i386 mac.
04255     if (!getDarwinToolChain().isTargetMacOS() ||
04256         getDarwinToolChain().getArchName() != "i386") {
04257       // If we don't have ARC or subscripting runtime support, link in the
04258       // runtime stubs.  We have to do this *before* adding any of the normal
04259       // linker inputs so that its initializer gets run first.
04260       ObjCRuntime runtime;
04261       getDarwinToolChain().configureObjCRuntime(runtime);
04262       // We use arclite library for both ARC and subscripting support.
04263       if ((!runtime.HasARC && isObjCAutoRefCount(Args)) ||
04264           !runtime.HasSubscripting)
04265         getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
04266     }
04267     CmdArgs.push_back("-framework");
04268     CmdArgs.push_back("Foundation");
04269     // Link libobj.
04270     CmdArgs.push_back("-lobjc");
04271   }
04272 
04273   if (LinkingOutput) {
04274     CmdArgs.push_back("-arch_multiple");
04275     CmdArgs.push_back("-final_output");
04276     CmdArgs.push_back(LinkingOutput);
04277   }
04278 
04279   if (Args.hasArg(options::OPT_fnested_functions))
04280     CmdArgs.push_back("-allow_stack_execute");
04281 
04282   if (!Args.hasArg(options::OPT_nostdlib) &&
04283       !Args.hasArg(options::OPT_nodefaultlibs)) {
04284     if (getToolChain().getDriver().CCCIsCXX)
04285       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
04286 
04287     // link_ssp spec is empty.
04288 
04289     // Let the tool chain choose which runtime library to link.
04290     getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
04291   }
04292 
04293   if (!Args.hasArg(options::OPT_nostdlib) &&
04294       !Args.hasArg(options::OPT_nostartfiles)) {
04295     // endfile_spec is empty.
04296   }
04297 
04298   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
04299   Args.AddAllArgs(CmdArgs, options::OPT_F);
04300 
04301   const char *Exec =
04302     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
04303   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04304 }
04305 
04306 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
04307                                 const InputInfo &Output,
04308                                 const InputInfoList &Inputs,
04309                                 const ArgList &Args,
04310                                 const char *LinkingOutput) const {
04311   ArgStringList CmdArgs;
04312 
04313   CmdArgs.push_back("-create");
04314   assert(Output.isFilename() && "Unexpected lipo output.");
04315 
04316   CmdArgs.push_back("-output");
04317   CmdArgs.push_back(Output.getFilename());
04318 
04319   for (InputInfoList::const_iterator
04320          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
04321     const InputInfo &II = *it;
04322     assert(II.isFilename() && "Unexpected lipo input.");
04323     CmdArgs.push_back(II.getFilename());
04324   }
04325   const char *Exec =
04326     Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
04327   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04328 }
04329 
04330 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
04331                                     const InputInfo &Output,
04332                                     const InputInfoList &Inputs,
04333                                     const ArgList &Args,
04334                                     const char *LinkingOutput) const {
04335   ArgStringList CmdArgs;
04336 
04337   CmdArgs.push_back("-o");
04338   CmdArgs.push_back(Output.getFilename());
04339 
04340   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
04341   const InputInfo &Input = Inputs[0];
04342   assert(Input.isFilename() && "Unexpected dsymutil input.");
04343   CmdArgs.push_back(Input.getFilename());
04344 
04345   const char *Exec =
04346     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
04347   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04348 }
04349 
04350 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
04351                const InputInfo &Output,
04352                const InputInfoList &Inputs,
04353                const ArgList &Args,
04354                const char *LinkingOutput) const {
04355   ArgStringList CmdArgs;
04356   CmdArgs.push_back("--verify");
04357   CmdArgs.push_back("--debug-info");
04358   CmdArgs.push_back("--eh-frame");
04359   CmdArgs.push_back("--quiet");
04360 
04361   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
04362   const InputInfo &Input = Inputs[0];
04363   assert(Input.isFilename() && "Unexpected verify input");
04364 
04365   // Grabbing the output of the earlier dsymutil run.
04366   CmdArgs.push_back(Input.getFilename());
04367 
04368   const char *Exec =
04369     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
04370   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04371 }
04372 
04373 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
04374                                       const InputInfo &Output,
04375                                       const InputInfoList &Inputs,
04376                                       const ArgList &Args,
04377                                       const char *LinkingOutput) const {
04378   ArgStringList CmdArgs;
04379 
04380   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
04381                        options::OPT_Xassembler);
04382 
04383   CmdArgs.push_back("-o");
04384   CmdArgs.push_back(Output.getFilename());
04385 
04386   for (InputInfoList::const_iterator
04387          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
04388     const InputInfo &II = *it;
04389     CmdArgs.push_back(II.getFilename());
04390   }
04391 
04392   const char *Exec =
04393     Args.MakeArgString(getToolChain().GetProgramPath("as"));
04394   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04395 }
04396 
04397 
04398 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
04399                                   const InputInfo &Output,
04400                                   const InputInfoList &Inputs,
04401                                   const ArgList &Args,
04402                                   const char *LinkingOutput) const {
04403   // FIXME: Find a real GCC, don't hard-code versions here
04404   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
04405   const llvm::Triple &T = getToolChain().getTriple();
04406   std::string LibPath = "/usr/lib/";
04407   llvm::Triple::ArchType Arch = T.getArch();
04408   switch (Arch) {
04409         case llvm::Triple::x86:
04410           GCCLibPath += ("i386-" + T.getVendorName() + "-" +
04411               T.getOSName()).str() + "/4.5.2/";
04412           break;
04413         case llvm::Triple::x86_64:
04414           GCCLibPath += ("i386-" + T.getVendorName() + "-" +
04415               T.getOSName()).str();
04416           GCCLibPath += "/4.5.2/amd64/";
04417           LibPath += "amd64/";
04418           break;
04419         default:
04420           assert(0 && "Unsupported architecture");
04421   }
04422 
04423   ArgStringList CmdArgs;
04424 
04425   // Demangle C++ names in errors
04426   CmdArgs.push_back("-C");
04427 
04428   if ((!Args.hasArg(options::OPT_nostdlib)) &&
04429       (!Args.hasArg(options::OPT_shared))) {
04430     CmdArgs.push_back("-e");
04431     CmdArgs.push_back("_start");
04432   }
04433 
04434   if (Args.hasArg(options::OPT_static)) {
04435     CmdArgs.push_back("-Bstatic");
04436     CmdArgs.push_back("-dn");
04437   } else {
04438     CmdArgs.push_back("-Bdynamic");
04439     if (Args.hasArg(options::OPT_shared)) {
04440       CmdArgs.push_back("-shared");
04441     } else {
04442       CmdArgs.push_back("--dynamic-linker");
04443       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
04444     }
04445   }
04446 
04447   if (Output.isFilename()) {
04448     CmdArgs.push_back("-o");
04449     CmdArgs.push_back(Output.getFilename());
04450   } else {
04451     assert(Output.isNothing() && "Invalid output.");
04452   }
04453 
04454   if (!Args.hasArg(options::OPT_nostdlib) &&
04455       !Args.hasArg(options::OPT_nostartfiles)) {
04456     if (!Args.hasArg(options::OPT_shared)) {
04457       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
04458       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
04459       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
04460       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
04461     } else {
04462       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
04463       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
04464       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
04465     }
04466     if (getToolChain().getDriver().CCCIsCXX)
04467       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
04468   }
04469 
04470   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
04471 
04472   Args.AddAllArgs(CmdArgs, options::OPT_L);
04473   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
04474   Args.AddAllArgs(CmdArgs, options::OPT_e);
04475   Args.AddAllArgs(CmdArgs, options::OPT_r);
04476 
04477   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
04478 
04479   if (!Args.hasArg(options::OPT_nostdlib) &&
04480       !Args.hasArg(options::OPT_nodefaultlibs)) {
04481     if (getToolChain().getDriver().CCCIsCXX)
04482       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
04483     CmdArgs.push_back("-lgcc_s");
04484     if (!Args.hasArg(options::OPT_shared)) {
04485       CmdArgs.push_back("-lgcc");
04486       CmdArgs.push_back("-lc");
04487       CmdArgs.push_back("-lm");
04488     }
04489   }
04490 
04491   if (!Args.hasArg(options::OPT_nostdlib) &&
04492       !Args.hasArg(options::OPT_nostartfiles)) {
04493     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
04494   }
04495   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
04496 
04497   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
04498 
04499   const char *Exec =
04500     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
04501   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04502 }
04503 
04504 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
04505                                       const InputInfo &Output,
04506                                       const InputInfoList &Inputs,
04507                                       const ArgList &Args,
04508                                       const char *LinkingOutput) const {
04509   ArgStringList CmdArgs;
04510 
04511   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
04512                        options::OPT_Xassembler);
04513 
04514   CmdArgs.push_back("-o");
04515   CmdArgs.push_back(Output.getFilename());
04516 
04517   for (InputInfoList::const_iterator
04518          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
04519     const InputInfo &II = *it;
04520     CmdArgs.push_back(II.getFilename());
04521   }
04522 
04523   const char *Exec =
04524     Args.MakeArgString(getToolChain().GetProgramPath("gas"));
04525   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04526 }
04527 
04528 void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
04529                                   const InputInfo &Output,
04530                                   const InputInfoList &Inputs,
04531                                   const ArgList &Args,
04532                                   const char *LinkingOutput) const {
04533   ArgStringList CmdArgs;
04534 
04535   if ((!Args.hasArg(options::OPT_nostdlib)) &&
04536       (!Args.hasArg(options::OPT_shared))) {
04537     CmdArgs.push_back("-e");
04538     CmdArgs.push_back("_start");
04539   }
04540 
04541   if (Args.hasArg(options::OPT_static)) {
04542     CmdArgs.push_back("-Bstatic");
04543     CmdArgs.push_back("-dn");
04544   } else {
04545 //    CmdArgs.push_back("--eh-frame-hdr");
04546     CmdArgs.push_back("-Bdynamic");
04547     if (Args.hasArg(options::OPT_shared)) {
04548       CmdArgs.push_back("-shared");
04549     } else {
04550       CmdArgs.push_back("--dynamic-linker");
04551       CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
04552     }
04553   }
04554 
04555   if (Output.isFilename()) {
04556     CmdArgs.push_back("-o");
04557     CmdArgs.push_back(Output.getFilename());
04558   } else {
04559     assert(Output.isNothing() && "Invalid output.");
04560   }
04561 
04562   if (!Args.hasArg(options::OPT_nostdlib) &&
04563       !Args.hasArg(options::OPT_nostartfiles)) {
04564     if (!Args.hasArg(options::OPT_shared)) {
04565       CmdArgs.push_back(Args.MakeArgString(
04566                                 getToolChain().GetFilePath("crt1.o")));
04567       CmdArgs.push_back(Args.MakeArgString(
04568                                 getToolChain().GetFilePath("crti.o")));
04569       CmdArgs.push_back(Args.MakeArgString(
04570                                 getToolChain().GetFilePath("crtbegin.o")));
04571     } else {
04572       CmdArgs.push_back(Args.MakeArgString(
04573                                 getToolChain().GetFilePath("crti.o")));
04574     }
04575     CmdArgs.push_back(Args.MakeArgString(
04576                                 getToolChain().GetFilePath("crtn.o")));
04577   }
04578 
04579   CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
04580                                        + getToolChain().getTripleString()
04581                                        + "/4.2.4"));
04582 
04583   Args.AddAllArgs(CmdArgs, options::OPT_L);
04584   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
04585   Args.AddAllArgs(CmdArgs, options::OPT_e);
04586 
04587   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
04588 
04589   if (!Args.hasArg(options::OPT_nostdlib) &&
04590       !Args.hasArg(options::OPT_nodefaultlibs)) {
04591     // FIXME: For some reason GCC passes -lgcc before adding
04592     // the default system libraries. Just mimic this for now.
04593     CmdArgs.push_back("-lgcc");
04594 
04595     if (Args.hasArg(options::OPT_pthread))
04596       CmdArgs.push_back("-pthread");
04597     if (!Args.hasArg(options::OPT_shared))
04598       CmdArgs.push_back("-lc");
04599     CmdArgs.push_back("-lgcc");
04600   }
04601 
04602   if (!Args.hasArg(options::OPT_nostdlib) &&
04603       !Args.hasArg(options::OPT_nostartfiles)) {
04604     if (!Args.hasArg(options::OPT_shared))
04605       CmdArgs.push_back(Args.MakeArgString(
04606                                 getToolChain().GetFilePath("crtend.o")));
04607   }
04608 
04609   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
04610 
04611   const char *Exec =
04612     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
04613   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04614 }
04615 
04616 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
04617                                      const InputInfo &Output,
04618                                      const InputInfoList &Inputs,
04619                                      const ArgList &Args,
04620                                      const char *LinkingOutput) const {
04621   ArgStringList CmdArgs;
04622 
04623   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
04624                        options::OPT_Xassembler);
04625 
04626   CmdArgs.push_back("-o");
04627   CmdArgs.push_back(Output.getFilename());
04628 
04629   for (InputInfoList::const_iterator
04630          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
04631     const InputInfo &II = *it;
04632     CmdArgs.push_back(II.getFilename());
04633   }
04634 
04635   const char *Exec =
04636     Args.MakeArgString(getToolChain().GetProgramPath("as"));
04637   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04638 }
04639 
04640 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
04641                                  const InputInfo &Output,
04642                                  const InputInfoList &Inputs,
04643                                  const ArgList &Args,
04644                                  const char *LinkingOutput) const {
04645   const Driver &D = getToolChain().getDriver();
04646   ArgStringList CmdArgs;
04647 
04648   if ((!Args.hasArg(options::OPT_nostdlib)) &&
04649       (!Args.hasArg(options::OPT_shared))) {
04650     CmdArgs.push_back("-e");
04651     CmdArgs.push_back("__start");
04652   }
04653 
04654   if (Args.hasArg(options::OPT_static)) {
04655     CmdArgs.push_back("-Bstatic");
04656   } else {
04657     if (Args.hasArg(options::OPT_rdynamic))
04658       CmdArgs.push_back("-export-dynamic");
04659     CmdArgs.push_back("--eh-frame-hdr");
04660     CmdArgs.push_back("-Bdynamic");
04661     if (Args.hasArg(options::OPT_shared)) {
04662       CmdArgs.push_back("-shared");
04663     } else {
04664       CmdArgs.push_back("-dynamic-linker");
04665       CmdArgs.push_back("/usr/libexec/ld.so");
04666     }
04667   }
04668 
04669   if (Output.isFilename()) {
04670     CmdArgs.push_back("-o");
04671     CmdArgs.push_back(Output.getFilename());
04672   } else {
04673     assert(Output.isNothing() && "Invalid output.");
04674   }
04675 
04676   if (!Args.hasArg(options::OPT_nostdlib) &&
04677       !Args.hasArg(options::OPT_nostartfiles)) {
04678     if (!Args.hasArg(options::OPT_shared)) {
04679       if (Args.hasArg(options::OPT_pg))  
04680         CmdArgs.push_back(Args.MakeArgString(
04681                                 getToolChain().GetFilePath("gcrt0.o")));
04682       else
04683         CmdArgs.push_back(Args.MakeArgString(
04684                                 getToolChain().GetFilePath("crt0.o")));
04685       CmdArgs.push_back(Args.MakeArgString(
04686                               getToolChain().GetFilePath("crtbegin.o")));
04687     } else {
04688       CmdArgs.push_back(Args.MakeArgString(
04689                               getToolChain().GetFilePath("crtbeginS.o")));
04690     }
04691   }
04692 
04693   std::string Triple = getToolChain().getTripleString();
04694   if (Triple.substr(0, 6) == "x86_64")
04695     Triple.replace(0, 6, "amd64");
04696   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
04697                                        "/4.2.1"));
04698 
04699   Args.AddAllArgs(CmdArgs, options::OPT_L);
04700   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
04701   Args.AddAllArgs(CmdArgs, options::OPT_e);
04702 
04703   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
04704 
04705   if (!Args.hasArg(options::OPT_nostdlib) &&
04706       !Args.hasArg(options::OPT_nodefaultlibs)) {
04707     if (D.CCCIsCXX) {
04708       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
04709       if (Args.hasArg(options::OPT_pg)) 
04710         CmdArgs.push_back("-lm_p");
04711       else
04712         CmdArgs.push_back("-lm");
04713     }
04714 
04715     // FIXME: For some reason GCC passes -lgcc before adding
04716     // the default system libraries. Just mimic this for now.
04717     CmdArgs.push_back("-lgcc");
04718 
04719     if (Args.hasArg(options::OPT_pthread))
04720       CmdArgs.push_back("-lpthread");
04721     if (!Args.hasArg(options::OPT_shared)) {
04722       if (Args.hasArg(options::OPT_pg)) 
04723          CmdArgs.push_back("-lc_p");
04724       else
04725          CmdArgs.push_back("-lc");
04726     }
04727     CmdArgs.push_back("-lgcc");
04728   }
04729 
04730   if (!Args.hasArg(options::OPT_nostdlib) &&
04731       !Args.hasArg(options::OPT_nostartfiles)) {
04732     if (!Args.hasArg(options::OPT_shared))
04733       CmdArgs.push_back(Args.MakeArgString(
04734                               getToolChain().GetFilePath("crtend.o")));
04735     else
04736       CmdArgs.push_back(Args.MakeArgString(
04737                               getToolChain().GetFilePath("crtendS.o")));
04738   }
04739 
04740   const char *Exec =
04741     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
04742   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04743 }
04744 
04745 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
04746                                      const InputInfo &Output,
04747                                      const InputInfoList &Inputs,
04748                                      const ArgList &Args,
04749                                      const char *LinkingOutput) const {
04750   ArgStringList CmdArgs;
04751 
04752   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
04753   // instruct as in the base system to assemble 32-bit code.
04754   if (getToolChain().getArchName() == "i386")
04755     CmdArgs.push_back("--32");
04756 
04757   if (getToolChain().getArchName() == "powerpc")
04758     CmdArgs.push_back("-a32");
04759 
04760   // Set byte order explicitly
04761   if (getToolChain().getArchName() == "mips")
04762     CmdArgs.push_back("-EB");
04763   else if (getToolChain().getArchName() == "mipsel")
04764     CmdArgs.push_back("-EL");
04765 
04766   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
04767                        options::OPT_Xassembler);
04768 
04769   CmdArgs.push_back("-o");
04770   CmdArgs.push_back(Output.getFilename());
04771 
04772   for (InputInfoList::const_iterator
04773          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
04774     const InputInfo &II = *it;
04775     CmdArgs.push_back(II.getFilename());
04776   }
04777 
04778   const char *Exec =
04779     Args.MakeArgString(getToolChain().GetProgramPath("as"));
04780   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04781 }
04782 
04783 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
04784                                  const InputInfo &Output,
04785                                  const InputInfoList &Inputs,
04786                                  const ArgList &Args,
04787                                  const char *LinkingOutput) const {
04788   const Driver &D = getToolChain().getDriver();
04789   ArgStringList CmdArgs;
04790 
04791   if (!D.SysRoot.empty())
04792     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
04793 
04794   if (Args.hasArg(options::OPT_static)) {
04795     CmdArgs.push_back("-Bstatic");
04796   } else {
04797     if (Args.hasArg(options::OPT_rdynamic))
04798       CmdArgs.push_back("-export-dynamic");
04799     CmdArgs.push_back("--eh-frame-hdr");
04800     if (Args.hasArg(options::OPT_shared)) {
04801       CmdArgs.push_back("-Bshareable");
04802     } else {
04803       CmdArgs.push_back("-dynamic-linker");
04804       CmdArgs.push_back("/libexec/ld-elf.so.1");
04805     }
04806   }
04807 
04808   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
04809   // instruct ld in the base system to link 32-bit code.
04810   if (getToolChain().getArchName() == "i386") {
04811     CmdArgs.push_back("-m");
04812     CmdArgs.push_back("elf_i386_fbsd");
04813   }
04814 
04815   if (getToolChain().getArchName() == "powerpc") {
04816     CmdArgs.push_back("-m");
04817     CmdArgs.push_back("elf32ppc_fbsd");
04818   }
04819 
04820   if (Output.isFilename()) {
04821     CmdArgs.push_back("-o");
04822     CmdArgs.push_back(Output.getFilename());
04823   } else {
04824     assert(Output.isNothing() && "Invalid output.");
04825   }
04826 
04827   if (!Args.hasArg(options::OPT_nostdlib) &&
04828       !Args.hasArg(options::OPT_nostartfiles)) {
04829     if (!Args.hasArg(options::OPT_shared)) {
04830       if (Args.hasArg(options::OPT_pg))
04831         CmdArgs.push_back(Args.MakeArgString(
04832                                 getToolChain().GetFilePath("gcrt1.o")));
04833       else {
04834         const char *crt = Args.hasArg(options::OPT_pie) ? "Scrt1.o" : "crt1.o";
04835         CmdArgs.push_back(Args.MakeArgString(
04836                                 getToolChain().GetFilePath(crt)));
04837       }
04838       CmdArgs.push_back(Args.MakeArgString(
04839                               getToolChain().GetFilePath("crti.o")));
04840       CmdArgs.push_back(Args.MakeArgString(
04841                               getToolChain().GetFilePath("crtbegin.o")));
04842     } else {
04843       CmdArgs.push_back(Args.MakeArgString(
04844                               getToolChain().GetFilePath("crti.o")));
04845       CmdArgs.push_back(Args.MakeArgString(
04846                               getToolChain().GetFilePath("crtbeginS.o")));
04847     }
04848   }
04849 
04850   Args.AddAllArgs(CmdArgs, options::OPT_L);
04851   const ToolChain::path_list Paths = getToolChain().getFilePaths();
04852   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
04853        i != e; ++i)
04854     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
04855   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
04856   Args.AddAllArgs(CmdArgs, options::OPT_e);
04857   Args.AddAllArgs(CmdArgs, options::OPT_s);
04858   Args.AddAllArgs(CmdArgs, options::OPT_t);
04859   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
04860   Args.AddAllArgs(CmdArgs, options::OPT_r);
04861 
04862   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
04863 
04864   if (!Args.hasArg(options::OPT_nostdlib) &&
04865       !Args.hasArg(options::OPT_nodefaultlibs)) {
04866     if (D.CCCIsCXX) {
04867       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
04868       if (Args.hasArg(options::OPT_pg))
04869         CmdArgs.push_back("-lm_p");
04870       else
04871         CmdArgs.push_back("-lm");
04872     }
04873     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
04874     // the default system libraries. Just mimic this for now.
04875     if (Args.hasArg(options::OPT_pg))
04876       CmdArgs.push_back("-lgcc_p");
04877     else
04878       CmdArgs.push_back("-lgcc");
04879     if (Args.hasArg(options::OPT_static)) {
04880       CmdArgs.push_back("-lgcc_eh");
04881     } else if (Args.hasArg(options::OPT_pg)) {
04882       CmdArgs.push_back("-lgcc_eh_p");
04883     } else {
04884       CmdArgs.push_back("--as-needed");
04885       CmdArgs.push_back("-lgcc_s");
04886       CmdArgs.push_back("--no-as-needed");
04887     }
04888 
04889     if (Args.hasArg(options::OPT_pthread)) {
04890       if (Args.hasArg(options::OPT_pg))
04891         CmdArgs.push_back("-lpthread_p");
04892       else
04893         CmdArgs.push_back("-lpthread");
04894     }
04895 
04896     if (Args.hasArg(options::OPT_pg)) {
04897       if (Args.hasArg(options::OPT_shared))
04898         CmdArgs.push_back("-lc");
04899       else
04900         CmdArgs.push_back("-lc_p");
04901       CmdArgs.push_back("-lgcc_p");
04902     } else {
04903       CmdArgs.push_back("-lc");
04904       CmdArgs.push_back("-lgcc");
04905     }
04906 
04907     if (Args.hasArg(options::OPT_static)) {
04908       CmdArgs.push_back("-lgcc_eh");
04909     } else if (Args.hasArg(options::OPT_pg)) {
04910       CmdArgs.push_back("-lgcc_eh_p");
04911     } else {
04912       CmdArgs.push_back("--as-needed");
04913       CmdArgs.push_back("-lgcc_s");
04914       CmdArgs.push_back("--no-as-needed");
04915     }
04916   }
04917 
04918   if (!Args.hasArg(options::OPT_nostdlib) &&
04919       !Args.hasArg(options::OPT_nostartfiles)) {
04920     if (!Args.hasArg(options::OPT_shared))
04921       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
04922                                                                   "crtend.o")));
04923     else
04924       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
04925                                                                  "crtendS.o")));
04926     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
04927                                                                     "crtn.o")));
04928   }
04929 
04930   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
04931 
04932   const char *Exec =
04933     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
04934   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04935 }
04936 
04937 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
04938                                      const InputInfo &Output,
04939                                      const InputInfoList &Inputs,
04940                                      const ArgList &Args,
04941                                      const char *LinkingOutput) const {
04942   ArgStringList CmdArgs;
04943 
04944   // When building 32-bit code on NetBSD/amd64, we have to explicitly
04945   // instruct as in the base system to assemble 32-bit code.
04946   if (getToolChain().getArch() == llvm::Triple::x86)
04947     CmdArgs.push_back("--32");
04948 
04949   // Set byte order explicitly
04950   if (getToolChain().getArchName() == "mips")
04951     CmdArgs.push_back("-EB");
04952   else if (getToolChain().getArchName() == "mipsel")
04953     CmdArgs.push_back("-EL");
04954 
04955   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
04956                        options::OPT_Xassembler);
04957 
04958   CmdArgs.push_back("-o");
04959   CmdArgs.push_back(Output.getFilename());
04960 
04961   for (InputInfoList::const_iterator
04962          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
04963     const InputInfo &II = *it;
04964     CmdArgs.push_back(II.getFilename());
04965   }
04966 
04967   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
04968   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
04969 }
04970 
04971 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
04972                                  const InputInfo &Output,
04973                                  const InputInfoList &Inputs,
04974                                  const ArgList &Args,
04975                                  const char *LinkingOutput) const {
04976   const Driver &D = getToolChain().getDriver();
04977   ArgStringList CmdArgs;
04978 
04979   if (!D.SysRoot.empty())
04980     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
04981 
04982   if (Args.hasArg(options::OPT_static)) {
04983     CmdArgs.push_back("-Bstatic");
04984   } else {
04985     if (Args.hasArg(options::OPT_rdynamic))
04986       CmdArgs.push_back("-export-dynamic");
04987     CmdArgs.push_back("--eh-frame-hdr");
04988     if (Args.hasArg(options::OPT_shared)) {
04989       CmdArgs.push_back("-Bshareable");
04990     } else {
04991       CmdArgs.push_back("-dynamic-linker");
04992       CmdArgs.push_back("/libexec/ld.elf_so");
04993     }
04994   }
04995 
04996   // When building 32-bit code on NetBSD/amd64, we have to explicitly
04997   // instruct ld in the base system to link 32-bit code.
04998   if (getToolChain().getArch() == llvm::Triple::x86) {
04999     CmdArgs.push_back("-m");
05000     CmdArgs.push_back("elf_i386");
05001   }
05002 
05003   if (Output.isFilename()) {
05004     CmdArgs.push_back("-o");
05005     CmdArgs.push_back(Output.getFilename());
05006   } else {
05007     assert(Output.isNothing() && "Invalid output.");
05008   }
05009 
05010   if (!Args.hasArg(options::OPT_nostdlib) &&
05011       !Args.hasArg(options::OPT_nostartfiles)) {
05012     if (!Args.hasArg(options::OPT_shared)) {
05013       CmdArgs.push_back(Args.MakeArgString(
05014                               getToolChain().GetFilePath("crt0.o")));
05015       CmdArgs.push_back(Args.MakeArgString(
05016                               getToolChain().GetFilePath("crti.o")));
05017       CmdArgs.push_back(Args.MakeArgString(
05018                               getToolChain().GetFilePath("crtbegin.o")));
05019     } else {
05020       CmdArgs.push_back(Args.MakeArgString(
05021                               getToolChain().GetFilePath("crti.o")));
05022       CmdArgs.push_back(Args.MakeArgString(
05023                               getToolChain().GetFilePath("crtbeginS.o")));
05024     }
05025   }
05026 
05027   Args.AddAllArgs(CmdArgs, options::OPT_L);
05028   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
05029   Args.AddAllArgs(CmdArgs, options::OPT_e);
05030   Args.AddAllArgs(CmdArgs, options::OPT_s);
05031   Args.AddAllArgs(CmdArgs, options::OPT_t);
05032   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
05033   Args.AddAllArgs(CmdArgs, options::OPT_r);
05034 
05035   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
05036 
05037   if (!Args.hasArg(options::OPT_nostdlib) &&
05038       !Args.hasArg(options::OPT_nodefaultlibs)) {
05039     if (D.CCCIsCXX) {
05040       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
05041       CmdArgs.push_back("-lm");
05042     }
05043     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
05044     // the default system libraries. Just mimic this for now.
05045     if (Args.hasArg(options::OPT_static)) {
05046       CmdArgs.push_back("-lgcc_eh");
05047     } else {
05048       CmdArgs.push_back("--as-needed");
05049       CmdArgs.push_back("-lgcc_s");
05050       CmdArgs.push_back("--no-as-needed");
05051     }
05052     CmdArgs.push_back("-lgcc");
05053 
05054     if (Args.hasArg(options::OPT_pthread))
05055       CmdArgs.push_back("-lpthread");
05056     CmdArgs.push_back("-lc");
05057 
05058     CmdArgs.push_back("-lgcc");
05059     if (Args.hasArg(options::OPT_static)) {
05060       CmdArgs.push_back("-lgcc_eh");
05061     } else {
05062       CmdArgs.push_back("--as-needed");
05063       CmdArgs.push_back("-lgcc_s");
05064       CmdArgs.push_back("--no-as-needed");
05065     }
05066   }
05067 
05068   if (!Args.hasArg(options::OPT_nostdlib) &&
05069       !Args.hasArg(options::OPT_nostartfiles)) {
05070     if (!Args.hasArg(options::OPT_shared))
05071       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
05072                                                                   "crtend.o")));
05073     else
05074       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
05075                                                                  "crtendS.o")));
05076     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
05077                                                                     "crtn.o")));
05078   }
05079 
05080   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
05081 
05082   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
05083   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
05084 }
05085 
05086 void linuxtools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
05087                                         const InputInfo &Output,
05088                                         const InputInfoList &Inputs,
05089                                         const ArgList &Args,
05090                                         const char *LinkingOutput) const {
05091   ArgStringList CmdArgs;
05092 
05093   // Add --32/--64 to make sure we get the format we want.
05094   // This is incomplete
05095   if (getToolChain().getArch() == llvm::Triple::x86) {
05096     CmdArgs.push_back("--32");
05097   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
05098     CmdArgs.push_back("--64");
05099   } else if (getToolChain().getArch() == llvm::Triple::ppc) {
05100     CmdArgs.push_back("-a32");
05101     CmdArgs.push_back("-mppc");
05102     CmdArgs.push_back("-many");
05103   } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
05104     CmdArgs.push_back("-a64");
05105     CmdArgs.push_back("-mppc64");
05106     CmdArgs.push_back("-many");
05107   } else if (getToolChain().getArch() == llvm::Triple::arm) {
05108     StringRef MArch = getToolChain().getArchName();
05109     if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
05110       CmdArgs.push_back("-mfpu=neon");
05111 
05112     StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args,
05113                                            getToolChain().getTriple());
05114     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
05115 
05116     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
05117     Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
05118     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
05119   } else if (getToolChain().getArch() == llvm::Triple::mips ||
05120              getToolChain().getArch() == llvm::Triple::mipsel ||
05121              getToolChain().getArch() == llvm::Triple::mips64 ||
05122              getToolChain().getArch() == llvm::Triple::mips64el) {
05123     StringRef CPUName;
05124     StringRef ABIName;
05125     getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
05126 
05127     CmdArgs.push_back("-march");
05128     CmdArgs.push_back(CPUName.data());
05129 
05130     // Convert ABI name to the GNU tools acceptable variant.
05131     if (ABIName == "o32")
05132       ABIName = "32";
05133     else if (ABIName == "n64")
05134       ABIName = "64";
05135 
05136     CmdArgs.push_back("-mabi");
05137     CmdArgs.push_back(ABIName.data());
05138 
05139     if (getToolChain().getArch() == llvm::Triple::mips ||
05140         getToolChain().getArch() == llvm::Triple::mips64)
05141       CmdArgs.push_back("-EB");
05142     else
05143       CmdArgs.push_back("-EL");
05144   }
05145 
05146   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
05147                        options::OPT_Xassembler);
05148 
05149   CmdArgs.push_back("-o");
05150   CmdArgs.push_back(Output.getFilename());
05151 
05152   for (InputInfoList::const_iterator
05153          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
05154     const InputInfo &II = *it;
05155     CmdArgs.push_back(II.getFilename());
05156   }
05157 
05158   const char *Exec =
05159     Args.MakeArgString(getToolChain().GetProgramPath("as"));
05160   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
05161 }
05162 
05163 static void AddLibgcc(llvm::Triple Triple, const Driver &D,
05164                       ArgStringList &CmdArgs, const ArgList &Args) {
05165   bool isAndroid = Triple.getEnvironment() == llvm::Triple::ANDROIDEABI;
05166   bool StaticLibgcc = isAndroid || Args.hasArg(options::OPT_static) ||
05167     Args.hasArg(options::OPT_static_libgcc);
05168   if (!D.CCCIsCXX)
05169     CmdArgs.push_back("-lgcc");
05170 
05171   if (StaticLibgcc) {
05172     if (D.CCCIsCXX)
05173       CmdArgs.push_back("-lgcc");
05174   } else {
05175     if (!D.CCCIsCXX)
05176       CmdArgs.push_back("--as-needed");
05177     CmdArgs.push_back("-lgcc_s");
05178     if (!D.CCCIsCXX)
05179       CmdArgs.push_back("--no-as-needed");
05180   }
05181 
05182   if (StaticLibgcc && !isAndroid)
05183     CmdArgs.push_back("-lgcc_eh");
05184   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
05185     CmdArgs.push_back("-lgcc");
05186 }
05187 
05188 void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA,
05189                                     const InputInfo &Output,
05190                                     const InputInfoList &Inputs,
05191                                     const ArgList &Args,
05192                                     const char *LinkingOutput) const {
05193   const toolchains::Linux& ToolChain =
05194     static_cast<const toolchains::Linux&>(getToolChain());
05195   const Driver &D = ToolChain.getDriver();
05196   const bool isAndroid = ToolChain.getTriple().getEnvironment() ==
05197     llvm::Triple::ANDROIDEABI;
05198 
05199   ArgStringList CmdArgs;
05200 
05201   // Silence warning for "clang -g foo.o -o foo"
05202   Args.ClaimAllArgs(options::OPT_g_Group);
05203   // and "clang -emit-llvm foo.o -o foo"
05204   Args.ClaimAllArgs(options::OPT_emit_llvm);
05205   // and for "clang -g foo.o -o foo". Other warning options are already
05206   // handled somewhere else.
05207   Args.ClaimAllArgs(options::OPT_w);
05208 
05209   if (!D.SysRoot.empty())
05210     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
05211 
05212   if (Args.hasArg(options::OPT_pie))
05213     CmdArgs.push_back("-pie");
05214 
05215   if (Args.hasArg(options::OPT_rdynamic))
05216     CmdArgs.push_back("-export-dynamic");
05217 
05218   if (Args.hasArg(options::OPT_s))
05219     CmdArgs.push_back("-s");
05220 
05221   for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
05222          e = ToolChain.ExtraOpts.end();
05223        i != e; ++i)
05224     CmdArgs.push_back(i->c_str());
05225 
05226   if (!Args.hasArg(options::OPT_static)) {
05227     CmdArgs.push_back("--eh-frame-hdr");
05228   }
05229 
05230   CmdArgs.push_back("-m");
05231   if (ToolChain.getArch() == llvm::Triple::x86)
05232     CmdArgs.push_back("elf_i386");
05233   else if (ToolChain.getArch() == llvm::Triple::arm
05234            ||  ToolChain.getArch() == llvm::Triple::thumb)
05235     CmdArgs.push_back("armelf_linux_eabi");
05236   else if (ToolChain.getArch() == llvm::Triple::ppc)
05237     CmdArgs.push_back("elf32ppclinux");
05238   else if (ToolChain.getArch() == llvm::Triple::ppc64)
05239     CmdArgs.push_back("elf64ppc");
05240   else if (ToolChain.getArch() == llvm::Triple::mips)
05241     CmdArgs.push_back("elf32btsmip");
05242   else if (ToolChain.getArch() == llvm::Triple::mipsel)
05243     CmdArgs.push_back("elf32ltsmip");
05244   else if (ToolChain.getArch() == llvm::Triple::mips64)
05245     CmdArgs.push_back("elf64btsmip");
05246   else if (ToolChain.getArch() == llvm::Triple::mips64el)
05247     CmdArgs.push_back("elf64ltsmip");
05248   else
05249     CmdArgs.push_back("elf_x86_64");
05250 
05251   if (Args.hasArg(options::OPT_static)) {
05252     if (ToolChain.getArch() == llvm::Triple::arm
05253         || ToolChain.getArch() == llvm::Triple::thumb)
05254       CmdArgs.push_back("-Bstatic");
05255     else
05256       CmdArgs.push_back("-static");
05257   } else if (Args.hasArg(options::OPT_shared)) {
05258     CmdArgs.push_back("-shared");
05259     if ((ToolChain.getArch() == llvm::Triple::arm
05260          || ToolChain.getArch() == llvm::Triple::thumb) && isAndroid) {
05261       CmdArgs.push_back("-Bsymbolic");
05262     }
05263   }
05264 
05265   if (ToolChain.getArch() == llvm::Triple::arm ||
05266       ToolChain.getArch() == llvm::Triple::thumb ||
05267       (!Args.hasArg(options::OPT_static) &&
05268        !Args.hasArg(options::OPT_shared))) {
05269     CmdArgs.push_back("-dynamic-linker");
05270     if (isAndroid)
05271       CmdArgs.push_back("/system/bin/linker");
05272     else if (ToolChain.getArch() == llvm::Triple::x86)
05273       CmdArgs.push_back("/lib/ld-linux.so.2");
05274     else if (ToolChain.getArch() == llvm::Triple::arm ||
05275              ToolChain.getArch() == llvm::Triple::thumb)
05276       CmdArgs.push_back("/lib/ld-linux.so.3");
05277     else if (ToolChain.getArch() == llvm::Triple::mips ||
05278              ToolChain.getArch() == llvm::Triple::mipsel)
05279       CmdArgs.push_back("/lib/ld.so.1");
05280     else if (ToolChain.getArch() == llvm::Triple::mips64 ||
05281              ToolChain.getArch() == llvm::Triple::mips64el)
05282       CmdArgs.push_back("/lib64/ld.so.1");
05283     else if (ToolChain.getArch() == llvm::Triple::ppc)
05284       CmdArgs.push_back("/lib/ld.so.1");
05285     else if (ToolChain.getArch() == llvm::Triple::ppc64)
05286       CmdArgs.push_back("/lib64/ld64.so.1");
05287     else
05288       CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
05289   }
05290 
05291   CmdArgs.push_back("-o");
05292   CmdArgs.push_back(Output.getFilename());
05293 
05294   if (!Args.hasArg(options::OPT_nostdlib) &&
05295       !Args.hasArg(options::OPT_nostartfiles)) {
05296     if (!isAndroid) {
05297       const char *crt1 = NULL;
05298       if (!Args.hasArg(options::OPT_shared)){
05299         if (Args.hasArg(options::OPT_pie))
05300           crt1 = "Scrt1.o";
05301         else
05302           crt1 = "crt1.o";
05303       }
05304       if (crt1)
05305         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
05306 
05307       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
05308     }
05309 
05310     const char *crtbegin;
05311     if (Args.hasArg(options::OPT_static))
05312       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
05313     else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
05314       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
05315     else
05316       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
05317     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
05318   }
05319 
05320   Args.AddAllArgs(CmdArgs, options::OPT_L);
05321 
05322   const ToolChain::path_list Paths = ToolChain.getFilePaths();
05323 
05324   for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
05325        i != e; ++i)
05326     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
05327 
05328   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
05329   // as gold requires -plugin to come before any -plugin-opt that -Wl might
05330   // forward.
05331   if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) {
05332     CmdArgs.push_back("-plugin");
05333     std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
05334     CmdArgs.push_back(Args.MakeArgString(Plugin));
05335   }
05336 
05337   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
05338 
05339   if (D.CCCIsCXX &&
05340       !Args.hasArg(options::OPT_nostdlib) &&
05341       !Args.hasArg(options::OPT_nodefaultlibs)) {
05342     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
05343       !Args.hasArg(options::OPT_static);
05344     if (OnlyLibstdcxxStatic)
05345       CmdArgs.push_back("-Bstatic");
05346     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
05347     if (OnlyLibstdcxxStatic)
05348       CmdArgs.push_back("-Bdynamic");
05349     CmdArgs.push_back("-lm");
05350   }
05351 
05352   // Call this before we add the C run-time.
05353   addAsanRTLinux(getToolChain(), Args, CmdArgs);
05354   addTsanRTLinux(getToolChain(), Args, CmdArgs);
05355 
05356   if (!Args.hasArg(options::OPT_nostdlib)) {
05357     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
05358       if (Args.hasArg(options::OPT_static))
05359         CmdArgs.push_back("--start-group");
05360 
05361       AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
05362 
05363       if (Args.hasArg(options::OPT_pthread) ||
05364           Args.hasArg(options::OPT_pthreads))
05365         CmdArgs.push_back("-lpthread");
05366 
05367       CmdArgs.push_back("-lc");
05368 
05369       if (Args.hasArg(options::OPT_static))
05370         CmdArgs.push_back("--end-group");
05371       else
05372         AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
05373     }
05374 
05375     if (!Args.hasArg(options::OPT_nostartfiles)) {
05376       const char *crtend;
05377       if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
05378         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
05379       else
05380         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
05381 
05382       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
05383       if (!isAndroid)
05384         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
05385     }
05386   }
05387 
05388   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
05389 
05390   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
05391 }
05392 
05393 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
05394                                    const InputInfo &Output,
05395                                    const InputInfoList &Inputs,
05396                                    const ArgList &Args,
05397                                    const char *LinkingOutput) const {
05398   ArgStringList CmdArgs;
05399 
05400   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
05401                        options::OPT_Xassembler);
05402 
05403   CmdArgs.push_back("-o");
05404   CmdArgs.push_back(Output.getFilename());
05405 
05406   for (InputInfoList::const_iterator
05407          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
05408     const InputInfo &II = *it;
05409     CmdArgs.push_back(II.getFilename());
05410   }
05411 
05412   const char *Exec =
05413     Args.MakeArgString(getToolChain().GetProgramPath("as"));
05414   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
05415 }
05416 
05417 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
05418                                const InputInfo &Output,
05419                                const InputInfoList &Inputs,
05420                                const ArgList &Args,
05421                                const char *LinkingOutput) const {
05422   const Driver &D = getToolChain().getDriver();
05423   ArgStringList CmdArgs;
05424 
05425   if (Output.isFilename()) {
05426     CmdArgs.push_back("-o");
05427     CmdArgs.push_back(Output.getFilename());
05428   } else {
05429     assert(Output.isNothing() && "Invalid output.");
05430   }
05431 
05432   if (!Args.hasArg(options::OPT_nostdlib) &&
05433       !Args.hasArg(options::OPT_nostartfiles)) {
05434       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
05435       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
05436       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
05437       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
05438   }
05439 
05440   Args.AddAllArgs(CmdArgs, options::OPT_L);
05441   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
05442   Args.AddAllArgs(CmdArgs, options::OPT_e);
05443 
05444   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
05445 
05446   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
05447 
05448   if (!Args.hasArg(options::OPT_nostdlib) &&
05449       !Args.hasArg(options::OPT_nodefaultlibs)) {
05450     if (D.CCCIsCXX) {
05451       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
05452       CmdArgs.push_back("-lm");
05453     }
05454   }
05455 
05456   if (!Args.hasArg(options::OPT_nostdlib) &&
05457       !Args.hasArg(options::OPT_nostartfiles)) {
05458     if (Args.hasArg(options::OPT_pthread))
05459       CmdArgs.push_back("-lpthread");
05460     CmdArgs.push_back("-lc");
05461     CmdArgs.push_back("-lCompilerRT-Generic");
05462     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
05463     CmdArgs.push_back(
05464    Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
05465   }
05466 
05467   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
05468   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
05469 }
05470 
05471 /// DragonFly Tools
05472 
05473 // For now, DragonFly Assemble does just about the same as for
05474 // FreeBSD, but this may change soon.
05475 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
05476                                        const InputInfo &Output,
05477                                        const InputInfoList &Inputs,
05478                                        const ArgList &Args,
05479                                        const char *LinkingOutput) const {
05480   ArgStringList CmdArgs;
05481 
05482   // When building 32-bit code on DragonFly/pc64, we have to explicitly
05483   // instruct as in the base system to assemble 32-bit code.
05484   if (getToolChain().getArchName() == "i386")
05485     CmdArgs.push_back("--32");
05486 
05487   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
05488                        options::OPT_Xassembler);
05489 
05490   CmdArgs.push_back("-o");
05491   CmdArgs.push_back(Output.getFilename());
05492 
05493   for (InputInfoList::const_iterator
05494          it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
05495     const InputInfo &II = *it;
05496     CmdArgs.push_back(II.getFilename());
05497   }
05498 
05499   const char *Exec =
05500     Args.MakeArgString(getToolChain().GetProgramPath("as"));
05501   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
05502 }
05503 
05504 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
05505                                    const InputInfo &Output,
05506                                    const InputInfoList &Inputs,
05507                                    const ArgList &Args,
05508                                    const char *LinkingOutput) const {
05509   const Driver &D = getToolChain().getDriver();
05510   ArgStringList CmdArgs;
05511 
05512   if (!D.SysRoot.empty())
05513     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
05514 
05515   if (Args.hasArg(options::OPT_static)) {
05516     CmdArgs.push_back("-Bstatic");
05517   } else {
05518     if (Args.hasArg(options::OPT_shared))
05519       CmdArgs.push_back("-Bshareable");
05520     else {
05521       CmdArgs.push_back("-dynamic-linker");
05522       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
05523     }
05524   }
05525 
05526   // When building 32-bit code on DragonFly/pc64, we have to explicitly
05527   // instruct ld in the base system to link 32-bit code.
05528   if (getToolChain().getArchName() == "i386") {
05529     CmdArgs.push_back("-m");
05530     CmdArgs.push_back("elf_i386");
05531   }
05532 
05533   if (Output.isFilename()) {
05534     CmdArgs.push_back("-o");
05535     CmdArgs.push_back(Output.getFilename());
05536   } else {
05537     assert(Output.isNothing() && "Invalid output.");
05538   }
05539 
05540   if (!Args.hasArg(options::OPT_nostdlib) &&
05541       !Args.hasArg(options::OPT_nostartfiles)) {
05542     if (!Args.hasArg(options::OPT_shared)) {
05543       CmdArgs.push_back(
05544             Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
05545       CmdArgs.push_back(
05546             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
05547       CmdArgs.push_back(
05548             Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
05549     } else {
05550       CmdArgs.push_back(
05551             Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
05552       CmdArgs.push_back(
05553             Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
05554     }
05555   }
05556 
05557   Args.AddAllArgs(CmdArgs, options::OPT_L);
05558   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
05559   Args.AddAllArgs(CmdArgs, options::OPT_e);
05560 
05561   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
05562 
05563   if (!Args.hasArg(options::OPT_nostdlib) &&
05564       !Args.hasArg(options::OPT_nodefaultlibs)) {
05565     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
05566     //         rpaths
05567     CmdArgs.push_back("-L/usr/lib/gcc41");
05568 
05569     if (!Args.hasArg(options::OPT_static)) {
05570       CmdArgs.push_back("-rpath");
05571       CmdArgs.push_back("/usr/lib/gcc41");
05572 
05573       CmdArgs.push_back("-rpath-link");
05574       CmdArgs.push_back("/usr/lib/gcc41");
05575 
05576       CmdArgs.push_back("-rpath");
05577       CmdArgs.push_back("/usr/lib");
05578 
05579       CmdArgs.push_back("-rpath-link");
05580       CmdArgs.push_back("/usr/lib");
05581     }
05582 
05583     if (D.CCCIsCXX) {
05584       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
05585       CmdArgs.push_back("-lm");
05586     }
05587 
05588     if (Args.hasArg(options::OPT_shared)) {
05589       CmdArgs.push_back("-lgcc_pic");
05590     } else {
05591       CmdArgs.push_back("-lgcc");
05592     }
05593 
05594 
05595     if (Args.hasArg(options::OPT_pthread))
05596       CmdArgs.push_back("-lpthread");
05597 
05598     if (!Args.hasArg(options::OPT_nolibc)) {
05599       CmdArgs.push_back("-lc");
05600     }
05601 
05602     if (Args.hasArg(options::OPT_shared)) {
05603       CmdArgs.push_back("-lgcc_pic");
05604     } else {
05605       CmdArgs.push_back("-lgcc");
05606     }
05607   }
05608 
05609   if (!Args.hasArg(options::OPT_nostdlib) &&
05610       !Args.hasArg(options::OPT_nostartfiles)) {
05611     if (!Args.hasArg(options::OPT_shared))
05612       CmdArgs.push_back(Args.MakeArgString(
05613                               getToolChain().GetFilePath("crtend.o")));
05614     else
05615       CmdArgs.push_back(Args.MakeArgString(
05616                               getToolChain().GetFilePath("crtendS.o")));
05617     CmdArgs.push_back(Args.MakeArgString(
05618                               getToolChain().GetFilePath("crtn.o")));
05619   }
05620 
05621   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
05622 
05623   const char *Exec =
05624     Args.MakeArgString(getToolChain().GetProgramPath("ld"));
05625   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
05626 }
05627 
05628 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
05629                                       const InputInfo &Output,
05630                                       const InputInfoList &Inputs,
05631                                       const ArgList &Args,
05632                                       const char *LinkingOutput) const {
05633   ArgStringList CmdArgs;
05634 
05635   if (Output.isFilename()) {
05636     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
05637                                          Output.getFilename()));
05638   } else {
05639     assert(Output.isNothing() && "Invalid output.");
05640   }
05641 
05642   if (!Args.hasArg(options::OPT_nostdlib) &&
05643     !Args.hasArg(options::OPT_nostartfiles)) {
05644     CmdArgs.push_back("-defaultlib:libcmt");
05645   }
05646 
05647   CmdArgs.push_back("-nologo");
05648 
05649   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
05650 
05651   const char *Exec =
05652     Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
05653   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
05654 }