Home | History | Annotate | Download | only in Driver
      1 //===--- Tools.cpp - Tools Implementations --------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "Tools.h"
     11 #include "InputInfo.h"
     12 #include "ToolChains.h"
     13 #include "clang/Basic/CharInfo.h"
     14 #include "clang/Basic/LangOptions.h"
     15 #include "clang/Basic/ObjCRuntime.h"
     16 #include "clang/Basic/Version.h"
     17 #include "clang/Config/config.h"
     18 #include "clang/Driver/Action.h"
     19 #include "clang/Driver/Compilation.h"
     20 #include "clang/Driver/Driver.h"
     21 #include "clang/Driver/DriverDiagnostic.h"
     22 #include "clang/Driver/Job.h"
     23 #include "clang/Driver/Options.h"
     24 #include "clang/Driver/SanitizerArgs.h"
     25 #include "clang/Driver/ToolChain.h"
     26 #include "clang/Driver/Util.h"
     27 #include "llvm/ADT/STLExtras.h"
     28 #include "llvm/ADT/SmallString.h"
     29 #include "llvm/ADT/StringExtras.h"
     30 #include "llvm/ADT/StringSwitch.h"
     31 #include "llvm/ADT/Twine.h"
     32 #include "llvm/Option/Arg.h"
     33 #include "llvm/Option/ArgList.h"
     34 #include "llvm/Option/Option.h"
     35 #include "llvm/Support/Compression.h"
     36 #include "llvm/Support/ErrorHandling.h"
     37 #include "llvm/Support/FileSystem.h"
     38 #include "llvm/Support/Host.h"
     39 #include "llvm/Support/Path.h"
     40 #include "llvm/Support/Process.h"
     41 #include "llvm/Support/Program.h"
     42 #include "llvm/Support/raw_ostream.h"
     43 
     44 #ifdef LLVM_ON_UNIX
     45 #include <unistd.h> // For getuid().
     46 #endif
     47 
     48 using namespace clang::driver;
     49 using namespace clang::driver::tools;
     50 using namespace clang;
     51 using namespace llvm::opt;
     52 
     53 static void addAssemblerKPIC(const ArgList &Args, ArgStringList &CmdArgs) {
     54   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
     55                                     options::OPT_fpic, options::OPT_fno_pic,
     56                                     options::OPT_fPIE, options::OPT_fno_PIE,
     57                                     options::OPT_fpie, options::OPT_fno_pie);
     58   if (!LastPICArg)
     59     return;
     60   if (LastPICArg->getOption().matches(options::OPT_fPIC) ||
     61       LastPICArg->getOption().matches(options::OPT_fpic) ||
     62       LastPICArg->getOption().matches(options::OPT_fPIE) ||
     63       LastPICArg->getOption().matches(options::OPT_fpie)) {
     64     CmdArgs.push_back("-KPIC");
     65   }
     66 }
     67 
     68 /// CheckPreprocessingOptions - Perform some validation of preprocessing
     69 /// arguments that is shared with gcc.
     70 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
     71   if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
     72     if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
     73         !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
     74       D.Diag(diag::err_drv_argument_only_allowed_with)
     75           << A->getBaseArg().getAsString(Args)
     76           << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
     77     }
     78   }
     79 }
     80 
     81 /// CheckCodeGenerationOptions - Perform some validation of code generation
     82 /// arguments that is shared with gcc.
     83 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
     84   // In gcc, only ARM checks this, but it seems reasonable to check universally.
     85   if (Args.hasArg(options::OPT_static))
     86     if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
     87                                        options::OPT_mdynamic_no_pic))
     88       D.Diag(diag::err_drv_argument_not_allowed_with)
     89         << A->getAsString(Args) << "-static";
     90 }
     91 
     92 // Add backslashes to escape spaces and other backslashes.
     93 // This is used for the space-separated argument list specified with
     94 // the -dwarf-debug-flags option.
     95 static void EscapeSpacesAndBackslashes(const char *Arg,
     96                                        SmallVectorImpl<char> &Res) {
     97   for ( ; *Arg; ++Arg) {
     98     switch (*Arg) {
     99     default: break;
    100     case ' ':
    101     case '\\':
    102       Res.push_back('\\');
    103       break;
    104     }
    105     Res.push_back(*Arg);
    106   }
    107 }
    108 
    109 // Quote target names for inclusion in GNU Make dependency files.
    110 // Only the characters '$', '#', ' ', '\t' are quoted.
    111 static void QuoteTarget(StringRef Target,
    112                         SmallVectorImpl<char> &Res) {
    113   for (unsigned i = 0, e = Target.size(); i != e; ++i) {
    114     switch (Target[i]) {
    115     case ' ':
    116     case '\t':
    117       // Escape the preceding backslashes
    118       for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
    119         Res.push_back('\\');
    120 
    121       // Escape the space/tab
    122       Res.push_back('\\');
    123       break;
    124     case '$':
    125       Res.push_back('$');
    126       break;
    127     case '#':
    128       Res.push_back('\\');
    129       break;
    130     default:
    131       break;
    132     }
    133 
    134     Res.push_back(Target[i]);
    135   }
    136 }
    137 
    138 static void addDirectoryList(const ArgList &Args,
    139                              ArgStringList &CmdArgs,
    140                              const char *ArgName,
    141                              const char *EnvVar) {
    142   const char *DirList = ::getenv(EnvVar);
    143   bool CombinedArg = false;
    144 
    145   if (!DirList)
    146     return; // Nothing to do.
    147 
    148   StringRef Name(ArgName);
    149   if (Name.equals("-I") || Name.equals("-L"))
    150     CombinedArg = true;
    151 
    152   StringRef Dirs(DirList);
    153   if (Dirs.empty()) // Empty string should not add '.'.
    154     return;
    155 
    156   StringRef::size_type Delim;
    157   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
    158     if (Delim == 0) { // Leading colon.
    159       if (CombinedArg) {
    160         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
    161       } else {
    162         CmdArgs.push_back(ArgName);
    163         CmdArgs.push_back(".");
    164       }
    165     } else {
    166       if (CombinedArg) {
    167         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
    168       } else {
    169         CmdArgs.push_back(ArgName);
    170         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
    171       }
    172     }
    173     Dirs = Dirs.substr(Delim + 1);
    174   }
    175 
    176   if (Dirs.empty()) { // Trailing colon.
    177     if (CombinedArg) {
    178       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
    179     } else {
    180       CmdArgs.push_back(ArgName);
    181       CmdArgs.push_back(".");
    182     }
    183   } else { // Add the last path.
    184     if (CombinedArg) {
    185       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
    186     } else {
    187       CmdArgs.push_back(ArgName);
    188       CmdArgs.push_back(Args.MakeArgString(Dirs));
    189     }
    190   }
    191 }
    192 
    193 static void AddLinkerInputs(const ToolChain &TC,
    194                             const InputInfoList &Inputs, const ArgList &Args,
    195                             ArgStringList &CmdArgs) {
    196   const Driver &D = TC.getDriver();
    197 
    198   // Add extra linker input arguments which are not treated as inputs
    199   // (constructed via -Xarch_).
    200   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
    201 
    202   for (const auto &II : Inputs) {
    203     if (!TC.HasNativeLLVMSupport()) {
    204       // Don't try to pass LLVM inputs unless we have native support.
    205       if (II.getType() == types::TY_LLVM_IR ||
    206           II.getType() == types::TY_LTO_IR ||
    207           II.getType() == types::TY_LLVM_BC ||
    208           II.getType() == types::TY_LTO_BC)
    209         D.Diag(diag::err_drv_no_linker_llvm_support)
    210           << TC.getTripleString();
    211     }
    212 
    213     // Add filenames immediately.
    214     if (II.isFilename()) {
    215       CmdArgs.push_back(II.getFilename());
    216       continue;
    217     }
    218 
    219     // Otherwise, this is a linker input argument.
    220     const Arg &A = II.getInputArg();
    221 
    222     // Handle reserved library options.
    223     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
    224       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
    225     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
    226       TC.AddCCKextLibArgs(Args, CmdArgs);
    227     else if (A.getOption().matches(options::OPT_z)) {
    228       // Pass -z prefix for gcc linker compatibility.
    229       A.claim();
    230       A.render(Args, CmdArgs);
    231     } else {
    232        A.renderAsInput(Args, CmdArgs);
    233     }
    234   }
    235 
    236   // LIBRARY_PATH - included following the user specified library paths.
    237   //                and only supported on native toolchains.
    238   if (!TC.isCrossCompiling())
    239     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
    240 }
    241 
    242 /// \brief Determine whether Objective-C automated reference counting is
    243 /// enabled.
    244 static bool isObjCAutoRefCount(const ArgList &Args) {
    245   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
    246 }
    247 
    248 /// \brief Determine whether we are linking the ObjC runtime.
    249 static bool isObjCRuntimeLinked(const ArgList &Args) {
    250   if (isObjCAutoRefCount(Args)) {
    251     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
    252     return true;
    253   }
    254   return Args.hasArg(options::OPT_fobjc_link_runtime);
    255 }
    256 
    257 static bool forwardToGCC(const Option &O) {
    258   // Don't forward inputs from the original command line.  They are added from
    259   // InputInfoList.
    260   return O.getKind() != Option::InputClass &&
    261          !O.hasFlag(options::DriverOption) &&
    262          !O.hasFlag(options::LinkerInput);
    263 }
    264 
    265 void Clang::AddPreprocessingOptions(Compilation &C,
    266                                     const JobAction &JA,
    267                                     const Driver &D,
    268                                     const ArgList &Args,
    269                                     ArgStringList &CmdArgs,
    270                                     const InputInfo &Output,
    271                                     const InputInfoList &Inputs) const {
    272   Arg *A;
    273 
    274   CheckPreprocessingOptions(D, Args);
    275 
    276   Args.AddLastArg(CmdArgs, options::OPT_C);
    277   Args.AddLastArg(CmdArgs, options::OPT_CC);
    278 
    279   // Handle dependency file generation.
    280   if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
    281       (A = Args.getLastArg(options::OPT_MD)) ||
    282       (A = Args.getLastArg(options::OPT_MMD))) {
    283     // Determine the output location.
    284     const char *DepFile;
    285     if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
    286       DepFile = MF->getValue();
    287       C.addFailureResultFile(DepFile, &JA);
    288     } else if (Output.getType() == types::TY_Dependencies) {
    289       DepFile = Output.getFilename();
    290     } else if (A->getOption().matches(options::OPT_M) ||
    291                A->getOption().matches(options::OPT_MM)) {
    292       DepFile = "-";
    293     } else {
    294       DepFile = getDependencyFileName(Args, Inputs);
    295       C.addFailureResultFile(DepFile, &JA);
    296     }
    297     CmdArgs.push_back("-dependency-file");
    298     CmdArgs.push_back(DepFile);
    299 
    300     // Add a default target if one wasn't specified.
    301     if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
    302       const char *DepTarget;
    303 
    304       // If user provided -o, that is the dependency target, except
    305       // when we are only generating a dependency file.
    306       Arg *OutputOpt = Args.getLastArg(options::OPT_o);
    307       if (OutputOpt && Output.getType() != types::TY_Dependencies) {
    308         DepTarget = OutputOpt->getValue();
    309       } else {
    310         // Otherwise derive from the base input.
    311         //
    312         // FIXME: This should use the computed output file location.
    313         SmallString<128> P(Inputs[0].getBaseInput());
    314         llvm::sys::path::replace_extension(P, "o");
    315         DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
    316       }
    317 
    318       CmdArgs.push_back("-MT");
    319       SmallString<128> Quoted;
    320       QuoteTarget(DepTarget, Quoted);
    321       CmdArgs.push_back(Args.MakeArgString(Quoted));
    322     }
    323 
    324     if (A->getOption().matches(options::OPT_M) ||
    325         A->getOption().matches(options::OPT_MD))
    326       CmdArgs.push_back("-sys-header-deps");
    327     if ((isa<PrecompileJobAction>(JA) &&
    328          !Args.hasArg(options::OPT_fno_module_file_deps)) ||
    329         Args.hasArg(options::OPT_fmodule_file_deps))
    330       CmdArgs.push_back("-module-file-deps");
    331   }
    332 
    333   if (Args.hasArg(options::OPT_MG)) {
    334     if (!A || A->getOption().matches(options::OPT_MD) ||
    335               A->getOption().matches(options::OPT_MMD))
    336       D.Diag(diag::err_drv_mg_requires_m_or_mm);
    337     CmdArgs.push_back("-MG");
    338   }
    339 
    340   Args.AddLastArg(CmdArgs, options::OPT_MP);
    341 
    342   // Convert all -MQ <target> args to -MT <quoted target>
    343   for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
    344                                              options::OPT_MQ),
    345          ie = Args.filtered_end(); it != ie; ++it) {
    346     const Arg *A = *it;
    347     A->claim();
    348 
    349     if (A->getOption().matches(options::OPT_MQ)) {
    350       CmdArgs.push_back("-MT");
    351       SmallString<128> Quoted;
    352       QuoteTarget(A->getValue(), Quoted);
    353       CmdArgs.push_back(Args.MakeArgString(Quoted));
    354 
    355     // -MT flag - no change
    356     } else {
    357       A->render(Args, CmdArgs);
    358     }
    359   }
    360 
    361   // Add -i* options, and automatically translate to
    362   // -include-pch/-include-pth for transparent PCH support. It's
    363   // wonky, but we include looking for .gch so we can support seamless
    364   // replacement into a build system already set up to be generating
    365   // .gch files.
    366   bool RenderedImplicitInclude = false;
    367   for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
    368          ie = Args.filtered_end(); it != ie; ++it) {
    369     const Arg *A = it;
    370 
    371     if (A->getOption().matches(options::OPT_include)) {
    372       bool IsFirstImplicitInclude = !RenderedImplicitInclude;
    373       RenderedImplicitInclude = true;
    374 
    375       // Use PCH if the user requested it.
    376       bool UsePCH = D.CCCUsePCH;
    377 
    378       bool FoundPTH = false;
    379       bool FoundPCH = false;
    380       SmallString<128> P(A->getValue());
    381       // We want the files to have a name like foo.h.pch. Add a dummy extension
    382       // so that replace_extension does the right thing.
    383       P += ".dummy";
    384       if (UsePCH) {
    385         llvm::sys::path::replace_extension(P, "pch");
    386         if (llvm::sys::fs::exists(P))
    387           FoundPCH = true;
    388       }
    389 
    390       if (!FoundPCH) {
    391         llvm::sys::path::replace_extension(P, "pth");
    392         if (llvm::sys::fs::exists(P))
    393           FoundPTH = true;
    394       }
    395 
    396       if (!FoundPCH && !FoundPTH) {
    397         llvm::sys::path::replace_extension(P, "gch");
    398         if (llvm::sys::fs::exists(P)) {
    399           FoundPCH = UsePCH;
    400           FoundPTH = !UsePCH;
    401         }
    402       }
    403 
    404       if (FoundPCH || FoundPTH) {
    405         if (IsFirstImplicitInclude) {
    406           A->claim();
    407           if (UsePCH)
    408             CmdArgs.push_back("-include-pch");
    409           else
    410             CmdArgs.push_back("-include-pth");
    411           CmdArgs.push_back(Args.MakeArgString(P));
    412           continue;
    413         } else {
    414           // Ignore the PCH if not first on command line and emit warning.
    415           D.Diag(diag::warn_drv_pch_not_first_include)
    416               << P << A->getAsString(Args);
    417         }
    418       }
    419     }
    420 
    421     // Not translated, render as usual.
    422     A->claim();
    423     A->render(Args, CmdArgs);
    424   }
    425 
    426   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
    427   Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
    428                   options::OPT_index_header_map);
    429 
    430   // Add -Wp, and -Xassembler if using the preprocessor.
    431 
    432   // FIXME: There is a very unfortunate problem here, some troubled
    433   // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
    434   // really support that we would have to parse and then translate
    435   // those options. :(
    436   Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
    437                        options::OPT_Xpreprocessor);
    438 
    439   // -I- is a deprecated GCC feature, reject it.
    440   if (Arg *A = Args.getLastArg(options::OPT_I_))
    441     D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
    442 
    443   // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
    444   // -isysroot to the CC1 invocation.
    445   StringRef sysroot = C.getSysRoot();
    446   if (sysroot != "") {
    447     if (!Args.hasArg(options::OPT_isysroot)) {
    448       CmdArgs.push_back("-isysroot");
    449       CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
    450     }
    451   }
    452 
    453   // Parse additional include paths from environment variables.
    454   // FIXME: We should probably sink the logic for handling these from the
    455   // frontend into the driver. It will allow deleting 4 otherwise unused flags.
    456   // CPATH - included following the user specified includes (but prior to
    457   // builtin and standard includes).
    458   addDirectoryList(Args, CmdArgs, "-I", "CPATH");
    459   // C_INCLUDE_PATH - system includes enabled when compiling C.
    460   addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
    461   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
    462   addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
    463   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
    464   addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
    465   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
    466   addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
    467 
    468   // Add C++ include arguments, if needed.
    469   if (types::isCXX(Inputs[0].getType()))
    470     getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
    471 
    472   // Add system include arguments.
    473   getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
    474 }
    475 
    476 // FIXME: Move to target hook.
    477 static bool isSignedCharDefault(const llvm::Triple &Triple) {
    478   switch (Triple.getArch()) {
    479   default:
    480     return true;
    481 
    482   case llvm::Triple::aarch64:
    483   case llvm::Triple::aarch64_be:
    484   case llvm::Triple::arm:
    485   case llvm::Triple::armeb:
    486   case llvm::Triple::thumb:
    487   case llvm::Triple::thumbeb:
    488     if (Triple.isOSDarwin() || Triple.isOSWindows())
    489       return true;
    490     return false;
    491 
    492   case llvm::Triple::ppc:
    493   case llvm::Triple::ppc64:
    494     if (Triple.isOSDarwin())
    495       return true;
    496     return false;
    497 
    498   case llvm::Triple::ppc64le:
    499   case llvm::Triple::systemz:
    500   case llvm::Triple::xcore:
    501     return false;
    502   }
    503 }
    504 
    505 static bool isNoCommonDefault(const llvm::Triple &Triple) {
    506   switch (Triple.getArch()) {
    507   default:
    508     return false;
    509 
    510   case llvm::Triple::xcore:
    511     return true;
    512   }
    513 }
    514 
    515 // Handle -mhwdiv=.
    516 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
    517                               const ArgList &Args,
    518                               std::vector<const char *> &Features) {
    519   StringRef HWDiv = A->getValue();
    520   if (HWDiv == "arm") {
    521     Features.push_back("+hwdiv-arm");
    522     Features.push_back("-hwdiv");
    523   } else if (HWDiv == "thumb") {
    524     Features.push_back("-hwdiv-arm");
    525     Features.push_back("+hwdiv");
    526   } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
    527     Features.push_back("+hwdiv-arm");
    528     Features.push_back("+hwdiv");
    529   } else if (HWDiv == "none") {
    530     Features.push_back("-hwdiv-arm");
    531     Features.push_back("-hwdiv");
    532   } else
    533     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
    534 }
    535 
    536 // Handle -mfpu=.
    537 //
    538 // FIXME: Centralize feature selection, defaulting shouldn't be also in the
    539 // frontend target.
    540 static void getARMFPUFeatures(const Driver &D, const Arg *A,
    541                               const ArgList &Args,
    542                               std::vector<const char *> &Features) {
    543   StringRef FPU = A->getValue();
    544 
    545   // Set the target features based on the FPU.
    546   if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
    547     // Disable any default FPU support.
    548     Features.push_back("-vfp2");
    549     Features.push_back("-vfp3");
    550     Features.push_back("-neon");
    551   } else if (FPU == "vfp") {
    552     Features.push_back("+vfp2");
    553     Features.push_back("-neon");
    554   } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
    555     Features.push_back("+vfp3");
    556     Features.push_back("+d16");
    557     Features.push_back("-neon");
    558   } else if (FPU == "vfp3" || FPU == "vfpv3") {
    559     Features.push_back("+vfp3");
    560     Features.push_back("-neon");
    561   } else if (FPU == "vfp4-d16" || FPU == "vfpv4-d16") {
    562     Features.push_back("+vfp4");
    563     Features.push_back("+d16");
    564     Features.push_back("-neon");
    565   } else if (FPU == "vfp4" || FPU == "vfpv4") {
    566     Features.push_back("+vfp4");
    567     Features.push_back("-neon");
    568   } else if (FPU == "fp4-sp-d16" || FPU == "fpv4-sp-d16") {
    569     Features.push_back("+vfp4");
    570     Features.push_back("+d16");
    571     Features.push_back("+fp-only-sp");
    572     Features.push_back("-neon");
    573   } else if (FPU == "fp5-sp-d16" || FPU == "fpv5-sp-d16") {
    574     Features.push_back("+fp-armv8");
    575     Features.push_back("+fp-only-sp");
    576     Features.push_back("+d16");
    577     Features.push_back("-neon");
    578     Features.push_back("-crypto");
    579   } else if (FPU == "fp5-dp-d16" || FPU == "fpv5-dp-d16" ||
    580              FPU == "fp5-d16" || FPU == "fpv5-d16") {
    581     Features.push_back("+fp-armv8");
    582     Features.push_back("+d16");
    583     Features.push_back("-neon");
    584     Features.push_back("-crypto");
    585   } else if (FPU == "fp-armv8") {
    586     Features.push_back("+fp-armv8");
    587     Features.push_back("-neon");
    588     Features.push_back("-crypto");
    589   } else if (FPU == "neon-fp-armv8") {
    590     Features.push_back("+fp-armv8");
    591     Features.push_back("+neon");
    592     Features.push_back("-crypto");
    593   } else if (FPU == "crypto-neon-fp-armv8") {
    594     Features.push_back("+fp-armv8");
    595     Features.push_back("+neon");
    596     Features.push_back("+crypto");
    597   } else if (FPU == "neon") {
    598     Features.push_back("+neon");
    599   } else if (FPU == "neon-vfpv3") {
    600     Features.push_back("+vfp3");
    601     Features.push_back("+neon");
    602   } else if (FPU == "neon-vfpv4") {
    603     Features.push_back("+neon");
    604     Features.push_back("+vfp4");
    605   } else if (FPU == "none") {
    606     Features.push_back("-vfp2");
    607     Features.push_back("-vfp3");
    608     Features.push_back("-vfp4");
    609     Features.push_back("-fp-armv8");
    610     Features.push_back("-crypto");
    611     Features.push_back("-neon");
    612   } else
    613     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
    614 }
    615 
    616 // Select the float ABI as determined by -msoft-float, -mhard-float, and
    617 // -mfloat-abi=.
    618 StringRef tools::arm::getARMFloatABI(const Driver &D, const ArgList &Args,
    619                                      const llvm::Triple &Triple) {
    620   StringRef FloatABI;
    621   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
    622                                options::OPT_mhard_float,
    623                                options::OPT_mfloat_abi_EQ)) {
    624     if (A->getOption().matches(options::OPT_msoft_float))
    625       FloatABI = "soft";
    626     else if (A->getOption().matches(options::OPT_mhard_float))
    627       FloatABI = "hard";
    628     else {
    629       FloatABI = A->getValue();
    630       if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
    631         D.Diag(diag::err_drv_invalid_mfloat_abi)
    632           << A->getAsString(Args);
    633         FloatABI = "soft";
    634       }
    635     }
    636   }
    637 
    638   // If unspecified, choose the default based on the platform.
    639   if (FloatABI.empty()) {
    640     switch (Triple.getOS()) {
    641     case llvm::Triple::Darwin:
    642     case llvm::Triple::MacOSX:
    643     case llvm::Triple::IOS: {
    644       // Darwin defaults to "softfp" for v6 and v7.
    645       //
    646       // FIXME: Factor out an ARM class so we can cache the arch somewhere.
    647       std::string ArchName =
    648         arm::getLLVMArchSuffixForARM(arm::getARMTargetCPU(Args, Triple));
    649       if (StringRef(ArchName).startswith("v6") ||
    650           StringRef(ArchName).startswith("v7"))
    651         FloatABI = "softfp";
    652       else
    653         FloatABI = "soft";
    654       break;
    655     }
    656 
    657     // FIXME: this is invalid for WindowsCE
    658     case llvm::Triple::Win32:
    659       FloatABI = "hard";
    660       break;
    661 
    662     case llvm::Triple::FreeBSD:
    663       switch(Triple.getEnvironment()) {
    664       case llvm::Triple::GNUEABIHF:
    665         FloatABI = "hard";
    666         break;
    667       default:
    668         // FreeBSD defaults to soft float
    669         FloatABI = "soft";
    670         break;
    671       }
    672       break;
    673 
    674     default:
    675       switch(Triple.getEnvironment()) {
    676       case llvm::Triple::GNUEABIHF:
    677         FloatABI = "hard";
    678         break;
    679       case llvm::Triple::GNUEABI:
    680         FloatABI = "softfp";
    681         break;
    682       case llvm::Triple::EABIHF:
    683         FloatABI = "hard";
    684         break;
    685       case llvm::Triple::EABI:
    686         // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
    687         FloatABI = "softfp";
    688         break;
    689       case llvm::Triple::Android: {
    690         std::string ArchName =
    691           arm::getLLVMArchSuffixForARM(arm::getARMTargetCPU(Args, Triple));
    692         if (StringRef(ArchName).startswith("v7"))
    693           FloatABI = "softfp";
    694         else
    695           FloatABI = "soft";
    696         break;
    697       }
    698       default:
    699         // Assume "soft", but warn the user we are guessing.
    700         FloatABI = "soft";
    701         if (Triple.getOS() != llvm::Triple::UnknownOS ||
    702             !Triple.isOSBinFormatMachO())
    703           D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
    704         break;
    705       }
    706     }
    707   }
    708 
    709   return FloatABI;
    710 }
    711 
    712 static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
    713                                  const ArgList &Args,
    714                                  std::vector<const char *> &Features,
    715                                  bool ForAS) {
    716   StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
    717   if (!ForAS) {
    718     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
    719     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
    720     // stripped out by the ARM target. We should probably pass this a new
    721     // -target-option, which is handled by the -cc1/-cc1as invocation.
    722     //
    723     // FIXME2:  For consistency, it would be ideal if we set up the target
    724     // machine state the same when using the frontend or the assembler. We don't
    725     // currently do that for the assembler, we pass the options directly to the
    726     // backend and never even instantiate the frontend TargetInfo. If we did,
    727     // and used its handleTargetFeatures hook, then we could ensure the
    728     // assembler and the frontend behave the same.
    729 
    730     // Use software floating point operations?
    731     if (FloatABI == "soft")
    732       Features.push_back("+soft-float");
    733 
    734     // Use software floating point argument passing?
    735     if (FloatABI != "hard")
    736       Features.push_back("+soft-float-abi");
    737   }
    738 
    739   // Honor -mfpu=.
    740   if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
    741     getARMFPUFeatures(D, A, Args, Features);
    742   if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
    743     getARMHWDivFeatures(D, A, Args, Features);
    744 
    745   // Setting -msoft-float effectively disables NEON because of the GCC
    746   // implementation, although the same isn't true of VFP or VFP3.
    747   if (FloatABI == "soft") {
    748     Features.push_back("-neon");
    749     // Also need to explicitly disable features which imply NEON.
    750     Features.push_back("-crypto");
    751   }
    752 
    753   // En/disable crc code generation.
    754   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
    755     if (A->getOption().matches(options::OPT_mcrc))
    756       Features.push_back("+crc");
    757     else
    758       Features.push_back("-crc");
    759   }
    760 }
    761 
    762 void Clang::AddARMTargetArgs(const ArgList &Args,
    763                              ArgStringList &CmdArgs,
    764                              bool KernelOrKext) const {
    765   const Driver &D = getToolChain().getDriver();
    766   // Get the effective triple, which takes into account the deployment target.
    767   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
    768   llvm::Triple Triple(TripleStr);
    769   std::string CPUName = arm::getARMTargetCPU(Args, Triple);
    770 
    771   // Select the ABI to use.
    772   //
    773   // FIXME: Support -meabi.
    774   // FIXME: Parts of this are duplicated in the backend, unify this somehow.
    775   const char *ABIName = nullptr;
    776   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
    777     ABIName = A->getValue();
    778   } else if (Triple.isOSBinFormatMachO()) {
    779     // The backend is hardwired to assume AAPCS for M-class processors, ensure
    780     // the frontend matches that.
    781     if (Triple.getEnvironment() == llvm::Triple::EABI ||
    782         Triple.getOS() == llvm::Triple::UnknownOS ||
    783         StringRef(CPUName).startswith("cortex-m")) {
    784       ABIName = "aapcs";
    785     } else {
    786       ABIName = "apcs-gnu";
    787     }
    788   } else if (Triple.isOSWindows()) {
    789     // FIXME: this is invalid for WindowsCE
    790     ABIName = "aapcs";
    791   } else {
    792     // Select the default based on the platform.
    793     switch(Triple.getEnvironment()) {
    794     case llvm::Triple::Android:
    795     case llvm::Triple::GNUEABI:
    796     case llvm::Triple::GNUEABIHF:
    797       ABIName = "aapcs-linux";
    798       break;
    799     case llvm::Triple::EABIHF:
    800     case llvm::Triple::EABI:
    801       ABIName = "aapcs";
    802       break;
    803     default:
    804       if (Triple.getOS() == llvm::Triple::NetBSD)
    805         ABIName = "apcs-gnu";
    806       else
    807         ABIName = "aapcs";
    808       break;
    809     }
    810   }
    811   CmdArgs.push_back("-target-abi");
    812   CmdArgs.push_back(ABIName);
    813 
    814   // Determine floating point ABI from the options & target defaults.
    815   StringRef FloatABI = tools::arm::getARMFloatABI(D, Args, Triple);
    816   if (FloatABI == "soft") {
    817     // Floating point operations and argument passing are soft.
    818     //
    819     // FIXME: This changes CPP defines, we need -target-soft-float.
    820     CmdArgs.push_back("-msoft-float");
    821     CmdArgs.push_back("-mfloat-abi");
    822     CmdArgs.push_back("soft");
    823   } else if (FloatABI == "softfp") {
    824     // Floating point operations are hard, but argument passing is soft.
    825     CmdArgs.push_back("-mfloat-abi");
    826     CmdArgs.push_back("soft");
    827   } else {
    828     // Floating point operations and argument passing are hard.
    829     assert(FloatABI == "hard" && "Invalid float abi!");
    830     CmdArgs.push_back("-mfloat-abi");
    831     CmdArgs.push_back("hard");
    832   }
    833 
    834   // Kernel code has more strict alignment requirements.
    835   if (KernelOrKext) {
    836     if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
    837       CmdArgs.push_back("-backend-option");
    838       CmdArgs.push_back("-arm-long-calls");
    839     }
    840 
    841     CmdArgs.push_back("-backend-option");
    842     CmdArgs.push_back("-arm-strict-align");
    843 
    844     // The kext linker doesn't know how to deal with movw/movt.
    845     CmdArgs.push_back("-backend-option");
    846     CmdArgs.push_back("-arm-use-movt=0");
    847   }
    848 
    849   // -mkernel implies -mstrict-align; don't add the redundant option.
    850   if (!KernelOrKext) {
    851     if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
    852                                  options::OPT_munaligned_access)) {
    853       CmdArgs.push_back("-backend-option");
    854       if (A->getOption().matches(options::OPT_mno_unaligned_access))
    855         CmdArgs.push_back("-arm-strict-align");
    856       else {
    857         if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
    858           D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
    859         CmdArgs.push_back("-arm-no-strict-align");
    860       }
    861     }
    862   }
    863 
    864   // Forward the -mglobal-merge option for explicit control over the pass.
    865   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
    866                                options::OPT_mno_global_merge)) {
    867     CmdArgs.push_back("-backend-option");
    868     if (A->getOption().matches(options::OPT_mno_global_merge))
    869       CmdArgs.push_back("-arm-global-merge=false");
    870     else
    871       CmdArgs.push_back("-arm-global-merge=true");
    872   }
    873 
    874   if (!Args.hasFlag(options::OPT_mimplicit_float,
    875                     options::OPT_mno_implicit_float,
    876                     true))
    877     CmdArgs.push_back("-no-implicit-float");
    878 
    879   // llvm does not support reserving registers in general. There is support
    880   // for reserving r9 on ARM though (defined as a platform-specific register
    881   // in ARM EABI).
    882   if (Args.hasArg(options::OPT_ffixed_r9)) {
    883     CmdArgs.push_back("-backend-option");
    884     CmdArgs.push_back("-arm-reserve-r9");
    885   }
    886 }
    887 
    888 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
    889 /// targeting.
    890 static std::string getAArch64TargetCPU(const ArgList &Args) {
    891   Arg *A;
    892   std::string CPU;
    893   // If we have -mtune or -mcpu, use that.
    894   if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
    895     CPU = A->getValue();
    896   } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
    897     StringRef Mcpu = A->getValue();
    898     CPU = Mcpu.split("+").first;
    899   }
    900 
    901   // Handle CPU name is 'native'.
    902   if (CPU == "native")
    903     return llvm::sys::getHostCPUName();
    904   else if (CPU.size())
    905     return CPU;
    906 
    907   // Make sure we pick "cyclone" if -arch is used.
    908   // FIXME: Should this be picked by checking the target triple instead?
    909   if (Args.getLastArg(options::OPT_arch))
    910     return "cyclone";
    911 
    912   return "generic";
    913 }
    914 
    915 void Clang::AddAArch64TargetArgs(const ArgList &Args,
    916                                  ArgStringList &CmdArgs) const {
    917   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
    918   llvm::Triple Triple(TripleStr);
    919 
    920   if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
    921       Args.hasArg(options::OPT_mkernel) ||
    922       Args.hasArg(options::OPT_fapple_kext))
    923     CmdArgs.push_back("-disable-red-zone");
    924 
    925   if (!Args.hasFlag(options::OPT_mimplicit_float,
    926                     options::OPT_mno_implicit_float, true))
    927     CmdArgs.push_back("-no-implicit-float");
    928 
    929   const char *ABIName = nullptr;
    930   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
    931     ABIName = A->getValue();
    932   else if (Triple.isOSDarwin())
    933     ABIName = "darwinpcs";
    934   else
    935     ABIName = "aapcs";
    936 
    937   CmdArgs.push_back("-target-abi");
    938   CmdArgs.push_back(ABIName);
    939 
    940   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
    941                                options::OPT_munaligned_access)) {
    942     CmdArgs.push_back("-backend-option");
    943     if (A->getOption().matches(options::OPT_mno_unaligned_access))
    944       CmdArgs.push_back("-aarch64-strict-align");
    945     else
    946       CmdArgs.push_back("-aarch64-no-strict-align");
    947   }
    948 
    949   if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
    950                                options::OPT_mno_fix_cortex_a53_835769)) {
    951     CmdArgs.push_back("-backend-option");
    952     if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
    953       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
    954     else
    955       CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
    956   } else if (Triple.getEnvironment() == llvm::Triple::Android) {
    957     // Enabled A53 errata (835769) workaround by default on android
    958     CmdArgs.push_back("-backend-option");
    959     CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
    960   }
    961 
    962   // Forward the -mglobal-merge option for explicit control over the pass.
    963   if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
    964                                options::OPT_mno_global_merge)) {
    965     CmdArgs.push_back("-backend-option");
    966     if (A->getOption().matches(options::OPT_mno_global_merge))
    967       CmdArgs.push_back("-aarch64-global-merge=false");
    968     else
    969       CmdArgs.push_back("-aarch64-global-merge=true");
    970   }
    971 
    972   if (Args.hasArg(options::OPT_ffixed_x18)) {
    973     CmdArgs.push_back("-backend-option");
    974     CmdArgs.push_back("-aarch64-reserve-x18");
    975   }
    976 }
    977 
    978 // Get CPU and ABI names. They are not independent
    979 // so we have to calculate them together.
    980 void mips::getMipsCPUAndABI(const ArgList &Args,
    981                             const llvm::Triple &Triple,
    982                             StringRef &CPUName,
    983                             StringRef &ABIName) {
    984   const char *DefMips32CPU = "mips32r2";
    985   const char *DefMips64CPU = "mips64r2";
    986 
    987   // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
    988   // default for mips64(el)?-img-linux-gnu.
    989   if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
    990       Triple.getEnvironment() == llvm::Triple::GNU) {
    991     DefMips32CPU = "mips32r6";
    992     DefMips64CPU = "mips64r6";
    993   }
    994 
    995   // MIPS3 is the default for mips64*-unknown-openbsd.
    996   if (Triple.getOS() == llvm::Triple::OpenBSD)
    997     DefMips64CPU = "mips3";
    998 
    999   if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
   1000                                options::OPT_mcpu_EQ))
   1001     CPUName = A->getValue();
   1002 
   1003   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
   1004     ABIName = A->getValue();
   1005     // Convert a GNU style Mips ABI name to the name
   1006     // accepted by LLVM Mips backend.
   1007     ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
   1008       .Case("32", "o32")
   1009       .Case("64", "n64")
   1010       .Default(ABIName);
   1011   }
   1012 
   1013   // Setup default CPU and ABI names.
   1014   if (CPUName.empty() && ABIName.empty()) {
   1015     switch (Triple.getArch()) {
   1016     default:
   1017       llvm_unreachable("Unexpected triple arch name");
   1018     case llvm::Triple::mips:
   1019     case llvm::Triple::mipsel:
   1020       CPUName = DefMips32CPU;
   1021       break;
   1022     case llvm::Triple::mips64:
   1023     case llvm::Triple::mips64el:
   1024       CPUName = DefMips64CPU;
   1025       break;
   1026     }
   1027   }
   1028 
   1029   if (ABIName.empty()) {
   1030     // Deduce ABI name from the target triple.
   1031     if (Triple.getArch() == llvm::Triple::mips ||
   1032         Triple.getArch() == llvm::Triple::mipsel)
   1033       ABIName = "o32";
   1034     else
   1035       ABIName = "n64";
   1036   }
   1037 
   1038   if (CPUName.empty()) {
   1039     // Deduce CPU name from ABI name.
   1040     CPUName = llvm::StringSwitch<const char *>(ABIName)
   1041       .Cases("o32", "eabi", DefMips32CPU)
   1042       .Cases("n32", "n64", DefMips64CPU)
   1043       .Default("");
   1044   }
   1045 
   1046   // FIXME: Warn on inconsistent use of -march and -mabi.
   1047 }
   1048 
   1049 // Convert ABI name to the GNU tools acceptable variant.
   1050 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
   1051   return llvm::StringSwitch<llvm::StringRef>(ABI)
   1052     .Case("o32", "32")
   1053     .Case("n64", "64")
   1054     .Default(ABI);
   1055 }
   1056 
   1057 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
   1058 // and -mfloat-abi=.
   1059 static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
   1060   StringRef FloatABI;
   1061   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
   1062                                options::OPT_mhard_float,
   1063                                options::OPT_mfloat_abi_EQ)) {
   1064     if (A->getOption().matches(options::OPT_msoft_float))
   1065       FloatABI = "soft";
   1066     else if (A->getOption().matches(options::OPT_mhard_float))
   1067       FloatABI = "hard";
   1068     else {
   1069       FloatABI = A->getValue();
   1070       if (FloatABI != "soft" && FloatABI != "hard") {
   1071         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
   1072         FloatABI = "hard";
   1073       }
   1074     }
   1075   }
   1076 
   1077   // If unspecified, choose the default based on the platform.
   1078   if (FloatABI.empty()) {
   1079     // Assume "hard", because it's a default value used by gcc.
   1080     // When we start to recognize specific target MIPS processors,
   1081     // we will be able to select the default more correctly.
   1082     FloatABI = "hard";
   1083   }
   1084 
   1085   return FloatABI;
   1086 }
   1087 
   1088 static void AddTargetFeature(const ArgList &Args,
   1089                              std::vector<const char *> &Features,
   1090                              OptSpecifier OnOpt, OptSpecifier OffOpt,
   1091                              StringRef FeatureName) {
   1092   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
   1093     if (A->getOption().matches(OnOpt))
   1094       Features.push_back(Args.MakeArgString("+" + FeatureName));
   1095     else
   1096       Features.push_back(Args.MakeArgString("-" + FeatureName));
   1097   }
   1098 }
   1099 
   1100 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
   1101                                   const ArgList &Args,
   1102                                   std::vector<const char *> &Features) {
   1103   StringRef CPUName;
   1104   StringRef ABIName;
   1105   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
   1106   ABIName = getGnuCompatibleMipsABIName(ABIName);
   1107 
   1108   AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
   1109                    options::OPT_mabicalls, "noabicalls");
   1110 
   1111   StringRef FloatABI = getMipsFloatABI(D, Args);
   1112   if (FloatABI == "soft") {
   1113     // FIXME: Note, this is a hack. We need to pass the selected float
   1114     // mode to the MipsTargetInfoBase to define appropriate macros there.
   1115     // Now it is the only method.
   1116     Features.push_back("+soft-float");
   1117   }
   1118 
   1119   if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
   1120     StringRef Val = StringRef(A->getValue());
   1121     if (Val == "2008") {
   1122       if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
   1123         Features.push_back("+nan2008");
   1124       else {
   1125         Features.push_back("-nan2008");
   1126         D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
   1127       }
   1128     } else if (Val == "legacy") {
   1129       if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
   1130         Features.push_back("-nan2008");
   1131       else {
   1132         Features.push_back("+nan2008");
   1133         D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
   1134       }
   1135     } else
   1136       D.Diag(diag::err_drv_unsupported_option_argument)
   1137           << A->getOption().getName() << Val;
   1138   }
   1139 
   1140   AddTargetFeature(Args, Features, options::OPT_msingle_float,
   1141                    options::OPT_mdouble_float, "single-float");
   1142   AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
   1143                    "mips16");
   1144   AddTargetFeature(Args, Features, options::OPT_mmicromips,
   1145                    options::OPT_mno_micromips, "micromips");
   1146   AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
   1147                    "dsp");
   1148   AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
   1149                    "dspr2");
   1150   AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
   1151                    "msa");
   1152 
   1153   // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
   1154   // pass -mfpxx
   1155   if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
   1156                                options::OPT_mfp64)) {
   1157     if (A->getOption().matches(options::OPT_mfp32))
   1158       Features.push_back(Args.MakeArgString("-fp64"));
   1159     else if (A->getOption().matches(options::OPT_mfpxx)) {
   1160       Features.push_back(Args.MakeArgString("+fpxx"));
   1161       Features.push_back(Args.MakeArgString("+nooddspreg"));
   1162     } else
   1163       Features.push_back(Args.MakeArgString("+fp64"));
   1164   } else if (mips::isFPXXDefault(Triple, CPUName, ABIName)) {
   1165     Features.push_back(Args.MakeArgString("+fpxx"));
   1166     Features.push_back(Args.MakeArgString("+nooddspreg"));
   1167   }
   1168 
   1169   AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
   1170                    options::OPT_modd_spreg, "nooddspreg");
   1171 }
   1172 
   1173 void Clang::AddMIPSTargetArgs(const ArgList &Args,
   1174                               ArgStringList &CmdArgs) const {
   1175   const Driver &D = getToolChain().getDriver();
   1176   StringRef CPUName;
   1177   StringRef ABIName;
   1178   const llvm::Triple &Triple = getToolChain().getTriple();
   1179   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
   1180 
   1181   CmdArgs.push_back("-target-abi");
   1182   CmdArgs.push_back(ABIName.data());
   1183 
   1184   StringRef FloatABI = getMipsFloatABI(D, Args);
   1185 
   1186   if (FloatABI == "soft") {
   1187     // Floating point operations and argument passing are soft.
   1188     CmdArgs.push_back("-msoft-float");
   1189     CmdArgs.push_back("-mfloat-abi");
   1190     CmdArgs.push_back("soft");
   1191   }
   1192   else {
   1193     // Floating point operations and argument passing are hard.
   1194     assert(FloatABI == "hard" && "Invalid float abi!");
   1195     CmdArgs.push_back("-mfloat-abi");
   1196     CmdArgs.push_back("hard");
   1197   }
   1198 
   1199   if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
   1200     if (A->getOption().matches(options::OPT_mxgot)) {
   1201       CmdArgs.push_back("-mllvm");
   1202       CmdArgs.push_back("-mxgot");
   1203     }
   1204   }
   1205 
   1206   if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
   1207                                options::OPT_mno_ldc1_sdc1)) {
   1208     if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
   1209       CmdArgs.push_back("-mllvm");
   1210       CmdArgs.push_back("-mno-ldc1-sdc1");
   1211     }
   1212   }
   1213 
   1214   if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
   1215                                options::OPT_mno_check_zero_division)) {
   1216     if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
   1217       CmdArgs.push_back("-mllvm");
   1218       CmdArgs.push_back("-mno-check-zero-division");
   1219     }
   1220   }
   1221 
   1222   if (Arg *A = Args.getLastArg(options::OPT_G)) {
   1223     StringRef v = A->getValue();
   1224     CmdArgs.push_back("-mllvm");
   1225     CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
   1226     A->claim();
   1227   }
   1228 }
   1229 
   1230 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
   1231 static std::string getPPCTargetCPU(const ArgList &Args) {
   1232   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
   1233     StringRef CPUName = A->getValue();
   1234 
   1235     if (CPUName == "native") {
   1236       std::string CPU = llvm::sys::getHostCPUName();
   1237       if (!CPU.empty() && CPU != "generic")
   1238         return CPU;
   1239       else
   1240         return "";
   1241     }
   1242 
   1243     return llvm::StringSwitch<const char *>(CPUName)
   1244       .Case("common", "generic")
   1245       .Case("440", "440")
   1246       .Case("440fp", "440")
   1247       .Case("450", "450")
   1248       .Case("601", "601")
   1249       .Case("602", "602")
   1250       .Case("603", "603")
   1251       .Case("603e", "603e")
   1252       .Case("603ev", "603ev")
   1253       .Case("604", "604")
   1254       .Case("604e", "604e")
   1255       .Case("620", "620")
   1256       .Case("630", "pwr3")
   1257       .Case("G3", "g3")
   1258       .Case("7400", "7400")
   1259       .Case("G4", "g4")
   1260       .Case("7450", "7450")
   1261       .Case("G4+", "g4+")
   1262       .Case("750", "750")
   1263       .Case("970", "970")
   1264       .Case("G5", "g5")
   1265       .Case("a2", "a2")
   1266       .Case("a2q", "a2q")
   1267       .Case("e500mc", "e500mc")
   1268       .Case("e5500", "e5500")
   1269       .Case("power3", "pwr3")
   1270       .Case("power4", "pwr4")
   1271       .Case("power5", "pwr5")
   1272       .Case("power5x", "pwr5x")
   1273       .Case("power6", "pwr6")
   1274       .Case("power6x", "pwr6x")
   1275       .Case("power7", "pwr7")
   1276       .Case("power8", "pwr8")
   1277       .Case("pwr3", "pwr3")
   1278       .Case("pwr4", "pwr4")
   1279       .Case("pwr5", "pwr5")
   1280       .Case("pwr5x", "pwr5x")
   1281       .Case("pwr6", "pwr6")
   1282       .Case("pwr6x", "pwr6x")
   1283       .Case("pwr7", "pwr7")
   1284       .Case("pwr8", "pwr8")
   1285       .Case("powerpc", "ppc")
   1286       .Case("powerpc64", "ppc64")
   1287       .Case("powerpc64le", "ppc64le")
   1288       .Default("");
   1289   }
   1290 
   1291   return "";
   1292 }
   1293 
   1294 static void getPPCTargetFeatures(const ArgList &Args,
   1295                                  std::vector<const char *> &Features) {
   1296   for (arg_iterator it = Args.filtered_begin(options::OPT_m_ppc_Features_Group),
   1297                     ie = Args.filtered_end();
   1298        it != ie; ++it) {
   1299     StringRef Name = (*it)->getOption().getName();
   1300     (*it)->claim();
   1301 
   1302     // Skip over "-m".
   1303     assert(Name.startswith("m") && "Invalid feature name.");
   1304     Name = Name.substr(1);
   1305 
   1306     bool IsNegative = Name.startswith("no-");
   1307     if (IsNegative)
   1308       Name = Name.substr(3);
   1309 
   1310     // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
   1311     // pass the correct option to the backend while calling the frontend
   1312     // option the same.
   1313     // TODO: Change the LLVM backend option maybe?
   1314     if (Name == "mfcrf")
   1315       Name = "mfocrf";
   1316 
   1317     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
   1318   }
   1319 
   1320   // Altivec is a bit weird, allow overriding of the Altivec feature here.
   1321   AddTargetFeature(Args, Features, options::OPT_faltivec,
   1322                    options::OPT_fno_altivec, "altivec");
   1323 }
   1324 
   1325 void Clang::AddPPCTargetArgs(const ArgList &Args,
   1326                              ArgStringList &CmdArgs) const {
   1327   // Select the ABI to use.
   1328   const char *ABIName = nullptr;
   1329   if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
   1330     ABIName = A->getValue();
   1331   } else if (getToolChain().getTriple().isOSLinux())
   1332     switch(getToolChain().getArch()) {
   1333     case llvm::Triple::ppc64: {
   1334       // When targeting a processor that supports QPX, or if QPX is
   1335       // specifically enabled, default to using the ABI that supports QPX (so
   1336       // long as it is not specifically disabled).
   1337       bool HasQPX = false;
   1338       if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
   1339         HasQPX = A->getValue() == StringRef("a2q");
   1340       HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
   1341       if (HasQPX) {
   1342         ABIName = "elfv1-qpx";
   1343         break;
   1344       }
   1345 
   1346       ABIName = "elfv1";
   1347       break;
   1348     }
   1349     case llvm::Triple::ppc64le:
   1350       ABIName = "elfv2";
   1351       break;
   1352     default:
   1353       break;
   1354   }
   1355 
   1356   if (ABIName) {
   1357     CmdArgs.push_back("-target-abi");
   1358     CmdArgs.push_back(ABIName);
   1359   }
   1360 }
   1361 
   1362 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
   1363   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
   1364   return A && (A->getValue() == StringRef(Value));
   1365 }
   1366 
   1367 /// Get the (LLVM) name of the R600 gpu we are targeting.
   1368 static std::string getR600TargetGPU(const ArgList &Args) {
   1369   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
   1370     const char *GPUName = A->getValue();
   1371     return llvm::StringSwitch<const char *>(GPUName)
   1372       .Cases("rv630", "rv635", "r600")
   1373       .Cases("rv610", "rv620", "rs780", "rs880")
   1374       .Case("rv740", "rv770")
   1375       .Case("palm", "cedar")
   1376       .Cases("sumo", "sumo2", "sumo")
   1377       .Case("hemlock", "cypress")
   1378       .Case("aruba", "cayman")
   1379       .Default(GPUName);
   1380   }
   1381   return "";
   1382 }
   1383 
   1384 static void getSparcTargetFeatures(const ArgList &Args,
   1385                                    std::vector<const char *> &Features) {
   1386   bool SoftFloatABI = true;
   1387   if (Arg *A =
   1388           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
   1389     if (A->getOption().matches(options::OPT_mhard_float))
   1390       SoftFloatABI = false;
   1391   }
   1392   if (SoftFloatABI)
   1393     Features.push_back("+soft-float");
   1394 }
   1395 
   1396 void Clang::AddSparcTargetArgs(const ArgList &Args,
   1397                              ArgStringList &CmdArgs) const {
   1398   const Driver &D = getToolChain().getDriver();
   1399 
   1400   // Select the float ABI as determined by -msoft-float and -mhard-float.
   1401   StringRef FloatABI;
   1402   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
   1403                                options::OPT_mhard_float)) {
   1404     if (A->getOption().matches(options::OPT_msoft_float))
   1405       FloatABI = "soft";
   1406     else if (A->getOption().matches(options::OPT_mhard_float))
   1407       FloatABI = "hard";
   1408   }
   1409 
   1410   // If unspecified, choose the default based on the platform.
   1411   if (FloatABI.empty()) {
   1412     // Assume "soft", but warn the user we are guessing.
   1413     FloatABI = "soft";
   1414     D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
   1415   }
   1416 
   1417   if (FloatABI == "soft") {
   1418     // Floating point operations and argument passing are soft.
   1419     //
   1420     // FIXME: This changes CPP defines, we need -target-soft-float.
   1421     CmdArgs.push_back("-msoft-float");
   1422   } else {
   1423     assert(FloatABI == "hard" && "Invalid float abi!");
   1424     CmdArgs.push_back("-mhard-float");
   1425   }
   1426 }
   1427 
   1428 static const char *getSystemZTargetCPU(const ArgList &Args) {
   1429   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
   1430     return A->getValue();
   1431   return "z10";
   1432 }
   1433 
   1434 static void getSystemZTargetFeatures(const ArgList &Args,
   1435                                      std::vector<const char *> &Features) {
   1436   // -m(no-)htm overrides use of the transactional-execution facility.
   1437   if (Arg *A = Args.getLastArg(options::OPT_mhtm,
   1438                                options::OPT_mno_htm)) {
   1439     if (A->getOption().matches(options::OPT_mhtm))
   1440       Features.push_back("+transactional-execution");
   1441     else
   1442       Features.push_back("-transactional-execution");
   1443   }
   1444 }
   1445 
   1446 static const char *getX86TargetCPU(const ArgList &Args,
   1447                                    const llvm::Triple &Triple) {
   1448   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
   1449     if (StringRef(A->getValue()) != "native") {
   1450       if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
   1451         return "core-avx2";
   1452 
   1453       return A->getValue();
   1454     }
   1455 
   1456     // FIXME: Reject attempts to use -march=native unless the target matches
   1457     // the host.
   1458     //
   1459     // FIXME: We should also incorporate the detected target features for use
   1460     // with -native.
   1461     std::string CPU = llvm::sys::getHostCPUName();
   1462     if (!CPU.empty() && CPU != "generic")
   1463       return Args.MakeArgString(CPU);
   1464   }
   1465 
   1466   // Select the default CPU if none was given (or detection failed).
   1467 
   1468   if (Triple.getArch() != llvm::Triple::x86_64 &&
   1469       Triple.getArch() != llvm::Triple::x86)
   1470     return nullptr; // This routine is only handling x86 targets.
   1471 
   1472   bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
   1473 
   1474   // FIXME: Need target hooks.
   1475   if (Triple.isOSDarwin()) {
   1476     if (Triple.getArchName() == "x86_64h")
   1477       return "core-avx2";
   1478     return Is64Bit ? "core2" : "yonah";
   1479   }
   1480 
   1481   // Set up default CPU name for PS4 compilers.
   1482   if (Triple.isPS4CPU())
   1483     return "btver2";
   1484 
   1485   // On Android use targets compatible with gcc
   1486   if (Triple.getEnvironment() == llvm::Triple::Android)
   1487     return Is64Bit ? "x86-64" : "i686";
   1488 
   1489   // Everything else goes to x86-64 in 64-bit mode.
   1490   if (Is64Bit)
   1491     return "x86-64";
   1492 
   1493   switch (Triple.getOS()) {
   1494   case llvm::Triple::FreeBSD:
   1495   case llvm::Triple::NetBSD:
   1496   case llvm::Triple::OpenBSD:
   1497     return "i486";
   1498   case llvm::Triple::Haiku:
   1499     return "i586";
   1500   case llvm::Triple::Bitrig:
   1501     return "i686";
   1502   default:
   1503     // Fallback to p4.
   1504     return "pentium4";
   1505   }
   1506 }
   1507 
   1508 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
   1509   switch(T.getArch()) {
   1510   default:
   1511     return "";
   1512 
   1513   case llvm::Triple::aarch64:
   1514   case llvm::Triple::aarch64_be:
   1515     return getAArch64TargetCPU(Args);
   1516 
   1517   case llvm::Triple::arm:
   1518   case llvm::Triple::armeb:
   1519   case llvm::Triple::thumb:
   1520   case llvm::Triple::thumbeb:
   1521     return arm::getARMTargetCPU(Args, T);
   1522 
   1523   case llvm::Triple::mips:
   1524   case llvm::Triple::mipsel:
   1525   case llvm::Triple::mips64:
   1526   case llvm::Triple::mips64el: {
   1527     StringRef CPUName;
   1528     StringRef ABIName;
   1529     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
   1530     return CPUName;
   1531   }
   1532 
   1533   case llvm::Triple::ppc:
   1534   case llvm::Triple::ppc64:
   1535   case llvm::Triple::ppc64le: {
   1536     std::string TargetCPUName = getPPCTargetCPU(Args);
   1537     // LLVM may default to generating code for the native CPU,
   1538     // but, like gcc, we default to a more generic option for
   1539     // each architecture. (except on Darwin)
   1540     if (TargetCPUName.empty() && !T.isOSDarwin()) {
   1541       if (T.getArch() == llvm::Triple::ppc64)
   1542         TargetCPUName = "ppc64";
   1543       else if (T.getArch() == llvm::Triple::ppc64le)
   1544         TargetCPUName = "ppc64le";
   1545       else
   1546         TargetCPUName = "ppc";
   1547     }
   1548     return TargetCPUName;
   1549   }
   1550 
   1551   case llvm::Triple::sparc:
   1552   case llvm::Triple::sparcv9:
   1553     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
   1554       return A->getValue();
   1555     return "";
   1556 
   1557   case llvm::Triple::x86:
   1558   case llvm::Triple::x86_64:
   1559     return getX86TargetCPU(Args, T);
   1560 
   1561   case llvm::Triple::hexagon:
   1562     return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
   1563 
   1564   case llvm::Triple::systemz:
   1565     return getSystemZTargetCPU(Args);
   1566 
   1567   case llvm::Triple::r600:
   1568   case llvm::Triple::amdgcn:
   1569     return getR600TargetGPU(Args);
   1570   }
   1571 }
   1572 
   1573 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
   1574                           ArgStringList &CmdArgs) {
   1575   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
   1576   // as gold requires -plugin to come before any -plugin-opt that -Wl might
   1577   // forward.
   1578   CmdArgs.push_back("-plugin");
   1579   std::string Plugin = ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
   1580   CmdArgs.push_back(Args.MakeArgString(Plugin));
   1581 
   1582   // Try to pass driver level flags relevant to LTO code generation down to
   1583   // the plugin.
   1584 
   1585   // Handle flags for selecting CPU variants.
   1586   std::string CPU = getCPUName(Args, ToolChain.getTriple());
   1587   if (!CPU.empty())
   1588     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
   1589 }
   1590 
   1591 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
   1592                                  const ArgList &Args,
   1593                                  std::vector<const char *> &Features) {
   1594   // If -march=native, autodetect the feature list.
   1595   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
   1596     if (StringRef(A->getValue()) == "native") {
   1597       llvm::StringMap<bool> HostFeatures;
   1598       if (llvm::sys::getHostCPUFeatures(HostFeatures))
   1599         for (auto &F : HostFeatures)
   1600           Features.push_back(Args.MakeArgString((F.second ? "+" : "-") +
   1601                                                 F.first()));
   1602     }
   1603   }
   1604 
   1605   if (Triple.getArchName() == "x86_64h") {
   1606     // x86_64h implies quite a few of the more modern subtarget features
   1607     // for Haswell class CPUs, but not all of them. Opt-out of a few.
   1608     Features.push_back("-rdrnd");
   1609     Features.push_back("-aes");
   1610     Features.push_back("-pclmul");
   1611     Features.push_back("-rtm");
   1612     Features.push_back("-hle");
   1613     Features.push_back("-fsgsbase");
   1614   }
   1615 
   1616   // Add features to be compatible with gcc for Android.
   1617   if (Triple.getEnvironment() == llvm::Triple::Android) {
   1618     if (Triple.getArch() == llvm::Triple::x86_64) {
   1619       Features.push_back("+sse4.2");
   1620       Features.push_back("+popcnt");
   1621     } else
   1622       Features.push_back("+ssse3");
   1623   }
   1624 
   1625   // Set features according to the -arch flag on MSVC.
   1626   if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
   1627     StringRef Arch = A->getValue();
   1628     bool ArchUsed = false;
   1629     // First, look for flags that are shared in x86 and x86-64.
   1630     if (Triple.getArch() == llvm::Triple::x86_64 ||
   1631         Triple.getArch() == llvm::Triple::x86) {
   1632       if (Arch == "AVX" || Arch == "AVX2") {
   1633         ArchUsed = true;
   1634         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
   1635       }
   1636     }
   1637     // Then, look for x86-specific flags.
   1638     if (Triple.getArch() == llvm::Triple::x86) {
   1639       if (Arch == "IA32") {
   1640         ArchUsed = true;
   1641       } else if (Arch == "SSE" || Arch == "SSE2") {
   1642         ArchUsed = true;
   1643         Features.push_back(Args.MakeArgString("+" + Arch.lower()));
   1644       }
   1645     }
   1646     if (!ArchUsed)
   1647       D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
   1648   }
   1649 
   1650   // Now add any that the user explicitly requested on the command line,
   1651   // which may override the defaults.
   1652   for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
   1653                     ie = Args.filtered_end();
   1654        it != ie; ++it) {
   1655     StringRef Name = (*it)->getOption().getName();
   1656     (*it)->claim();
   1657 
   1658     // Skip over "-m".
   1659     assert(Name.startswith("m") && "Invalid feature name.");
   1660     Name = Name.substr(1);
   1661 
   1662     bool IsNegative = Name.startswith("no-");
   1663     if (IsNegative)
   1664       Name = Name.substr(3);
   1665 
   1666     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
   1667   }
   1668 }
   1669 
   1670 void Clang::AddX86TargetArgs(const ArgList &Args,
   1671                              ArgStringList &CmdArgs) const {
   1672   if (!Args.hasFlag(options::OPT_mred_zone,
   1673                     options::OPT_mno_red_zone,
   1674                     true) ||
   1675       Args.hasArg(options::OPT_mkernel) ||
   1676       Args.hasArg(options::OPT_fapple_kext))
   1677     CmdArgs.push_back("-disable-red-zone");
   1678 
   1679   // Default to avoid implicit floating-point for kernel/kext code, but allow
   1680   // that to be overridden with -mno-soft-float.
   1681   bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
   1682                           Args.hasArg(options::OPT_fapple_kext));
   1683   if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
   1684                                options::OPT_mno_soft_float,
   1685                                options::OPT_mimplicit_float,
   1686                                options::OPT_mno_implicit_float)) {
   1687     const Option &O = A->getOption();
   1688     NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
   1689                        O.matches(options::OPT_msoft_float));
   1690   }
   1691   if (NoImplicitFloat)
   1692     CmdArgs.push_back("-no-implicit-float");
   1693 
   1694   if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
   1695     StringRef Value = A->getValue();
   1696     if (Value == "intel" || Value == "att") {
   1697       CmdArgs.push_back("-mllvm");
   1698       CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
   1699     } else {
   1700       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
   1701           << A->getOption().getName() << Value;
   1702     }
   1703   }
   1704 }
   1705 
   1706 static inline bool HasPICArg(const ArgList &Args) {
   1707   return Args.hasArg(options::OPT_fPIC)
   1708     || Args.hasArg(options::OPT_fpic);
   1709 }
   1710 
   1711 static Arg *GetLastSmallDataThresholdArg(const ArgList &Args) {
   1712   return Args.getLastArg(options::OPT_G,
   1713                          options::OPT_G_EQ,
   1714                          options::OPT_msmall_data_threshold_EQ);
   1715 }
   1716 
   1717 static std::string GetHexagonSmallDataThresholdValue(const ArgList &Args) {
   1718   std::string value;
   1719   if (HasPICArg(Args))
   1720     value = "0";
   1721   else if (Arg *A = GetLastSmallDataThresholdArg(Args)) {
   1722     value = A->getValue();
   1723     A->claim();
   1724   }
   1725   return value;
   1726 }
   1727 
   1728 void Clang::AddHexagonTargetArgs(const ArgList &Args,
   1729                                  ArgStringList &CmdArgs) const {
   1730   CmdArgs.push_back("-fno-signed-char");
   1731   CmdArgs.push_back("-mqdsp6-compat");
   1732   CmdArgs.push_back("-Wreturn-type");
   1733 
   1734   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
   1735   if (!SmallDataThreshold.empty()) {
   1736     CmdArgs.push_back ("-mllvm");
   1737     CmdArgs.push_back(Args.MakeArgString(
   1738                         "-hexagon-small-data-threshold=" + SmallDataThreshold));
   1739   }
   1740 
   1741   if (!Args.hasArg(options::OPT_fno_short_enums))
   1742     CmdArgs.push_back("-fshort-enums");
   1743   if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
   1744     CmdArgs.push_back ("-mllvm");
   1745     CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
   1746   }
   1747   CmdArgs.push_back ("-mllvm");
   1748   CmdArgs.push_back ("-machine-sink-split=0");
   1749 }
   1750 
   1751 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
   1752 static bool DecodeAArch64Features(const Driver &D, StringRef text,
   1753                                   std::vector<const char *> &Features) {
   1754   SmallVector<StringRef, 8> Split;
   1755   text.split(Split, StringRef("+"), -1, false);
   1756 
   1757   for (unsigned I = 0, E = Split.size(); I != E; ++I) {
   1758     const char *result = llvm::StringSwitch<const char *>(Split[I])
   1759                              .Case("fp", "+fp-armv8")
   1760                              .Case("simd", "+neon")
   1761                              .Case("crc", "+crc")
   1762                              .Case("crypto", "+crypto")
   1763                              .Case("nofp", "-fp-armv8")
   1764                              .Case("nosimd", "-neon")
   1765                              .Case("nocrc", "-crc")
   1766                              .Case("nocrypto", "-crypto")
   1767                              .Default(nullptr);
   1768     if (result)
   1769       Features.push_back(result);
   1770     else if (Split[I] == "neon" || Split[I] == "noneon")
   1771       D.Diag(diag::err_drv_no_neon_modifier);
   1772     else
   1773       return false;
   1774   }
   1775   return true;
   1776 }
   1777 
   1778 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
   1779 // decode CPU and feature.
   1780 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
   1781                               std::vector<const char *> &Features) {
   1782   std::pair<StringRef, StringRef> Split = Mcpu.split("+");
   1783   CPU = Split.first;
   1784   if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" || CPU == "cortex-a72") {
   1785     Features.push_back("+neon");
   1786     Features.push_back("+crc");
   1787     Features.push_back("+crypto");
   1788   } else if (CPU == "generic") {
   1789     Features.push_back("+neon");
   1790   } else {
   1791     return false;
   1792   }
   1793 
   1794   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
   1795     return false;
   1796 
   1797   return true;
   1798 }
   1799 
   1800 static bool
   1801 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
   1802                                 const ArgList &Args,
   1803                                 std::vector<const char *> &Features) {
   1804   std::pair<StringRef, StringRef> Split = March.split("+");
   1805 
   1806   if (Split.first == "armv8-a" ||
   1807       Split.first == "armv8a") {
   1808     // ok, no additional features.
   1809   } else if (
   1810       Split.first == "armv8.1-a" ||
   1811       Split.first == "armv8.1a" ) {
   1812     Features.push_back("+v8.1a");
   1813   } else {
   1814     return false;
   1815   }
   1816 
   1817   if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
   1818     return false;
   1819 
   1820   return true;
   1821 }
   1822 
   1823 static bool
   1824 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
   1825                                const ArgList &Args,
   1826                                std::vector<const char *> &Features) {
   1827   StringRef CPU;
   1828   if (!DecodeAArch64Mcpu(D, Mcpu, CPU, Features))
   1829     return false;
   1830 
   1831   return true;
   1832 }
   1833 
   1834 static bool
   1835 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
   1836                                      const ArgList &Args,
   1837                                      std::vector<const char *> &Features) {
   1838   // Handle CPU name is 'native'.
   1839   if (Mtune == "native")
   1840     Mtune = llvm::sys::getHostCPUName();
   1841   if (Mtune == "cyclone") {
   1842     Features.push_back("+zcm");
   1843     Features.push_back("+zcz");
   1844   }
   1845   return true;
   1846 }
   1847 
   1848 static bool
   1849 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
   1850                                     const ArgList &Args,
   1851                                     std::vector<const char *> &Features) {
   1852   StringRef CPU;
   1853   std::vector<const char *> DecodedFeature;
   1854   if (!DecodeAArch64Mcpu(D, Mcpu, CPU, DecodedFeature))
   1855     return false;
   1856 
   1857   return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
   1858 }
   1859 
   1860 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
   1861                                      std::vector<const char *> &Features) {
   1862   Arg *A;
   1863   bool success = true;
   1864   // Enable NEON by default.
   1865   Features.push_back("+neon");
   1866   if ((A = Args.getLastArg(options::OPT_march_EQ)))
   1867     success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
   1868   else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
   1869     success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
   1870   else if (Args.hasArg(options::OPT_arch))
   1871     success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
   1872                                              Features);
   1873 
   1874   if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
   1875     success =
   1876         getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
   1877   else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
   1878     success =
   1879         getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
   1880   else if (Args.hasArg(options::OPT_arch))
   1881     success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
   1882                                                   Args, Features);
   1883 
   1884   if (!success)
   1885     D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
   1886 
   1887   if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
   1888     Features.push_back("-fp-armv8");
   1889     Features.push_back("-crypto");
   1890     Features.push_back("-neon");
   1891   }
   1892 
   1893   // En/disable crc
   1894   if (Arg *A = Args.getLastArg(options::OPT_mcrc,
   1895                                options::OPT_mnocrc)) {
   1896     if (A->getOption().matches(options::OPT_mcrc))
   1897       Features.push_back("+crc");
   1898     else
   1899       Features.push_back("-crc");
   1900   }
   1901 }
   1902 
   1903 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
   1904                               const ArgList &Args, ArgStringList &CmdArgs,
   1905                               bool ForAS) {
   1906   std::vector<const char *> Features;
   1907   switch (Triple.getArch()) {
   1908   default:
   1909     break;
   1910   case llvm::Triple::mips:
   1911   case llvm::Triple::mipsel:
   1912   case llvm::Triple::mips64:
   1913   case llvm::Triple::mips64el:
   1914     getMIPSTargetFeatures(D, Triple, Args, Features);
   1915     break;
   1916 
   1917   case llvm::Triple::arm:
   1918   case llvm::Triple::armeb:
   1919   case llvm::Triple::thumb:
   1920   case llvm::Triple::thumbeb:
   1921     getARMTargetFeatures(D, Triple, Args, Features, ForAS);
   1922     break;
   1923 
   1924   case llvm::Triple::ppc:
   1925   case llvm::Triple::ppc64:
   1926   case llvm::Triple::ppc64le:
   1927     getPPCTargetFeatures(Args, Features);
   1928     break;
   1929   case llvm::Triple::sparc:
   1930   case llvm::Triple::sparcv9:
   1931     getSparcTargetFeatures(Args, Features);
   1932     break;
   1933   case llvm::Triple::systemz:
   1934     getSystemZTargetFeatures(Args, Features);
   1935     break;
   1936   case llvm::Triple::aarch64:
   1937   case llvm::Triple::aarch64_be:
   1938     getAArch64TargetFeatures(D, Args, Features);
   1939     break;
   1940   case llvm::Triple::x86:
   1941   case llvm::Triple::x86_64:
   1942     getX86TargetFeatures(D, Triple, Args, Features);
   1943     break;
   1944   }
   1945 
   1946   // Find the last of each feature.
   1947   llvm::StringMap<unsigned> LastOpt;
   1948   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
   1949     const char *Name = Features[I];
   1950     assert(Name[0] == '-' || Name[0] == '+');
   1951     LastOpt[Name + 1] = I;
   1952   }
   1953 
   1954   for (unsigned I = 0, N = Features.size(); I < N; ++I) {
   1955     // If this feature was overridden, ignore it.
   1956     const char *Name = Features[I];
   1957     llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
   1958     assert(LastI != LastOpt.end());
   1959     unsigned Last = LastI->second;
   1960     if (Last != I)
   1961       continue;
   1962 
   1963     CmdArgs.push_back("-target-feature");
   1964     CmdArgs.push_back(Name);
   1965   }
   1966 }
   1967 
   1968 static bool
   1969 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
   1970                                           const llvm::Triple &Triple) {
   1971   // We use the zero-cost exception tables for Objective-C if the non-fragile
   1972   // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
   1973   // later.
   1974   if (runtime.isNonFragile())
   1975     return true;
   1976 
   1977   if (!Triple.isMacOSX())
   1978     return false;
   1979 
   1980   return (!Triple.isMacOSXVersionLT(10,5) &&
   1981           (Triple.getArch() == llvm::Triple::x86_64 ||
   1982            Triple.getArch() == llvm::Triple::arm));
   1983 }
   1984 
   1985 // exceptionSettings() exists to share the logic between -cc1 and linker
   1986 // invocations.
   1987 static bool exceptionSettings(const ArgList &Args, const llvm::Triple &Triple) {
   1988   if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
   1989                                options::OPT_fno_exceptions))
   1990     if (A->getOption().matches(options::OPT_fexceptions))
   1991       return true;
   1992 
   1993   return false;
   1994 }
   1995 
   1996 /// Adds exception related arguments to the driver command arguments. There's a
   1997 /// master flag, -fexceptions and also language specific flags to enable/disable
   1998 /// C++ and Objective-C exceptions. This makes it possible to for example
   1999 /// disable C++ exceptions but enable Objective-C exceptions.
   2000 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
   2001                              const ToolChain &TC, bool KernelOrKext,
   2002                              const ObjCRuntime &objcRuntime,
   2003                              ArgStringList &CmdArgs) {
   2004   const Driver &D = TC.getDriver();
   2005   const llvm::Triple &Triple = TC.getTriple();
   2006 
   2007   if (KernelOrKext) {
   2008     // -mkernel and -fapple-kext imply no exceptions, so claim exception related
   2009     // arguments now to avoid warnings about unused arguments.
   2010     Args.ClaimAllArgs(options::OPT_fexceptions);
   2011     Args.ClaimAllArgs(options::OPT_fno_exceptions);
   2012     Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
   2013     Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
   2014     Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
   2015     Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
   2016     return;
   2017   }
   2018 
   2019   // Gather the exception settings from the command line arguments.
   2020   bool EH = exceptionSettings(Args, Triple);
   2021 
   2022   // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
   2023   // is not necessarily sensible, but follows GCC.
   2024   if (types::isObjC(InputType) &&
   2025       Args.hasFlag(options::OPT_fobjc_exceptions,
   2026                    options::OPT_fno_objc_exceptions,
   2027                    true)) {
   2028     CmdArgs.push_back("-fobjc-exceptions");
   2029 
   2030     EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
   2031   }
   2032 
   2033   if (types::isCXX(InputType)) {
   2034     bool CXXExceptionsEnabled =
   2035         Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
   2036     Arg *ExceptionArg = Args.getLastArg(
   2037         options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
   2038         options::OPT_fexceptions, options::OPT_fno_exceptions);
   2039     if (ExceptionArg)
   2040       CXXExceptionsEnabled =
   2041           ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
   2042           ExceptionArg->getOption().matches(options::OPT_fexceptions);
   2043 
   2044     if (CXXExceptionsEnabled) {
   2045       if (Triple.isPS4CPU()) {
   2046         ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
   2047         assert(ExceptionArg &&
   2048                "On the PS4 exceptions should only be enabled if passing "
   2049                "an argument");
   2050         if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
   2051           const Arg *RTTIArg = TC.getRTTIArg();
   2052           assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
   2053           D.Diag(diag::err_drv_argument_not_allowed_with)
   2054               << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
   2055         } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
   2056           D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
   2057       } else
   2058         assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
   2059 
   2060       CmdArgs.push_back("-fcxx-exceptions");
   2061 
   2062       EH = true;
   2063     }
   2064   }
   2065 
   2066   if (EH)
   2067     CmdArgs.push_back("-fexceptions");
   2068 }
   2069 
   2070 static bool ShouldDisableAutolink(const ArgList &Args,
   2071                              const ToolChain &TC) {
   2072   bool Default = true;
   2073   if (TC.getTriple().isOSDarwin()) {
   2074     // The native darwin assembler doesn't support the linker_option directives,
   2075     // so we disable them if we think the .s file will be passed to it.
   2076     Default = TC.useIntegratedAs();
   2077   }
   2078   return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
   2079                        Default);
   2080 }
   2081 
   2082 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
   2083                                         const ToolChain &TC) {
   2084   bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
   2085                                         options::OPT_fno_dwarf_directory_asm,
   2086                                         TC.useIntegratedAs());
   2087   return !UseDwarfDirectory;
   2088 }
   2089 
   2090 /// \brief Check whether the given input tree contains any compilation actions.
   2091 static bool ContainsCompileAction(const Action *A) {
   2092   if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
   2093     return true;
   2094 
   2095   for (const auto &Act : *A)
   2096     if (ContainsCompileAction(Act))
   2097       return true;
   2098 
   2099   return false;
   2100 }
   2101 
   2102 /// \brief Check if -relax-all should be passed to the internal assembler.
   2103 /// This is done by default when compiling non-assembler source with -O0.
   2104 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
   2105   bool RelaxDefault = true;
   2106 
   2107   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
   2108     RelaxDefault = A->getOption().matches(options::OPT_O0);
   2109 
   2110   if (RelaxDefault) {
   2111     RelaxDefault = false;
   2112     for (const auto &Act : C.getActions()) {
   2113       if (ContainsCompileAction(Act)) {
   2114         RelaxDefault = true;
   2115         break;
   2116       }
   2117     }
   2118   }
   2119 
   2120   return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
   2121     RelaxDefault);
   2122 }
   2123 
   2124 static void CollectArgsForIntegratedAssembler(Compilation &C,
   2125                                               const ArgList &Args,
   2126                                               ArgStringList &CmdArgs,
   2127                                               const Driver &D) {
   2128     if (UseRelaxAll(C, Args))
   2129       CmdArgs.push_back("-mrelax-all");
   2130 
   2131     // When passing -I arguments to the assembler we sometimes need to
   2132     // unconditionally take the next argument.  For example, when parsing
   2133     // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
   2134     // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
   2135     // arg after parsing the '-I' arg.
   2136     bool TakeNextArg = false;
   2137 
   2138     // When using an integrated assembler, translate -Wa, and -Xassembler
   2139     // options.
   2140     bool CompressDebugSections = false;
   2141     for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
   2142                                                options::OPT_Xassembler),
   2143            ie = Args.filtered_end(); it != ie; ++it) {
   2144       const Arg *A = *it;
   2145       A->claim();
   2146 
   2147       for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
   2148         StringRef Value = A->getValue(i);
   2149         if (TakeNextArg) {
   2150           CmdArgs.push_back(Value.data());
   2151           TakeNextArg = false;
   2152           continue;
   2153         }
   2154 
   2155         if (Value == "-force_cpusubtype_ALL") {
   2156           // Do nothing, this is the default and we don't support anything else.
   2157         } else if (Value == "-L") {
   2158           CmdArgs.push_back("-msave-temp-labels");
   2159         } else if (Value == "--fatal-warnings") {
   2160           CmdArgs.push_back("-massembler-fatal-warnings");
   2161         } else if (Value == "--noexecstack") {
   2162           CmdArgs.push_back("-mnoexecstack");
   2163         } else if (Value == "-compress-debug-sections" ||
   2164                    Value == "--compress-debug-sections") {
   2165           CompressDebugSections = true;
   2166         } else if (Value == "-nocompress-debug-sections" ||
   2167                    Value == "--nocompress-debug-sections") {
   2168           CompressDebugSections = false;
   2169         } else if (Value.startswith("-I")) {
   2170           CmdArgs.push_back(Value.data());
   2171           // We need to consume the next argument if the current arg is a plain
   2172           // -I. The next arg will be the include directory.
   2173           if (Value == "-I")
   2174             TakeNextArg = true;
   2175         } else if (Value.startswith("-gdwarf-")) {
   2176           CmdArgs.push_back(Value.data());
   2177         } else {
   2178           D.Diag(diag::err_drv_unsupported_option_argument)
   2179             << A->getOption().getName() << Value;
   2180         }
   2181       }
   2182     }
   2183     if (CompressDebugSections) {
   2184       if (llvm::zlib::isAvailable())
   2185         CmdArgs.push_back("-compress-debug-sections");
   2186       else
   2187         D.Diag(diag::warn_debug_compression_unavailable);
   2188     }
   2189 }
   2190 
   2191 // Until ARM libraries are build separately, we have them all in one library
   2192 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC) {
   2193   // FIXME: handle 64-bit
   2194   if (TC.getTriple().isOSWindows() &&
   2195       !TC.getTriple().isWindowsItaniumEnvironment())
   2196     return "i386";
   2197   if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
   2198     return "arm";
   2199   return TC.getArchName();
   2200 }
   2201 
   2202 static SmallString<128> getCompilerRTLibDir(const ToolChain &TC) {
   2203   // The runtimes are located in the OS-specific resource directory.
   2204   SmallString<128> Res(TC.getDriver().ResourceDir);
   2205   const llvm::Triple &Triple = TC.getTriple();
   2206   // TC.getOS() yield "freebsd10.0" whereas "freebsd" is expected.
   2207   StringRef OSLibName =
   2208       (Triple.getOS() == llvm::Triple::FreeBSD) ? "freebsd" : TC.getOS();
   2209   llvm::sys::path::append(Res, "lib", OSLibName);
   2210   return Res;
   2211 }
   2212 
   2213 static SmallString<128> getCompilerRT(const ToolChain &TC, StringRef Component,
   2214                                       bool Shared = false) {
   2215   const char *Env = TC.getTriple().getEnvironment() == llvm::Triple::Android
   2216                         ? "-android"
   2217                         : "";
   2218 
   2219   bool IsOSWindows = TC.getTriple().isOSWindows();
   2220   StringRef Arch = getArchNameForCompilerRTLib(TC);
   2221   const char *Prefix = IsOSWindows ? "" : "lib";
   2222   const char *Suffix =
   2223       Shared ? (IsOSWindows ? ".dll" : ".so") : (IsOSWindows ? ".lib" : ".a");
   2224 
   2225   SmallString<128> Path = getCompilerRTLibDir(TC);
   2226   llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
   2227                                     Arch + Env + Suffix);
   2228 
   2229   return Path;
   2230 }
   2231 
   2232 // This adds the static libclang_rt.builtins-arch.a directly to the command line
   2233 // FIXME: Make sure we can also emit shared objects if they're requested
   2234 // and available, check for possible errors, etc.
   2235 static void addClangRT(const ToolChain &TC, const ArgList &Args,
   2236                        ArgStringList &CmdArgs) {
   2237   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "builtins")));
   2238 
   2239   if (!TC.getTriple().isOSWindows()) {
   2240     // FIXME: why do we link against gcc when we are using compiler-rt?
   2241     CmdArgs.push_back("-lgcc_s");
   2242     if (TC.getDriver().CCCIsCXX())
   2243       CmdArgs.push_back("-lgcc_eh");
   2244   }
   2245 }
   2246 
   2247 static void addProfileRT(const ToolChain &TC, const ArgList &Args,
   2248                          ArgStringList &CmdArgs) {
   2249   if (!(Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
   2250                      false) ||
   2251         Args.hasArg(options::OPT_fprofile_generate) ||
   2252         Args.hasArg(options::OPT_fprofile_instr_generate) ||
   2253         Args.hasArg(options::OPT_fcreate_profile) ||
   2254         Args.hasArg(options::OPT_coverage)))
   2255     return;
   2256 
   2257   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "profile")));
   2258 }
   2259 
   2260 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
   2261                                 ArgStringList &CmdArgs, StringRef Sanitizer,
   2262                                 bool IsShared) {
   2263   // Static runtimes must be forced into executable, so we wrap them in
   2264   // whole-archive.
   2265   if (!IsShared)
   2266     CmdArgs.push_back("-whole-archive");
   2267   CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Sanitizer, IsShared)));
   2268   if (!IsShared)
   2269     CmdArgs.push_back("-no-whole-archive");
   2270 }
   2271 
   2272 // Tries to use a file with the list of dynamic symbols that need to be exported
   2273 // from the runtime library. Returns true if the file was found.
   2274 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
   2275                                     ArgStringList &CmdArgs,
   2276                                     StringRef Sanitizer) {
   2277   SmallString<128> SanRT = getCompilerRT(TC, Sanitizer);
   2278   if (llvm::sys::fs::exists(SanRT + ".syms")) {
   2279     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
   2280     return true;
   2281   }
   2282   return false;
   2283 }
   2284 
   2285 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
   2286                                      ArgStringList &CmdArgs) {
   2287   // Force linking against the system libraries sanitizers depends on
   2288   // (see PR15823 why this is necessary).
   2289   CmdArgs.push_back("--no-as-needed");
   2290   CmdArgs.push_back("-lpthread");
   2291   CmdArgs.push_back("-lrt");
   2292   CmdArgs.push_back("-lm");
   2293   // There's no libdl on FreeBSD.
   2294   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
   2295     CmdArgs.push_back("-ldl");
   2296 }
   2297 
   2298 static void
   2299 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
   2300                          SmallVectorImpl<StringRef> &SharedRuntimes,
   2301                          SmallVectorImpl<StringRef> &StaticRuntimes,
   2302                          SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
   2303   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
   2304   // Collect shared runtimes.
   2305   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
   2306     SharedRuntimes.push_back("asan");
   2307   }
   2308 
   2309   // Collect static runtimes.
   2310   if (Args.hasArg(options::OPT_shared) ||
   2311       (TC.getTriple().getEnvironment() == llvm::Triple::Android)) {
   2312     // Don't link static runtimes into DSOs or if compiling for Android.
   2313     return;
   2314   }
   2315   if (SanArgs.needsAsanRt()) {
   2316     if (SanArgs.needsSharedAsanRt()) {
   2317       HelperStaticRuntimes.push_back("asan-preinit");
   2318     } else {
   2319       StaticRuntimes.push_back("asan");
   2320       if (SanArgs.linkCXXRuntimes())
   2321         StaticRuntimes.push_back("asan_cxx");
   2322     }
   2323   }
   2324   if (SanArgs.needsDfsanRt())
   2325     StaticRuntimes.push_back("dfsan");
   2326   if (SanArgs.needsLsanRt())
   2327     StaticRuntimes.push_back("lsan");
   2328   if (SanArgs.needsMsanRt())
   2329     StaticRuntimes.push_back("msan");
   2330   if (SanArgs.needsTsanRt())
   2331     StaticRuntimes.push_back("tsan");
   2332   if (SanArgs.needsUbsanRt()) {
   2333     StaticRuntimes.push_back("ubsan_standalone");
   2334     if (SanArgs.linkCXXRuntimes())
   2335       StaticRuntimes.push_back("ubsan_standalone_cxx");
   2336   }
   2337 }
   2338 
   2339 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
   2340 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
   2341 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
   2342                                  ArgStringList &CmdArgs) {
   2343   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
   2344       HelperStaticRuntimes;
   2345   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
   2346                            HelperStaticRuntimes);
   2347   for (auto RT : SharedRuntimes)
   2348     addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
   2349   for (auto RT : HelperStaticRuntimes)
   2350     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
   2351   bool AddExportDynamic = false;
   2352   for (auto RT : StaticRuntimes) {
   2353     addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
   2354     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
   2355   }
   2356   // If there is a static runtime with no dynamic list, force all the symbols
   2357   // to be dynamic to be sure we export sanitizer interface functions.
   2358   if (AddExportDynamic)
   2359     CmdArgs.push_back("-export-dynamic");
   2360   return !StaticRuntimes.empty();
   2361 }
   2362 
   2363 static bool areOptimizationsEnabled(const ArgList &Args) {
   2364   // Find the last -O arg and see if it is non-zero.
   2365   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
   2366     return !A->getOption().matches(options::OPT_O0);
   2367   // Defaults to -O0.
   2368   return false;
   2369 }
   2370 
   2371 static bool shouldUseFramePointerForTarget(const ArgList &Args,
   2372                                            const llvm::Triple &Triple) {
   2373   // XCore never wants frame pointers, regardless of OS.
   2374   if (Triple.getArch() == llvm::Triple::xcore) {
   2375     return false;
   2376   }
   2377 
   2378   if (Triple.isOSLinux()) {
   2379     switch (Triple.getArch()) {
   2380     // Don't use a frame pointer on linux if optimizing for certain targets.
   2381     case llvm::Triple::mips64:
   2382     case llvm::Triple::mips64el:
   2383     case llvm::Triple::mips:
   2384     case llvm::Triple::mipsel:
   2385     case llvm::Triple::systemz:
   2386     case llvm::Triple::x86:
   2387     case llvm::Triple::x86_64:
   2388       return !areOptimizationsEnabled(Args);
   2389     default:
   2390       return true;
   2391     }
   2392   }
   2393 
   2394   if (Triple.isOSWindows()) {
   2395     switch (Triple.getArch()) {
   2396     case llvm::Triple::x86:
   2397       return !areOptimizationsEnabled(Args);
   2398     default:
   2399       // All other supported Windows ISAs use xdata unwind information, so frame
   2400       // pointers are not generally useful.
   2401       return false;
   2402     }
   2403   }
   2404 
   2405   return true;
   2406 }
   2407 
   2408 static bool shouldUseFramePointer(const ArgList &Args,
   2409                                   const llvm::Triple &Triple) {
   2410   if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
   2411                                options::OPT_fomit_frame_pointer))
   2412     return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
   2413 
   2414   return shouldUseFramePointerForTarget(Args, Triple);
   2415 }
   2416 
   2417 static bool shouldUseLeafFramePointer(const ArgList &Args,
   2418                                       const llvm::Triple &Triple) {
   2419   if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
   2420                                options::OPT_momit_leaf_frame_pointer))
   2421     return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
   2422 
   2423   if (Triple.isPS4CPU())
   2424     return false;
   2425 
   2426   return shouldUseFramePointerForTarget(Args, Triple);
   2427 }
   2428 
   2429 /// Add a CC1 option to specify the debug compilation directory.
   2430 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
   2431   SmallString<128> cwd;
   2432   if (!llvm::sys::fs::current_path(cwd)) {
   2433     CmdArgs.push_back("-fdebug-compilation-dir");
   2434     CmdArgs.push_back(Args.MakeArgString(cwd));
   2435   }
   2436 }
   2437 
   2438 static const char *SplitDebugName(const ArgList &Args,
   2439                                   const InputInfoList &Inputs) {
   2440   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
   2441   if (FinalOutput && Args.hasArg(options::OPT_c)) {
   2442     SmallString<128> T(FinalOutput->getValue());
   2443     llvm::sys::path::replace_extension(T, "dwo");
   2444     return Args.MakeArgString(T);
   2445   } else {
   2446     // Use the compilation dir.
   2447     SmallString<128> T(
   2448         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
   2449     SmallString<128> F(llvm::sys::path::stem(Inputs[0].getBaseInput()));
   2450     llvm::sys::path::replace_extension(F, "dwo");
   2451     T += F;
   2452     return Args.MakeArgString(F);
   2453   }
   2454 }
   2455 
   2456 static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
   2457                            const Tool &T, const JobAction &JA,
   2458                            const ArgList &Args, const InputInfo &Output,
   2459                            const char *OutFile) {
   2460   ArgStringList ExtractArgs;
   2461   ExtractArgs.push_back("--extract-dwo");
   2462 
   2463   ArgStringList StripArgs;
   2464   StripArgs.push_back("--strip-dwo");
   2465 
   2466   // Grabbing the output of the earlier compile step.
   2467   StripArgs.push_back(Output.getFilename());
   2468   ExtractArgs.push_back(Output.getFilename());
   2469   ExtractArgs.push_back(OutFile);
   2470 
   2471   const char *Exec =
   2472     Args.MakeArgString(TC.GetProgramPath("objcopy"));
   2473 
   2474   // First extract the dwo sections.
   2475   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs));
   2476 
   2477   // Then remove them from the original .o file.
   2478   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs));
   2479 }
   2480 
   2481 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
   2482 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
   2483 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
   2484   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
   2485     if (A->getOption().matches(options::OPT_O4) ||
   2486         A->getOption().matches(options::OPT_Ofast))
   2487       return true;
   2488 
   2489     if (A->getOption().matches(options::OPT_O0))
   2490       return false;
   2491 
   2492     assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
   2493 
   2494     // Vectorize -Os.
   2495     StringRef S(A->getValue());
   2496     if (S == "s")
   2497       return true;
   2498 
   2499     // Don't vectorize -Oz, unless it's the slp vectorizer.
   2500     if (S == "z")
   2501       return isSlpVec;
   2502 
   2503     unsigned OptLevel = 0;
   2504     if (S.getAsInteger(10, OptLevel))
   2505       return false;
   2506 
   2507     return OptLevel > 1;
   2508   }
   2509 
   2510   return false;
   2511 }
   2512 
   2513 /// Add -x lang to \p CmdArgs for \p Input.
   2514 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
   2515                              ArgStringList &CmdArgs) {
   2516   // When using -verify-pch, we don't want to provide the type
   2517   // 'precompiled-header' if it was inferred from the file extension
   2518   if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
   2519     return;
   2520 
   2521   CmdArgs.push_back("-x");
   2522   if (Args.hasArg(options::OPT_rewrite_objc))
   2523     CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
   2524   else
   2525     CmdArgs.push_back(types::getTypeName(Input.getType()));
   2526 }
   2527 
   2528 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
   2529   if (Version < 100)
   2530     return VersionTuple(Version);
   2531 
   2532   if (Version < 10000)
   2533     return VersionTuple(Version / 100, Version % 100);
   2534 
   2535   unsigned Build = 0, Factor = 1;
   2536   for ( ; Version > 10000; Version = Version / 10, Factor = Factor * 10)
   2537     Build = Build + (Version % 10) * Factor;
   2538   return VersionTuple(Version / 100, Version % 100, Build);
   2539 }
   2540 
   2541 // Claim options we don't want to warn if they are unused. We do this for
   2542 // options that build systems might add but are unused when assembling or only
   2543 // running the preprocessor for example.
   2544 static void claimNoWarnArgs(const ArgList &Args) {
   2545   // Don't warn about unused -f(no-)?lto.  This can happen when we're
   2546   // preprocessing, precompiling or assembling.
   2547   Args.ClaimAllArgs(options::OPT_flto);
   2548   Args.ClaimAllArgs(options::OPT_fno_lto);
   2549 }
   2550 
   2551 static void appendUserToPath(SmallVectorImpl<char> &Result) {
   2552 #ifdef LLVM_ON_UNIX
   2553   const char *Username = getenv("LOGNAME");
   2554 #else
   2555   const char *Username = getenv("USERNAME");
   2556 #endif
   2557   if (Username) {
   2558     // Validate that LoginName can be used in a path, and get its length.
   2559     size_t Len = 0;
   2560     for (const char *P = Username; *P; ++P, ++Len) {
   2561       if (!isAlphanumeric(*P) && *P != '_') {
   2562         Username = nullptr;
   2563         break;
   2564       }
   2565     }
   2566 
   2567     if (Username && Len > 0) {
   2568       Result.append(Username, Username + Len);
   2569       return;
   2570     }
   2571   }
   2572 
   2573   // Fallback to user id.
   2574 #ifdef LLVM_ON_UNIX
   2575   std::string UID = llvm::utostr(getuid());
   2576 #else
   2577   // FIXME: Windows seems to have an 'SID' that might work.
   2578   std::string UID = "9999";
   2579 #endif
   2580   Result.append(UID.begin(), UID.end());
   2581 }
   2582 
   2583 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
   2584                          const InputInfo &Output,
   2585                          const InputInfoList &Inputs,
   2586                          const ArgList &Args,
   2587                          const char *LinkingOutput) const {
   2588   bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
   2589                                   options::OPT_fapple_kext);
   2590   const Driver &D = getToolChain().getDriver();
   2591   ArgStringList CmdArgs;
   2592 
   2593   bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
   2594   bool IsWindowsCygnus =
   2595       getToolChain().getTriple().isWindowsCygwinEnvironment();
   2596   bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
   2597 
   2598   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
   2599 
   2600   // Invoke ourselves in -cc1 mode.
   2601   //
   2602   // FIXME: Implement custom jobs for internal actions.
   2603   CmdArgs.push_back("-cc1");
   2604 
   2605   // Add the "effective" target triple.
   2606   CmdArgs.push_back("-triple");
   2607   std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
   2608   CmdArgs.push_back(Args.MakeArgString(TripleStr));
   2609 
   2610   const llvm::Triple TT(TripleStr);
   2611   if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
   2612                            TT.getArch() == llvm::Triple::thumb)) {
   2613     unsigned Offset = TT.getArch() == llvm::Triple::arm ? 4 : 6;
   2614     unsigned Version;
   2615     TT.getArchName().substr(Offset).getAsInteger(10, Version);
   2616     if (Version < 7)
   2617       D.Diag(diag::err_target_unsupported_arch) << TT.getArchName()
   2618                                                 << TripleStr;
   2619   }
   2620 
   2621   // Push all default warning arguments that are specific to
   2622   // the given target.  These come before user provided warning options
   2623   // are provided.
   2624   getToolChain().addClangWarningOptions(CmdArgs);
   2625 
   2626   // Select the appropriate action.
   2627   RewriteKind rewriteKind = RK_None;
   2628 
   2629   if (isa<AnalyzeJobAction>(JA)) {
   2630     assert(JA.getType() == types::TY_Plist && "Invalid output type.");
   2631     CmdArgs.push_back("-analyze");
   2632   } else if (isa<MigrateJobAction>(JA)) {
   2633     CmdArgs.push_back("-migrate");
   2634   } else if (isa<PreprocessJobAction>(JA)) {
   2635     if (Output.getType() == types::TY_Dependencies)
   2636       CmdArgs.push_back("-Eonly");
   2637     else {
   2638       CmdArgs.push_back("-E");
   2639       if (Args.hasArg(options::OPT_rewrite_objc) &&
   2640           !Args.hasArg(options::OPT_g_Group))
   2641         CmdArgs.push_back("-P");
   2642     }
   2643   } else if (isa<AssembleJobAction>(JA)) {
   2644     CmdArgs.push_back("-emit-obj");
   2645 
   2646     CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
   2647 
   2648     // Also ignore explicit -force_cpusubtype_ALL option.
   2649     (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
   2650   } else if (isa<PrecompileJobAction>(JA)) {
   2651     // Use PCH if the user requested it.
   2652     bool UsePCH = D.CCCUsePCH;
   2653 
   2654     if (JA.getType() == types::TY_Nothing)
   2655       CmdArgs.push_back("-fsyntax-only");
   2656     else if (UsePCH)
   2657       CmdArgs.push_back("-emit-pch");
   2658     else
   2659       CmdArgs.push_back("-emit-pth");
   2660   } else if (isa<VerifyPCHJobAction>(JA)) {
   2661     CmdArgs.push_back("-verify-pch");
   2662   } else {
   2663     assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
   2664            "Invalid action for clang tool.");
   2665 
   2666     if (JA.getType() == types::TY_Nothing) {
   2667       CmdArgs.push_back("-fsyntax-only");
   2668     } else if (JA.getType() == types::TY_LLVM_IR ||
   2669                JA.getType() == types::TY_LTO_IR) {
   2670       CmdArgs.push_back("-emit-llvm");
   2671     } else if (JA.getType() == types::TY_LLVM_BC ||
   2672                JA.getType() == types::TY_LTO_BC) {
   2673       CmdArgs.push_back("-emit-llvm-bc");
   2674     } else if (JA.getType() == types::TY_PP_Asm) {
   2675       CmdArgs.push_back("-S");
   2676     } else if (JA.getType() == types::TY_AST) {
   2677       CmdArgs.push_back("-emit-pch");
   2678     } else if (JA.getType() == types::TY_ModuleFile) {
   2679       CmdArgs.push_back("-module-file-info");
   2680     } else if (JA.getType() == types::TY_RewrittenObjC) {
   2681       CmdArgs.push_back("-rewrite-objc");
   2682       rewriteKind = RK_NonFragile;
   2683     } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
   2684       CmdArgs.push_back("-rewrite-objc");
   2685       rewriteKind = RK_Fragile;
   2686     } else {
   2687       assert(JA.getType() == types::TY_PP_Asm &&
   2688              "Unexpected output type!");
   2689     }
   2690 
   2691     // Preserve use-list order by default when emitting bitcode, so that
   2692     // loading the bitcode up in 'opt' or 'llc' and running passes gives the
   2693     // same result as running passes here.  For LTO, we don't need to preserve
   2694     // the use-list order, since serialization to bitcode is part of the flow.
   2695     if (JA.getType() == types::TY_LLVM_BC)
   2696       CmdArgs.push_back("-emit-llvm-uselists");
   2697   }
   2698 
   2699   // We normally speed up the clang process a bit by skipping destructors at
   2700   // exit, but when we're generating diagnostics we can rely on some of the
   2701   // cleanup.
   2702   if (!C.isForDiagnostics())
   2703     CmdArgs.push_back("-disable-free");
   2704 
   2705   // Disable the verification pass in -asserts builds.
   2706 #ifdef NDEBUG
   2707   CmdArgs.push_back("-disable-llvm-verifier");
   2708 #endif
   2709 
   2710   // Set the main file name, so that debug info works even with
   2711   // -save-temps.
   2712   CmdArgs.push_back("-main-file-name");
   2713   CmdArgs.push_back(getBaseInputName(Args, Inputs));
   2714 
   2715   // Some flags which affect the language (via preprocessor
   2716   // defines).
   2717   if (Args.hasArg(options::OPT_static))
   2718     CmdArgs.push_back("-static-define");
   2719 
   2720   if (isa<AnalyzeJobAction>(JA)) {
   2721     // Enable region store model by default.
   2722     CmdArgs.push_back("-analyzer-store=region");
   2723 
   2724     // Treat blocks as analysis entry points.
   2725     CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
   2726 
   2727     CmdArgs.push_back("-analyzer-eagerly-assume");
   2728 
   2729     // Add default argument set.
   2730     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
   2731       CmdArgs.push_back("-analyzer-checker=core");
   2732 
   2733       if (!IsWindowsMSVC)
   2734         CmdArgs.push_back("-analyzer-checker=unix");
   2735 
   2736       if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
   2737         CmdArgs.push_back("-analyzer-checker=osx");
   2738 
   2739       CmdArgs.push_back("-analyzer-checker=deadcode");
   2740 
   2741       if (types::isCXX(Inputs[0].getType()))
   2742         CmdArgs.push_back("-analyzer-checker=cplusplus");
   2743 
   2744       // Enable the following experimental checkers for testing.
   2745       CmdArgs.push_back(
   2746           "-analyzer-checker=security.insecureAPI.UncheckedReturn");
   2747       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
   2748       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
   2749       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
   2750       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
   2751       CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
   2752     }
   2753 
   2754     // Set the output format. The default is plist, for (lame) historical
   2755     // reasons.
   2756     CmdArgs.push_back("-analyzer-output");
   2757     if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
   2758       CmdArgs.push_back(A->getValue());
   2759     else
   2760       CmdArgs.push_back("plist");
   2761 
   2762     // Disable the presentation of standard compiler warnings when
   2763     // using --analyze.  We only want to show static analyzer diagnostics
   2764     // or frontend errors.
   2765     CmdArgs.push_back("-w");
   2766 
   2767     // Add -Xanalyzer arguments when running as analyzer.
   2768     Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
   2769   }
   2770 
   2771   CheckCodeGenerationOptions(D, Args);
   2772 
   2773   bool PIE = getToolChain().isPIEDefault();
   2774   bool PIC = PIE || getToolChain().isPICDefault();
   2775   bool IsPICLevelTwo = PIC;
   2776 
   2777   // Android-specific defaults for PIC/PIE
   2778   if (getToolChain().getTriple().getEnvironment() == llvm::Triple::Android) {
   2779     switch (getToolChain().getTriple().getArch()) {
   2780     case llvm::Triple::arm:
   2781     case llvm::Triple::armeb:
   2782     case llvm::Triple::thumb:
   2783     case llvm::Triple::thumbeb:
   2784     case llvm::Triple::aarch64:
   2785     case llvm::Triple::mips:
   2786     case llvm::Triple::mipsel:
   2787     case llvm::Triple::mips64:
   2788     case llvm::Triple::mips64el:
   2789       PIC = true; // "-fpic"
   2790       break;
   2791 
   2792     case llvm::Triple::x86:
   2793     case llvm::Triple::x86_64:
   2794       PIC = true; // "-fPIC"
   2795       IsPICLevelTwo = true;
   2796       break;
   2797 
   2798     default:
   2799       break;
   2800     }
   2801   }
   2802 
   2803   // OpenBSD-specific defaults for PIE
   2804   if (getToolChain().getTriple().getOS() == llvm::Triple::OpenBSD) {
   2805     switch (getToolChain().getTriple().getArch()) {
   2806     case llvm::Triple::mips64:
   2807     case llvm::Triple::mips64el:
   2808     case llvm::Triple::sparc:
   2809     case llvm::Triple::x86:
   2810     case llvm::Triple::x86_64:
   2811       IsPICLevelTwo = false; // "-fpie"
   2812       break;
   2813 
   2814     case llvm::Triple::ppc:
   2815     case llvm::Triple::sparcv9:
   2816       IsPICLevelTwo = true; // "-fPIE"
   2817       break;
   2818 
   2819     default:
   2820       break;
   2821     }
   2822   }
   2823 
   2824   // For the PIC and PIE flag options, this logic is different from the
   2825   // legacy logic in very old versions of GCC, as that logic was just
   2826   // a bug no one had ever fixed. This logic is both more rational and
   2827   // consistent with GCC's new logic now that the bugs are fixed. The last
   2828   // argument relating to either PIC or PIE wins, and no other argument is
   2829   // used. If the last argument is any flavor of the '-fno-...' arguments,
   2830   // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
   2831   // at the same level.
   2832   Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
   2833                                  options::OPT_fpic, options::OPT_fno_pic,
   2834                                  options::OPT_fPIE, options::OPT_fno_PIE,
   2835                                  options::OPT_fpie, options::OPT_fno_pie);
   2836   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
   2837   // is forced, then neither PIC nor PIE flags will have no effect.
   2838   if (!getToolChain().isPICDefaultForced()) {
   2839     if (LastPICArg) {
   2840       Option O = LastPICArg->getOption();
   2841       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
   2842           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
   2843         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
   2844         PIC = PIE || O.matches(options::OPT_fPIC) ||
   2845               O.matches(options::OPT_fpic);
   2846         IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
   2847                         O.matches(options::OPT_fPIC);
   2848       } else {
   2849         PIE = PIC = false;
   2850       }
   2851     }
   2852   }
   2853 
   2854   // Introduce a Darwin-specific hack. If the default is PIC but the flags
   2855   // specified while enabling PIC enabled level 1 PIC, just force it back to
   2856   // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
   2857   // informal testing).
   2858   if (PIC && getToolChain().getTriple().isOSDarwin())
   2859     IsPICLevelTwo |= getToolChain().isPICDefault();
   2860 
   2861   // Note that these flags are trump-cards. Regardless of the order w.r.t. the
   2862   // PIC or PIE options above, if these show up, PIC is disabled.
   2863   llvm::Triple Triple(TripleStr);
   2864   if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)))
   2865     PIC = PIE = false;
   2866   if (Args.hasArg(options::OPT_static))
   2867     PIC = PIE = false;
   2868 
   2869   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
   2870     // This is a very special mode. It trumps the other modes, almost no one
   2871     // uses it, and it isn't even valid on any OS but Darwin.
   2872     if (!getToolChain().getTriple().isOSDarwin())
   2873       D.Diag(diag::err_drv_unsupported_opt_for_target)
   2874         << A->getSpelling() << getToolChain().getTriple().str();
   2875 
   2876     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
   2877 
   2878     CmdArgs.push_back("-mrelocation-model");
   2879     CmdArgs.push_back("dynamic-no-pic");
   2880 
   2881     // Only a forced PIC mode can cause the actual compile to have PIC defines
   2882     // etc., no flags are sufficient. This behavior was selected to closely
   2883     // match that of llvm-gcc and Apple GCC before that.
   2884     if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
   2885       CmdArgs.push_back("-pic-level");
   2886       CmdArgs.push_back("2");
   2887     }
   2888   } else {
   2889     // Currently, LLVM only knows about PIC vs. static; the PIE differences are
   2890     // handled in Clang's IRGen by the -pie-level flag.
   2891     CmdArgs.push_back("-mrelocation-model");
   2892     CmdArgs.push_back(PIC ? "pic" : "static");
   2893 
   2894     if (PIC) {
   2895       CmdArgs.push_back("-pic-level");
   2896       CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
   2897       if (PIE) {
   2898         CmdArgs.push_back("-pie-level");
   2899         CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
   2900       }
   2901     }
   2902   }
   2903 
   2904   CmdArgs.push_back("-mthread-model");
   2905   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
   2906     CmdArgs.push_back(A->getValue());
   2907   else
   2908     CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
   2909 
   2910   Args.AddLastArg(CmdArgs, options::OPT_fveclib);
   2911 
   2912   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
   2913                     options::OPT_fno_merge_all_constants))
   2914     CmdArgs.push_back("-fno-merge-all-constants");
   2915 
   2916   // LLVM Code Generator Options.
   2917 
   2918   if (Args.hasArg(options::OPT_frewrite_map_file) ||
   2919       Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
   2920     for (arg_iterator
   2921              MFI = Args.filtered_begin(options::OPT_frewrite_map_file,
   2922                                        options::OPT_frewrite_map_file_EQ),
   2923              MFE = Args.filtered_end();
   2924          MFI != MFE; ++MFI) {
   2925       CmdArgs.push_back("-frewrite-map-file");
   2926       CmdArgs.push_back((*MFI)->getValue());
   2927       (*MFI)->claim();
   2928     }
   2929   }
   2930 
   2931   if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
   2932     StringRef v = A->getValue();
   2933     CmdArgs.push_back("-mllvm");
   2934     CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
   2935     A->claim();
   2936   }
   2937 
   2938   if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
   2939     CmdArgs.push_back("-mregparm");
   2940     CmdArgs.push_back(A->getValue());
   2941   }
   2942 
   2943   if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
   2944                                options::OPT_freg_struct_return)) {
   2945     if (getToolChain().getArch() != llvm::Triple::x86) {
   2946       D.Diag(diag::err_drv_unsupported_opt_for_target)
   2947         << A->getSpelling() << getToolChain().getTriple().str();
   2948     } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
   2949       CmdArgs.push_back("-fpcc-struct-return");
   2950     } else {
   2951       assert(A->getOption().matches(options::OPT_freg_struct_return));
   2952       CmdArgs.push_back("-freg-struct-return");
   2953     }
   2954   }
   2955 
   2956   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
   2957     CmdArgs.push_back("-mrtd");
   2958 
   2959   if (shouldUseFramePointer(Args, getToolChain().getTriple()))
   2960     CmdArgs.push_back("-mdisable-fp-elim");
   2961   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
   2962                     options::OPT_fno_zero_initialized_in_bss))
   2963     CmdArgs.push_back("-mno-zero-initialized-in-bss");
   2964 
   2965   bool OFastEnabled = isOptimizationLevelFast(Args);
   2966   // If -Ofast is the optimization level, then -fstrict-aliasing should be
   2967   // enabled.  This alias option is being used to simplify the hasFlag logic.
   2968   OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
   2969     options::OPT_fstrict_aliasing;
   2970   // We turn strict aliasing off by default if we're in CL mode, since MSVC
   2971   // doesn't do any TBAA.
   2972   bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
   2973   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
   2974                     options::OPT_fno_strict_aliasing, TBAAOnByDefault))
   2975     CmdArgs.push_back("-relaxed-aliasing");
   2976   if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
   2977                     options::OPT_fno_struct_path_tbaa))
   2978     CmdArgs.push_back("-no-struct-path-tbaa");
   2979   if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
   2980                    false))
   2981     CmdArgs.push_back("-fstrict-enums");
   2982   if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
   2983                     options::OPT_fno_optimize_sibling_calls))
   2984     CmdArgs.push_back("-mdisable-tail-calls");
   2985 
   2986   // Handle segmented stacks.
   2987   if (Args.hasArg(options::OPT_fsplit_stack))
   2988     CmdArgs.push_back("-split-stacks");
   2989 
   2990   // If -Ofast is the optimization level, then -ffast-math should be enabled.
   2991   // This alias option is being used to simplify the getLastArg logic.
   2992   OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
   2993     options::OPT_ffast_math;
   2994 
   2995   // Handle various floating point optimization flags, mapping them to the
   2996   // appropriate LLVM code generation flags. The pattern for all of these is to
   2997   // default off the codegen optimizations, and if any flag enables them and no
   2998   // flag disables them after the flag enabling them, enable the codegen
   2999   // optimization. This is complicated by several "umbrella" flags.
   3000   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3001                                options::OPT_fno_fast_math,
   3002                                options::OPT_ffinite_math_only,
   3003                                options::OPT_fno_finite_math_only,
   3004                                options::OPT_fhonor_infinities,
   3005                                options::OPT_fno_honor_infinities))
   3006     if (A->getOption().getID() != options::OPT_fno_fast_math &&
   3007         A->getOption().getID() != options::OPT_fno_finite_math_only &&
   3008         A->getOption().getID() != options::OPT_fhonor_infinities)
   3009       CmdArgs.push_back("-menable-no-infs");
   3010   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3011                                options::OPT_fno_fast_math,
   3012                                options::OPT_ffinite_math_only,
   3013                                options::OPT_fno_finite_math_only,
   3014                                options::OPT_fhonor_nans,
   3015                                options::OPT_fno_honor_nans))
   3016     if (A->getOption().getID() != options::OPT_fno_fast_math &&
   3017         A->getOption().getID() != options::OPT_fno_finite_math_only &&
   3018         A->getOption().getID() != options::OPT_fhonor_nans)
   3019       CmdArgs.push_back("-menable-no-nans");
   3020 
   3021   // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
   3022   bool MathErrno = getToolChain().IsMathErrnoDefault();
   3023   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3024                                options::OPT_fno_fast_math,
   3025                                options::OPT_fmath_errno,
   3026                                options::OPT_fno_math_errno)) {
   3027     // Turning on -ffast_math (with either flag) removes the need for MathErrno.
   3028     // However, turning *off* -ffast_math merely restores the toolchain default
   3029     // (which may be false).
   3030     if (A->getOption().getID() == options::OPT_fno_math_errno ||
   3031         A->getOption().getID() == options::OPT_ffast_math ||
   3032         A->getOption().getID() == options::OPT_Ofast)
   3033       MathErrno = false;
   3034     else if (A->getOption().getID() == options::OPT_fmath_errno)
   3035       MathErrno = true;
   3036   }
   3037   if (MathErrno)
   3038     CmdArgs.push_back("-fmath-errno");
   3039 
   3040   // There are several flags which require disabling very specific
   3041   // optimizations. Any of these being disabled forces us to turn off the
   3042   // entire set of LLVM optimizations, so collect them through all the flag
   3043   // madness.
   3044   bool AssociativeMath = false;
   3045   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3046                                options::OPT_fno_fast_math,
   3047                                options::OPT_funsafe_math_optimizations,
   3048                                options::OPT_fno_unsafe_math_optimizations,
   3049                                options::OPT_fassociative_math,
   3050                                options::OPT_fno_associative_math))
   3051     if (A->getOption().getID() != options::OPT_fno_fast_math &&
   3052         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
   3053         A->getOption().getID() != options::OPT_fno_associative_math)
   3054       AssociativeMath = true;
   3055   bool ReciprocalMath = false;
   3056   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3057                                options::OPT_fno_fast_math,
   3058                                options::OPT_funsafe_math_optimizations,
   3059                                options::OPT_fno_unsafe_math_optimizations,
   3060                                options::OPT_freciprocal_math,
   3061                                options::OPT_fno_reciprocal_math))
   3062     if (A->getOption().getID() != options::OPT_fno_fast_math &&
   3063         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
   3064         A->getOption().getID() != options::OPT_fno_reciprocal_math)
   3065       ReciprocalMath = true;
   3066   bool SignedZeros = true;
   3067   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3068                                options::OPT_fno_fast_math,
   3069                                options::OPT_funsafe_math_optimizations,
   3070                                options::OPT_fno_unsafe_math_optimizations,
   3071                                options::OPT_fsigned_zeros,
   3072                                options::OPT_fno_signed_zeros))
   3073     if (A->getOption().getID() != options::OPT_fno_fast_math &&
   3074         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
   3075         A->getOption().getID() != options::OPT_fsigned_zeros)
   3076       SignedZeros = false;
   3077   bool TrappingMath = true;
   3078   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3079                                options::OPT_fno_fast_math,
   3080                                options::OPT_funsafe_math_optimizations,
   3081                                options::OPT_fno_unsafe_math_optimizations,
   3082                                options::OPT_ftrapping_math,
   3083                                options::OPT_fno_trapping_math))
   3084     if (A->getOption().getID() != options::OPT_fno_fast_math &&
   3085         A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
   3086         A->getOption().getID() != options::OPT_ftrapping_math)
   3087       TrappingMath = false;
   3088   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
   3089       !TrappingMath)
   3090     CmdArgs.push_back("-menable-unsafe-fp-math");
   3091 
   3092   if (!SignedZeros)
   3093     CmdArgs.push_back("-fno-signed-zeros");
   3094 
   3095   if (ReciprocalMath)
   3096     CmdArgs.push_back("-freciprocal-math");
   3097 
   3098   // Validate and pass through -fp-contract option.
   3099   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3100                                options::OPT_fno_fast_math,
   3101                                options::OPT_ffp_contract)) {
   3102     if (A->getOption().getID() == options::OPT_ffp_contract) {
   3103       StringRef Val = A->getValue();
   3104       if (Val == "fast" || Val == "on" || Val == "off") {
   3105         CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
   3106       } else {
   3107         D.Diag(diag::err_drv_unsupported_option_argument)
   3108           << A->getOption().getName() << Val;
   3109       }
   3110     } else if (A->getOption().matches(options::OPT_ffast_math) ||
   3111                (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
   3112       // If fast-math is set then set the fp-contract mode to fast.
   3113       CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
   3114     }
   3115   }
   3116 
   3117   // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
   3118   // and if we find them, tell the frontend to provide the appropriate
   3119   // preprocessor macros. This is distinct from enabling any optimizations as
   3120   // these options induce language changes which must survive serialization
   3121   // and deserialization, etc.
   3122   if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
   3123                                options::OPT_fno_fast_math))
   3124       if (!A->getOption().matches(options::OPT_fno_fast_math))
   3125         CmdArgs.push_back("-ffast-math");
   3126   if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
   3127                                options::OPT_fno_fast_math))
   3128     if (A->getOption().matches(options::OPT_ffinite_math_only))
   3129       CmdArgs.push_back("-ffinite-math-only");
   3130 
   3131   // Decide whether to use verbose asm. Verbose assembly is the default on
   3132   // toolchains which have the integrated assembler on by default.
   3133   bool IsIntegratedAssemblerDefault =
   3134       getToolChain().IsIntegratedAssemblerDefault();
   3135   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
   3136                    IsIntegratedAssemblerDefault) ||
   3137       Args.hasArg(options::OPT_dA))
   3138     CmdArgs.push_back("-masm-verbose");
   3139 
   3140   bool UsingIntegratedAssembler =
   3141       Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
   3142                    IsIntegratedAssemblerDefault);
   3143   if (!UsingIntegratedAssembler)
   3144     CmdArgs.push_back("-no-integrated-as");
   3145 
   3146   if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
   3147     CmdArgs.push_back("-mdebug-pass");
   3148     CmdArgs.push_back("Structure");
   3149   }
   3150   if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
   3151     CmdArgs.push_back("-mdebug-pass");
   3152     CmdArgs.push_back("Arguments");
   3153   }
   3154 
   3155   // Enable -mconstructor-aliases except on darwin, where we have to
   3156   // work around a linker bug;  see <rdar://problem/7651567>.
   3157   if (!getToolChain().getTriple().isOSDarwin())
   3158     CmdArgs.push_back("-mconstructor-aliases");
   3159 
   3160   // Darwin's kernel doesn't support guard variables; just die if we
   3161   // try to use them.
   3162   if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
   3163     CmdArgs.push_back("-fforbid-guard-variables");
   3164 
   3165   if (Args.hasArg(options::OPT_mms_bitfields)) {
   3166     CmdArgs.push_back("-mms-bitfields");
   3167   }
   3168 
   3169   // This is a coarse approximation of what llvm-gcc actually does, both
   3170   // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
   3171   // complicated ways.
   3172   bool AsynchronousUnwindTables =
   3173       Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
   3174                    options::OPT_fno_asynchronous_unwind_tables,
   3175                    (getToolChain().IsUnwindTablesDefault() ||
   3176                     getToolChain().getSanitizerArgs().needsUnwindTables()) &&
   3177                        !KernelOrKext);
   3178   if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
   3179                    AsynchronousUnwindTables))
   3180     CmdArgs.push_back("-munwind-tables");
   3181 
   3182   getToolChain().addClangTargetOptions(Args, CmdArgs);
   3183 
   3184   if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
   3185     CmdArgs.push_back("-mlimit-float-precision");
   3186     CmdArgs.push_back(A->getValue());
   3187   }
   3188 
   3189   // FIXME: Handle -mtune=.
   3190   (void) Args.hasArg(options::OPT_mtune_EQ);
   3191 
   3192   if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
   3193     CmdArgs.push_back("-mcode-model");
   3194     CmdArgs.push_back(A->getValue());
   3195   }
   3196 
   3197   // Add the target cpu
   3198   std::string ETripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
   3199   llvm::Triple ETriple(ETripleStr);
   3200   std::string CPU = getCPUName(Args, ETriple);
   3201   if (!CPU.empty()) {
   3202     CmdArgs.push_back("-target-cpu");
   3203     CmdArgs.push_back(Args.MakeArgString(CPU));
   3204   }
   3205 
   3206   if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
   3207     CmdArgs.push_back("-mfpmath");
   3208     CmdArgs.push_back(A->getValue());
   3209   }
   3210 
   3211   // Add the target features
   3212   getTargetFeatures(D, ETriple, Args, CmdArgs, false);
   3213 
   3214   // Add target specific flags.
   3215   switch(getToolChain().getArch()) {
   3216   default:
   3217     break;
   3218 
   3219   case llvm::Triple::arm:
   3220   case llvm::Triple::armeb:
   3221   case llvm::Triple::thumb:
   3222   case llvm::Triple::thumbeb:
   3223     AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
   3224     break;
   3225 
   3226   case llvm::Triple::aarch64:
   3227   case llvm::Triple::aarch64_be:
   3228     AddAArch64TargetArgs(Args, CmdArgs);
   3229     break;
   3230 
   3231   case llvm::Triple::mips:
   3232   case llvm::Triple::mipsel:
   3233   case llvm::Triple::mips64:
   3234   case llvm::Triple::mips64el:
   3235     AddMIPSTargetArgs(Args, CmdArgs);
   3236     break;
   3237 
   3238   case llvm::Triple::ppc:
   3239   case llvm::Triple::ppc64:
   3240   case llvm::Triple::ppc64le:
   3241     AddPPCTargetArgs(Args, CmdArgs);
   3242     break;
   3243 
   3244   case llvm::Triple::sparc:
   3245   case llvm::Triple::sparcv9:
   3246     AddSparcTargetArgs(Args, CmdArgs);
   3247     break;
   3248 
   3249   case llvm::Triple::x86:
   3250   case llvm::Triple::x86_64:
   3251     AddX86TargetArgs(Args, CmdArgs);
   3252     break;
   3253 
   3254   case llvm::Triple::hexagon:
   3255     AddHexagonTargetArgs(Args, CmdArgs);
   3256     break;
   3257   }
   3258 
   3259   // Add clang-cl arguments.
   3260   if (getToolChain().getDriver().IsCLMode())
   3261     AddClangCLArgs(Args, CmdArgs);
   3262 
   3263   // Pass the linker version in use.
   3264   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
   3265     CmdArgs.push_back("-target-linker-version");
   3266     CmdArgs.push_back(A->getValue());
   3267   }
   3268 
   3269   if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
   3270     CmdArgs.push_back("-momit-leaf-frame-pointer");
   3271 
   3272   // Explicitly error on some things we know we don't support and can't just
   3273   // ignore.
   3274   types::ID InputType = Inputs[0].getType();
   3275   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
   3276     Arg *Unsupported;
   3277     if (types::isCXX(InputType) &&
   3278         getToolChain().getTriple().isOSDarwin() &&
   3279         getToolChain().getArch() == llvm::Triple::x86) {
   3280       if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
   3281           (Unsupported = Args.getLastArg(options::OPT_mkernel)))
   3282         D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
   3283           << Unsupported->getOption().getName();
   3284     }
   3285   }
   3286 
   3287   Args.AddAllArgs(CmdArgs, options::OPT_v);
   3288   Args.AddLastArg(CmdArgs, options::OPT_H);
   3289   if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
   3290     CmdArgs.push_back("-header-include-file");
   3291     CmdArgs.push_back(D.CCPrintHeadersFilename ?
   3292                       D.CCPrintHeadersFilename : "-");
   3293   }
   3294   Args.AddLastArg(CmdArgs, options::OPT_P);
   3295   Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
   3296 
   3297   if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
   3298     CmdArgs.push_back("-diagnostic-log-file");
   3299     CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
   3300                       D.CCLogDiagnosticsFilename : "-");
   3301   }
   3302 
   3303   // Use the last option from "-g" group. "-gline-tables-only" and "-gdwarf-x"
   3304   // are preserved, all other debug options are substituted with "-g".
   3305   Args.ClaimAllArgs(options::OPT_g_Group);
   3306   if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
   3307     if (A->getOption().matches(options::OPT_gline_tables_only) ||
   3308         A->getOption().matches(options::OPT_g1)) {
   3309       // FIXME: we should support specifying dwarf version with
   3310       // -gline-tables-only.
   3311       CmdArgs.push_back("-gline-tables-only");
   3312       // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
   3313       const llvm::Triple &Triple = getToolChain().getTriple();
   3314       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
   3315           Triple.getOS() == llvm::Triple::FreeBSD ||
   3316           Triple.getOS() == llvm::Triple::Solaris)
   3317         CmdArgs.push_back("-gdwarf-2");
   3318     } else if (A->getOption().matches(options::OPT_gdwarf_2))
   3319       CmdArgs.push_back("-gdwarf-2");
   3320     else if (A->getOption().matches(options::OPT_gdwarf_3))
   3321       CmdArgs.push_back("-gdwarf-3");
   3322     else if (A->getOption().matches(options::OPT_gdwarf_4))
   3323       CmdArgs.push_back("-gdwarf-4");
   3324     else if (!A->getOption().matches(options::OPT_g0) &&
   3325              !A->getOption().matches(options::OPT_ggdb0)) {
   3326       // Default is dwarf-2 for Darwin, OpenBSD, FreeBSD and Solaris.
   3327       const llvm::Triple &Triple = getToolChain().getTriple();
   3328       if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::OpenBSD ||
   3329           Triple.getOS() == llvm::Triple::FreeBSD ||
   3330           Triple.getOS() == llvm::Triple::Solaris)
   3331         CmdArgs.push_back("-gdwarf-2");
   3332       else
   3333         CmdArgs.push_back("-g");
   3334     }
   3335   }
   3336 
   3337   // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
   3338   Args.ClaimAllArgs(options::OPT_g_flags_Group);
   3339   if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
   3340                    /*Default*/ true))
   3341     CmdArgs.push_back("-dwarf-column-info");
   3342 
   3343   // FIXME: Move backend command line options to the module.
   3344   // -gsplit-dwarf should turn on -g and enable the backend dwarf
   3345   // splitting and extraction.
   3346   // FIXME: Currently only works on Linux.
   3347   if (getToolChain().getTriple().isOSLinux() &&
   3348       Args.hasArg(options::OPT_gsplit_dwarf)) {
   3349     CmdArgs.push_back("-g");
   3350     CmdArgs.push_back("-backend-option");
   3351     CmdArgs.push_back("-split-dwarf=Enable");
   3352   }
   3353 
   3354   // -ggnu-pubnames turns on gnu style pubnames in the backend.
   3355   if (Args.hasArg(options::OPT_ggnu_pubnames)) {
   3356     CmdArgs.push_back("-backend-option");
   3357     CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
   3358   }
   3359 
   3360   // -gdwarf-aranges turns on the emission of the aranges section in the
   3361   // backend.
   3362   if (Args.hasArg(options::OPT_gdwarf_aranges)) {
   3363     CmdArgs.push_back("-backend-option");
   3364     CmdArgs.push_back("-generate-arange-section");
   3365   }
   3366 
   3367   if (Args.hasFlag(options::OPT_fdebug_types_section,
   3368                    options::OPT_fno_debug_types_section, false)) {
   3369     CmdArgs.push_back("-backend-option");
   3370     CmdArgs.push_back("-generate-type-units");
   3371   }
   3372 
   3373   // CloudABI uses -ffunction-sections and -fdata-sections by default.
   3374   bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI;
   3375 
   3376   if (Args.hasFlag(options::OPT_ffunction_sections,
   3377                    options::OPT_fno_function_sections, UseSeparateSections)) {
   3378     CmdArgs.push_back("-ffunction-sections");
   3379   }
   3380 
   3381   if (Args.hasFlag(options::OPT_fdata_sections,
   3382                    options::OPT_fno_data_sections, UseSeparateSections)) {
   3383     CmdArgs.push_back("-fdata-sections");
   3384   }
   3385 
   3386   if (!Args.hasFlag(options::OPT_funique_section_names,
   3387                     options::OPT_fno_unique_section_names,
   3388                     !UsingIntegratedAssembler))
   3389     CmdArgs.push_back("-fno-unique-section-names");
   3390 
   3391   Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
   3392 
   3393   if (Args.hasArg(options::OPT_fprofile_instr_generate) &&
   3394       (Args.hasArg(options::OPT_fprofile_instr_use) ||
   3395        Args.hasArg(options::OPT_fprofile_instr_use_EQ)))
   3396     D.Diag(diag::err_drv_argument_not_allowed_with)
   3397       << "-fprofile-instr-generate" << "-fprofile-instr-use";
   3398 
   3399   Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
   3400 
   3401   if (Arg *A = Args.getLastArg(options::OPT_fprofile_instr_use_EQ))
   3402     A->render(Args, CmdArgs);
   3403   else if (Args.hasArg(options::OPT_fprofile_instr_use))
   3404     CmdArgs.push_back("-fprofile-instr-use=pgo-data");
   3405 
   3406   if (Args.hasArg(options::OPT_ftest_coverage) ||
   3407       Args.hasArg(options::OPT_coverage))
   3408     CmdArgs.push_back("-femit-coverage-notes");
   3409   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
   3410                    false) ||
   3411       Args.hasArg(options::OPT_coverage))
   3412     CmdArgs.push_back("-femit-coverage-data");
   3413 
   3414   if (Args.hasArg(options::OPT_fcoverage_mapping) &&
   3415       !Args.hasArg(options::OPT_fprofile_instr_generate))
   3416     D.Diag(diag::err_drv_argument_only_allowed_with)
   3417       << "-fcoverage-mapping" << "-fprofile-instr-generate";
   3418 
   3419   if (Args.hasArg(options::OPT_fcoverage_mapping))
   3420     CmdArgs.push_back("-fcoverage-mapping");
   3421 
   3422   if (C.getArgs().hasArg(options::OPT_c) ||
   3423       C.getArgs().hasArg(options::OPT_S)) {
   3424     if (Output.isFilename()) {
   3425       CmdArgs.push_back("-coverage-file");
   3426       SmallString<128> CoverageFilename;
   3427       if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
   3428         CoverageFilename = FinalOutput->getValue();
   3429       } else {
   3430         CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
   3431       }
   3432       if (llvm::sys::path::is_relative(CoverageFilename)) {
   3433         SmallString<128> Pwd;
   3434         if (!llvm::sys::fs::current_path(Pwd)) {
   3435           llvm::sys::path::append(Pwd, CoverageFilename);
   3436           CoverageFilename.swap(Pwd);
   3437         }
   3438       }
   3439       CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
   3440     }
   3441   }
   3442 
   3443   // Pass options for controlling the default header search paths.
   3444   if (Args.hasArg(options::OPT_nostdinc)) {
   3445     CmdArgs.push_back("-nostdsysteminc");
   3446     CmdArgs.push_back("-nobuiltininc");
   3447   } else {
   3448     if (Args.hasArg(options::OPT_nostdlibinc))
   3449         CmdArgs.push_back("-nostdsysteminc");
   3450     Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
   3451     Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
   3452   }
   3453 
   3454   // Pass the path to compiler resource files.
   3455   CmdArgs.push_back("-resource-dir");
   3456   CmdArgs.push_back(D.ResourceDir.c_str());
   3457 
   3458   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
   3459 
   3460   bool ARCMTEnabled = false;
   3461   if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
   3462     if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
   3463                                        options::OPT_ccc_arcmt_modify,
   3464                                        options::OPT_ccc_arcmt_migrate)) {
   3465       ARCMTEnabled = true;
   3466       switch (A->getOption().getID()) {
   3467       default:
   3468         llvm_unreachable("missed a case");
   3469       case options::OPT_ccc_arcmt_check:
   3470         CmdArgs.push_back("-arcmt-check");
   3471         break;
   3472       case options::OPT_ccc_arcmt_modify:
   3473         CmdArgs.push_back("-arcmt-modify");
   3474         break;
   3475       case options::OPT_ccc_arcmt_migrate:
   3476         CmdArgs.push_back("-arcmt-migrate");
   3477         CmdArgs.push_back("-mt-migrate-directory");
   3478         CmdArgs.push_back(A->getValue());
   3479 
   3480         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
   3481         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
   3482         break;
   3483       }
   3484     }
   3485   } else {
   3486     Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
   3487     Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
   3488     Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
   3489   }
   3490 
   3491   if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
   3492     if (ARCMTEnabled) {
   3493       D.Diag(diag::err_drv_argument_not_allowed_with)
   3494         << A->getAsString(Args) << "-ccc-arcmt-migrate";
   3495     }
   3496     CmdArgs.push_back("-mt-migrate-directory");
   3497     CmdArgs.push_back(A->getValue());
   3498 
   3499     if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
   3500                      options::OPT_objcmt_migrate_subscripting,
   3501                      options::OPT_objcmt_migrate_property)) {
   3502       // None specified, means enable them all.
   3503       CmdArgs.push_back("-objcmt-migrate-literals");
   3504       CmdArgs.push_back("-objcmt-migrate-subscripting");
   3505       CmdArgs.push_back("-objcmt-migrate-property");
   3506     } else {
   3507       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
   3508       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
   3509       Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
   3510     }
   3511   } else {
   3512     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
   3513     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
   3514     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
   3515     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
   3516     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
   3517     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
   3518     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
   3519     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
   3520     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
   3521     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
   3522     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
   3523     Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
   3524     Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
   3525     Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
   3526     Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
   3527     Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
   3528   }
   3529 
   3530   // Add preprocessing options like -I, -D, etc. if we are using the
   3531   // preprocessor.
   3532   //
   3533   // FIXME: Support -fpreprocessed
   3534   if (types::getPreprocessedType(InputType) != types::TY_INVALID)
   3535     AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
   3536 
   3537   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
   3538   // that "The compiler can only warn and ignore the option if not recognized".
   3539   // When building with ccache, it will pass -D options to clang even on
   3540   // preprocessed inputs and configure concludes that -fPIC is not supported.
   3541   Args.ClaimAllArgs(options::OPT_D);
   3542 
   3543   // Manually translate -O4 to -O3; let clang reject others.
   3544   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
   3545     if (A->getOption().matches(options::OPT_O4)) {
   3546       CmdArgs.push_back("-O3");
   3547       D.Diag(diag::warn_O4_is_O3);
   3548     } else {
   3549       A->render(Args, CmdArgs);
   3550     }
   3551   }
   3552 
   3553   // Warn about ignored options to clang.
   3554   for (arg_iterator it = Args.filtered_begin(
   3555        options::OPT_clang_ignored_gcc_optimization_f_Group),
   3556        ie = Args.filtered_end(); it != ie; ++it) {
   3557     D.Diag(diag::warn_ignored_gcc_optimization) << (*it)->getAsString(Args);
   3558   }
   3559 
   3560   claimNoWarnArgs(Args);
   3561 
   3562   Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
   3563   Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
   3564   if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
   3565     CmdArgs.push_back("-pedantic");
   3566   Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
   3567   Args.AddLastArg(CmdArgs, options::OPT_w);
   3568 
   3569   // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
   3570   // (-ansi is equivalent to -std=c89 or -std=c++98).
   3571   //
   3572   // If a std is supplied, only add -trigraphs if it follows the
   3573   // option.
   3574   if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
   3575     if (Std->getOption().matches(options::OPT_ansi))
   3576       if (types::isCXX(InputType))
   3577         CmdArgs.push_back("-std=c++98");
   3578       else
   3579         CmdArgs.push_back("-std=c89");
   3580     else
   3581       Std->render(Args, CmdArgs);
   3582 
   3583     // If -f(no-)trigraphs appears after the language standard flag, honor it.
   3584     if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
   3585                                  options::OPT_ftrigraphs,
   3586                                  options::OPT_fno_trigraphs))
   3587       if (A != Std)
   3588         A->render(Args, CmdArgs);
   3589   } else {
   3590     // Honor -std-default.
   3591     //
   3592     // FIXME: Clang doesn't correctly handle -std= when the input language
   3593     // doesn't match. For the time being just ignore this for C++ inputs;
   3594     // eventually we want to do all the standard defaulting here instead of
   3595     // splitting it between the driver and clang -cc1.
   3596     if (!types::isCXX(InputType))
   3597       Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
   3598                                 "-std=", /*Joined=*/true);
   3599     else if (IsWindowsMSVC)
   3600       CmdArgs.push_back("-std=c++11");
   3601 
   3602     Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
   3603                     options::OPT_fno_trigraphs);
   3604   }
   3605 
   3606   // GCC's behavior for -Wwrite-strings is a bit strange:
   3607   //  * In C, this "warning flag" changes the types of string literals from
   3608   //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
   3609   //    for the discarded qualifier.
   3610   //  * In C++, this is just a normal warning flag.
   3611   //
   3612   // Implementing this warning correctly in C is hard, so we follow GCC's
   3613   // behavior for now. FIXME: Directly diagnose uses of a string literal as
   3614   // a non-const char* in C, rather than using this crude hack.
   3615   if (!types::isCXX(InputType)) {
   3616     // FIXME: This should behave just like a warning flag, and thus should also
   3617     // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
   3618     Arg *WriteStrings =
   3619         Args.getLastArg(options::OPT_Wwrite_strings,
   3620                         options::OPT_Wno_write_strings, options::OPT_w);
   3621     if (WriteStrings &&
   3622         WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
   3623       CmdArgs.push_back("-fconst-strings");
   3624   }
   3625 
   3626   // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
   3627   // during C++ compilation, which it is by default. GCC keeps this define even
   3628   // in the presence of '-w', match this behavior bug-for-bug.
   3629   if (types::isCXX(InputType) &&
   3630       Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
   3631                    true)) {
   3632     CmdArgs.push_back("-fdeprecated-macro");
   3633   }
   3634 
   3635   // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
   3636   if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
   3637     if (Asm->getOption().matches(options::OPT_fasm))
   3638       CmdArgs.push_back("-fgnu-keywords");
   3639     else
   3640       CmdArgs.push_back("-fno-gnu-keywords");
   3641   }
   3642 
   3643   if (ShouldDisableDwarfDirectory(Args, getToolChain()))
   3644     CmdArgs.push_back("-fno-dwarf-directory-asm");
   3645 
   3646   if (ShouldDisableAutolink(Args, getToolChain()))
   3647     CmdArgs.push_back("-fno-autolink");
   3648 
   3649   // Add in -fdebug-compilation-dir if necessary.
   3650   addDebugCompDirArg(Args, CmdArgs);
   3651 
   3652   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
   3653                                options::OPT_ftemplate_depth_EQ)) {
   3654     CmdArgs.push_back("-ftemplate-depth");
   3655     CmdArgs.push_back(A->getValue());
   3656   }
   3657 
   3658   if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
   3659     CmdArgs.push_back("-foperator-arrow-depth");
   3660     CmdArgs.push_back(A->getValue());
   3661   }
   3662 
   3663   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
   3664     CmdArgs.push_back("-fconstexpr-depth");
   3665     CmdArgs.push_back(A->getValue());
   3666   }
   3667 
   3668   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
   3669     CmdArgs.push_back("-fconstexpr-steps");
   3670     CmdArgs.push_back(A->getValue());
   3671   }
   3672 
   3673   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
   3674     CmdArgs.push_back("-fbracket-depth");
   3675     CmdArgs.push_back(A->getValue());
   3676   }
   3677 
   3678   if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
   3679                                options::OPT_Wlarge_by_value_copy_def)) {
   3680     if (A->getNumValues()) {
   3681       StringRef bytes = A->getValue();
   3682       CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
   3683     } else
   3684       CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
   3685   }
   3686 
   3687 
   3688   if (Args.hasArg(options::OPT_relocatable_pch))
   3689     CmdArgs.push_back("-relocatable-pch");
   3690 
   3691   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
   3692     CmdArgs.push_back("-fconstant-string-class");
   3693     CmdArgs.push_back(A->getValue());
   3694   }
   3695 
   3696   if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
   3697     CmdArgs.push_back("-ftabstop");
   3698     CmdArgs.push_back(A->getValue());
   3699   }
   3700 
   3701   CmdArgs.push_back("-ferror-limit");
   3702   if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
   3703     CmdArgs.push_back(A->getValue());
   3704   else
   3705     CmdArgs.push_back("19");
   3706 
   3707   if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
   3708     CmdArgs.push_back("-fmacro-backtrace-limit");
   3709     CmdArgs.push_back(A->getValue());
   3710   }
   3711 
   3712   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
   3713     CmdArgs.push_back("-ftemplate-backtrace-limit");
   3714     CmdArgs.push_back(A->getValue());
   3715   }
   3716 
   3717   if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
   3718     CmdArgs.push_back("-fconstexpr-backtrace-limit");
   3719     CmdArgs.push_back(A->getValue());
   3720   }
   3721 
   3722   if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
   3723     CmdArgs.push_back("-fspell-checking-limit");
   3724     CmdArgs.push_back(A->getValue());
   3725   }
   3726 
   3727   // Pass -fmessage-length=.
   3728   CmdArgs.push_back("-fmessage-length");
   3729   if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
   3730     CmdArgs.push_back(A->getValue());
   3731   } else {
   3732     // If -fmessage-length=N was not specified, determine whether this is a
   3733     // terminal and, if so, implicitly define -fmessage-length appropriately.
   3734     unsigned N = llvm::sys::Process::StandardErrColumns();
   3735     CmdArgs.push_back(Args.MakeArgString(Twine(N)));
   3736   }
   3737 
   3738   // -fvisibility= and -fvisibility-ms-compat are of a piece.
   3739   if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
   3740                                      options::OPT_fvisibility_ms_compat)) {
   3741     if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
   3742       CmdArgs.push_back("-fvisibility");
   3743       CmdArgs.push_back(A->getValue());
   3744     } else {
   3745       assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
   3746       CmdArgs.push_back("-fvisibility");
   3747       CmdArgs.push_back("hidden");
   3748       CmdArgs.push_back("-ftype-visibility");
   3749       CmdArgs.push_back("default");
   3750     }
   3751   }
   3752 
   3753   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
   3754 
   3755   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
   3756 
   3757   // -fhosted is default.
   3758   if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
   3759       KernelOrKext)
   3760     CmdArgs.push_back("-ffreestanding");
   3761 
   3762   // Forward -f (flag) options which we can pass directly.
   3763   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
   3764   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
   3765   Args.AddLastArg(CmdArgs, options::OPT_fstandalone_debug);
   3766   Args.AddLastArg(CmdArgs, options::OPT_fno_standalone_debug);
   3767   Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
   3768   // AltiVec language extensions aren't relevant for assembling.
   3769   if (!isa<PreprocessJobAction>(JA) ||
   3770       Output.getType() != types::TY_PP_Asm)
   3771     Args.AddLastArg(CmdArgs, options::OPT_faltivec);
   3772   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
   3773   Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
   3774 
   3775   const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
   3776   Sanitize.addArgs(Args, CmdArgs);
   3777 
   3778   // Report an error for -faltivec on anything other than PowerPC.
   3779   if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
   3780     if (!(getToolChain().getArch() == llvm::Triple::ppc ||
   3781           getToolChain().getArch() == llvm::Triple::ppc64 ||
   3782           getToolChain().getArch() == llvm::Triple::ppc64le))
   3783       D.Diag(diag::err_drv_argument_only_allowed_with)
   3784         << A->getAsString(Args) << "ppc/ppc64/ppc64le";
   3785 
   3786   if (getToolChain().SupportsProfiling())
   3787     Args.AddLastArg(CmdArgs, options::OPT_pg);
   3788 
   3789   // -flax-vector-conversions is default.
   3790   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
   3791                     options::OPT_fno_lax_vector_conversions))
   3792     CmdArgs.push_back("-fno-lax-vector-conversions");
   3793 
   3794   if (Args.getLastArg(options::OPT_fapple_kext))
   3795     CmdArgs.push_back("-fapple-kext");
   3796 
   3797   Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
   3798   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
   3799   Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
   3800   Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
   3801   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
   3802 
   3803   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
   3804     CmdArgs.push_back("-ftrapv-handler");
   3805     CmdArgs.push_back(A->getValue());
   3806   }
   3807 
   3808   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
   3809 
   3810   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
   3811   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
   3812   if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
   3813                                options::OPT_fno_wrapv)) {
   3814     if (A->getOption().matches(options::OPT_fwrapv))
   3815       CmdArgs.push_back("-fwrapv");
   3816   } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
   3817                                       options::OPT_fno_strict_overflow)) {
   3818     if (A->getOption().matches(options::OPT_fno_strict_overflow))
   3819       CmdArgs.push_back("-fwrapv");
   3820   }
   3821 
   3822   if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
   3823                                options::OPT_fno_reroll_loops))
   3824     if (A->getOption().matches(options::OPT_freroll_loops))
   3825       CmdArgs.push_back("-freroll-loops");
   3826 
   3827   Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
   3828   Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
   3829                   options::OPT_fno_unroll_loops);
   3830 
   3831   Args.AddLastArg(CmdArgs, options::OPT_pthread);
   3832 
   3833 
   3834   // -stack-protector=0 is default.
   3835   unsigned StackProtectorLevel = 0;
   3836   if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
   3837                                options::OPT_fstack_protector_all,
   3838                                options::OPT_fstack_protector_strong,
   3839                                options::OPT_fstack_protector)) {
   3840     if (A->getOption().matches(options::OPT_fstack_protector)) {
   3841       StackProtectorLevel = std::max<unsigned>(LangOptions::SSPOn,
   3842         getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
   3843     } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
   3844       StackProtectorLevel = LangOptions::SSPStrong;
   3845     else if (A->getOption().matches(options::OPT_fstack_protector_all))
   3846       StackProtectorLevel = LangOptions::SSPReq;
   3847   } else {
   3848     StackProtectorLevel =
   3849       getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
   3850   }
   3851   if (StackProtectorLevel) {
   3852     CmdArgs.push_back("-stack-protector");
   3853     CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
   3854   }
   3855 
   3856   // --param ssp-buffer-size=
   3857   for (arg_iterator it = Args.filtered_begin(options::OPT__param),
   3858        ie = Args.filtered_end(); it != ie; ++it) {
   3859     StringRef Str((*it)->getValue());
   3860     if (Str.startswith("ssp-buffer-size=")) {
   3861       if (StackProtectorLevel) {
   3862         CmdArgs.push_back("-stack-protector-buffer-size");
   3863         // FIXME: Verify the argument is a valid integer.
   3864         CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
   3865       }
   3866       (*it)->claim();
   3867     }
   3868   }
   3869 
   3870   // Translate -mstackrealign
   3871   if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
   3872                    false)) {
   3873     CmdArgs.push_back("-backend-option");
   3874     CmdArgs.push_back("-force-align-stack");
   3875   }
   3876   if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
   3877                    false)) {
   3878     CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
   3879   }
   3880 
   3881   if (Args.hasArg(options::OPT_mstack_alignment)) {
   3882     StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
   3883     CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
   3884   }
   3885 
   3886   if (Args.hasArg(options::OPT_mstack_probe_size)) {
   3887     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
   3888 
   3889     if (!Size.empty())
   3890       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
   3891     else
   3892       CmdArgs.push_back("-mstack-probe-size=0");
   3893   }
   3894 
   3895   if (getToolChain().getTriple().getArch() == llvm::Triple::aarch64 ||
   3896       getToolChain().getTriple().getArch() == llvm::Triple::aarch64_be)
   3897     CmdArgs.push_back("-fallow-half-arguments-and-returns");
   3898 
   3899   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
   3900                                options::OPT_mno_restrict_it)) {
   3901     if (A->getOption().matches(options::OPT_mrestrict_it)) {
   3902       CmdArgs.push_back("-backend-option");
   3903       CmdArgs.push_back("-arm-restrict-it");
   3904     } else {
   3905       CmdArgs.push_back("-backend-option");
   3906       CmdArgs.push_back("-arm-no-restrict-it");
   3907     }
   3908   } else if (TT.isOSWindows() && (TT.getArch() == llvm::Triple::arm ||
   3909                                   TT.getArch() == llvm::Triple::thumb)) {
   3910     // Windows on ARM expects restricted IT blocks
   3911     CmdArgs.push_back("-backend-option");
   3912     CmdArgs.push_back("-arm-restrict-it");
   3913   }
   3914 
   3915   if (TT.getArch() == llvm::Triple::arm ||
   3916       TT.getArch() == llvm::Triple::thumb) {
   3917     if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
   3918                                  options::OPT_mno_long_calls)) {
   3919       if (A->getOption().matches(options::OPT_mlong_calls)) {
   3920         CmdArgs.push_back("-backend-option");
   3921         CmdArgs.push_back("-arm-long-calls");
   3922       }
   3923     }
   3924   }
   3925 
   3926   // Forward -f options with positive and negative forms; we translate
   3927   // these by hand.
   3928   if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
   3929     StringRef fname = A->getValue();
   3930     if (!llvm::sys::fs::exists(fname))
   3931       D.Diag(diag::err_drv_no_such_file) << fname;
   3932     else
   3933       A->render(Args, CmdArgs);
   3934   }
   3935 
   3936   if (Args.hasArg(options::OPT_mkernel)) {
   3937     if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
   3938       CmdArgs.push_back("-fapple-kext");
   3939     if (!Args.hasArg(options::OPT_fbuiltin))
   3940       CmdArgs.push_back("-fno-builtin");
   3941     Args.ClaimAllArgs(options::OPT_fno_builtin);
   3942   }
   3943   // -fbuiltin is default.
   3944   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
   3945     CmdArgs.push_back("-fno-builtin");
   3946 
   3947   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
   3948                     options::OPT_fno_assume_sane_operator_new))
   3949     CmdArgs.push_back("-fno-assume-sane-operator-new");
   3950 
   3951   // -fblocks=0 is default.
   3952   if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
   3953                    getToolChain().IsBlocksDefault()) ||
   3954         (Args.hasArg(options::OPT_fgnu_runtime) &&
   3955          Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
   3956          !Args.hasArg(options::OPT_fno_blocks))) {
   3957     CmdArgs.push_back("-fblocks");
   3958 
   3959     if (!Args.hasArg(options::OPT_fgnu_runtime) &&
   3960         !getToolChain().hasBlocksRuntime())
   3961       CmdArgs.push_back("-fblocks-runtime-optional");
   3962   }
   3963 
   3964   // -fmodules enables modules (off by default).
   3965   // Users can pass -fno-cxx-modules to turn off modules support for
   3966   // C++/Objective-C++ programs, which is a little less mature.
   3967   bool HaveModules = false;
   3968   if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
   3969     bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
   3970                                      options::OPT_fno_cxx_modules,
   3971                                      true);
   3972     if (AllowedInCXX || !types::isCXX(InputType)) {
   3973       CmdArgs.push_back("-fmodules");
   3974       HaveModules = true;
   3975     }
   3976   }
   3977 
   3978   // -fmodule-maps enables module map processing (off by default) for header
   3979   // checking.  It is implied by -fmodules.
   3980   if (Args.hasFlag(options::OPT_fmodule_maps, options::OPT_fno_module_maps,
   3981                    false)) {
   3982     CmdArgs.push_back("-fmodule-maps");
   3983   }
   3984 
   3985   // -fmodules-decluse checks that modules used are declared so (off by
   3986   // default).
   3987   if (Args.hasFlag(options::OPT_fmodules_decluse,
   3988                    options::OPT_fno_modules_decluse,
   3989                    false)) {
   3990     CmdArgs.push_back("-fmodules-decluse");
   3991   }
   3992 
   3993   // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
   3994   // all #included headers are part of modules.
   3995   if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
   3996                    options::OPT_fno_modules_strict_decluse,
   3997                    false)) {
   3998     CmdArgs.push_back("-fmodules-strict-decluse");
   3999   }
   4000 
   4001   // -fno-implicit-modules turns off implicitly compiling modules on demand.
   4002   if (!Args.hasFlag(options::OPT_fimplicit_modules,
   4003                     options::OPT_fno_implicit_modules)) {
   4004     CmdArgs.push_back("-fno-implicit-modules");
   4005   }
   4006 
   4007   // -fmodule-name specifies the module that is currently being built (or
   4008   // used for header checking by -fmodule-maps).
   4009   Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
   4010 
   4011   // -fmodule-map-file can be used to specify files containing module
   4012   // definitions.
   4013   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
   4014 
   4015   // -fmodule-file can be used to specify files containing precompiled modules.
   4016   Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
   4017 
   4018   // -fmodule-cache-path specifies where our implicitly-built module files
   4019   // should be written.
   4020   SmallString<128> ModuleCachePath;
   4021   if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
   4022     ModuleCachePath = A->getValue();
   4023   if (HaveModules) {
   4024     if (C.isForDiagnostics()) {
   4025       // When generating crash reports, we want to emit the modules along with
   4026       // the reproduction sources, so we ignore any provided module path.
   4027       ModuleCachePath = Output.getFilename();
   4028       llvm::sys::path::replace_extension(ModuleCachePath, ".cache");
   4029       llvm::sys::path::append(ModuleCachePath, "modules");
   4030     } else if (ModuleCachePath.empty()) {
   4031       // No module path was provided: use the default.
   4032       llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
   4033                                              ModuleCachePath);
   4034       llvm::sys::path::append(ModuleCachePath, "org.llvm.clang.");
   4035       appendUserToPath(ModuleCachePath);
   4036       llvm::sys::path::append(ModuleCachePath, "ModuleCache");
   4037     }
   4038     const char Arg[] = "-fmodules-cache-path=";
   4039     ModuleCachePath.insert(ModuleCachePath.begin(), Arg, Arg + strlen(Arg));
   4040     CmdArgs.push_back(Args.MakeArgString(ModuleCachePath));
   4041   }
   4042 
   4043   // When building modules and generating crashdumps, we need to dump a module
   4044   // dependency VFS alongside the output.
   4045   if (HaveModules && C.isForDiagnostics()) {
   4046     SmallString<128> VFSDir(Output.getFilename());
   4047     llvm::sys::path::replace_extension(VFSDir, ".cache");
   4048     // Add the cache directory as a temp so the crash diagnostics pick it up.
   4049     C.addTempFile(Args.MakeArgString(VFSDir));
   4050 
   4051     llvm::sys::path::append(VFSDir, "vfs");
   4052     CmdArgs.push_back("-module-dependency-dir");
   4053     CmdArgs.push_back(Args.MakeArgString(VFSDir));
   4054   }
   4055 
   4056   if (HaveModules)
   4057     Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
   4058 
   4059   // Pass through all -fmodules-ignore-macro arguments.
   4060   Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
   4061   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
   4062   Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
   4063 
   4064   Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
   4065 
   4066   if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
   4067     if (Args.hasArg(options::OPT_fbuild_session_timestamp))
   4068       D.Diag(diag::err_drv_argument_not_allowed_with)
   4069           << A->getAsString(Args) << "-fbuild-session-timestamp";
   4070 
   4071     llvm::sys::fs::file_status Status;
   4072     if (llvm::sys::fs::status(A->getValue(), Status))
   4073       D.Diag(diag::err_drv_no_such_file) << A->getValue();
   4074     CmdArgs.push_back(Args.MakeArgString(
   4075         "-fbuild-session-timestamp=" +
   4076         Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
   4077   }
   4078 
   4079   if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
   4080     if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
   4081                          options::OPT_fbuild_session_file))
   4082       D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
   4083 
   4084     Args.AddLastArg(CmdArgs,
   4085                     options::OPT_fmodules_validate_once_per_build_session);
   4086   }
   4087 
   4088   Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
   4089 
   4090   // -faccess-control is default.
   4091   if (Args.hasFlag(options::OPT_fno_access_control,
   4092                    options::OPT_faccess_control,
   4093                    false))
   4094     CmdArgs.push_back("-fno-access-control");
   4095 
   4096   // -felide-constructors is the default.
   4097   if (Args.hasFlag(options::OPT_fno_elide_constructors,
   4098                    options::OPT_felide_constructors,
   4099                    false))
   4100     CmdArgs.push_back("-fno-elide-constructors");
   4101 
   4102   ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
   4103 
   4104   if (KernelOrKext || (types::isCXX(InputType) &&
   4105                        (RTTIMode == ToolChain::RM_DisabledExplicitly ||
   4106                         RTTIMode == ToolChain::RM_DisabledImplicitly)))
   4107     CmdArgs.push_back("-fno-rtti");
   4108 
   4109   // -fshort-enums=0 is default for all architectures except Hexagon.
   4110   if (Args.hasFlag(options::OPT_fshort_enums,
   4111                    options::OPT_fno_short_enums,
   4112                    getToolChain().getArch() ==
   4113                    llvm::Triple::hexagon))
   4114     CmdArgs.push_back("-fshort-enums");
   4115 
   4116   // -fsigned-char is default.
   4117   if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
   4118                     isSignedCharDefault(getToolChain().getTriple())))
   4119     CmdArgs.push_back("-fno-signed-char");
   4120 
   4121   // -fuse-cxa-atexit is default.
   4122   if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
   4123                     options::OPT_fno_use_cxa_atexit,
   4124                     !IsWindowsCygnus && !IsWindowsGNU &&
   4125                     getToolChain().getArch() != llvm::Triple::hexagon &&
   4126                     getToolChain().getArch() != llvm::Triple::xcore) ||
   4127       KernelOrKext)
   4128     CmdArgs.push_back("-fno-use-cxa-atexit");
   4129 
   4130   // -fms-extensions=0 is default.
   4131   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
   4132                    IsWindowsMSVC))
   4133     CmdArgs.push_back("-fms-extensions");
   4134 
   4135   // -fno-use-line-directives is default.
   4136   if (Args.hasFlag(options::OPT_fuse_line_directives,
   4137                    options::OPT_fno_use_line_directives, false))
   4138     CmdArgs.push_back("-fuse-line-directives");
   4139 
   4140   // -fms-compatibility=0 is default.
   4141   if (Args.hasFlag(options::OPT_fms_compatibility,
   4142                    options::OPT_fno_ms_compatibility,
   4143                    (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
   4144                                                   options::OPT_fno_ms_extensions,
   4145                                                   true))))
   4146     CmdArgs.push_back("-fms-compatibility");
   4147 
   4148   // -fms-compatibility-version=18.00 is default.
   4149   VersionTuple MSVT;
   4150   if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
   4151                    IsWindowsMSVC) ||
   4152       Args.hasArg(options::OPT_fmsc_version) ||
   4153       Args.hasArg(options::OPT_fms_compatibility_version)) {
   4154     const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
   4155     const Arg *MSCompatibilityVersion =
   4156       Args.getLastArg(options::OPT_fms_compatibility_version);
   4157 
   4158     if (MSCVersion && MSCompatibilityVersion)
   4159       D.Diag(diag::err_drv_argument_not_allowed_with)
   4160           << MSCVersion->getAsString(Args)
   4161           << MSCompatibilityVersion->getAsString(Args);
   4162 
   4163     if (MSCompatibilityVersion) {
   4164       if (MSVT.tryParse(MSCompatibilityVersion->getValue()))
   4165         D.Diag(diag::err_drv_invalid_value)
   4166             << MSCompatibilityVersion->getAsString(Args)
   4167             << MSCompatibilityVersion->getValue();
   4168     } else if (MSCVersion) {
   4169       unsigned Version = 0;
   4170       if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version))
   4171         D.Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
   4172                                             << MSCVersion->getValue();
   4173       MSVT = getMSCompatibilityVersion(Version);
   4174     } else {
   4175       MSVT = VersionTuple(18);
   4176     }
   4177 
   4178     CmdArgs.push_back(
   4179         Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
   4180   }
   4181 
   4182   // -fno-borland-extensions is default.
   4183   if (Args.hasFlag(options::OPT_fborland_extensions,
   4184                    options::OPT_fno_borland_extensions, false))
   4185     CmdArgs.push_back("-fborland-extensions");
   4186 
   4187   // -fthreadsafe-static is default, except for MSVC compatibility versions less
   4188   // than 19.
   4189   if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
   4190                     options::OPT_fno_threadsafe_statics,
   4191                     !IsWindowsMSVC || MSVT.getMajor() >= 19))
   4192     CmdArgs.push_back("-fno-threadsafe-statics");
   4193 
   4194   // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
   4195   // needs it.
   4196   if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
   4197                    options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
   4198     CmdArgs.push_back("-fdelayed-template-parsing");
   4199 
   4200   // -fgnu-keywords default varies depending on language; only pass if
   4201   // specified.
   4202   if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
   4203                                options::OPT_fno_gnu_keywords))
   4204     A->render(Args, CmdArgs);
   4205 
   4206   if (Args.hasFlag(options::OPT_fgnu89_inline,
   4207                    options::OPT_fno_gnu89_inline,
   4208                    false))
   4209     CmdArgs.push_back("-fgnu89-inline");
   4210 
   4211   if (Args.hasArg(options::OPT_fno_inline))
   4212     CmdArgs.push_back("-fno-inline");
   4213 
   4214   if (Args.hasArg(options::OPT_fno_inline_functions))
   4215     CmdArgs.push_back("-fno-inline-functions");
   4216 
   4217   ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
   4218 
   4219   // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
   4220   // legacy is the default. Except for deployment taget of 10.5,
   4221   // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
   4222   // gets ignored silently.
   4223   if (objcRuntime.isNonFragile()) {
   4224     if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
   4225                       options::OPT_fno_objc_legacy_dispatch,
   4226                       objcRuntime.isLegacyDispatchDefaultForArch(
   4227                         getToolChain().getArch()))) {
   4228       if (getToolChain().UseObjCMixedDispatch())
   4229         CmdArgs.push_back("-fobjc-dispatch-method=mixed");
   4230       else
   4231         CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
   4232     }
   4233   }
   4234 
   4235   // When ObjectiveC legacy runtime is in effect on MacOSX,
   4236   // turn on the option to do Array/Dictionary subscripting
   4237   // by default.
   4238   if (getToolChain().getTriple().getArch() == llvm::Triple::x86 &&
   4239       getToolChain().getTriple().isMacOSX() &&
   4240       !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
   4241       objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
   4242       objcRuntime.isNeXTFamily())
   4243     CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
   4244 
   4245   // -fencode-extended-block-signature=1 is default.
   4246   if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
   4247     CmdArgs.push_back("-fencode-extended-block-signature");
   4248   }
   4249 
   4250   // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
   4251   // NOTE: This logic is duplicated in ToolChains.cpp.
   4252   bool ARC = isObjCAutoRefCount(Args);
   4253   if (ARC) {
   4254     getToolChain().CheckObjCARC();
   4255 
   4256     CmdArgs.push_back("-fobjc-arc");
   4257 
   4258     // FIXME: It seems like this entire block, and several around it should be
   4259     // wrapped in isObjC, but for now we just use it here as this is where it
   4260     // was being used previously.
   4261     if (types::isCXX(InputType) && types::isObjC(InputType)) {
   4262       if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
   4263         CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
   4264       else
   4265         CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
   4266     }
   4267 
   4268     // Allow the user to enable full exceptions code emission.
   4269     // We define off for Objective-CC, on for Objective-C++.
   4270     if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
   4271                      options::OPT_fno_objc_arc_exceptions,
   4272                      /*default*/ types::isCXX(InputType)))
   4273       CmdArgs.push_back("-fobjc-arc-exceptions");
   4274   }
   4275 
   4276   // -fobjc-infer-related-result-type is the default, except in the Objective-C
   4277   // rewriter.
   4278   if (rewriteKind != RK_None)
   4279     CmdArgs.push_back("-fno-objc-infer-related-result-type");
   4280 
   4281   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
   4282   // takes precedence.
   4283   const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
   4284   if (!GCArg)
   4285     GCArg = Args.getLastArg(options::OPT_fobjc_gc);
   4286   if (GCArg) {
   4287     if (ARC) {
   4288       D.Diag(diag::err_drv_objc_gc_arr)
   4289         << GCArg->getAsString(Args);
   4290     } else if (getToolChain().SupportsObjCGC()) {
   4291       GCArg->render(Args, CmdArgs);
   4292     } else {
   4293       // FIXME: We should move this to a hard error.
   4294       D.Diag(diag::warn_drv_objc_gc_unsupported)
   4295         << GCArg->getAsString(Args);
   4296     }
   4297   }
   4298 
   4299   if (Args.hasFlag(options::OPT_fapplication_extension,
   4300                    options::OPT_fno_application_extension, false))
   4301     CmdArgs.push_back("-fapplication-extension");
   4302 
   4303   // Handle GCC-style exception args.
   4304   if (!C.getDriver().IsCLMode())
   4305     addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext,
   4306                      objcRuntime, CmdArgs);
   4307 
   4308   if (getToolChain().UseSjLjExceptions())
   4309     CmdArgs.push_back("-fsjlj-exceptions");
   4310 
   4311   // C++ "sane" operator new.
   4312   if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
   4313                     options::OPT_fno_assume_sane_operator_new))
   4314     CmdArgs.push_back("-fno-assume-sane-operator-new");
   4315 
   4316   // -fsized-deallocation is off by default, as it is an ABI-breaking change for
   4317   // most platforms.
   4318   if (Args.hasFlag(options::OPT_fsized_deallocation,
   4319                    options::OPT_fno_sized_deallocation, false))
   4320     CmdArgs.push_back("-fsized-deallocation");
   4321 
   4322   // -fconstant-cfstrings is default, and may be subject to argument translation
   4323   // on Darwin.
   4324   if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
   4325                     options::OPT_fno_constant_cfstrings) ||
   4326       !Args.hasFlag(options::OPT_mconstant_cfstrings,
   4327                     options::OPT_mno_constant_cfstrings))
   4328     CmdArgs.push_back("-fno-constant-cfstrings");
   4329 
   4330   // -fshort-wchar default varies depending on platform; only
   4331   // pass if specified.
   4332   if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
   4333                                options::OPT_fno_short_wchar))
   4334     A->render(Args, CmdArgs);
   4335 
   4336   // -fno-pascal-strings is default, only pass non-default.
   4337   if (Args.hasFlag(options::OPT_fpascal_strings,
   4338                    options::OPT_fno_pascal_strings,
   4339                    false))
   4340     CmdArgs.push_back("-fpascal-strings");
   4341 
   4342   // Honor -fpack-struct= and -fpack-struct, if given. Note that
   4343   // -fno-pack-struct doesn't apply to -fpack-struct=.
   4344   if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
   4345     std::string PackStructStr = "-fpack-struct=";
   4346     PackStructStr += A->getValue();
   4347     CmdArgs.push_back(Args.MakeArgString(PackStructStr));
   4348   } else if (Args.hasFlag(options::OPT_fpack_struct,
   4349                           options::OPT_fno_pack_struct, false)) {
   4350     CmdArgs.push_back("-fpack-struct=1");
   4351   }
   4352 
   4353   // Handle -fmax-type-align=N and -fno-type-align
   4354   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
   4355   if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
   4356     if (!SkipMaxTypeAlign) {
   4357       std::string MaxTypeAlignStr = "-fmax-type-align=";
   4358       MaxTypeAlignStr += A->getValue();
   4359       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
   4360     }
   4361   } else if (getToolChain().getTriple().isOSDarwin()) {
   4362     if (!SkipMaxTypeAlign) {
   4363       std::string MaxTypeAlignStr = "-fmax-type-align=16";
   4364       CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
   4365     }
   4366   }
   4367 
   4368   if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
   4369     if (!Args.hasArg(options::OPT_fcommon))
   4370       CmdArgs.push_back("-fno-common");
   4371     Args.ClaimAllArgs(options::OPT_fno_common);
   4372   }
   4373 
   4374   // -fcommon is default, only pass non-default.
   4375   else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
   4376     CmdArgs.push_back("-fno-common");
   4377 
   4378   // -fsigned-bitfields is default, and clang doesn't yet support
   4379   // -funsigned-bitfields.
   4380   if (!Args.hasFlag(options::OPT_fsigned_bitfields,
   4381                     options::OPT_funsigned_bitfields))
   4382     D.Diag(diag::warn_drv_clang_unsupported)
   4383       << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
   4384 
   4385   // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
   4386   if (!Args.hasFlag(options::OPT_ffor_scope,
   4387                     options::OPT_fno_for_scope))
   4388     D.Diag(diag::err_drv_clang_unsupported)
   4389       << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
   4390 
   4391   // -finput_charset=UTF-8 is default. Reject others
   4392   if (Arg *inputCharset = Args.getLastArg(
   4393           options::OPT_finput_charset_EQ)) {
   4394       StringRef value = inputCharset->getValue();
   4395       if (value != "UTF-8")
   4396           D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) << value;
   4397   }
   4398 
   4399   // -fexec_charset=UTF-8 is default. Reject others
   4400   if (Arg *execCharset = Args.getLastArg(
   4401           options::OPT_fexec_charset_EQ)) {
   4402       StringRef value = execCharset->getValue();
   4403       if (value != "UTF-8")
   4404           D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args) << value;
   4405   }
   4406 
   4407   // -fcaret-diagnostics is default.
   4408   if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
   4409                     options::OPT_fno_caret_diagnostics, true))
   4410     CmdArgs.push_back("-fno-caret-diagnostics");
   4411 
   4412   // -fdiagnostics-fixit-info is default, only pass non-default.
   4413   if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
   4414                     options::OPT_fno_diagnostics_fixit_info))
   4415     CmdArgs.push_back("-fno-diagnostics-fixit-info");
   4416 
   4417   // Enable -fdiagnostics-show-option by default.
   4418   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
   4419                    options::OPT_fno_diagnostics_show_option))
   4420     CmdArgs.push_back("-fdiagnostics-show-option");
   4421 
   4422   if (const Arg *A =
   4423         Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
   4424     CmdArgs.push_back("-fdiagnostics-show-category");
   4425     CmdArgs.push_back(A->getValue());
   4426   }
   4427 
   4428   if (const Arg *A =
   4429         Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
   4430     CmdArgs.push_back("-fdiagnostics-format");
   4431     CmdArgs.push_back(A->getValue());
   4432   }
   4433 
   4434   if (Arg *A = Args.getLastArg(
   4435       options::OPT_fdiagnostics_show_note_include_stack,
   4436       options::OPT_fno_diagnostics_show_note_include_stack)) {
   4437     if (A->getOption().matches(
   4438         options::OPT_fdiagnostics_show_note_include_stack))
   4439       CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
   4440     else
   4441       CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
   4442   }
   4443 
   4444   // Color diagnostics are the default, unless the terminal doesn't support
   4445   // them.
   4446   // Support both clang's -f[no-]color-diagnostics and gcc's
   4447   // -f[no-]diagnostics-colors[=never|always|auto].
   4448   enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
   4449   for (const auto &Arg : Args) {
   4450     const Option &O = Arg->getOption();
   4451     if (!O.matches(options::OPT_fcolor_diagnostics) &&
   4452         !O.matches(options::OPT_fdiagnostics_color) &&
   4453         !O.matches(options::OPT_fno_color_diagnostics) &&
   4454         !O.matches(options::OPT_fno_diagnostics_color) &&
   4455         !O.matches(options::OPT_fdiagnostics_color_EQ))
   4456       continue;
   4457 
   4458     Arg->claim();
   4459     if (O.matches(options::OPT_fcolor_diagnostics) ||
   4460         O.matches(options::OPT_fdiagnostics_color)) {
   4461       ShowColors = Colors_On;
   4462     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
   4463                O.matches(options::OPT_fno_diagnostics_color)) {
   4464       ShowColors = Colors_Off;
   4465     } else {
   4466       assert(O.matches(options::OPT_fdiagnostics_color_EQ));
   4467       StringRef value(Arg->getValue());
   4468       if (value == "always")
   4469         ShowColors = Colors_On;
   4470       else if (value == "never")
   4471         ShowColors = Colors_Off;
   4472       else if (value == "auto")
   4473         ShowColors = Colors_Auto;
   4474       else
   4475         getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
   4476           << ("-fdiagnostics-color=" + value).str();
   4477     }
   4478   }
   4479   if (ShowColors == Colors_On ||
   4480       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
   4481     CmdArgs.push_back("-fcolor-diagnostics");
   4482 
   4483   if (Args.hasArg(options::OPT_fansi_escape_codes))
   4484     CmdArgs.push_back("-fansi-escape-codes");
   4485 
   4486   if (!Args.hasFlag(options::OPT_fshow_source_location,
   4487                     options::OPT_fno_show_source_location))
   4488     CmdArgs.push_back("-fno-show-source-location");
   4489 
   4490   if (!Args.hasFlag(options::OPT_fshow_column,
   4491                     options::OPT_fno_show_column,
   4492                     true))
   4493     CmdArgs.push_back("-fno-show-column");
   4494 
   4495   if (!Args.hasFlag(options::OPT_fspell_checking,
   4496                     options::OPT_fno_spell_checking))
   4497     CmdArgs.push_back("-fno-spell-checking");
   4498 
   4499 
   4500   // -fno-asm-blocks is default.
   4501   if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
   4502                    false))
   4503     CmdArgs.push_back("-fasm-blocks");
   4504 
   4505   // -fgnu-inline-asm is default.
   4506   if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
   4507                     options::OPT_fno_gnu_inline_asm, true))
   4508     CmdArgs.push_back("-fno-gnu-inline-asm");
   4509 
   4510   // Enable vectorization per default according to the optimization level
   4511   // selected. For optimization levels that want vectorization we use the alias
   4512   // option to simplify the hasFlag logic.
   4513   bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
   4514   OptSpecifier VectorizeAliasOption = EnableVec ? options::OPT_O_Group :
   4515     options::OPT_fvectorize;
   4516   if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
   4517                    options::OPT_fno_vectorize, EnableVec))
   4518     CmdArgs.push_back("-vectorize-loops");
   4519 
   4520   // -fslp-vectorize is enabled based on the optimization level selected.
   4521   bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
   4522   OptSpecifier SLPVectAliasOption = EnableSLPVec ? options::OPT_O_Group :
   4523     options::OPT_fslp_vectorize;
   4524   if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
   4525                    options::OPT_fno_slp_vectorize, EnableSLPVec))
   4526     CmdArgs.push_back("-vectorize-slp");
   4527 
   4528   // -fno-slp-vectorize-aggressive is default.
   4529   if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
   4530                    options::OPT_fno_slp_vectorize_aggressive, false))
   4531     CmdArgs.push_back("-vectorize-slp-aggressive");
   4532 
   4533   if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
   4534     A->render(Args, CmdArgs);
   4535 
   4536   // -fdollars-in-identifiers default varies depending on platform and
   4537   // language; only pass if specified.
   4538   if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
   4539                                options::OPT_fno_dollars_in_identifiers)) {
   4540     if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
   4541       CmdArgs.push_back("-fdollars-in-identifiers");
   4542     else
   4543       CmdArgs.push_back("-fno-dollars-in-identifiers");
   4544   }
   4545 
   4546   // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
   4547   // practical purposes.
   4548   if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
   4549                                options::OPT_fno_unit_at_a_time)) {
   4550     if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
   4551       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
   4552   }
   4553 
   4554   if (Args.hasFlag(options::OPT_fapple_pragma_pack,
   4555                    options::OPT_fno_apple_pragma_pack, false))
   4556     CmdArgs.push_back("-fapple-pragma-pack");
   4557 
   4558   // le32-specific flags:
   4559   //  -fno-math-builtin: clang should not convert math builtins to intrinsics
   4560   //                     by default.
   4561   if (getToolChain().getArch() == llvm::Triple::le32) {
   4562     CmdArgs.push_back("-fno-math-builtin");
   4563   }
   4564 
   4565   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
   4566   //
   4567   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
   4568 #if 0
   4569   if (getToolChain().getTriple().isOSDarwin() &&
   4570       (getToolChain().getArch() == llvm::Triple::arm ||
   4571        getToolChain().getArch() == llvm::Triple::thumb)) {
   4572     if (!Args.hasArg(options::OPT_fbuiltin_strcat))
   4573       CmdArgs.push_back("-fno-builtin-strcat");
   4574     if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
   4575       CmdArgs.push_back("-fno-builtin-strcpy");
   4576   }
   4577 #endif
   4578 
   4579   // Enable rewrite includes if the user's asked for it or if we're generating
   4580   // diagnostics.
   4581   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
   4582   // nice to enable this when doing a crashdump for modules as well.
   4583   if (Args.hasFlag(options::OPT_frewrite_includes,
   4584                    options::OPT_fno_rewrite_includes, false) ||
   4585       (C.isForDiagnostics() && !HaveModules))
   4586     CmdArgs.push_back("-frewrite-includes");
   4587 
   4588   // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
   4589   if (Arg *A = Args.getLastArg(options::OPT_traditional,
   4590                                options::OPT_traditional_cpp)) {
   4591     if (isa<PreprocessJobAction>(JA))
   4592       CmdArgs.push_back("-traditional-cpp");
   4593     else
   4594       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
   4595   }
   4596 
   4597   Args.AddLastArg(CmdArgs, options::OPT_dM);
   4598   Args.AddLastArg(CmdArgs, options::OPT_dD);
   4599 
   4600   // Handle serialized diagnostics.
   4601   if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
   4602     CmdArgs.push_back("-serialize-diagnostic-file");
   4603     CmdArgs.push_back(Args.MakeArgString(A->getValue()));
   4604   }
   4605 
   4606   if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
   4607     CmdArgs.push_back("-fretain-comments-from-system-headers");
   4608 
   4609   // Forward -fcomment-block-commands to -cc1.
   4610   Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
   4611   // Forward -fparse-all-comments to -cc1.
   4612   Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
   4613 
   4614   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
   4615   // parser.
   4616   Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
   4617   bool OptDisabled = false;
   4618   for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
   4619          ie = Args.filtered_end(); it != ie; ++it) {
   4620     (*it)->claim();
   4621 
   4622     // We translate this by hand to the -cc1 argument, since nightly test uses
   4623     // it and developers have been trained to spell it with -mllvm.
   4624     if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns") {
   4625       CmdArgs.push_back("-disable-llvm-optzns");
   4626       OptDisabled = true;
   4627     } else
   4628       (*it)->render(Args, CmdArgs);
   4629   }
   4630 
   4631   // With -save-temps, we want to save the unoptimized bitcode output from the
   4632   // CompileJobAction, so disable optimizations if they are not already
   4633   // disabled.
   4634   if (C.getDriver().isSaveTempsEnabled() && !OptDisabled &&
   4635       isa<CompileJobAction>(JA))
   4636     CmdArgs.push_back("-disable-llvm-optzns");
   4637 
   4638   if (Output.getType() == types::TY_Dependencies) {
   4639     // Handled with other dependency code.
   4640   } else if (Output.isFilename()) {
   4641     CmdArgs.push_back("-o");
   4642     CmdArgs.push_back(Output.getFilename());
   4643   } else {
   4644     assert(Output.isNothing() && "Invalid output.");
   4645   }
   4646 
   4647   for (const auto &II : Inputs) {
   4648     addDashXForInput(Args, II, CmdArgs);
   4649 
   4650     if (II.isFilename())
   4651       CmdArgs.push_back(II.getFilename());
   4652     else
   4653       II.getInputArg().renderAsInput(Args, CmdArgs);
   4654   }
   4655 
   4656   Args.AddAllArgs(CmdArgs, options::OPT_undef);
   4657 
   4658   const char *Exec = getToolChain().getDriver().getClangProgramPath();
   4659 
   4660   // Optionally embed the -cc1 level arguments into the debug info, for build
   4661   // analysis.
   4662   if (getToolChain().UseDwarfDebugFlags()) {
   4663     ArgStringList OriginalArgs;
   4664     for (const auto &Arg : Args)
   4665       Arg->render(Args, OriginalArgs);
   4666 
   4667     SmallString<256> Flags;
   4668     Flags += Exec;
   4669     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
   4670       SmallString<128> EscapedArg;
   4671       EscapeSpacesAndBackslashes(OriginalArgs[i], EscapedArg);
   4672       Flags += " ";
   4673       Flags += EscapedArg;
   4674     }
   4675     CmdArgs.push_back("-dwarf-debug-flags");
   4676     CmdArgs.push_back(Args.MakeArgString(Flags));
   4677   }
   4678 
   4679   // Add the split debug info name to the command lines here so we
   4680   // can propagate it to the backend.
   4681   bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
   4682     getToolChain().getTriple().isOSLinux() &&
   4683     (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
   4684      isa<BackendJobAction>(JA));
   4685   const char *SplitDwarfOut;
   4686   if (SplitDwarf) {
   4687     CmdArgs.push_back("-split-dwarf-file");
   4688     SplitDwarfOut = SplitDebugName(Args, Inputs);
   4689     CmdArgs.push_back(SplitDwarfOut);
   4690   }
   4691 
   4692   // Finally add the compile command to the compilation.
   4693   if (Args.hasArg(options::OPT__SLASH_fallback) &&
   4694       Output.getType() == types::TY_Object &&
   4695       (InputType == types::TY_C || InputType == types::TY_CXX)) {
   4696     auto CLCommand =
   4697         getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
   4698     C.addCommand(llvm::make_unique<FallbackCommand>(JA, *this, Exec, CmdArgs,
   4699                                                     std::move(CLCommand)));
   4700   } else {
   4701     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   4702   }
   4703 
   4704 
   4705   // Handle the debug info splitting at object creation time if we're
   4706   // creating an object.
   4707   // TODO: Currently only works on linux with newer objcopy.
   4708   if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
   4709     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
   4710 
   4711   if (Arg *A = Args.getLastArg(options::OPT_pg))
   4712     if (Args.hasArg(options::OPT_fomit_frame_pointer))
   4713       D.Diag(diag::err_drv_argument_not_allowed_with)
   4714         << "-fomit-frame-pointer" << A->getAsString(Args);
   4715 
   4716   // Claim some arguments which clang supports automatically.
   4717 
   4718   // -fpch-preprocess is used with gcc to add a special marker in the output to
   4719   // include the PCH file. Clang's PTH solution is completely transparent, so we
   4720   // do not need to deal with it at all.
   4721   Args.ClaimAllArgs(options::OPT_fpch_preprocess);
   4722 
   4723   // Claim some arguments which clang doesn't support, but we don't
   4724   // care to warn the user about.
   4725   Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
   4726   Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
   4727 
   4728   // Disable warnings for clang -E -emit-llvm foo.c
   4729   Args.ClaimAllArgs(options::OPT_emit_llvm);
   4730 }
   4731 
   4732 /// Add options related to the Objective-C runtime/ABI.
   4733 ///
   4734 /// Returns true if the runtime is non-fragile.
   4735 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
   4736                                       ArgStringList &cmdArgs,
   4737                                       RewriteKind rewriteKind) const {
   4738   // Look for the controlling runtime option.
   4739   Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
   4740                                     options::OPT_fgnu_runtime,
   4741                                     options::OPT_fobjc_runtime_EQ);
   4742 
   4743   // Just forward -fobjc-runtime= to the frontend.  This supercedes
   4744   // options about fragility.
   4745   if (runtimeArg &&
   4746       runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
   4747     ObjCRuntime runtime;
   4748     StringRef value = runtimeArg->getValue();
   4749     if (runtime.tryParse(value)) {
   4750       getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
   4751         << value;
   4752     }
   4753 
   4754     runtimeArg->render(args, cmdArgs);
   4755     return runtime;
   4756   }
   4757 
   4758   // Otherwise, we'll need the ABI "version".  Version numbers are
   4759   // slightly confusing for historical reasons:
   4760   //   1 - Traditional "fragile" ABI
   4761   //   2 - Non-fragile ABI, version 1
   4762   //   3 - Non-fragile ABI, version 2
   4763   unsigned objcABIVersion = 1;
   4764   // If -fobjc-abi-version= is present, use that to set the version.
   4765   if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
   4766     StringRef value = abiArg->getValue();
   4767     if (value == "1")
   4768       objcABIVersion = 1;
   4769     else if (value == "2")
   4770       objcABIVersion = 2;
   4771     else if (value == "3")
   4772       objcABIVersion = 3;
   4773     else
   4774       getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
   4775         << value;
   4776   } else {
   4777     // Otherwise, determine if we are using the non-fragile ABI.
   4778     bool nonFragileABIIsDefault =
   4779       (rewriteKind == RK_NonFragile ||
   4780        (rewriteKind == RK_None &&
   4781         getToolChain().IsObjCNonFragileABIDefault()));
   4782     if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
   4783                      options::OPT_fno_objc_nonfragile_abi,
   4784                      nonFragileABIIsDefault)) {
   4785       // Determine the non-fragile ABI version to use.
   4786 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
   4787       unsigned nonFragileABIVersion = 1;
   4788 #else
   4789       unsigned nonFragileABIVersion = 2;
   4790 #endif
   4791 
   4792       if (Arg *abiArg = args.getLastArg(
   4793             options::OPT_fobjc_nonfragile_abi_version_EQ)) {
   4794         StringRef value = abiArg->getValue();
   4795         if (value == "1")
   4796           nonFragileABIVersion = 1;
   4797         else if (value == "2")
   4798           nonFragileABIVersion = 2;
   4799         else
   4800           getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
   4801             << value;
   4802       }
   4803 
   4804       objcABIVersion = 1 + nonFragileABIVersion;
   4805     } else {
   4806       objcABIVersion = 1;
   4807     }
   4808   }
   4809 
   4810   // We don't actually care about the ABI version other than whether
   4811   // it's non-fragile.
   4812   bool isNonFragile = objcABIVersion != 1;
   4813 
   4814   // If we have no runtime argument, ask the toolchain for its default runtime.
   4815   // However, the rewriter only really supports the Mac runtime, so assume that.
   4816   ObjCRuntime runtime;
   4817   if (!runtimeArg) {
   4818     switch (rewriteKind) {
   4819     case RK_None:
   4820       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
   4821       break;
   4822     case RK_Fragile:
   4823       runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
   4824       break;
   4825     case RK_NonFragile:
   4826       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
   4827       break;
   4828     }
   4829 
   4830   // -fnext-runtime
   4831   } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
   4832     // On Darwin, make this use the default behavior for the toolchain.
   4833     if (getToolChain().getTriple().isOSDarwin()) {
   4834       runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
   4835 
   4836     // Otherwise, build for a generic macosx port.
   4837     } else {
   4838       runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
   4839     }
   4840 
   4841   // -fgnu-runtime
   4842   } else {
   4843     assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
   4844     // Legacy behaviour is to target the gnustep runtime if we are i
   4845     // non-fragile mode or the GCC runtime in fragile mode.
   4846     if (isNonFragile)
   4847       runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
   4848     else
   4849       runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
   4850   }
   4851 
   4852   cmdArgs.push_back(args.MakeArgString(
   4853                                  "-fobjc-runtime=" + runtime.getAsString()));
   4854   return runtime;
   4855 }
   4856 
   4857 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
   4858   bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
   4859   I += HaveDash;
   4860   return !HaveDash;
   4861 }
   4862 
   4863 struct EHFlags {
   4864   EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
   4865   bool Synch;
   4866   bool Asynch;
   4867   bool NoExceptC;
   4868 };
   4869 
   4870 /// /EH controls whether to run destructor cleanups when exceptions are
   4871 /// thrown.  There are three modifiers:
   4872 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
   4873 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
   4874 ///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
   4875 /// - c: Assume that extern "C" functions are implicitly noexcept.  This
   4876 ///      modifier is an optimization, so we ignore it for now.
   4877 /// The default is /EHs-c-, meaning cleanups are disabled.
   4878 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
   4879   EHFlags EH;
   4880   std::vector<std::string> EHArgs = Args.getAllArgValues(options::OPT__SLASH_EH);
   4881   for (auto EHVal : EHArgs) {
   4882     for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
   4883       switch (EHVal[I]) {
   4884       case 'a': EH.Asynch = maybeConsumeDash(EHVal, I); continue;
   4885       case 'c': EH.NoExceptC = maybeConsumeDash(EHVal, I); continue;
   4886       case 's': EH.Synch = maybeConsumeDash(EHVal, I); continue;
   4887       default: break;
   4888       }
   4889       D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
   4890       break;
   4891     }
   4892   }
   4893   return EH;
   4894 }
   4895 
   4896 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
   4897   unsigned RTOptionID = options::OPT__SLASH_MT;
   4898 
   4899   if (Args.hasArg(options::OPT__SLASH_LDd))
   4900     // The /LDd option implies /MTd. The dependent lib part can be overridden,
   4901     // but defining _DEBUG is sticky.
   4902     RTOptionID = options::OPT__SLASH_MTd;
   4903 
   4904   if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
   4905     RTOptionID = A->getOption().getID();
   4906 
   4907   switch(RTOptionID) {
   4908     case options::OPT__SLASH_MD:
   4909       if (Args.hasArg(options::OPT__SLASH_LDd))
   4910         CmdArgs.push_back("-D_DEBUG");
   4911       CmdArgs.push_back("-D_MT");
   4912       CmdArgs.push_back("-D_DLL");
   4913       CmdArgs.push_back("--dependent-lib=msvcrt");
   4914       break;
   4915     case options::OPT__SLASH_MDd:
   4916       CmdArgs.push_back("-D_DEBUG");
   4917       CmdArgs.push_back("-D_MT");
   4918       CmdArgs.push_back("-D_DLL");
   4919       CmdArgs.push_back("--dependent-lib=msvcrtd");
   4920       break;
   4921     case options::OPT__SLASH_MT:
   4922       if (Args.hasArg(options::OPT__SLASH_LDd))
   4923         CmdArgs.push_back("-D_DEBUG");
   4924       CmdArgs.push_back("-D_MT");
   4925       CmdArgs.push_back("--dependent-lib=libcmt");
   4926       break;
   4927     case options::OPT__SLASH_MTd:
   4928       CmdArgs.push_back("-D_DEBUG");
   4929       CmdArgs.push_back("-D_MT");
   4930       CmdArgs.push_back("--dependent-lib=libcmtd");
   4931       break;
   4932     default:
   4933       llvm_unreachable("Unexpected option ID.");
   4934   }
   4935 
   4936   // This provides POSIX compatibility (maps 'open' to '_open'), which most
   4937   // users want.  The /Za flag to cl.exe turns this off, but it's not
   4938   // implemented in clang.
   4939   CmdArgs.push_back("--dependent-lib=oldnames");
   4940 
   4941   // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
   4942   // would produce interleaved output, so ignore /showIncludes in such cases.
   4943   if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
   4944     if (Arg *A = Args.getLastArg(options::OPT_show_includes))
   4945       A->render(Args, CmdArgs);
   4946 
   4947   // This controls whether or not we emit RTTI data for polymorphic types.
   4948   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
   4949                    /*default=*/false))
   4950     CmdArgs.push_back("-fno-rtti-data");
   4951 
   4952   const Driver &D = getToolChain().getDriver();
   4953   EHFlags EH = parseClangCLEHFlags(D, Args);
   4954   // FIXME: Do something with NoExceptC.
   4955   if (EH.Synch || EH.Asynch) {
   4956     CmdArgs.push_back("-fcxx-exceptions");
   4957     CmdArgs.push_back("-fexceptions");
   4958   }
   4959 
   4960   // /EP should expand to -E -P.
   4961   if (Args.hasArg(options::OPT__SLASH_EP)) {
   4962     CmdArgs.push_back("-E");
   4963     CmdArgs.push_back("-P");
   4964   }
   4965 
   4966   unsigned VolatileOptionID;
   4967   if (getToolChain().getTriple().getArch() == llvm::Triple::x86_64 ||
   4968       getToolChain().getTriple().getArch() == llvm::Triple::x86)
   4969     VolatileOptionID = options::OPT__SLASH_volatile_ms;
   4970   else
   4971     VolatileOptionID = options::OPT__SLASH_volatile_iso;
   4972 
   4973   if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
   4974     VolatileOptionID = A->getOption().getID();
   4975 
   4976   if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
   4977     CmdArgs.push_back("-fms-volatile");
   4978 
   4979   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
   4980   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
   4981   if (MostGeneralArg && BestCaseArg)
   4982     D.Diag(clang::diag::err_drv_argument_not_allowed_with)
   4983         << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
   4984 
   4985   if (MostGeneralArg) {
   4986     Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
   4987     Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
   4988     Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
   4989 
   4990     Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
   4991     Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
   4992     if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
   4993       D.Diag(clang::diag::err_drv_argument_not_allowed_with)
   4994           << FirstConflict->getAsString(Args)
   4995           << SecondConflict->getAsString(Args);
   4996 
   4997     if (SingleArg)
   4998       CmdArgs.push_back("-fms-memptr-rep=single");
   4999     else if (MultipleArg)
   5000       CmdArgs.push_back("-fms-memptr-rep=multiple");
   5001     else
   5002       CmdArgs.push_back("-fms-memptr-rep=virtual");
   5003   }
   5004 
   5005   if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
   5006     A->render(Args, CmdArgs);
   5007 
   5008   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
   5009     CmdArgs.push_back("-fdiagnostics-format");
   5010     if (Args.hasArg(options::OPT__SLASH_fallback))
   5011       CmdArgs.push_back("msvc-fallback");
   5012     else
   5013       CmdArgs.push_back("msvc");
   5014   }
   5015 }
   5016 
   5017 visualstudio::Compile *Clang::getCLFallback() const {
   5018   if (!CLFallback)
   5019     CLFallback.reset(new visualstudio::Compile(getToolChain()));
   5020   return CLFallback.get();
   5021 }
   5022 
   5023 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
   5024                                 ArgStringList &CmdArgs) const {
   5025   StringRef CPUName;
   5026   StringRef ABIName;
   5027   const llvm::Triple &Triple = getToolChain().getTriple();
   5028   mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
   5029 
   5030   CmdArgs.push_back("-target-abi");
   5031   CmdArgs.push_back(ABIName.data());
   5032 }
   5033 
   5034 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
   5035                            const InputInfo &Output,
   5036                            const InputInfoList &Inputs,
   5037                            const ArgList &Args,
   5038                            const char *LinkingOutput) const {
   5039   ArgStringList CmdArgs;
   5040 
   5041   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
   5042   const InputInfo &Input = Inputs[0];
   5043 
   5044   // Don't warn about "clang -w -c foo.s"
   5045   Args.ClaimAllArgs(options::OPT_w);
   5046   // and "clang -emit-llvm -c foo.s"
   5047   Args.ClaimAllArgs(options::OPT_emit_llvm);
   5048 
   5049   claimNoWarnArgs(Args);
   5050 
   5051   // Invoke ourselves in -cc1as mode.
   5052   //
   5053   // FIXME: Implement custom jobs for internal actions.
   5054   CmdArgs.push_back("-cc1as");
   5055 
   5056   // Add the "effective" target triple.
   5057   CmdArgs.push_back("-triple");
   5058   std::string TripleStr =
   5059     getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
   5060   CmdArgs.push_back(Args.MakeArgString(TripleStr));
   5061 
   5062   // Set the output mode, we currently only expect to be used as a real
   5063   // assembler.
   5064   CmdArgs.push_back("-filetype");
   5065   CmdArgs.push_back("obj");
   5066 
   5067   // Set the main file name, so that debug info works even with
   5068   // -save-temps or preprocessed assembly.
   5069   CmdArgs.push_back("-main-file-name");
   5070   CmdArgs.push_back(Clang::getBaseInputName(Args, Inputs));
   5071 
   5072   // Add the target cpu
   5073   const llvm::Triple &Triple = getToolChain().getTriple();
   5074   std::string CPU = getCPUName(Args, Triple);
   5075   if (!CPU.empty()) {
   5076     CmdArgs.push_back("-target-cpu");
   5077     CmdArgs.push_back(Args.MakeArgString(CPU));
   5078   }
   5079 
   5080   // Add the target features
   5081   const Driver &D = getToolChain().getDriver();
   5082   getTargetFeatures(D, Triple, Args, CmdArgs, true);
   5083 
   5084   // Ignore explicit -force_cpusubtype_ALL option.
   5085   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
   5086 
   5087   // Determine the original source input.
   5088   const Action *SourceAction = &JA;
   5089   while (SourceAction->getKind() != Action::InputClass) {
   5090     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
   5091     SourceAction = SourceAction->getInputs()[0];
   5092   }
   5093 
   5094   // Forward -g and handle debug info related flags, assuming we are dealing
   5095   // with an actual assembly file.
   5096   if (SourceAction->getType() == types::TY_Asm ||
   5097       SourceAction->getType() == types::TY_PP_Asm) {
   5098     Args.ClaimAllArgs(options::OPT_g_Group);
   5099     if (Arg *A = Args.getLastArg(options::OPT_g_Group))
   5100       if (!A->getOption().matches(options::OPT_g0))
   5101         CmdArgs.push_back("-g");
   5102 
   5103     if (Args.hasArg(options::OPT_gdwarf_2))
   5104       CmdArgs.push_back("-gdwarf-2");
   5105     if (Args.hasArg(options::OPT_gdwarf_3))
   5106       CmdArgs.push_back("-gdwarf-3");
   5107     if (Args.hasArg(options::OPT_gdwarf_4))
   5108       CmdArgs.push_back("-gdwarf-4");
   5109 
   5110     // Add the -fdebug-compilation-dir flag if needed.
   5111     addDebugCompDirArg(Args, CmdArgs);
   5112 
   5113     // Set the AT_producer to the clang version when using the integrated
   5114     // assembler on assembly source files.
   5115     CmdArgs.push_back("-dwarf-debug-producer");
   5116     CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
   5117   }
   5118 
   5119   // Optionally embed the -cc1as level arguments into the debug info, for build
   5120   // analysis.
   5121   if (getToolChain().UseDwarfDebugFlags()) {
   5122     ArgStringList OriginalArgs;
   5123     for (const auto &Arg : Args)
   5124       Arg->render(Args, OriginalArgs);
   5125 
   5126     SmallString<256> Flags;
   5127     const char *Exec = getToolChain().getDriver().getClangProgramPath();
   5128     Flags += Exec;
   5129     for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
   5130       SmallString<128> EscapedArg;
   5131       EscapeSpacesAndBackslashes(OriginalArgs[i], EscapedArg);
   5132       Flags += " ";
   5133       Flags += EscapedArg;
   5134     }
   5135     CmdArgs.push_back("-dwarf-debug-flags");
   5136     CmdArgs.push_back(Args.MakeArgString(Flags));
   5137   }
   5138 
   5139   // FIXME: Add -static support, once we have it.
   5140 
   5141   // Add target specific flags.
   5142   switch(getToolChain().getArch()) {
   5143   default:
   5144     break;
   5145 
   5146   case llvm::Triple::mips:
   5147   case llvm::Triple::mipsel:
   5148   case llvm::Triple::mips64:
   5149   case llvm::Triple::mips64el:
   5150     AddMIPSTargetArgs(Args, CmdArgs);
   5151     break;
   5152   }
   5153 
   5154   // Consume all the warning flags. Usually this would be handled more
   5155   // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
   5156   // doesn't handle that so rather than warning about unused flags that are
   5157   // actually used, we'll lie by omission instead.
   5158   // FIXME: Stop lying and consume only the appropriate driver flags
   5159   for (arg_iterator it = Args.filtered_begin(options::OPT_W_Group),
   5160                     ie = Args.filtered_end();
   5161        it != ie; ++it)
   5162     (*it)->claim();
   5163 
   5164   CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
   5165                                     getToolChain().getDriver());
   5166 
   5167   Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
   5168 
   5169   assert(Output.isFilename() && "Unexpected lipo output.");
   5170   CmdArgs.push_back("-o");
   5171   CmdArgs.push_back(Output.getFilename());
   5172 
   5173   assert(Input.isFilename() && "Invalid input.");
   5174   CmdArgs.push_back(Input.getFilename());
   5175 
   5176   const char *Exec = getToolChain().getDriver().getClangProgramPath();
   5177   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   5178 
   5179   // Handle the debug info splitting at object creation time if we're
   5180   // creating an object.
   5181   // TODO: Currently only works on linux with newer objcopy.
   5182   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
   5183       getToolChain().getTriple().isOSLinux())
   5184     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
   5185                    SplitDebugName(Args, Inputs));
   5186 }
   5187 
   5188 void GnuTool::anchor() {}
   5189 
   5190 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
   5191                                const InputInfo &Output,
   5192                                const InputInfoList &Inputs,
   5193                                const ArgList &Args,
   5194                                const char *LinkingOutput) const {
   5195   const Driver &D = getToolChain().getDriver();
   5196   ArgStringList CmdArgs;
   5197 
   5198   for (const auto &A : Args) {
   5199     if (forwardToGCC(A->getOption())) {
   5200       // Don't forward any -g arguments to assembly steps.
   5201       if (isa<AssembleJobAction>(JA) &&
   5202           A->getOption().matches(options::OPT_g_Group))
   5203         continue;
   5204 
   5205       // Don't forward any -W arguments to assembly and link steps.
   5206       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
   5207           A->getOption().matches(options::OPT_W_Group))
   5208         continue;
   5209 
   5210       // It is unfortunate that we have to claim here, as this means
   5211       // we will basically never report anything interesting for
   5212       // platforms using a generic gcc, even if we are just using gcc
   5213       // to get to the assembler.
   5214       A->claim();
   5215       A->render(Args, CmdArgs);
   5216     }
   5217   }
   5218 
   5219   RenderExtraToolArgs(JA, CmdArgs);
   5220 
   5221   // If using a driver driver, force the arch.
   5222   if (getToolChain().getTriple().isOSDarwin()) {
   5223     CmdArgs.push_back("-arch");
   5224     CmdArgs.push_back(
   5225       Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
   5226   }
   5227 
   5228   // Try to force gcc to match the tool chain we want, if we recognize
   5229   // the arch.
   5230   //
   5231   // FIXME: The triple class should directly provide the information we want
   5232   // here.
   5233   llvm::Triple::ArchType Arch = getToolChain().getArch();
   5234   if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
   5235     CmdArgs.push_back("-m32");
   5236   else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
   5237            Arch == llvm::Triple::ppc64le)
   5238     CmdArgs.push_back("-m64");
   5239 
   5240   if (Output.isFilename()) {
   5241     CmdArgs.push_back("-o");
   5242     CmdArgs.push_back(Output.getFilename());
   5243   } else {
   5244     assert(Output.isNothing() && "Unexpected output");
   5245     CmdArgs.push_back("-fsyntax-only");
   5246   }
   5247 
   5248   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   5249                        options::OPT_Xassembler);
   5250 
   5251   // Only pass -x if gcc will understand it; otherwise hope gcc
   5252   // understands the suffix correctly. The main use case this would go
   5253   // wrong in is for linker inputs if they happened to have an odd
   5254   // suffix; really the only way to get this to happen is a command
   5255   // like '-x foobar a.c' which will treat a.c like a linker input.
   5256   //
   5257   // FIXME: For the linker case specifically, can we safely convert
   5258   // inputs into '-Wl,' options?
   5259   for (const auto &II : Inputs) {
   5260     // Don't try to pass LLVM or AST inputs to a generic gcc.
   5261     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
   5262         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
   5263       D.Diag(diag::err_drv_no_linker_llvm_support)
   5264         << getToolChain().getTripleString();
   5265     else if (II.getType() == types::TY_AST)
   5266       D.Diag(diag::err_drv_no_ast_support)
   5267         << getToolChain().getTripleString();
   5268     else if (II.getType() == types::TY_ModuleFile)
   5269       D.Diag(diag::err_drv_no_module_support)
   5270         << getToolChain().getTripleString();
   5271 
   5272     if (types::canTypeBeUserSpecified(II.getType())) {
   5273       CmdArgs.push_back("-x");
   5274       CmdArgs.push_back(types::getTypeName(II.getType()));
   5275     }
   5276 
   5277     if (II.isFilename())
   5278       CmdArgs.push_back(II.getFilename());
   5279     else {
   5280       const Arg &A = II.getInputArg();
   5281 
   5282       // Reverse translate some rewritten options.
   5283       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
   5284         CmdArgs.push_back("-lstdc++");
   5285         continue;
   5286       }
   5287 
   5288       // Don't render as input, we need gcc to do the translations.
   5289       A.render(Args, CmdArgs);
   5290     }
   5291   }
   5292 
   5293   const std::string customGCCName = D.getCCCGenericGCCName();
   5294   const char *GCCName;
   5295   if (!customGCCName.empty())
   5296     GCCName = customGCCName.c_str();
   5297   else if (D.CCCIsCXX()) {
   5298     GCCName = "g++";
   5299   } else
   5300     GCCName = "gcc";
   5301 
   5302   const char *Exec =
   5303     Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
   5304   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   5305 }
   5306 
   5307 void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
   5308                                           ArgStringList &CmdArgs) const {
   5309   CmdArgs.push_back("-E");
   5310 }
   5311 
   5312 void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
   5313                                        ArgStringList &CmdArgs) const {
   5314   const Driver &D = getToolChain().getDriver();
   5315 
   5316   switch (JA.getType()) {
   5317   // If -flto, etc. are present then make sure not to force assembly output.
   5318   case types::TY_LLVM_IR:
   5319   case types::TY_LTO_IR:
   5320   case types::TY_LLVM_BC:
   5321   case types::TY_LTO_BC:
   5322     CmdArgs.push_back("-c");
   5323     break;
   5324   case types::TY_PP_Asm:
   5325     CmdArgs.push_back("-S");
   5326     break;
   5327   case types::TY_Nothing:
   5328     CmdArgs.push_back("-fsyntax-only");
   5329     break;
   5330   default:
   5331     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
   5332   }
   5333 }
   5334 
   5335 void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
   5336                                     ArgStringList &CmdArgs) const {
   5337   // The types are (hopefully) good enough.
   5338 }
   5339 
   5340 // Hexagon tools start.
   5341 void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
   5342                                         ArgStringList &CmdArgs) const {
   5343 
   5344 }
   5345 void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   5346                                const InputInfo &Output,
   5347                                const InputInfoList &Inputs,
   5348                                const ArgList &Args,
   5349                                const char *LinkingOutput) const {
   5350   claimNoWarnArgs(Args);
   5351 
   5352   const Driver &D = getToolChain().getDriver();
   5353   ArgStringList CmdArgs;
   5354 
   5355   std::string MarchString = "-march=";
   5356   MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
   5357   CmdArgs.push_back(Args.MakeArgString(MarchString));
   5358 
   5359   RenderExtraToolArgs(JA, CmdArgs);
   5360 
   5361   if (Output.isFilename()) {
   5362     CmdArgs.push_back("-o");
   5363     CmdArgs.push_back(Output.getFilename());
   5364   } else {
   5365     assert(Output.isNothing() && "Unexpected output");
   5366     CmdArgs.push_back("-fsyntax-only");
   5367   }
   5368 
   5369   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
   5370   if (!SmallDataThreshold.empty())
   5371     CmdArgs.push_back(
   5372       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
   5373 
   5374   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   5375                        options::OPT_Xassembler);
   5376 
   5377   // Only pass -x if gcc will understand it; otherwise hope gcc
   5378   // understands the suffix correctly. The main use case this would go
   5379   // wrong in is for linker inputs if they happened to have an odd
   5380   // suffix; really the only way to get this to happen is a command
   5381   // like '-x foobar a.c' which will treat a.c like a linker input.
   5382   //
   5383   // FIXME: For the linker case specifically, can we safely convert
   5384   // inputs into '-Wl,' options?
   5385   for (const auto &II : Inputs) {
   5386     // Don't try to pass LLVM or AST inputs to a generic gcc.
   5387     if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
   5388         II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
   5389       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
   5390         << getToolChain().getTripleString();
   5391     else if (II.getType() == types::TY_AST)
   5392       D.Diag(clang::diag::err_drv_no_ast_support)
   5393         << getToolChain().getTripleString();
   5394     else if (II.getType() == types::TY_ModuleFile)
   5395       D.Diag(diag::err_drv_no_module_support)
   5396       << getToolChain().getTripleString();
   5397 
   5398     if (II.isFilename())
   5399       CmdArgs.push_back(II.getFilename());
   5400     else
   5401       // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
   5402       II.getInputArg().render(Args, CmdArgs);
   5403   }
   5404 
   5405   const char *GCCName = "hexagon-as";
   5406   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
   5407   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   5408 }
   5409 
   5410 void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
   5411                                     ArgStringList &CmdArgs) const {
   5412   // The types are (hopefully) good enough.
   5413 }
   5414 
   5415 void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
   5416                                const InputInfo &Output,
   5417                                const InputInfoList &Inputs,
   5418                                const ArgList &Args,
   5419                                const char *LinkingOutput) const {
   5420 
   5421   const toolchains::Hexagon_TC& ToolChain =
   5422     static_cast<const toolchains::Hexagon_TC&>(getToolChain());
   5423   const Driver &D = ToolChain.getDriver();
   5424 
   5425   ArgStringList CmdArgs;
   5426 
   5427   //----------------------------------------------------------------------------
   5428   //
   5429   //----------------------------------------------------------------------------
   5430   bool hasStaticArg = Args.hasArg(options::OPT_static);
   5431   bool buildingLib = Args.hasArg(options::OPT_shared);
   5432   bool buildPIE = Args.hasArg(options::OPT_pie);
   5433   bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
   5434   bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
   5435   bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
   5436   bool useShared = buildingLib && !hasStaticArg;
   5437 
   5438   //----------------------------------------------------------------------------
   5439   // Silence warnings for various options
   5440   //----------------------------------------------------------------------------
   5441 
   5442   Args.ClaimAllArgs(options::OPT_g_Group);
   5443   Args.ClaimAllArgs(options::OPT_emit_llvm);
   5444   Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
   5445                                      // handled somewhere else.
   5446   Args.ClaimAllArgs(options::OPT_static_libgcc);
   5447 
   5448   //----------------------------------------------------------------------------
   5449   //
   5450   //----------------------------------------------------------------------------
   5451   for (const auto &Opt : ToolChain.ExtraOpts)
   5452     CmdArgs.push_back(Opt.c_str());
   5453 
   5454   std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
   5455   CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
   5456 
   5457   if (buildingLib) {
   5458     CmdArgs.push_back("-shared");
   5459     CmdArgs.push_back("-call_shared"); // should be the default, but doing as
   5460                                        // hexagon-gcc does
   5461   }
   5462 
   5463   if (hasStaticArg)
   5464     CmdArgs.push_back("-static");
   5465 
   5466   if (buildPIE && !buildingLib)
   5467     CmdArgs.push_back("-pie");
   5468 
   5469   std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
   5470   if (!SmallDataThreshold.empty()) {
   5471     CmdArgs.push_back(
   5472       Args.MakeArgString(std::string("-G") + SmallDataThreshold));
   5473   }
   5474 
   5475   //----------------------------------------------------------------------------
   5476   //
   5477   //----------------------------------------------------------------------------
   5478   CmdArgs.push_back("-o");
   5479   CmdArgs.push_back(Output.getFilename());
   5480 
   5481   const std::string MarchSuffix = "/" + MarchString;
   5482   const std::string G0Suffix = "/G0";
   5483   const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
   5484   const std::string RootDir =
   5485       toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir, Args) + "/";
   5486   const std::string StartFilesDir = RootDir
   5487                                     + "hexagon/lib"
   5488                                     + (buildingLib
   5489                                        ? MarchG0Suffix : MarchSuffix);
   5490 
   5491   //----------------------------------------------------------------------------
   5492   // moslib
   5493   //----------------------------------------------------------------------------
   5494   std::vector<std::string> oslibs;
   5495   bool hasStandalone= false;
   5496 
   5497   for (arg_iterator it = Args.filtered_begin(options::OPT_moslib_EQ),
   5498          ie = Args.filtered_end(); it != ie; ++it) {
   5499     (*it)->claim();
   5500     oslibs.push_back((*it)->getValue());
   5501     hasStandalone = hasStandalone || (oslibs.back() == "standalone");
   5502   }
   5503   if (oslibs.empty()) {
   5504     oslibs.push_back("standalone");
   5505     hasStandalone = true;
   5506   }
   5507 
   5508   //----------------------------------------------------------------------------
   5509   // Start Files
   5510   //----------------------------------------------------------------------------
   5511   if (incStdLib && incStartFiles) {
   5512 
   5513     if (!buildingLib) {
   5514       if (hasStandalone) {
   5515         CmdArgs.push_back(
   5516           Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
   5517       }
   5518       CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
   5519     }
   5520     std::string initObj = useShared ? "/initS.o" : "/init.o";
   5521     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
   5522   }
   5523 
   5524   //----------------------------------------------------------------------------
   5525   // Library Search Paths
   5526   //----------------------------------------------------------------------------
   5527   const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
   5528   for (const auto &LibPath : LibPaths)
   5529     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
   5530 
   5531   //----------------------------------------------------------------------------
   5532   //
   5533   //----------------------------------------------------------------------------
   5534   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   5535   Args.AddAllArgs(CmdArgs, options::OPT_e);
   5536   Args.AddAllArgs(CmdArgs, options::OPT_s);
   5537   Args.AddAllArgs(CmdArgs, options::OPT_t);
   5538   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
   5539 
   5540   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
   5541 
   5542   //----------------------------------------------------------------------------
   5543   // Libraries
   5544   //----------------------------------------------------------------------------
   5545   if (incStdLib && incDefLibs) {
   5546     if (D.CCCIsCXX()) {
   5547       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
   5548       CmdArgs.push_back("-lm");
   5549     }
   5550 
   5551     CmdArgs.push_back("--start-group");
   5552 
   5553     if (!buildingLib) {
   5554       for(std::vector<std::string>::iterator i = oslibs.begin(),
   5555             e = oslibs.end(); i != e; ++i)
   5556         CmdArgs.push_back(Args.MakeArgString("-l" + *i));
   5557       CmdArgs.push_back("-lc");
   5558     }
   5559     CmdArgs.push_back("-lgcc");
   5560 
   5561     CmdArgs.push_back("--end-group");
   5562   }
   5563 
   5564   //----------------------------------------------------------------------------
   5565   // End files
   5566   //----------------------------------------------------------------------------
   5567   if (incStdLib && incStartFiles) {
   5568     std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
   5569     CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
   5570   }
   5571 
   5572   std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
   5573   C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
   5574                                           CmdArgs));
   5575 }
   5576 // Hexagon tools end.
   5577 
   5578 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
   5579 const char *arm::getARMCPUForMArch(const ArgList &Args,
   5580                                    const llvm::Triple &Triple) {
   5581   StringRef MArch;
   5582   if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
   5583     // Otherwise, if we have -march= choose the base CPU for that arch.
   5584     MArch = A->getValue();
   5585   } else {
   5586     // Otherwise, use the Arch from the triple.
   5587     MArch = Triple.getArchName();
   5588   }
   5589 
   5590   // Handle -march=native.
   5591   if (MArch == "native") {
   5592     std::string CPU = llvm::sys::getHostCPUName();
   5593     if (CPU != "generic") {
   5594       // Translate the native cpu into the architecture. The switch below will
   5595       // then chose the minimum cpu for that arch.
   5596       MArch = std::string("arm") + arm::getLLVMArchSuffixForARM(CPU);
   5597     }
   5598   }
   5599 
   5600   return Triple.getARMCPUForArch(MArch);
   5601 }
   5602 
   5603 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
   5604 StringRef arm::getARMTargetCPU(const ArgList &Args,
   5605                                const llvm::Triple &Triple) {
   5606   // FIXME: Warn on inconsistent use of -mcpu and -march.
   5607   // If we have -mcpu=, use that.
   5608   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
   5609     StringRef MCPU = A->getValue();
   5610     // Handle -mcpu=native.
   5611     if (MCPU == "native")
   5612       return llvm::sys::getHostCPUName();
   5613     else
   5614       return MCPU;
   5615   }
   5616 
   5617   return getARMCPUForMArch(Args, Triple);
   5618 }
   5619 
   5620 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
   5621 /// CPU.
   5622 //
   5623 // FIXME: This is redundant with -mcpu, why does LLVM use this.
   5624 // FIXME: tblgen this, or kill it!
   5625 const char *arm::getLLVMArchSuffixForARM(StringRef CPU) {
   5626   return llvm::StringSwitch<const char *>(CPU)
   5627     .Case("strongarm", "v4")
   5628     .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
   5629     .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
   5630     .Cases("arm920", "arm920t", "arm922t", "v4t")
   5631     .Cases("arm940t", "ep9312","v4t")
   5632     .Cases("arm10tdmi",  "arm1020t", "v5")
   5633     .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
   5634     .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
   5635     .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
   5636     .Cases("arm1136j-s",  "arm1136jf-s", "v6")
   5637     .Cases("arm1176jz-s", "arm1176jzf-s", "v6k")
   5638     .Cases("mpcorenovfp",  "mpcore", "v6k")
   5639     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
   5640     .Cases("cortex-a5", "cortex-a7", "cortex-a8", "v7")
   5641     .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "v7")
   5642     .Cases("cortex-r4", "cortex-r4f", "cortex-r5", "cortex-r7", "v7r")
   5643     .Cases("sc000", "cortex-m0", "cortex-m0plus", "cortex-m1", "v6m")
   5644     .Cases("sc300", "cortex-m3", "v7m")
   5645     .Cases("cortex-m4", "cortex-m7", "v7em")
   5646     .Case("swift", "v7s")
   5647     .Case("cyclone", "v8")
   5648     .Cases("cortex-a53", "cortex-a57", "cortex-a72", "v8")
   5649     .Default("");
   5650 }
   5651 
   5652 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple) {
   5653   if (Args.hasArg(options::OPT_r))
   5654     return;
   5655 
   5656   StringRef Suffix = getLLVMArchSuffixForARM(getARMCPUForMArch(Args, Triple));
   5657   const char *LinkFlag = llvm::StringSwitch<const char *>(Suffix)
   5658     .Cases("v4", "v4t", "v5", "v5e", nullptr)
   5659     .Cases("v6", "v6k", "v6t2", nullptr)
   5660     .Default("--be8");
   5661 
   5662   if (LinkFlag)
   5663     CmdArgs.push_back(LinkFlag);
   5664 }
   5665 
   5666 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
   5667   return (NanEncoding)llvm::StringSwitch<int>(CPU)
   5668       .Case("mips1", NanLegacy)
   5669       .Case("mips2", NanLegacy)
   5670       .Case("mips3", NanLegacy)
   5671       .Case("mips4", NanLegacy)
   5672       .Case("mips5", NanLegacy)
   5673       .Case("mips32", NanLegacy)
   5674       .Case("mips32r2", NanLegacy)
   5675       .Case("mips32r3", NanLegacy | Nan2008)
   5676       .Case("mips32r5", NanLegacy | Nan2008)
   5677       .Case("mips32r6", Nan2008)
   5678       .Case("mips64", NanLegacy)
   5679       .Case("mips64r2", NanLegacy)
   5680       .Case("mips64r3", NanLegacy | Nan2008)
   5681       .Case("mips64r5", NanLegacy | Nan2008)
   5682       .Case("mips64r6", Nan2008)
   5683       .Default(NanLegacy);
   5684 }
   5685 
   5686 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
   5687   Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
   5688   return A && (A->getValue() == StringRef(Value));
   5689 }
   5690 
   5691 bool mips::isUCLibc(const ArgList &Args) {
   5692   Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
   5693   return A && A->getOption().matches(options::OPT_muclibc);
   5694 }
   5695 
   5696 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
   5697   if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
   5698     return llvm::StringSwitch<bool>(NaNArg->getValue())
   5699                .Case("2008", true)
   5700                .Case("legacy", false)
   5701                .Default(false);
   5702 
   5703   // NaN2008 is the default for MIPS32r6/MIPS64r6.
   5704   return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
   5705              .Cases("mips32r6", "mips64r6", true)
   5706              .Default(false);
   5707 
   5708   return false;
   5709 }
   5710 
   5711 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
   5712                          StringRef ABIName) {
   5713   if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
   5714       Triple.getVendor() != llvm::Triple::MipsTechnologies)
   5715     return false;
   5716 
   5717   if (ABIName != "32")
   5718     return false;
   5719 
   5720   return llvm::StringSwitch<bool>(CPUName)
   5721              .Cases("mips2", "mips3", "mips4", "mips5", true)
   5722              .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
   5723              .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
   5724              .Default(false);
   5725 }
   5726 
   5727 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
   5728   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
   5729   // archs which Darwin doesn't use.
   5730 
   5731   // The matching this routine does is fairly pointless, since it is neither the
   5732   // complete architecture list, nor a reasonable subset. The problem is that
   5733   // historically the driver driver accepts this and also ties its -march=
   5734   // handling to the architecture name, so we need to be careful before removing
   5735   // support for it.
   5736 
   5737   // This code must be kept in sync with Clang's Darwin specific argument
   5738   // translation.
   5739 
   5740   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
   5741     .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
   5742     .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
   5743     .Case("ppc64", llvm::Triple::ppc64)
   5744     .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
   5745     .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
   5746            llvm::Triple::x86)
   5747     .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
   5748     // This is derived from the driver driver.
   5749     .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
   5750     .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
   5751     .Cases("armv7s", "xscale", llvm::Triple::arm)
   5752     .Case("arm64", llvm::Triple::aarch64)
   5753     .Case("r600", llvm::Triple::r600)
   5754     .Case("amdgcn", llvm::Triple::amdgcn)
   5755     .Case("nvptx", llvm::Triple::nvptx)
   5756     .Case("nvptx64", llvm::Triple::nvptx64)
   5757     .Case("amdil", llvm::Triple::amdil)
   5758     .Case("spir", llvm::Triple::spir)
   5759     .Default(llvm::Triple::UnknownArch);
   5760 }
   5761 
   5762 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
   5763   llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
   5764   T.setArch(Arch);
   5765 
   5766   if (Str == "x86_64h")
   5767     T.setArchName(Str);
   5768   else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
   5769     T.setOS(llvm::Triple::UnknownOS);
   5770     T.setObjectFormat(llvm::Triple::MachO);
   5771   }
   5772 }
   5773 
   5774 const char *Clang::getBaseInputName(const ArgList &Args,
   5775                                     const InputInfoList &Inputs) {
   5776   return Args.MakeArgString(
   5777     llvm::sys::path::filename(Inputs[0].getBaseInput()));
   5778 }
   5779 
   5780 const char *Clang::getBaseInputStem(const ArgList &Args,
   5781                                     const InputInfoList &Inputs) {
   5782   const char *Str = getBaseInputName(Args, Inputs);
   5783 
   5784   if (const char *End = strrchr(Str, '.'))
   5785     return Args.MakeArgString(std::string(Str, End));
   5786 
   5787   return Str;
   5788 }
   5789 
   5790 const char *Clang::getDependencyFileName(const ArgList &Args,
   5791                                          const InputInfoList &Inputs) {
   5792   // FIXME: Think about this more.
   5793   std::string Res;
   5794 
   5795   if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
   5796     std::string Str(OutputOpt->getValue());
   5797     Res = Str.substr(0, Str.rfind('.'));
   5798   } else {
   5799     Res = getBaseInputStem(Args, Inputs);
   5800   }
   5801   return Args.MakeArgString(Res + ".d");
   5802 }
   5803 
   5804 void cloudabi::Link::ConstructJob(Compilation &C, const JobAction &JA,
   5805                                   const InputInfo &Output,
   5806                                   const InputInfoList &Inputs,
   5807                                   const ArgList &Args,
   5808                                   const char *LinkingOutput) const {
   5809   const ToolChain &ToolChain = getToolChain();
   5810   const Driver &D = ToolChain.getDriver();
   5811   ArgStringList CmdArgs;
   5812 
   5813   // Silence warning for "clang -g foo.o -o foo"
   5814   Args.ClaimAllArgs(options::OPT_g_Group);
   5815   // and "clang -emit-llvm foo.o -o foo"
   5816   Args.ClaimAllArgs(options::OPT_emit_llvm);
   5817   // and for "clang -w foo.o -o foo". Other warning options are already
   5818   // handled somewhere else.
   5819   Args.ClaimAllArgs(options::OPT_w);
   5820 
   5821   if (!D.SysRoot.empty())
   5822     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
   5823 
   5824   // CloudABI only supports static linkage.
   5825   CmdArgs.push_back("-Bstatic");
   5826   CmdArgs.push_back("--eh-frame-hdr");
   5827   CmdArgs.push_back("--gc-sections");
   5828 
   5829   if (Output.isFilename()) {
   5830     CmdArgs.push_back("-o");
   5831     CmdArgs.push_back(Output.getFilename());
   5832   } else {
   5833     assert(Output.isNothing() && "Invalid output.");
   5834   }
   5835 
   5836   if (!Args.hasArg(options::OPT_nostdlib) &&
   5837       !Args.hasArg(options::OPT_nostartfiles)) {
   5838     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
   5839     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
   5840   }
   5841 
   5842   Args.AddAllArgs(CmdArgs, options::OPT_L);
   5843   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
   5844   for (const auto &Path : Paths)
   5845     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
   5846   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   5847   Args.AddAllArgs(CmdArgs, options::OPT_e);
   5848   Args.AddAllArgs(CmdArgs, options::OPT_s);
   5849   Args.AddAllArgs(CmdArgs, options::OPT_t);
   5850   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
   5851   Args.AddAllArgs(CmdArgs, options::OPT_r);
   5852 
   5853   if (D.IsUsingLTO(ToolChain, Args))
   5854     AddGoldPlugin(ToolChain, Args, CmdArgs);
   5855 
   5856   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
   5857 
   5858   if (!Args.hasArg(options::OPT_nostdlib) &&
   5859       !Args.hasArg(options::OPT_nodefaultlibs)) {
   5860     if (D.CCCIsCXX())
   5861       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
   5862     CmdArgs.push_back("-lc");
   5863     CmdArgs.push_back("-lcompiler_rt");
   5864   }
   5865 
   5866   if (!Args.hasArg(options::OPT_nostdlib) &&
   5867       !Args.hasArg(options::OPT_nostartfiles))
   5868     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
   5869 
   5870   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
   5871   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   5872 }
   5873 
   5874 void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   5875                                     const InputInfo &Output,
   5876                                     const InputInfoList &Inputs,
   5877                                     const ArgList &Args,
   5878                                     const char *LinkingOutput) const {
   5879   ArgStringList CmdArgs;
   5880 
   5881   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
   5882   const InputInfo &Input = Inputs[0];
   5883 
   5884   // Determine the original source input.
   5885   const Action *SourceAction = &JA;
   5886   while (SourceAction->getKind() != Action::InputClass) {
   5887     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
   5888     SourceAction = SourceAction->getInputs()[0];
   5889   }
   5890 
   5891   // If -fno_integrated_as is used add -Q to the darwin assember driver to make
   5892   // sure it runs its system assembler not clang's integrated assembler.
   5893   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
   5894   // FIXME: at run-time detect assembler capabilities or rely on version
   5895   // information forwarded by -target-assembler-version (future)
   5896   if (Args.hasArg(options::OPT_fno_integrated_as)) {
   5897     const llvm::Triple &T(getToolChain().getTriple());
   5898     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
   5899       CmdArgs.push_back("-Q");
   5900   }
   5901 
   5902   // Forward -g, assuming we are dealing with an actual assembly file.
   5903   if (SourceAction->getType() == types::TY_Asm ||
   5904       SourceAction->getType() == types::TY_PP_Asm) {
   5905     if (Args.hasArg(options::OPT_gstabs))
   5906       CmdArgs.push_back("--gstabs");
   5907     else if (Args.hasArg(options::OPT_g_Group))
   5908       CmdArgs.push_back("-g");
   5909   }
   5910 
   5911   // Derived from asm spec.
   5912   AddMachOArch(Args, CmdArgs);
   5913 
   5914   // Use -force_cpusubtype_ALL on x86 by default.
   5915   if (getToolChain().getArch() == llvm::Triple::x86 ||
   5916       getToolChain().getArch() == llvm::Triple::x86_64 ||
   5917       Args.hasArg(options::OPT_force__cpusubtype__ALL))
   5918     CmdArgs.push_back("-force_cpusubtype_ALL");
   5919 
   5920   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
   5921       (((Args.hasArg(options::OPT_mkernel) ||
   5922          Args.hasArg(options::OPT_fapple_kext)) &&
   5923         getMachOToolChain().isKernelStatic()) ||
   5924        Args.hasArg(options::OPT_static)))
   5925     CmdArgs.push_back("-static");
   5926 
   5927   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   5928                        options::OPT_Xassembler);
   5929 
   5930   assert(Output.isFilename() && "Unexpected lipo output.");
   5931   CmdArgs.push_back("-o");
   5932   CmdArgs.push_back(Output.getFilename());
   5933 
   5934   assert(Input.isFilename() && "Invalid input.");
   5935   CmdArgs.push_back(Input.getFilename());
   5936 
   5937   // asm_final spec is empty.
   5938 
   5939   const char *Exec =
   5940     Args.MakeArgString(getToolChain().GetProgramPath("as"));
   5941   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   5942 }
   5943 
   5944 void darwin::MachOTool::anchor() {}
   5945 
   5946 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
   5947                                      ArgStringList &CmdArgs) const {
   5948   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
   5949 
   5950   // Derived from darwin_arch spec.
   5951   CmdArgs.push_back("-arch");
   5952   CmdArgs.push_back(Args.MakeArgString(ArchName));
   5953 
   5954   // FIXME: Is this needed anymore?
   5955   if (ArchName == "arm")
   5956     CmdArgs.push_back("-force_cpusubtype_ALL");
   5957 }
   5958 
   5959 bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
   5960   // We only need to generate a temp path for LTO if we aren't compiling object
   5961   // files. When compiling source files, we run 'dsymutil' after linking. We
   5962   // don't run 'dsymutil' when compiling object files.
   5963   for (const auto &Input : Inputs)
   5964     if (Input.getType() != types::TY_Object)
   5965       return true;
   5966 
   5967   return false;
   5968 }
   5969 
   5970 void darwin::Link::AddLinkArgs(Compilation &C,
   5971                                const ArgList &Args,
   5972                                ArgStringList &CmdArgs,
   5973                                const InputInfoList &Inputs) const {
   5974   const Driver &D = getToolChain().getDriver();
   5975   const toolchains::MachO &MachOTC = getMachOToolChain();
   5976 
   5977   unsigned Version[3] = { 0, 0, 0 };
   5978   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
   5979     bool HadExtra;
   5980     if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
   5981                                    Version[1], Version[2], HadExtra) ||
   5982         HadExtra)
   5983       D.Diag(diag::err_drv_invalid_version_number)
   5984         << A->getAsString(Args);
   5985   }
   5986 
   5987   // Newer linkers support -demangle. Pass it if supported and not disabled by
   5988   // the user.
   5989   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
   5990     CmdArgs.push_back("-demangle");
   5991 
   5992   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
   5993     CmdArgs.push_back("-export_dynamic");
   5994 
   5995   // If we are using App Extension restrictions, pass a flag to the linker
   5996   // telling it that the compiled code has been audited.
   5997   if (Args.hasFlag(options::OPT_fapplication_extension,
   5998                    options::OPT_fno_application_extension, false))
   5999     CmdArgs.push_back("-application_extension");
   6000 
   6001   // If we are using LTO, then automatically create a temporary file path for
   6002   // the linker to use, so that it's lifetime will extend past a possible
   6003   // dsymutil step.
   6004   if (Version[0] >= 116 && D.IsUsingLTO(getToolChain(), Args) &&
   6005       NeedsTempPath(Inputs)) {
   6006     const char *TmpPath = C.getArgs().MakeArgString(
   6007       D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
   6008     C.addTempFile(TmpPath);
   6009     CmdArgs.push_back("-object_path_lto");
   6010     CmdArgs.push_back(TmpPath);
   6011   }
   6012 
   6013   // Derived from the "link" spec.
   6014   Args.AddAllArgs(CmdArgs, options::OPT_static);
   6015   if (!Args.hasArg(options::OPT_static))
   6016     CmdArgs.push_back("-dynamic");
   6017   if (Args.hasArg(options::OPT_fgnu_runtime)) {
   6018     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
   6019     // here. How do we wish to handle such things?
   6020   }
   6021 
   6022   if (!Args.hasArg(options::OPT_dynamiclib)) {
   6023     AddMachOArch(Args, CmdArgs);
   6024     // FIXME: Why do this only on this path?
   6025     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
   6026 
   6027     Args.AddLastArg(CmdArgs, options::OPT_bundle);
   6028     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
   6029     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
   6030 
   6031     Arg *A;
   6032     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
   6033         (A = Args.getLastArg(options::OPT_current__version)) ||
   6034         (A = Args.getLastArg(options::OPT_install__name)))
   6035       D.Diag(diag::err_drv_argument_only_allowed_with)
   6036         << A->getAsString(Args) << "-dynamiclib";
   6037 
   6038     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
   6039     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
   6040     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
   6041   } else {
   6042     CmdArgs.push_back("-dylib");
   6043 
   6044     Arg *A;
   6045     if ((A = Args.getLastArg(options::OPT_bundle)) ||
   6046         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
   6047         (A = Args.getLastArg(options::OPT_client__name)) ||
   6048         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
   6049         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
   6050         (A = Args.getLastArg(options::OPT_private__bundle)))
   6051       D.Diag(diag::err_drv_argument_not_allowed_with)
   6052         << A->getAsString(Args) << "-dynamiclib";
   6053 
   6054     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
   6055                               "-dylib_compatibility_version");
   6056     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
   6057                               "-dylib_current_version");
   6058 
   6059     AddMachOArch(Args, CmdArgs);
   6060 
   6061     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
   6062                               "-dylib_install_name");
   6063   }
   6064 
   6065   Args.AddLastArg(CmdArgs, options::OPT_all__load);
   6066   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
   6067   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
   6068   if (MachOTC.isTargetIOSBased())
   6069     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
   6070   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
   6071   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
   6072   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
   6073   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
   6074   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
   6075   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
   6076   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
   6077   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
   6078   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
   6079   Args.AddAllArgs(CmdArgs, options::OPT_init);
   6080 
   6081   // Add the deployment target.
   6082   MachOTC.addMinVersionArgs(Args, CmdArgs);
   6083 
   6084   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
   6085   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
   6086   Args.AddLastArg(CmdArgs, options::OPT_single__module);
   6087   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
   6088   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
   6089 
   6090   if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
   6091                                      options::OPT_fno_pie,
   6092                                      options::OPT_fno_PIE)) {
   6093     if (A->getOption().matches(options::OPT_fpie) ||
   6094         A->getOption().matches(options::OPT_fPIE))
   6095       CmdArgs.push_back("-pie");
   6096     else
   6097       CmdArgs.push_back("-no_pie");
   6098   }
   6099 
   6100   Args.AddLastArg(CmdArgs, options::OPT_prebind);
   6101   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
   6102   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
   6103   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
   6104   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
   6105   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
   6106   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
   6107   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
   6108   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
   6109   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
   6110   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
   6111   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
   6112   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
   6113   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
   6114   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
   6115   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
   6116 
   6117   // Give --sysroot= preference, over the Apple specific behavior to also use
   6118   // --isysroot as the syslibroot.
   6119   StringRef sysroot = C.getSysRoot();
   6120   if (sysroot != "") {
   6121     CmdArgs.push_back("-syslibroot");
   6122     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
   6123   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
   6124     CmdArgs.push_back("-syslibroot");
   6125     CmdArgs.push_back(A->getValue());
   6126   }
   6127 
   6128   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
   6129   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
   6130   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
   6131   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
   6132   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
   6133   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
   6134   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
   6135   Args.AddAllArgs(CmdArgs, options::OPT_y);
   6136   Args.AddLastArg(CmdArgs, options::OPT_w);
   6137   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
   6138   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
   6139   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
   6140   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
   6141   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
   6142   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
   6143   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
   6144   Args.AddLastArg(CmdArgs, options::OPT_whyload);
   6145   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
   6146   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
   6147   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
   6148   Args.AddLastArg(CmdArgs, options::OPT_Mach);
   6149 }
   6150 
   6151 enum LibOpenMP {
   6152   LibUnknown,
   6153   LibGOMP,
   6154   LibIOMP5
   6155 };
   6156 
   6157 void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
   6158                                 const InputInfo &Output,
   6159                                 const InputInfoList &Inputs,
   6160                                 const ArgList &Args,
   6161                                 const char *LinkingOutput) const {
   6162   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
   6163 
   6164   // If the number of arguments surpasses the system limits, we will encode the
   6165   // input files in a separate file, shortening the command line. To this end,
   6166   // build a list of input file names that can be passed via a file with the
   6167   // -filelist linker option.
   6168   llvm::opt::ArgStringList InputFileList;
   6169 
   6170   // The logic here is derived from gcc's behavior; most of which
   6171   // comes from specs (starting with link_command). Consult gcc for
   6172   // more information.
   6173   ArgStringList CmdArgs;
   6174 
   6175   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
   6176   if (Args.hasArg(options::OPT_ccc_arcmt_check,
   6177                   options::OPT_ccc_arcmt_migrate)) {
   6178     for (const auto &Arg : Args)
   6179       Arg->claim();
   6180     const char *Exec =
   6181       Args.MakeArgString(getToolChain().GetProgramPath("touch"));
   6182     CmdArgs.push_back(Output.getFilename());
   6183     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6184     return;
   6185   }
   6186 
   6187   // I'm not sure why this particular decomposition exists in gcc, but
   6188   // we follow suite for ease of comparison.
   6189   AddLinkArgs(C, Args, CmdArgs, Inputs);
   6190 
   6191   Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
   6192   Args.AddAllArgs(CmdArgs, options::OPT_s);
   6193   Args.AddAllArgs(CmdArgs, options::OPT_t);
   6194   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
   6195   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
   6196   Args.AddLastArg(CmdArgs, options::OPT_e);
   6197   Args.AddAllArgs(CmdArgs, options::OPT_r);
   6198 
   6199   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
   6200   // members of static archive libraries which implement Objective-C classes or
   6201   // categories.
   6202   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
   6203     CmdArgs.push_back("-ObjC");
   6204 
   6205   CmdArgs.push_back("-o");
   6206   CmdArgs.push_back(Output.getFilename());
   6207 
   6208   if (!Args.hasArg(options::OPT_nostdlib) &&
   6209       !Args.hasArg(options::OPT_nostartfiles))
   6210     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
   6211 
   6212   Args.AddAllArgs(CmdArgs, options::OPT_L);
   6213 
   6214   LibOpenMP UsedOpenMPLib = LibUnknown;
   6215   if (Args.hasArg(options::OPT_fopenmp)) {
   6216     UsedOpenMPLib = LibGOMP;
   6217   } else if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
   6218     UsedOpenMPLib = llvm::StringSwitch<LibOpenMP>(A->getValue())
   6219         .Case("libgomp",  LibGOMP)
   6220         .Case("libiomp5", LibIOMP5)
   6221         .Default(LibUnknown);
   6222     if (UsedOpenMPLib == LibUnknown)
   6223       getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
   6224         << A->getOption().getName() << A->getValue();
   6225   }
   6226   switch (UsedOpenMPLib) {
   6227   case LibGOMP:
   6228     CmdArgs.push_back("-lgomp");
   6229     break;
   6230   case LibIOMP5:
   6231     CmdArgs.push_back("-liomp5");
   6232     break;
   6233   case LibUnknown:
   6234     break;
   6235   }
   6236 
   6237   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
   6238   // Build the input file for -filelist (list of linker input files) in case we
   6239   // need it later
   6240   for (const auto &II : Inputs) {
   6241     if (!II.isFilename()) {
   6242       // This is a linker input argument.
   6243       // We cannot mix input arguments and file names in a -filelist input, thus
   6244       // we prematurely stop our list (remaining files shall be passed as
   6245       // arguments).
   6246       if (InputFileList.size() > 0)
   6247         break;
   6248 
   6249       continue;
   6250     }
   6251 
   6252     InputFileList.push_back(II.getFilename());
   6253   }
   6254 
   6255   if (isObjCRuntimeLinked(Args) &&
   6256       !Args.hasArg(options::OPT_nostdlib) &&
   6257       !Args.hasArg(options::OPT_nodefaultlibs)) {
   6258     // We use arclite library for both ARC and subscripting support.
   6259     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
   6260 
   6261     CmdArgs.push_back("-framework");
   6262     CmdArgs.push_back("Foundation");
   6263     // Link libobj.
   6264     CmdArgs.push_back("-lobjc");
   6265   }
   6266 
   6267   if (LinkingOutput) {
   6268     CmdArgs.push_back("-arch_multiple");
   6269     CmdArgs.push_back("-final_output");
   6270     CmdArgs.push_back(LinkingOutput);
   6271   }
   6272 
   6273   if (Args.hasArg(options::OPT_fnested_functions))
   6274     CmdArgs.push_back("-allow_stack_execute");
   6275 
   6276   if (!Args.hasArg(options::OPT_nostdlib) &&
   6277       !Args.hasArg(options::OPT_nodefaultlibs)) {
   6278     if (getToolChain().getDriver().CCCIsCXX())
   6279       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
   6280 
   6281     // link_ssp spec is empty.
   6282 
   6283     // Let the tool chain choose which runtime library to link.
   6284     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
   6285   }
   6286 
   6287   if (!Args.hasArg(options::OPT_nostdlib) &&
   6288       !Args.hasArg(options::OPT_nostartfiles)) {
   6289     // endfile_spec is empty.
   6290   }
   6291 
   6292   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   6293   Args.AddAllArgs(CmdArgs, options::OPT_F);
   6294 
   6295   // -iframework should be forwarded as -F.
   6296   for (auto it = Args.filtered_begin(options::OPT_iframework),
   6297          ie = Args.filtered_end(); it != ie; ++it)
   6298     CmdArgs.push_back(Args.MakeArgString(std::string("-F") +
   6299                                          (*it)->getValue()));
   6300 
   6301   if (!Args.hasArg(options::OPT_nostdlib) &&
   6302       !Args.hasArg(options::OPT_nodefaultlibs)) {
   6303     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
   6304       if (A->getValue() == StringRef("Accelerate")) {
   6305         CmdArgs.push_back("-framework");
   6306         CmdArgs.push_back("Accelerate");
   6307       }
   6308     }
   6309   }
   6310 
   6311   const char *Exec =
   6312     Args.MakeArgString(getToolChain().GetLinkerPath());
   6313   std::unique_ptr<Command> Cmd =
   6314     llvm::make_unique<Command>(JA, *this, Exec, CmdArgs);
   6315   Cmd->setInputFileList(std::move(InputFileList));
   6316   C.addCommand(std::move(Cmd));
   6317 }
   6318 
   6319 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
   6320                                 const InputInfo &Output,
   6321                                 const InputInfoList &Inputs,
   6322                                 const ArgList &Args,
   6323                                 const char *LinkingOutput) const {
   6324   ArgStringList CmdArgs;
   6325 
   6326   CmdArgs.push_back("-create");
   6327   assert(Output.isFilename() && "Unexpected lipo output.");
   6328 
   6329   CmdArgs.push_back("-output");
   6330   CmdArgs.push_back(Output.getFilename());
   6331 
   6332   for (const auto &II : Inputs) {
   6333     assert(II.isFilename() && "Unexpected lipo input.");
   6334     CmdArgs.push_back(II.getFilename());
   6335   }
   6336 
   6337   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
   6338   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6339 }
   6340 
   6341 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
   6342                                     const InputInfo &Output,
   6343                                     const InputInfoList &Inputs,
   6344                                     const ArgList &Args,
   6345                                     const char *LinkingOutput) const {
   6346   ArgStringList CmdArgs;
   6347 
   6348   CmdArgs.push_back("-o");
   6349   CmdArgs.push_back(Output.getFilename());
   6350 
   6351   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
   6352   const InputInfo &Input = Inputs[0];
   6353   assert(Input.isFilename() && "Unexpected dsymutil input.");
   6354   CmdArgs.push_back(Input.getFilename());
   6355 
   6356   const char *Exec =
   6357     Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
   6358   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6359 }
   6360 
   6361 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
   6362                                        const InputInfo &Output,
   6363                                        const InputInfoList &Inputs,
   6364                                        const ArgList &Args,
   6365                                        const char *LinkingOutput) const {
   6366   ArgStringList CmdArgs;
   6367   CmdArgs.push_back("--verify");
   6368   CmdArgs.push_back("--debug-info");
   6369   CmdArgs.push_back("--eh-frame");
   6370   CmdArgs.push_back("--quiet");
   6371 
   6372   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
   6373   const InputInfo &Input = Inputs[0];
   6374   assert(Input.isFilename() && "Unexpected verify input");
   6375 
   6376   // Grabbing the output of the earlier dsymutil run.
   6377   CmdArgs.push_back(Input.getFilename());
   6378 
   6379   const char *Exec =
   6380     Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
   6381   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6382 }
   6383 
   6384 void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   6385                                       const InputInfo &Output,
   6386                                       const InputInfoList &Inputs,
   6387                                       const ArgList &Args,
   6388                                       const char *LinkingOutput) const {
   6389   claimNoWarnArgs(Args);
   6390   ArgStringList CmdArgs;
   6391 
   6392   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   6393                        options::OPT_Xassembler);
   6394 
   6395   CmdArgs.push_back("-o");
   6396   CmdArgs.push_back(Output.getFilename());
   6397 
   6398   for (const auto &II : Inputs)
   6399     CmdArgs.push_back(II.getFilename());
   6400 
   6401   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
   6402   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6403 }
   6404 
   6405 void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
   6406                                   const InputInfo &Output,
   6407                                   const InputInfoList &Inputs,
   6408                                   const ArgList &Args,
   6409                                   const char *LinkingOutput) const {
   6410   // FIXME: Find a real GCC, don't hard-code versions here
   6411   std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
   6412   const llvm::Triple &T = getToolChain().getTriple();
   6413   std::string LibPath = "/usr/lib/";
   6414   llvm::Triple::ArchType Arch = T.getArch();
   6415   switch (Arch) {
   6416   case llvm::Triple::x86:
   6417     GCCLibPath +=
   6418         ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
   6419     break;
   6420   case llvm::Triple::x86_64:
   6421     GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
   6422     GCCLibPath += "/4.5.2/amd64/";
   6423     LibPath += "amd64/";
   6424     break;
   6425   default:
   6426     llvm_unreachable("Unsupported architecture");
   6427   }
   6428 
   6429   ArgStringList CmdArgs;
   6430 
   6431   // Demangle C++ names in errors
   6432   CmdArgs.push_back("-C");
   6433 
   6434   if ((!Args.hasArg(options::OPT_nostdlib)) &&
   6435       (!Args.hasArg(options::OPT_shared))) {
   6436     CmdArgs.push_back("-e");
   6437     CmdArgs.push_back("_start");
   6438   }
   6439 
   6440   if (Args.hasArg(options::OPT_static)) {
   6441     CmdArgs.push_back("-Bstatic");
   6442     CmdArgs.push_back("-dn");
   6443   } else {
   6444     CmdArgs.push_back("-Bdynamic");
   6445     if (Args.hasArg(options::OPT_shared)) {
   6446       CmdArgs.push_back("-shared");
   6447     } else {
   6448       CmdArgs.push_back("--dynamic-linker");
   6449       CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
   6450     }
   6451   }
   6452 
   6453   if (Output.isFilename()) {
   6454     CmdArgs.push_back("-o");
   6455     CmdArgs.push_back(Output.getFilename());
   6456   } else {
   6457     assert(Output.isNothing() && "Invalid output.");
   6458   }
   6459 
   6460   if (!Args.hasArg(options::OPT_nostdlib) &&
   6461       !Args.hasArg(options::OPT_nostartfiles)) {
   6462     if (!Args.hasArg(options::OPT_shared)) {
   6463       CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
   6464       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
   6465       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
   6466       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
   6467     } else {
   6468       CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
   6469       CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
   6470       CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
   6471     }
   6472     if (getToolChain().getDriver().CCCIsCXX())
   6473       CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
   6474   }
   6475 
   6476   CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
   6477 
   6478   Args.AddAllArgs(CmdArgs, options::OPT_L);
   6479   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   6480   Args.AddAllArgs(CmdArgs, options::OPT_e);
   6481   Args.AddAllArgs(CmdArgs, options::OPT_r);
   6482 
   6483   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
   6484 
   6485   if (!Args.hasArg(options::OPT_nostdlib) &&
   6486       !Args.hasArg(options::OPT_nodefaultlibs)) {
   6487     if (getToolChain().getDriver().CCCIsCXX())
   6488       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
   6489     CmdArgs.push_back("-lgcc_s");
   6490     if (!Args.hasArg(options::OPT_shared)) {
   6491       CmdArgs.push_back("-lgcc");
   6492       CmdArgs.push_back("-lc");
   6493       CmdArgs.push_back("-lm");
   6494     }
   6495   }
   6496 
   6497   if (!Args.hasArg(options::OPT_nostdlib) &&
   6498       !Args.hasArg(options::OPT_nostartfiles)) {
   6499     CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
   6500   }
   6501   CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
   6502 
   6503   addProfileRT(getToolChain(), Args, CmdArgs);
   6504 
   6505   const char *Exec =
   6506     Args.MakeArgString(getToolChain().GetLinkerPath());
   6507   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6508 }
   6509 
   6510 void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   6511                                      const InputInfo &Output,
   6512                                      const InputInfoList &Inputs,
   6513                                      const ArgList &Args,
   6514                                      const char *LinkingOutput) const {
   6515   claimNoWarnArgs(Args);
   6516   ArgStringList CmdArgs;
   6517   bool NeedsKPIC = false;
   6518 
   6519   switch (getToolChain().getArch()) {
   6520   case llvm::Triple::x86:
   6521     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
   6522     // instruct as in the base system to assemble 32-bit code.
   6523     CmdArgs.push_back("--32");
   6524     break;
   6525 
   6526   case llvm::Triple::ppc:
   6527     CmdArgs.push_back("-mppc");
   6528     CmdArgs.push_back("-many");
   6529     break;
   6530 
   6531   case llvm::Triple::sparc:
   6532     CmdArgs.push_back("-32");
   6533     NeedsKPIC = true;
   6534     break;
   6535 
   6536   case llvm::Triple::sparcv9:
   6537     CmdArgs.push_back("-64");
   6538     CmdArgs.push_back("-Av9a");
   6539     NeedsKPIC = true;
   6540     break;
   6541 
   6542   case llvm::Triple::mips64:
   6543   case llvm::Triple::mips64el: {
   6544     StringRef CPUName;
   6545     StringRef ABIName;
   6546     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
   6547 
   6548     CmdArgs.push_back("-mabi");
   6549     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
   6550 
   6551     if (getToolChain().getArch() == llvm::Triple::mips64)
   6552       CmdArgs.push_back("-EB");
   6553     else
   6554       CmdArgs.push_back("-EL");
   6555 
   6556     NeedsKPIC = true;
   6557     break;
   6558   }
   6559 
   6560   default:
   6561     break;
   6562   }
   6563 
   6564   if (NeedsKPIC)
   6565     addAssemblerKPIC(Args, CmdArgs);
   6566 
   6567   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   6568                        options::OPT_Xassembler);
   6569 
   6570   CmdArgs.push_back("-o");
   6571   CmdArgs.push_back(Output.getFilename());
   6572 
   6573   for (const auto &II : Inputs)
   6574     CmdArgs.push_back(II.getFilename());
   6575 
   6576   const char *Exec =
   6577     Args.MakeArgString(getToolChain().GetProgramPath("as"));
   6578   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6579 }
   6580 
   6581 void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
   6582                                  const InputInfo &Output,
   6583                                  const InputInfoList &Inputs,
   6584                                  const ArgList &Args,
   6585                                  const char *LinkingOutput) const {
   6586   const Driver &D = getToolChain().getDriver();
   6587   ArgStringList CmdArgs;
   6588 
   6589   // Silence warning for "clang -g foo.o -o foo"
   6590   Args.ClaimAllArgs(options::OPT_g_Group);
   6591   // and "clang -emit-llvm foo.o -o foo"
   6592   Args.ClaimAllArgs(options::OPT_emit_llvm);
   6593   // and for "clang -w foo.o -o foo". Other warning options are already
   6594   // handled somewhere else.
   6595   Args.ClaimAllArgs(options::OPT_w);
   6596 
   6597   if (getToolChain().getArch() == llvm::Triple::mips64)
   6598     CmdArgs.push_back("-EB");
   6599   else if (getToolChain().getArch() == llvm::Triple::mips64el)
   6600     CmdArgs.push_back("-EL");
   6601 
   6602   if ((!Args.hasArg(options::OPT_nostdlib)) &&
   6603       (!Args.hasArg(options::OPT_shared))) {
   6604     CmdArgs.push_back("-e");
   6605     CmdArgs.push_back("__start");
   6606   }
   6607 
   6608   if (Args.hasArg(options::OPT_static)) {
   6609     CmdArgs.push_back("-Bstatic");
   6610   } else {
   6611     if (Args.hasArg(options::OPT_rdynamic))
   6612       CmdArgs.push_back("-export-dynamic");
   6613     CmdArgs.push_back("--eh-frame-hdr");
   6614     CmdArgs.push_back("-Bdynamic");
   6615     if (Args.hasArg(options::OPT_shared)) {
   6616       CmdArgs.push_back("-shared");
   6617     } else {
   6618       CmdArgs.push_back("-dynamic-linker");
   6619       CmdArgs.push_back("/usr/libexec/ld.so");
   6620     }
   6621   }
   6622 
   6623   if (Args.hasArg(options::OPT_nopie))
   6624     CmdArgs.push_back("-nopie");
   6625 
   6626   if (Output.isFilename()) {
   6627     CmdArgs.push_back("-o");
   6628     CmdArgs.push_back(Output.getFilename());
   6629   } else {
   6630     assert(Output.isNothing() && "Invalid output.");
   6631   }
   6632 
   6633   if (!Args.hasArg(options::OPT_nostdlib) &&
   6634       !Args.hasArg(options::OPT_nostartfiles)) {
   6635     if (!Args.hasArg(options::OPT_shared)) {
   6636       if (Args.hasArg(options::OPT_pg))
   6637         CmdArgs.push_back(Args.MakeArgString(
   6638                                 getToolChain().GetFilePath("gcrt0.o")));
   6639       else
   6640         CmdArgs.push_back(Args.MakeArgString(
   6641                                 getToolChain().GetFilePath("crt0.o")));
   6642       CmdArgs.push_back(Args.MakeArgString(
   6643                               getToolChain().GetFilePath("crtbegin.o")));
   6644     } else {
   6645       CmdArgs.push_back(Args.MakeArgString(
   6646                               getToolChain().GetFilePath("crtbeginS.o")));
   6647     }
   6648   }
   6649 
   6650   std::string Triple = getToolChain().getTripleString();
   6651   if (Triple.substr(0, 6) == "x86_64")
   6652     Triple.replace(0, 6, "amd64");
   6653   CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
   6654                                        "/4.2.1"));
   6655 
   6656   Args.AddAllArgs(CmdArgs, options::OPT_L);
   6657   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   6658   Args.AddAllArgs(CmdArgs, options::OPT_e);
   6659   Args.AddAllArgs(CmdArgs, options::OPT_s);
   6660   Args.AddAllArgs(CmdArgs, options::OPT_t);
   6661   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
   6662   Args.AddAllArgs(CmdArgs, options::OPT_r);
   6663 
   6664   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
   6665 
   6666   if (!Args.hasArg(options::OPT_nostdlib) &&
   6667       !Args.hasArg(options::OPT_nodefaultlibs)) {
   6668     if (D.CCCIsCXX()) {
   6669       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
   6670       if (Args.hasArg(options::OPT_pg))
   6671         CmdArgs.push_back("-lm_p");
   6672       else
   6673         CmdArgs.push_back("-lm");
   6674     }
   6675 
   6676     // FIXME: For some reason GCC passes -lgcc before adding
   6677     // the default system libraries. Just mimic this for now.
   6678     CmdArgs.push_back("-lgcc");
   6679 
   6680     if (Args.hasArg(options::OPT_pthread)) {
   6681       if (!Args.hasArg(options::OPT_shared) &&
   6682           Args.hasArg(options::OPT_pg))
   6683          CmdArgs.push_back("-lpthread_p");
   6684       else
   6685          CmdArgs.push_back("-lpthread");
   6686     }
   6687 
   6688     if (!Args.hasArg(options::OPT_shared)) {
   6689       if (Args.hasArg(options::OPT_pg))
   6690          CmdArgs.push_back("-lc_p");
   6691       else
   6692          CmdArgs.push_back("-lc");
   6693     }
   6694 
   6695     CmdArgs.push_back("-lgcc");
   6696   }
   6697 
   6698   if (!Args.hasArg(options::OPT_nostdlib) &&
   6699       !Args.hasArg(options::OPT_nostartfiles)) {
   6700     if (!Args.hasArg(options::OPT_shared))
   6701       CmdArgs.push_back(Args.MakeArgString(
   6702                               getToolChain().GetFilePath("crtend.o")));
   6703     else
   6704       CmdArgs.push_back(Args.MakeArgString(
   6705                               getToolChain().GetFilePath("crtendS.o")));
   6706   }
   6707 
   6708   const char *Exec =
   6709     Args.MakeArgString(getToolChain().GetLinkerPath());
   6710   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6711 }
   6712 
   6713 void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   6714                                     const InputInfo &Output,
   6715                                     const InputInfoList &Inputs,
   6716                                     const ArgList &Args,
   6717                                     const char *LinkingOutput) const {
   6718   claimNoWarnArgs(Args);
   6719   ArgStringList CmdArgs;
   6720 
   6721   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   6722                        options::OPT_Xassembler);
   6723 
   6724   CmdArgs.push_back("-o");
   6725   CmdArgs.push_back(Output.getFilename());
   6726 
   6727   for (const auto &II : Inputs)
   6728     CmdArgs.push_back(II.getFilename());
   6729 
   6730   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
   6731   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6732 }
   6733 
   6734 void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
   6735                                 const InputInfo &Output,
   6736                                 const InputInfoList &Inputs,
   6737                                 const ArgList &Args,
   6738                                 const char *LinkingOutput) const {
   6739   const Driver &D = getToolChain().getDriver();
   6740   ArgStringList CmdArgs;
   6741 
   6742   if ((!Args.hasArg(options::OPT_nostdlib)) &&
   6743       (!Args.hasArg(options::OPT_shared))) {
   6744     CmdArgs.push_back("-e");
   6745     CmdArgs.push_back("__start");
   6746   }
   6747 
   6748   if (Args.hasArg(options::OPT_static)) {
   6749     CmdArgs.push_back("-Bstatic");
   6750   } else {
   6751     if (Args.hasArg(options::OPT_rdynamic))
   6752       CmdArgs.push_back("-export-dynamic");
   6753     CmdArgs.push_back("--eh-frame-hdr");
   6754     CmdArgs.push_back("-Bdynamic");
   6755     if (Args.hasArg(options::OPT_shared)) {
   6756       CmdArgs.push_back("-shared");
   6757     } else {
   6758       CmdArgs.push_back("-dynamic-linker");
   6759       CmdArgs.push_back("/usr/libexec/ld.so");
   6760     }
   6761   }
   6762 
   6763   if (Output.isFilename()) {
   6764     CmdArgs.push_back("-o");
   6765     CmdArgs.push_back(Output.getFilename());
   6766   } else {
   6767     assert(Output.isNothing() && "Invalid output.");
   6768   }
   6769 
   6770   if (!Args.hasArg(options::OPT_nostdlib) &&
   6771       !Args.hasArg(options::OPT_nostartfiles)) {
   6772     if (!Args.hasArg(options::OPT_shared)) {
   6773       if (Args.hasArg(options::OPT_pg))
   6774         CmdArgs.push_back(Args.MakeArgString(
   6775                                 getToolChain().GetFilePath("gcrt0.o")));
   6776       else
   6777         CmdArgs.push_back(Args.MakeArgString(
   6778                                 getToolChain().GetFilePath("crt0.o")));
   6779       CmdArgs.push_back(Args.MakeArgString(
   6780                               getToolChain().GetFilePath("crtbegin.o")));
   6781     } else {
   6782       CmdArgs.push_back(Args.MakeArgString(
   6783                               getToolChain().GetFilePath("crtbeginS.o")));
   6784     }
   6785   }
   6786 
   6787   Args.AddAllArgs(CmdArgs, options::OPT_L);
   6788   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   6789   Args.AddAllArgs(CmdArgs, options::OPT_e);
   6790 
   6791   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
   6792 
   6793   if (!Args.hasArg(options::OPT_nostdlib) &&
   6794       !Args.hasArg(options::OPT_nodefaultlibs)) {
   6795     if (D.CCCIsCXX()) {
   6796       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
   6797       if (Args.hasArg(options::OPT_pg))
   6798         CmdArgs.push_back("-lm_p");
   6799       else
   6800         CmdArgs.push_back("-lm");
   6801     }
   6802 
   6803     if (Args.hasArg(options::OPT_pthread)) {
   6804       if (!Args.hasArg(options::OPT_shared) &&
   6805           Args.hasArg(options::OPT_pg))
   6806         CmdArgs.push_back("-lpthread_p");
   6807       else
   6808         CmdArgs.push_back("-lpthread");
   6809     }
   6810 
   6811     if (!Args.hasArg(options::OPT_shared)) {
   6812       if (Args.hasArg(options::OPT_pg))
   6813         CmdArgs.push_back("-lc_p");
   6814       else
   6815         CmdArgs.push_back("-lc");
   6816     }
   6817 
   6818     StringRef MyArch;
   6819     switch (getToolChain().getTriple().getArch()) {
   6820     case llvm::Triple::arm:
   6821       MyArch = "arm";
   6822       break;
   6823     case llvm::Triple::x86:
   6824       MyArch = "i386";
   6825       break;
   6826     case llvm::Triple::x86_64:
   6827       MyArch = "amd64";
   6828       break;
   6829     default:
   6830       llvm_unreachable("Unsupported architecture");
   6831     }
   6832     CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
   6833   }
   6834 
   6835   if (!Args.hasArg(options::OPT_nostdlib) &&
   6836       !Args.hasArg(options::OPT_nostartfiles)) {
   6837     if (!Args.hasArg(options::OPT_shared))
   6838       CmdArgs.push_back(Args.MakeArgString(
   6839                               getToolChain().GetFilePath("crtend.o")));
   6840     else
   6841       CmdArgs.push_back(Args.MakeArgString(
   6842                               getToolChain().GetFilePath("crtendS.o")));
   6843   }
   6844 
   6845   const char *Exec =
   6846     Args.MakeArgString(getToolChain().GetLinkerPath());
   6847   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6848 }
   6849 
   6850 void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   6851                                      const InputInfo &Output,
   6852                                      const InputInfoList &Inputs,
   6853                                      const ArgList &Args,
   6854                                      const char *LinkingOutput) const {
   6855   claimNoWarnArgs(Args);
   6856   ArgStringList CmdArgs;
   6857 
   6858   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
   6859   // instruct as in the base system to assemble 32-bit code.
   6860   if (getToolChain().getArch() == llvm::Triple::x86)
   6861     CmdArgs.push_back("--32");
   6862   else if (getToolChain().getArch() == llvm::Triple::ppc)
   6863     CmdArgs.push_back("-a32");
   6864   else if (getToolChain().getArch() == llvm::Triple::mips ||
   6865            getToolChain().getArch() == llvm::Triple::mipsel ||
   6866            getToolChain().getArch() == llvm::Triple::mips64 ||
   6867            getToolChain().getArch() == llvm::Triple::mips64el) {
   6868     StringRef CPUName;
   6869     StringRef ABIName;
   6870     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
   6871 
   6872     CmdArgs.push_back("-march");
   6873     CmdArgs.push_back(CPUName.data());
   6874 
   6875     CmdArgs.push_back("-mabi");
   6876     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
   6877 
   6878     if (getToolChain().getArch() == llvm::Triple::mips ||
   6879         getToolChain().getArch() == llvm::Triple::mips64)
   6880       CmdArgs.push_back("-EB");
   6881     else
   6882       CmdArgs.push_back("-EL");
   6883 
   6884     addAssemblerKPIC(Args, CmdArgs);
   6885   } else if (getToolChain().getArch() == llvm::Triple::arm ||
   6886              getToolChain().getArch() == llvm::Triple::armeb ||
   6887              getToolChain().getArch() == llvm::Triple::thumb ||
   6888              getToolChain().getArch() == llvm::Triple::thumbeb) {
   6889     const Driver &D = getToolChain().getDriver();
   6890     const llvm::Triple &Triple = getToolChain().getTriple();
   6891     StringRef FloatABI = arm::getARMFloatABI(D, Args, Triple);
   6892 
   6893     if (FloatABI == "hard") {
   6894       CmdArgs.push_back("-mfpu=vfp");
   6895     } else {
   6896       CmdArgs.push_back("-mfpu=softvfp");
   6897     }
   6898 
   6899     switch(getToolChain().getTriple().getEnvironment()) {
   6900     case llvm::Triple::GNUEABIHF:
   6901     case llvm::Triple::GNUEABI:
   6902     case llvm::Triple::EABI:
   6903       CmdArgs.push_back("-meabi=5");
   6904       break;
   6905 
   6906     default:
   6907       CmdArgs.push_back("-matpcs");
   6908     }
   6909   } else if (getToolChain().getArch() == llvm::Triple::sparc ||
   6910              getToolChain().getArch() == llvm::Triple::sparcv9) {
   6911     if (getToolChain().getArch() == llvm::Triple::sparc)
   6912       CmdArgs.push_back("-Av8plusa");
   6913     else
   6914       CmdArgs.push_back("-Av9a");
   6915 
   6916     addAssemblerKPIC(Args, CmdArgs);
   6917   }
   6918 
   6919   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   6920                        options::OPT_Xassembler);
   6921 
   6922   CmdArgs.push_back("-o");
   6923   CmdArgs.push_back(Output.getFilename());
   6924 
   6925   for (const auto &II : Inputs)
   6926     CmdArgs.push_back(II.getFilename());
   6927 
   6928   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
   6929   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   6930 }
   6931 
   6932 void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
   6933                                  const InputInfo &Output,
   6934                                  const InputInfoList &Inputs,
   6935                                  const ArgList &Args,
   6936                                  const char *LinkingOutput) const {
   6937   const toolchains::FreeBSD& ToolChain =
   6938     static_cast<const toolchains::FreeBSD&>(getToolChain());
   6939   const Driver &D = ToolChain.getDriver();
   6940   const bool IsPIE =
   6941     !Args.hasArg(options::OPT_shared) &&
   6942     (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
   6943   ArgStringList CmdArgs;
   6944 
   6945   // Silence warning for "clang -g foo.o -o foo"
   6946   Args.ClaimAllArgs(options::OPT_g_Group);
   6947   // and "clang -emit-llvm foo.o -o foo"
   6948   Args.ClaimAllArgs(options::OPT_emit_llvm);
   6949   // and for "clang -w foo.o -o foo". Other warning options are already
   6950   // handled somewhere else.
   6951   Args.ClaimAllArgs(options::OPT_w);
   6952 
   6953   if (!D.SysRoot.empty())
   6954     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
   6955 
   6956   if (IsPIE)
   6957     CmdArgs.push_back("-pie");
   6958 
   6959   if (Args.hasArg(options::OPT_static)) {
   6960     CmdArgs.push_back("-Bstatic");
   6961   } else {
   6962     if (Args.hasArg(options::OPT_rdynamic))
   6963       CmdArgs.push_back("-export-dynamic");
   6964     CmdArgs.push_back("--eh-frame-hdr");
   6965     if (Args.hasArg(options::OPT_shared)) {
   6966       CmdArgs.push_back("-Bshareable");
   6967     } else {
   6968       CmdArgs.push_back("-dynamic-linker");
   6969       CmdArgs.push_back("/libexec/ld-elf.so.1");
   6970     }
   6971     if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
   6972       llvm::Triple::ArchType Arch = ToolChain.getArch();
   6973       if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
   6974           Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
   6975         CmdArgs.push_back("--hash-style=both");
   6976       }
   6977     }
   6978     CmdArgs.push_back("--enable-new-dtags");
   6979   }
   6980 
   6981   // When building 32-bit code on FreeBSD/amd64, we have to explicitly
   6982   // instruct ld in the base system to link 32-bit code.
   6983   if (ToolChain.getArch() == llvm::Triple::x86) {
   6984     CmdArgs.push_back("-m");
   6985     CmdArgs.push_back("elf_i386_fbsd");
   6986   }
   6987 
   6988   if (ToolChain.getArch() == llvm::Triple::ppc) {
   6989     CmdArgs.push_back("-m");
   6990     CmdArgs.push_back("elf32ppc_fbsd");
   6991   }
   6992 
   6993   if (Output.isFilename()) {
   6994     CmdArgs.push_back("-o");
   6995     CmdArgs.push_back(Output.getFilename());
   6996   } else {
   6997     assert(Output.isNothing() && "Invalid output.");
   6998   }
   6999 
   7000   if (!Args.hasArg(options::OPT_nostdlib) &&
   7001       !Args.hasArg(options::OPT_nostartfiles)) {
   7002     const char *crt1 = nullptr;
   7003     if (!Args.hasArg(options::OPT_shared)) {
   7004       if (Args.hasArg(options::OPT_pg))
   7005         crt1 = "gcrt1.o";
   7006       else if (IsPIE)
   7007         crt1 = "Scrt1.o";
   7008       else
   7009         crt1 = "crt1.o";
   7010     }
   7011     if (crt1)
   7012       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
   7013 
   7014     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
   7015 
   7016     const char *crtbegin = nullptr;
   7017     if (Args.hasArg(options::OPT_static))
   7018       crtbegin = "crtbeginT.o";
   7019     else if (Args.hasArg(options::OPT_shared) || IsPIE)
   7020       crtbegin = "crtbeginS.o";
   7021     else
   7022       crtbegin = "crtbegin.o";
   7023 
   7024     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
   7025   }
   7026 
   7027   Args.AddAllArgs(CmdArgs, options::OPT_L);
   7028   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
   7029   for (const auto &Path : Paths)
   7030     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
   7031   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   7032   Args.AddAllArgs(CmdArgs, options::OPT_e);
   7033   Args.AddAllArgs(CmdArgs, options::OPT_s);
   7034   Args.AddAllArgs(CmdArgs, options::OPT_t);
   7035   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
   7036   Args.AddAllArgs(CmdArgs, options::OPT_r);
   7037 
   7038   if (D.IsUsingLTO(getToolChain(), Args))
   7039     AddGoldPlugin(ToolChain, Args, CmdArgs);
   7040 
   7041   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
   7042   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
   7043 
   7044   if (!Args.hasArg(options::OPT_nostdlib) &&
   7045       !Args.hasArg(options::OPT_nodefaultlibs)) {
   7046     if (D.CCCIsCXX()) {
   7047       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
   7048       if (Args.hasArg(options::OPT_pg))
   7049         CmdArgs.push_back("-lm_p");
   7050       else
   7051         CmdArgs.push_back("-lm");
   7052     }
   7053     if (NeedsSanitizerDeps)
   7054       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
   7055     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
   7056     // the default system libraries. Just mimic this for now.
   7057     if (Args.hasArg(options::OPT_pg))
   7058       CmdArgs.push_back("-lgcc_p");
   7059     else
   7060       CmdArgs.push_back("-lgcc");
   7061     if (Args.hasArg(options::OPT_static)) {
   7062       CmdArgs.push_back("-lgcc_eh");
   7063     } else if (Args.hasArg(options::OPT_pg)) {
   7064       CmdArgs.push_back("-lgcc_eh_p");
   7065     } else {
   7066       CmdArgs.push_back("--as-needed");
   7067       CmdArgs.push_back("-lgcc_s");
   7068       CmdArgs.push_back("--no-as-needed");
   7069     }
   7070 
   7071     if (Args.hasArg(options::OPT_pthread)) {
   7072       if (Args.hasArg(options::OPT_pg))
   7073         CmdArgs.push_back("-lpthread_p");
   7074       else
   7075         CmdArgs.push_back("-lpthread");
   7076     }
   7077 
   7078     if (Args.hasArg(options::OPT_pg)) {
   7079       if (Args.hasArg(options::OPT_shared))
   7080         CmdArgs.push_back("-lc");
   7081       else
   7082         CmdArgs.push_back("-lc_p");
   7083       CmdArgs.push_back("-lgcc_p");
   7084     } else {
   7085       CmdArgs.push_back("-lc");
   7086       CmdArgs.push_back("-lgcc");
   7087     }
   7088 
   7089     if (Args.hasArg(options::OPT_static)) {
   7090       CmdArgs.push_back("-lgcc_eh");
   7091     } else if (Args.hasArg(options::OPT_pg)) {
   7092       CmdArgs.push_back("-lgcc_eh_p");
   7093     } else {
   7094       CmdArgs.push_back("--as-needed");
   7095       CmdArgs.push_back("-lgcc_s");
   7096       CmdArgs.push_back("--no-as-needed");
   7097     }
   7098   }
   7099 
   7100   if (!Args.hasArg(options::OPT_nostdlib) &&
   7101       !Args.hasArg(options::OPT_nostartfiles)) {
   7102     if (Args.hasArg(options::OPT_shared) || IsPIE)
   7103       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
   7104     else
   7105       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
   7106     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
   7107   }
   7108 
   7109   addProfileRT(ToolChain, Args, CmdArgs);
   7110 
   7111   const char *Exec =
   7112     Args.MakeArgString(getToolChain().GetLinkerPath());
   7113   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   7114 }
   7115 
   7116 void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   7117                                      const InputInfo &Output,
   7118                                      const InputInfoList &Inputs,
   7119                                      const ArgList &Args,
   7120                                      const char *LinkingOutput) const {
   7121   claimNoWarnArgs(Args);
   7122   ArgStringList CmdArgs;
   7123 
   7124   // GNU as needs different flags for creating the correct output format
   7125   // on architectures with different ABIs or optional feature sets.
   7126   switch (getToolChain().getArch()) {
   7127   case llvm::Triple::x86:
   7128     CmdArgs.push_back("--32");
   7129     break;
   7130   case llvm::Triple::arm:
   7131   case llvm::Triple::armeb:
   7132   case llvm::Triple::thumb:
   7133   case llvm::Triple::thumbeb: {
   7134     std::string MArch(arm::getARMTargetCPU(Args, getToolChain().getTriple()));
   7135     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
   7136     break;
   7137   }
   7138 
   7139   case llvm::Triple::mips:
   7140   case llvm::Triple::mipsel:
   7141   case llvm::Triple::mips64:
   7142   case llvm::Triple::mips64el: {
   7143     StringRef CPUName;
   7144     StringRef ABIName;
   7145     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
   7146 
   7147     CmdArgs.push_back("-march");
   7148     CmdArgs.push_back(CPUName.data());
   7149 
   7150     CmdArgs.push_back("-mabi");
   7151     CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
   7152 
   7153     if (getToolChain().getArch() == llvm::Triple::mips ||
   7154         getToolChain().getArch() == llvm::Triple::mips64)
   7155       CmdArgs.push_back("-EB");
   7156     else
   7157       CmdArgs.push_back("-EL");
   7158 
   7159     addAssemblerKPIC(Args, CmdArgs);
   7160     break;
   7161   }
   7162 
   7163   case llvm::Triple::sparc:
   7164     CmdArgs.push_back("-32");
   7165     addAssemblerKPIC(Args, CmdArgs);
   7166     break;
   7167 
   7168   case llvm::Triple::sparcv9:
   7169     CmdArgs.push_back("-64");
   7170     CmdArgs.push_back("-Av9");
   7171     addAssemblerKPIC(Args, CmdArgs);
   7172     break;
   7173 
   7174   default:
   7175     break;
   7176   }
   7177 
   7178   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   7179                        options::OPT_Xassembler);
   7180 
   7181   CmdArgs.push_back("-o");
   7182   CmdArgs.push_back(Output.getFilename());
   7183 
   7184   for (const auto &II : Inputs)
   7185     CmdArgs.push_back(II.getFilename());
   7186 
   7187   const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
   7188   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   7189 }
   7190 
   7191 void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
   7192                                  const InputInfo &Output,
   7193                                  const InputInfoList &Inputs,
   7194                                  const ArgList &Args,
   7195                                  const char *LinkingOutput) const {
   7196   const Driver &D = getToolChain().getDriver();
   7197   ArgStringList CmdArgs;
   7198 
   7199   if (!D.SysRoot.empty())
   7200     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
   7201 
   7202   CmdArgs.push_back("--eh-frame-hdr");
   7203   if (Args.hasArg(options::OPT_static)) {
   7204     CmdArgs.push_back("-Bstatic");
   7205   } else {
   7206     if (Args.hasArg(options::OPT_rdynamic))
   7207       CmdArgs.push_back("-export-dynamic");
   7208     if (Args.hasArg(options::OPT_shared)) {
   7209       CmdArgs.push_back("-Bshareable");
   7210     } else {
   7211       CmdArgs.push_back("-dynamic-linker");
   7212       CmdArgs.push_back("/libexec/ld.elf_so");
   7213     }
   7214   }
   7215 
   7216   // Many NetBSD architectures support more than one ABI.
   7217   // Determine the correct emulation for ld.
   7218   switch (getToolChain().getArch()) {
   7219   case llvm::Triple::x86:
   7220     CmdArgs.push_back("-m");
   7221     CmdArgs.push_back("elf_i386");
   7222     break;
   7223   case llvm::Triple::arm:
   7224   case llvm::Triple::thumb:
   7225     CmdArgs.push_back("-m");
   7226     switch (getToolChain().getTriple().getEnvironment()) {
   7227     case llvm::Triple::EABI:
   7228     case llvm::Triple::GNUEABI:
   7229       CmdArgs.push_back("armelf_nbsd_eabi");
   7230       break;
   7231     case llvm::Triple::EABIHF:
   7232     case llvm::Triple::GNUEABIHF:
   7233       CmdArgs.push_back("armelf_nbsd_eabihf");
   7234       break;
   7235     default:
   7236       CmdArgs.push_back("armelf_nbsd");
   7237       break;
   7238     }
   7239     break;
   7240   case llvm::Triple::armeb:
   7241   case llvm::Triple::thumbeb:
   7242     arm::appendEBLinkFlags(Args, CmdArgs, getToolChain().getTriple());
   7243     CmdArgs.push_back("-m");
   7244     switch (getToolChain().getTriple().getEnvironment()) {
   7245     case llvm::Triple::EABI:
   7246     case llvm::Triple::GNUEABI:
   7247       CmdArgs.push_back("armelfb_nbsd_eabi");
   7248       break;
   7249     case llvm::Triple::EABIHF:
   7250     case llvm::Triple::GNUEABIHF:
   7251       CmdArgs.push_back("armelfb_nbsd_eabihf");
   7252       break;
   7253     default:
   7254       CmdArgs.push_back("armelfb_nbsd");
   7255       break;
   7256     }
   7257     break;
   7258   case llvm::Triple::mips64:
   7259   case llvm::Triple::mips64el:
   7260     if (mips::hasMipsAbiArg(Args, "32")) {
   7261       CmdArgs.push_back("-m");
   7262       if (getToolChain().getArch() == llvm::Triple::mips64)
   7263         CmdArgs.push_back("elf32btsmip");
   7264       else
   7265         CmdArgs.push_back("elf32ltsmip");
   7266    } else if (mips::hasMipsAbiArg(Args, "64")) {
   7267      CmdArgs.push_back("-m");
   7268      if (getToolChain().getArch() == llvm::Triple::mips64)
   7269        CmdArgs.push_back("elf64btsmip");
   7270      else
   7271        CmdArgs.push_back("elf64ltsmip");
   7272    }
   7273    break;
   7274   case llvm::Triple::ppc:
   7275     CmdArgs.push_back("-m");
   7276     CmdArgs.push_back("elf32ppc_nbsd");
   7277     break;
   7278 
   7279   case llvm::Triple::ppc64:
   7280   case llvm::Triple::ppc64le:
   7281     CmdArgs.push_back("-m");
   7282     CmdArgs.push_back("elf64ppc");
   7283     break;
   7284 
   7285   case llvm::Triple::sparc:
   7286     CmdArgs.push_back("-m");
   7287     CmdArgs.push_back("elf32_sparc");
   7288     break;
   7289 
   7290   case llvm::Triple::sparcv9:
   7291     CmdArgs.push_back("-m");
   7292     CmdArgs.push_back("elf64_sparc");
   7293     break;
   7294 
   7295   default:
   7296     break;
   7297   }
   7298 
   7299   if (Output.isFilename()) {
   7300     CmdArgs.push_back("-o");
   7301     CmdArgs.push_back(Output.getFilename());
   7302   } else {
   7303     assert(Output.isNothing() && "Invalid output.");
   7304   }
   7305 
   7306   if (!Args.hasArg(options::OPT_nostdlib) &&
   7307       !Args.hasArg(options::OPT_nostartfiles)) {
   7308     if (!Args.hasArg(options::OPT_shared)) {
   7309       CmdArgs.push_back(Args.MakeArgString(
   7310                               getToolChain().GetFilePath("crt0.o")));
   7311       CmdArgs.push_back(Args.MakeArgString(
   7312                               getToolChain().GetFilePath("crti.o")));
   7313       CmdArgs.push_back(Args.MakeArgString(
   7314                               getToolChain().GetFilePath("crtbegin.o")));
   7315     } else {
   7316       CmdArgs.push_back(Args.MakeArgString(
   7317                               getToolChain().GetFilePath("crti.o")));
   7318       CmdArgs.push_back(Args.MakeArgString(
   7319                               getToolChain().GetFilePath("crtbeginS.o")));
   7320     }
   7321   }
   7322 
   7323   Args.AddAllArgs(CmdArgs, options::OPT_L);
   7324   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   7325   Args.AddAllArgs(CmdArgs, options::OPT_e);
   7326   Args.AddAllArgs(CmdArgs, options::OPT_s);
   7327   Args.AddAllArgs(CmdArgs, options::OPT_t);
   7328   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
   7329   Args.AddAllArgs(CmdArgs, options::OPT_r);
   7330 
   7331   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
   7332 
   7333   unsigned Major, Minor, Micro;
   7334   getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
   7335   bool useLibgcc = true;
   7336   if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
   7337     switch(getToolChain().getArch()) {
   7338     case llvm::Triple::aarch64:
   7339     case llvm::Triple::arm:
   7340     case llvm::Triple::armeb:
   7341     case llvm::Triple::thumb:
   7342     case llvm::Triple::thumbeb:
   7343     case llvm::Triple::ppc:
   7344     case llvm::Triple::ppc64:
   7345     case llvm::Triple::ppc64le:
   7346     case llvm::Triple::x86:
   7347     case llvm::Triple::x86_64:
   7348       useLibgcc = false;
   7349       break;
   7350     default:
   7351       break;
   7352     }
   7353   }
   7354 
   7355   if (!Args.hasArg(options::OPT_nostdlib) &&
   7356       !Args.hasArg(options::OPT_nodefaultlibs)) {
   7357     if (D.CCCIsCXX()) {
   7358       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
   7359       CmdArgs.push_back("-lm");
   7360     }
   7361     if (Args.hasArg(options::OPT_pthread))
   7362       CmdArgs.push_back("-lpthread");
   7363     CmdArgs.push_back("-lc");
   7364 
   7365     if (useLibgcc) {
   7366       if (Args.hasArg(options::OPT_static)) {
   7367         // libgcc_eh depends on libc, so resolve as much as possible,
   7368         // pull in any new requirements from libc and then get the rest
   7369         // of libgcc.
   7370         CmdArgs.push_back("-lgcc_eh");
   7371         CmdArgs.push_back("-lc");
   7372         CmdArgs.push_back("-lgcc");
   7373       } else {
   7374         CmdArgs.push_back("-lgcc");
   7375         CmdArgs.push_back("--as-needed");
   7376         CmdArgs.push_back("-lgcc_s");
   7377         CmdArgs.push_back("--no-as-needed");
   7378       }
   7379     }
   7380   }
   7381 
   7382   if (!Args.hasArg(options::OPT_nostdlib) &&
   7383       !Args.hasArg(options::OPT_nostartfiles)) {
   7384     if (!Args.hasArg(options::OPT_shared))
   7385       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
   7386                                                                   "crtend.o")));
   7387     else
   7388       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
   7389                                                                  "crtendS.o")));
   7390     CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
   7391                                                                     "crtn.o")));
   7392   }
   7393 
   7394   addProfileRT(getToolChain(), Args, CmdArgs);
   7395 
   7396   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
   7397   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   7398 }
   7399 
   7400 void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   7401                                       const InputInfo &Output,
   7402                                       const InputInfoList &Inputs,
   7403                                       const ArgList &Args,
   7404                                       const char *LinkingOutput) const {
   7405   claimNoWarnArgs(Args);
   7406 
   7407   ArgStringList CmdArgs;
   7408   bool NeedsKPIC = false;
   7409 
   7410   switch (getToolChain().getArch()) {
   7411   default:
   7412     break;
   7413   // Add --32/--64 to make sure we get the format we want.
   7414   // This is incomplete
   7415   case llvm::Triple::x86:
   7416     CmdArgs.push_back("--32");
   7417     break;
   7418   case llvm::Triple::x86_64:
   7419     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
   7420       CmdArgs.push_back("--x32");
   7421     else
   7422       CmdArgs.push_back("--64");
   7423     break;
   7424   case llvm::Triple::ppc:
   7425     CmdArgs.push_back("-a32");
   7426     CmdArgs.push_back("-mppc");
   7427     CmdArgs.push_back("-many");
   7428     break;
   7429   case llvm::Triple::ppc64:
   7430     CmdArgs.push_back("-a64");
   7431     CmdArgs.push_back("-mppc64");
   7432     CmdArgs.push_back("-many");
   7433     break;
   7434   case llvm::Triple::ppc64le:
   7435     CmdArgs.push_back("-a64");
   7436     CmdArgs.push_back("-mppc64");
   7437     CmdArgs.push_back("-many");
   7438     CmdArgs.push_back("-mlittle-endian");
   7439     break;
   7440   case llvm::Triple::sparc:
   7441     CmdArgs.push_back("-32");
   7442     CmdArgs.push_back("-Av8plusa");
   7443     NeedsKPIC = true;
   7444     break;
   7445   case llvm::Triple::sparcv9:
   7446     CmdArgs.push_back("-64");
   7447     CmdArgs.push_back("-Av9a");
   7448     NeedsKPIC = true;
   7449     break;
   7450   case llvm::Triple::arm:
   7451   case llvm::Triple::armeb:
   7452   case llvm::Triple::thumb:
   7453   case llvm::Triple::thumbeb: {
   7454     const llvm::Triple &Triple = getToolChain().getTriple();
   7455     switch (Triple.getSubArch()) {
   7456     case llvm::Triple::ARMSubArch_v7:
   7457       CmdArgs.push_back("-mfpu=neon");
   7458       break;
   7459     case llvm::Triple::ARMSubArch_v8:
   7460       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
   7461       break;
   7462     default:
   7463       break;
   7464     }
   7465 
   7466     StringRef ARMFloatABI = tools::arm::getARMFloatABI(
   7467         getToolChain().getDriver(), Args,
   7468         llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
   7469     CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
   7470 
   7471     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
   7472 
   7473     // FIXME: remove krait check when GNU tools support krait cpu
   7474     // for now replace it with -march=armv7-a  to avoid a lower
   7475     // march from being picked in the absence of a cpu flag.
   7476     Arg *A;
   7477     if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
   7478       StringRef(A->getValue()) == "krait")
   7479         CmdArgs.push_back("-march=armv7-a");
   7480     else
   7481       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
   7482     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
   7483     break;
   7484   }
   7485   case llvm::Triple::mips:
   7486   case llvm::Triple::mipsel:
   7487   case llvm::Triple::mips64:
   7488   case llvm::Triple::mips64el: {
   7489     StringRef CPUName;
   7490     StringRef ABIName;
   7491     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
   7492     ABIName = getGnuCompatibleMipsABIName(ABIName);
   7493 
   7494     CmdArgs.push_back("-march");
   7495     CmdArgs.push_back(CPUName.data());
   7496 
   7497     CmdArgs.push_back("-mabi");
   7498     CmdArgs.push_back(ABIName.data());
   7499 
   7500     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
   7501     // or -mshared (not implemented) is in effect.
   7502     bool IsPicOrPie = false;
   7503     if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
   7504                                  options::OPT_fpic, options::OPT_fno_pic,
   7505                                  options::OPT_fPIE, options::OPT_fno_PIE,
   7506                                  options::OPT_fpie, options::OPT_fno_pie)) {
   7507       if (A->getOption().matches(options::OPT_fPIC) ||
   7508           A->getOption().matches(options::OPT_fpic) ||
   7509           A->getOption().matches(options::OPT_fPIE) ||
   7510           A->getOption().matches(options::OPT_fpie))
   7511         IsPicOrPie = true;
   7512     }
   7513     if (!IsPicOrPie)
   7514       CmdArgs.push_back("-mno-shared");
   7515 
   7516     // LLVM doesn't support -mplt yet and acts as if it is always given.
   7517     // However, -mplt has no effect with the N64 ABI.
   7518     CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
   7519 
   7520     if (getToolChain().getArch() == llvm::Triple::mips ||
   7521         getToolChain().getArch() == llvm::Triple::mips64)
   7522       CmdArgs.push_back("-EB");
   7523     else
   7524       CmdArgs.push_back("-EL");
   7525 
   7526     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
   7527       if (StringRef(A->getValue()) == "2008")
   7528         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
   7529     }
   7530 
   7531     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
   7532     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
   7533                                  options::OPT_mfp64)) {
   7534       A->claim();
   7535       A->render(Args, CmdArgs);
   7536     } else if (mips::isFPXXDefault(getToolChain().getTriple(), CPUName,
   7537                                    ABIName))
   7538       CmdArgs.push_back("-mfpxx");
   7539 
   7540     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
   7541     // -mno-mips16 is actually -no-mips16.
   7542     if (Arg *A = Args.getLastArg(options::OPT_mips16,
   7543                                  options::OPT_mno_mips16)) {
   7544       if (A->getOption().matches(options::OPT_mips16)) {
   7545         A->claim();
   7546         A->render(Args, CmdArgs);
   7547       } else {
   7548         A->claim();
   7549         CmdArgs.push_back("-no-mips16");
   7550       }
   7551     }
   7552 
   7553     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
   7554                     options::OPT_mno_micromips);
   7555     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
   7556     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
   7557 
   7558     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
   7559       // Do not use AddLastArg because not all versions of MIPS assembler
   7560       // support -mmsa / -mno-msa options.
   7561       if (A->getOption().matches(options::OPT_mmsa))
   7562         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
   7563     }
   7564 
   7565     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
   7566                     options::OPT_msoft_float);
   7567 
   7568     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
   7569                     options::OPT_mno_odd_spreg);
   7570 
   7571     NeedsKPIC = true;
   7572     break;
   7573   }
   7574   case llvm::Triple::systemz: {
   7575     // Always pass an -march option, since our default of z10 is later
   7576     // than the GNU assembler's default.
   7577     StringRef CPUName = getSystemZTargetCPU(Args);
   7578     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
   7579     break;
   7580   }
   7581   }
   7582 
   7583   if (NeedsKPIC)
   7584     addAssemblerKPIC(Args, CmdArgs);
   7585 
   7586   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   7587                        options::OPT_Xassembler);
   7588 
   7589   CmdArgs.push_back("-o");
   7590   CmdArgs.push_back(Output.getFilename());
   7591 
   7592   for (const auto &II : Inputs)
   7593     CmdArgs.push_back(II.getFilename());
   7594 
   7595   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
   7596   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   7597 
   7598   // Handle the debug info splitting at object creation time if we're
   7599   // creating an object.
   7600   // TODO: Currently only works on linux with newer objcopy.
   7601   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
   7602       getToolChain().getTriple().isOSLinux())
   7603     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
   7604                    SplitDebugName(Args, Inputs));
   7605 }
   7606 
   7607 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
   7608                       ArgStringList &CmdArgs, const ArgList &Args) {
   7609   bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
   7610   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
   7611                       Args.hasArg(options::OPT_static);
   7612   if (!D.CCCIsCXX())
   7613     CmdArgs.push_back("-lgcc");
   7614 
   7615   if (StaticLibgcc || isAndroid) {
   7616     if (D.CCCIsCXX())
   7617       CmdArgs.push_back("-lgcc");
   7618   } else {
   7619     if (!D.CCCIsCXX())
   7620       CmdArgs.push_back("--as-needed");
   7621     CmdArgs.push_back("-lgcc_s");
   7622     if (!D.CCCIsCXX())
   7623       CmdArgs.push_back("--no-as-needed");
   7624   }
   7625 
   7626   if (StaticLibgcc && !isAndroid)
   7627     CmdArgs.push_back("-lgcc_eh");
   7628   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
   7629     CmdArgs.push_back("-lgcc");
   7630 
   7631   // According to Android ABI, we have to link with libdl if we are
   7632   // linking with non-static libgcc.
   7633   //
   7634   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
   7635   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
   7636   if (isAndroid && !StaticLibgcc)
   7637     CmdArgs.push_back("-ldl");
   7638 }
   7639 
   7640 static std::string getLinuxDynamicLinker(const ArgList &Args,
   7641                                          const toolchains::Linux &ToolChain) {
   7642   if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android) {
   7643     if (ToolChain.getTriple().isArch64Bit())
   7644       return "/system/bin/linker64";
   7645     else
   7646       return "/system/bin/linker";
   7647   } else if (ToolChain.getArch() == llvm::Triple::x86 ||
   7648              ToolChain.getArch() == llvm::Triple::sparc)
   7649     return "/lib/ld-linux.so.2";
   7650   else if (ToolChain.getArch() == llvm::Triple::aarch64)
   7651     return "/lib/ld-linux-aarch64.so.1";
   7652   else if (ToolChain.getArch() == llvm::Triple::aarch64_be)
   7653     return "/lib/ld-linux-aarch64_be.so.1";
   7654   else if (ToolChain.getArch() == llvm::Triple::arm ||
   7655            ToolChain.getArch() == llvm::Triple::thumb) {
   7656     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
   7657       return "/lib/ld-linux-armhf.so.3";
   7658     else
   7659       return "/lib/ld-linux.so.3";
   7660   } else if (ToolChain.getArch() == llvm::Triple::armeb ||
   7661              ToolChain.getArch() == llvm::Triple::thumbeb) {
   7662     if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
   7663       return "/lib/ld-linux-armhf.so.3";        /* TODO: check which dynamic linker name.  */
   7664     else
   7665       return "/lib/ld-linux.so.3";              /* TODO: check which dynamic linker name.  */
   7666   } else if (ToolChain.getArch() == llvm::Triple::mips ||
   7667              ToolChain.getArch() == llvm::Triple::mipsel ||
   7668              ToolChain.getArch() == llvm::Triple::mips64 ||
   7669              ToolChain.getArch() == llvm::Triple::mips64el) {
   7670     StringRef CPUName;
   7671     StringRef ABIName;
   7672     mips::getMipsCPUAndABI(Args, ToolChain.getTriple(), CPUName, ABIName);
   7673     bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
   7674 
   7675     StringRef LibDir = llvm::StringSwitch<llvm::StringRef>(ABIName)
   7676                            .Case("o32", "/lib")
   7677                            .Case("n32", "/lib32")
   7678                            .Case("n64", "/lib64")
   7679                            .Default("/lib");
   7680     StringRef LibName;
   7681     if (mips::isUCLibc(Args))
   7682       LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
   7683     else
   7684       LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
   7685 
   7686     return (LibDir + "/" + LibName).str();
   7687   } else if (ToolChain.getArch() == llvm::Triple::ppc)
   7688     return "/lib/ld.so.1";
   7689   else if (ToolChain.getArch() == llvm::Triple::ppc64) {
   7690     if (ppc::hasPPCAbiArg(Args, "elfv2"))
   7691       return "/lib64/ld64.so.2";
   7692     return "/lib64/ld64.so.1";
   7693   } else if (ToolChain.getArch() == llvm::Triple::ppc64le) {
   7694     if (ppc::hasPPCAbiArg(Args, "elfv1"))
   7695       return "/lib64/ld64.so.1";
   7696     return "/lib64/ld64.so.2";
   7697   } else if (ToolChain.getArch() == llvm::Triple::systemz)
   7698     return "/lib64/ld64.so.1";
   7699   else if (ToolChain.getArch() == llvm::Triple::sparcv9)
   7700     return "/lib64/ld-linux.so.2";
   7701   else if (ToolChain.getArch() == llvm::Triple::x86_64 &&
   7702            ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
   7703     return "/libx32/ld-linux-x32.so.2";
   7704   else
   7705     return "/lib64/ld-linux-x86-64.so.2";
   7706 }
   7707 
   7708 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
   7709                            ArgStringList &CmdArgs, const ArgList &Args) {
   7710   // Make use of compiler-rt if --rtlib option is used
   7711   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
   7712 
   7713   switch (RLT) {
   7714   case ToolChain::RLT_CompilerRT:
   7715     switch (TC.getTriple().getOS()) {
   7716     default: llvm_unreachable("unsupported OS");
   7717     case llvm::Triple::Win32:
   7718     case llvm::Triple::Linux:
   7719       addClangRT(TC, Args, CmdArgs);
   7720       break;
   7721     }
   7722     break;
   7723   case ToolChain::RLT_Libgcc:
   7724     AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
   7725     break;
   7726   }
   7727 }
   7728 
   7729 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
   7730   switch (T.getArch()) {
   7731   case llvm::Triple::x86:
   7732     return "elf_i386";
   7733   case llvm::Triple::aarch64:
   7734     return "aarch64linux";
   7735   case llvm::Triple::aarch64_be:
   7736     return "aarch64_be_linux";
   7737   case llvm::Triple::arm:
   7738   case llvm::Triple::thumb:
   7739     return "armelf_linux_eabi";
   7740   case llvm::Triple::armeb:
   7741   case llvm::Triple::thumbeb:
   7742     return "armebelf_linux_eabi"; /* TODO: check which NAME.  */
   7743   case llvm::Triple::ppc:
   7744     return "elf32ppclinux";
   7745   case llvm::Triple::ppc64:
   7746     return "elf64ppc";
   7747   case llvm::Triple::ppc64le:
   7748     return "elf64lppc";
   7749   case llvm::Triple::sparc:
   7750     return "elf32_sparc";
   7751   case llvm::Triple::sparcv9:
   7752     return "elf64_sparc";
   7753   case llvm::Triple::mips:
   7754     return "elf32btsmip";
   7755   case llvm::Triple::mipsel:
   7756     return "elf32ltsmip";
   7757   case llvm::Triple::mips64:
   7758     if (mips::hasMipsAbiArg(Args, "n32"))
   7759       return "elf32btsmipn32";
   7760     return "elf64btsmip";
   7761   case llvm::Triple::mips64el:
   7762     if (mips::hasMipsAbiArg(Args, "n32"))
   7763       return "elf32ltsmipn32";
   7764     return "elf64ltsmip";
   7765   case llvm::Triple::systemz:
   7766     return "elf64_s390";
   7767   case llvm::Triple::x86_64:
   7768     if (T.getEnvironment() == llvm::Triple::GNUX32)
   7769       return "elf32_x86_64";
   7770     return "elf_x86_64";
   7771   default:
   7772     llvm_unreachable("Unexpected arch");
   7773   }
   7774 }
   7775 
   7776 void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
   7777                                   const InputInfo &Output,
   7778                                   const InputInfoList &Inputs,
   7779                                   const ArgList &Args,
   7780                                   const char *LinkingOutput) const {
   7781   const toolchains::Linux& ToolChain =
   7782     static_cast<const toolchains::Linux&>(getToolChain());
   7783   const Driver &D = ToolChain.getDriver();
   7784   const bool isAndroid =
   7785     ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
   7786   const bool IsPIE =
   7787     !Args.hasArg(options::OPT_shared) &&
   7788     !Args.hasArg(options::OPT_static) &&
   7789     (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
   7790 
   7791   ArgStringList CmdArgs;
   7792 
   7793   // Silence warning for "clang -g foo.o -o foo"
   7794   Args.ClaimAllArgs(options::OPT_g_Group);
   7795   // and "clang -emit-llvm foo.o -o foo"
   7796   Args.ClaimAllArgs(options::OPT_emit_llvm);
   7797   // and for "clang -w foo.o -o foo". Other warning options are already
   7798   // handled somewhere else.
   7799   Args.ClaimAllArgs(options::OPT_w);
   7800 
   7801   if (!D.SysRoot.empty())
   7802     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
   7803 
   7804   if (IsPIE)
   7805     CmdArgs.push_back("-pie");
   7806 
   7807   if (Args.hasArg(options::OPT_rdynamic))
   7808     CmdArgs.push_back("-export-dynamic");
   7809 
   7810   if (Args.hasArg(options::OPT_s))
   7811     CmdArgs.push_back("-s");
   7812 
   7813   if (ToolChain.getArch() == llvm::Triple::armeb ||
   7814       ToolChain.getArch() == llvm::Triple::thumbeb)
   7815     arm::appendEBLinkFlags(Args, CmdArgs, getToolChain().getTriple());
   7816 
   7817   for (const auto &Opt : ToolChain.ExtraOpts)
   7818     CmdArgs.push_back(Opt.c_str());
   7819 
   7820   if (!Args.hasArg(options::OPT_static)) {
   7821     CmdArgs.push_back("--eh-frame-hdr");
   7822   }
   7823 
   7824   CmdArgs.push_back("-m");
   7825   CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
   7826 
   7827   if (Args.hasArg(options::OPT_static)) {
   7828     if (ToolChain.getArch() == llvm::Triple::arm ||
   7829         ToolChain.getArch() == llvm::Triple::armeb ||
   7830         ToolChain.getArch() == llvm::Triple::thumb ||
   7831         ToolChain.getArch() == llvm::Triple::thumbeb)
   7832       CmdArgs.push_back("-Bstatic");
   7833     else
   7834       CmdArgs.push_back("-static");
   7835   } else if (Args.hasArg(options::OPT_shared)) {
   7836     CmdArgs.push_back("-shared");
   7837   }
   7838 
   7839   if (ToolChain.getArch() == llvm::Triple::arm ||
   7840       ToolChain.getArch() == llvm::Triple::armeb ||
   7841       ToolChain.getArch() == llvm::Triple::thumb ||
   7842       ToolChain.getArch() == llvm::Triple::thumbeb ||
   7843       (!Args.hasArg(options::OPT_static) &&
   7844        !Args.hasArg(options::OPT_shared))) {
   7845     CmdArgs.push_back("-dynamic-linker");
   7846     CmdArgs.push_back(Args.MakeArgString(
   7847         D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
   7848   }
   7849 
   7850   CmdArgs.push_back("-o");
   7851   CmdArgs.push_back(Output.getFilename());
   7852 
   7853   if (!Args.hasArg(options::OPT_nostdlib) &&
   7854       !Args.hasArg(options::OPT_nostartfiles)) {
   7855     if (!isAndroid) {
   7856       const char *crt1 = nullptr;
   7857       if (!Args.hasArg(options::OPT_shared)){
   7858         if (Args.hasArg(options::OPT_pg))
   7859           crt1 = "gcrt1.o";
   7860         else if (IsPIE)
   7861           crt1 = "Scrt1.o";
   7862         else
   7863           crt1 = "crt1.o";
   7864       }
   7865       if (crt1)
   7866         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
   7867 
   7868       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
   7869     }
   7870 
   7871     const char *crtbegin;
   7872     if (Args.hasArg(options::OPT_static))
   7873       crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
   7874     else if (Args.hasArg(options::OPT_shared))
   7875       crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
   7876     else if (IsPIE)
   7877       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
   7878     else
   7879       crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
   7880     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
   7881 
   7882     // Add crtfastmath.o if available and fast math is enabled.
   7883     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
   7884   }
   7885 
   7886   Args.AddAllArgs(CmdArgs, options::OPT_L);
   7887   Args.AddAllArgs(CmdArgs, options::OPT_u);
   7888 
   7889   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
   7890 
   7891   for (const auto &Path : Paths)
   7892     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
   7893 
   7894   if (D.IsUsingLTO(getToolChain(), Args))
   7895     AddGoldPlugin(ToolChain, Args, CmdArgs);
   7896 
   7897   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
   7898     CmdArgs.push_back("--no-demangle");
   7899 
   7900   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
   7901   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
   7902   // The profile runtime also needs access to system libraries.
   7903   addProfileRT(getToolChain(), Args, CmdArgs);
   7904 
   7905   if (D.CCCIsCXX() &&
   7906       !Args.hasArg(options::OPT_nostdlib) &&
   7907       !Args.hasArg(options::OPT_nodefaultlibs)) {
   7908     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
   7909       !Args.hasArg(options::OPT_static);
   7910     if (OnlyLibstdcxxStatic)
   7911       CmdArgs.push_back("-Bstatic");
   7912     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
   7913     if (OnlyLibstdcxxStatic)
   7914       CmdArgs.push_back("-Bdynamic");
   7915     CmdArgs.push_back("-lm");
   7916   }
   7917   // Silence warnings when linking C code with a C++ '-stdlib' argument.
   7918   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
   7919 
   7920   if (!Args.hasArg(options::OPT_nostdlib)) {
   7921     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
   7922       if (Args.hasArg(options::OPT_static))
   7923         CmdArgs.push_back("--start-group");
   7924 
   7925       if (NeedsSanitizerDeps)
   7926         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
   7927 
   7928       LibOpenMP UsedOpenMPLib = LibUnknown;
   7929       if (Args.hasArg(options::OPT_fopenmp)) {
   7930         UsedOpenMPLib = LibGOMP;
   7931       } else if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
   7932         UsedOpenMPLib = llvm::StringSwitch<LibOpenMP>(A->getValue())
   7933             .Case("libgomp",  LibGOMP)
   7934             .Case("libiomp5", LibIOMP5)
   7935             .Default(LibUnknown);
   7936         if (UsedOpenMPLib == LibUnknown)
   7937           D.Diag(diag::err_drv_unsupported_option_argument)
   7938             << A->getOption().getName() << A->getValue();
   7939       }
   7940       switch (UsedOpenMPLib) {
   7941       case LibGOMP:
   7942         CmdArgs.push_back("-lgomp");
   7943 
   7944         // FIXME: Exclude this for platforms with libgomp that don't require
   7945         // librt. Most modern Linux platforms require it, but some may not.
   7946         CmdArgs.push_back("-lrt");
   7947         break;
   7948       case LibIOMP5:
   7949         CmdArgs.push_back("-liomp5");
   7950         break;
   7951       case LibUnknown:
   7952         break;
   7953       }
   7954       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
   7955 
   7956       if ((Args.hasArg(options::OPT_pthread) ||
   7957            Args.hasArg(options::OPT_pthreads) || UsedOpenMPLib != LibUnknown) &&
   7958           !isAndroid)
   7959         CmdArgs.push_back("-lpthread");
   7960 
   7961       CmdArgs.push_back("-lc");
   7962 
   7963       if (Args.hasArg(options::OPT_static))
   7964         CmdArgs.push_back("--end-group");
   7965       else
   7966         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
   7967     }
   7968 
   7969     if (!Args.hasArg(options::OPT_nostartfiles)) {
   7970       const char *crtend;
   7971       if (Args.hasArg(options::OPT_shared))
   7972         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
   7973       else if (IsPIE)
   7974         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
   7975       else
   7976         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
   7977 
   7978       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
   7979       if (!isAndroid)
   7980         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
   7981     }
   7982   }
   7983 
   7984   C.addCommand(
   7985       llvm::make_unique<Command>(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
   7986 }
   7987 
   7988 
   7989 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
   7990 // for the various SFI requirements like register masking. The assembly tool
   7991 // inserts the file containing the macros as an input into all the assembly
   7992 // jobs.
   7993 void nacltools::AssembleARM::ConstructJob(Compilation &C, const JobAction &JA,
   7994                                           const InputInfo &Output,
   7995                                           const InputInfoList &Inputs,
   7996                                           const ArgList &Args,
   7997                                           const char *LinkingOutput) const {
   7998   const toolchains::NaCl_TC& ToolChain =
   7999     static_cast<const toolchains::NaCl_TC&>(getToolChain());
   8000   InputInfo NaClMacros(ToolChain.GetNaClArmMacrosPath(), types::TY_PP_Asm,
   8001                        "nacl-arm-macros.s");
   8002   InputInfoList NewInputs;
   8003   NewInputs.push_back(NaClMacros);
   8004   NewInputs.append(Inputs.begin(), Inputs.end());
   8005   gnutools::Assemble::ConstructJob(C, JA, Output, NewInputs, Args,
   8006                                    LinkingOutput);
   8007 }
   8008 
   8009 
   8010 // This is quite similar to gnutools::link::ConstructJob with changes that
   8011 // we use static by default, do not yet support sanitizers or LTO, and a few
   8012 // others. Eventually we can support more of that and hopefully migrate back
   8013 // to gnutools::link.
   8014 void nacltools::Link::ConstructJob(Compilation &C, const JobAction &JA,
   8015                                   const InputInfo &Output,
   8016                                   const InputInfoList &Inputs,
   8017                                   const ArgList &Args,
   8018                                   const char *LinkingOutput) const {
   8019 
   8020   const toolchains::NaCl_TC& ToolChain =
   8021     static_cast<const toolchains::NaCl_TC&>(getToolChain());
   8022   const Driver &D = ToolChain.getDriver();
   8023   const bool IsStatic =
   8024     !Args.hasArg(options::OPT_dynamic) &&
   8025     !Args.hasArg(options::OPT_shared);
   8026 
   8027   ArgStringList CmdArgs;
   8028 
   8029   // Silence warning for "clang -g foo.o -o foo"
   8030   Args.ClaimAllArgs(options::OPT_g_Group);
   8031   // and "clang -emit-llvm foo.o -o foo"
   8032   Args.ClaimAllArgs(options::OPT_emit_llvm);
   8033   // and for "clang -w foo.o -o foo". Other warning options are already
   8034   // handled somewhere else.
   8035   Args.ClaimAllArgs(options::OPT_w);
   8036 
   8037   if (!D.SysRoot.empty())
   8038     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
   8039 
   8040   if (Args.hasArg(options::OPT_rdynamic))
   8041     CmdArgs.push_back("-export-dynamic");
   8042 
   8043   if (Args.hasArg(options::OPT_s))
   8044     CmdArgs.push_back("-s");
   8045 
   8046   // NaCl_TC doesn't have ExtraOpts like Linux; the only relevant flag from
   8047   // there is --build-id, which we do want.
   8048   CmdArgs.push_back("--build-id");
   8049 
   8050   if (!IsStatic)
   8051     CmdArgs.push_back("--eh-frame-hdr");
   8052 
   8053   CmdArgs.push_back("-m");
   8054   if (ToolChain.getArch() == llvm::Triple::x86)
   8055     CmdArgs.push_back("elf_i386_nacl");
   8056   else if (ToolChain.getArch() == llvm::Triple::arm)
   8057     CmdArgs.push_back("armelf_nacl");
   8058   else if (ToolChain.getArch() == llvm::Triple::x86_64)
   8059     CmdArgs.push_back("elf_x86_64_nacl");
   8060   else
   8061     D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName() <<
   8062         "Native Client";
   8063 
   8064 
   8065   if (IsStatic)
   8066     CmdArgs.push_back("-static");
   8067   else if (Args.hasArg(options::OPT_shared))
   8068     CmdArgs.push_back("-shared");
   8069 
   8070   CmdArgs.push_back("-o");
   8071   CmdArgs.push_back(Output.getFilename());
   8072   if (!Args.hasArg(options::OPT_nostdlib) &&
   8073       !Args.hasArg(options::OPT_nostartfiles)) {
   8074     if (!Args.hasArg(options::OPT_shared))
   8075       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
   8076     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
   8077 
   8078     const char *crtbegin;
   8079     if (IsStatic)
   8080       crtbegin = "crtbeginT.o";
   8081     else if (Args.hasArg(options::OPT_shared))
   8082       crtbegin = "crtbeginS.o";
   8083     else
   8084       crtbegin = "crtbegin.o";
   8085     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
   8086   }
   8087 
   8088   Args.AddAllArgs(CmdArgs, options::OPT_L);
   8089   Args.AddAllArgs(CmdArgs, options::OPT_u);
   8090 
   8091   const ToolChain::path_list &Paths = ToolChain.getFilePaths();
   8092 
   8093   for (const auto &Path : Paths)
   8094     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
   8095 
   8096   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
   8097     CmdArgs.push_back("--no-demangle");
   8098 
   8099   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
   8100 
   8101   if (D.CCCIsCXX() &&
   8102       !Args.hasArg(options::OPT_nostdlib) &&
   8103       !Args.hasArg(options::OPT_nodefaultlibs)) {
   8104     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
   8105       !IsStatic;
   8106     if (OnlyLibstdcxxStatic)
   8107       CmdArgs.push_back("-Bstatic");
   8108     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
   8109     if (OnlyLibstdcxxStatic)
   8110       CmdArgs.push_back("-Bdynamic");
   8111     CmdArgs.push_back("-lm");
   8112   }
   8113 
   8114   if (!Args.hasArg(options::OPT_nostdlib)) {
   8115     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
   8116       // Always use groups, since it has no effect on dynamic libraries.
   8117       CmdArgs.push_back("--start-group");
   8118       CmdArgs.push_back("-lc");
   8119       // NaCl's libc++ currently requires libpthread, so just always include it
   8120       // in the group for C++.
   8121       if (Args.hasArg(options::OPT_pthread) ||
   8122           Args.hasArg(options::OPT_pthreads) ||
   8123           D.CCCIsCXX()) {
   8124         CmdArgs.push_back("-lpthread");
   8125       }
   8126 
   8127       CmdArgs.push_back("-lgcc");
   8128       CmdArgs.push_back("--as-needed");
   8129       if (IsStatic)
   8130         CmdArgs.push_back("-lgcc_eh");
   8131       else
   8132         CmdArgs.push_back("-lgcc_s");
   8133       CmdArgs.push_back("--no-as-needed");
   8134       CmdArgs.push_back("--end-group");
   8135     }
   8136 
   8137     if (!Args.hasArg(options::OPT_nostartfiles)) {
   8138       const char *crtend;
   8139       if (Args.hasArg(options::OPT_shared))
   8140         crtend = "crtendS.o";
   8141       else
   8142         crtend = "crtend.o";
   8143 
   8144       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
   8145       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
   8146     }
   8147   }
   8148 
   8149   C.addCommand(llvm::make_unique<Command>(JA, *this,
   8150                                           ToolChain.Linker.c_str(), CmdArgs));
   8151 }
   8152 
   8153 
   8154 void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   8155                                    const InputInfo &Output,
   8156                                    const InputInfoList &Inputs,
   8157                                    const ArgList &Args,
   8158                                    const char *LinkingOutput) const {
   8159   claimNoWarnArgs(Args);
   8160   ArgStringList CmdArgs;
   8161 
   8162   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
   8163 
   8164   CmdArgs.push_back("-o");
   8165   CmdArgs.push_back(Output.getFilename());
   8166 
   8167   for (const auto &II : Inputs)
   8168     CmdArgs.push_back(II.getFilename());
   8169 
   8170   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
   8171   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8172 }
   8173 
   8174 void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
   8175                                const InputInfo &Output,
   8176                                const InputInfoList &Inputs,
   8177                                const ArgList &Args,
   8178                                const char *LinkingOutput) const {
   8179   const Driver &D = getToolChain().getDriver();
   8180   ArgStringList CmdArgs;
   8181 
   8182   if (Output.isFilename()) {
   8183     CmdArgs.push_back("-o");
   8184     CmdArgs.push_back(Output.getFilename());
   8185   } else {
   8186     assert(Output.isNothing() && "Invalid output.");
   8187   }
   8188 
   8189   if (!Args.hasArg(options::OPT_nostdlib) &&
   8190       !Args.hasArg(options::OPT_nostartfiles)) {
   8191       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
   8192       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
   8193       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
   8194       CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
   8195   }
   8196 
   8197   Args.AddAllArgs(CmdArgs, options::OPT_L);
   8198   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   8199   Args.AddAllArgs(CmdArgs, options::OPT_e);
   8200 
   8201   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
   8202 
   8203   addProfileRT(getToolChain(), Args, CmdArgs);
   8204 
   8205   if (!Args.hasArg(options::OPT_nostdlib) &&
   8206       !Args.hasArg(options::OPT_nodefaultlibs)) {
   8207     if (D.CCCIsCXX()) {
   8208       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
   8209       CmdArgs.push_back("-lm");
   8210     }
   8211   }
   8212 
   8213   if (!Args.hasArg(options::OPT_nostdlib) &&
   8214       !Args.hasArg(options::OPT_nostartfiles)) {
   8215     if (Args.hasArg(options::OPT_pthread))
   8216       CmdArgs.push_back("-lpthread");
   8217     CmdArgs.push_back("-lc");
   8218     CmdArgs.push_back("-lCompilerRT-Generic");
   8219     CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
   8220     CmdArgs.push_back(
   8221          Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
   8222   }
   8223 
   8224   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
   8225   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8226 }
   8227 
   8228 /// DragonFly Tools
   8229 
   8230 // For now, DragonFly Assemble does just about the same as for
   8231 // FreeBSD, but this may change soon.
   8232 void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   8233                                        const InputInfo &Output,
   8234                                        const InputInfoList &Inputs,
   8235                                        const ArgList &Args,
   8236                                        const char *LinkingOutput) const {
   8237   claimNoWarnArgs(Args);
   8238   ArgStringList CmdArgs;
   8239 
   8240   // When building 32-bit code on DragonFly/pc64, we have to explicitly
   8241   // instruct as in the base system to assemble 32-bit code.
   8242   if (getToolChain().getArch() == llvm::Triple::x86)
   8243     CmdArgs.push_back("--32");
   8244 
   8245   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
   8246 
   8247   CmdArgs.push_back("-o");
   8248   CmdArgs.push_back(Output.getFilename());
   8249 
   8250   for (const auto &II : Inputs)
   8251     CmdArgs.push_back(II.getFilename());
   8252 
   8253   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
   8254   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8255 }
   8256 
   8257 void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
   8258                                    const InputInfo &Output,
   8259                                    const InputInfoList &Inputs,
   8260                                    const ArgList &Args,
   8261                                    const char *LinkingOutput) const {
   8262   const Driver &D = getToolChain().getDriver();
   8263   ArgStringList CmdArgs;
   8264   bool UseGCC47 = llvm::sys::fs::exists("/usr/lib/gcc47");
   8265 
   8266   if (!D.SysRoot.empty())
   8267     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
   8268 
   8269   CmdArgs.push_back("--eh-frame-hdr");
   8270   if (Args.hasArg(options::OPT_static)) {
   8271     CmdArgs.push_back("-Bstatic");
   8272   } else {
   8273     if (Args.hasArg(options::OPT_rdynamic))
   8274       CmdArgs.push_back("-export-dynamic");
   8275     if (Args.hasArg(options::OPT_shared))
   8276       CmdArgs.push_back("-Bshareable");
   8277     else {
   8278       CmdArgs.push_back("-dynamic-linker");
   8279       CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
   8280     }
   8281     CmdArgs.push_back("--hash-style=both");
   8282   }
   8283 
   8284   // When building 32-bit code on DragonFly/pc64, we have to explicitly
   8285   // instruct ld in the base system to link 32-bit code.
   8286   if (getToolChain().getArch() == llvm::Triple::x86) {
   8287     CmdArgs.push_back("-m");
   8288     CmdArgs.push_back("elf_i386");
   8289   }
   8290 
   8291   if (Output.isFilename()) {
   8292     CmdArgs.push_back("-o");
   8293     CmdArgs.push_back(Output.getFilename());
   8294   } else {
   8295     assert(Output.isNothing() && "Invalid output.");
   8296   }
   8297 
   8298   if (!Args.hasArg(options::OPT_nostdlib) &&
   8299       !Args.hasArg(options::OPT_nostartfiles)) {
   8300     if (!Args.hasArg(options::OPT_shared)) {
   8301       if (Args.hasArg(options::OPT_pg))
   8302         CmdArgs.push_back(Args.MakeArgString(
   8303                                 getToolChain().GetFilePath("gcrt1.o")));
   8304       else {
   8305         if (Args.hasArg(options::OPT_pie))
   8306           CmdArgs.push_back(Args.MakeArgString(
   8307                                   getToolChain().GetFilePath("Scrt1.o")));
   8308         else
   8309           CmdArgs.push_back(Args.MakeArgString(
   8310                                   getToolChain().GetFilePath("crt1.o")));
   8311       }
   8312     }
   8313     CmdArgs.push_back(Args.MakeArgString(
   8314                             getToolChain().GetFilePath("crti.o")));
   8315     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
   8316       CmdArgs.push_back(Args.MakeArgString(
   8317                               getToolChain().GetFilePath("crtbeginS.o")));
   8318     else
   8319       CmdArgs.push_back(Args.MakeArgString(
   8320                               getToolChain().GetFilePath("crtbegin.o")));
   8321   }
   8322 
   8323   Args.AddAllArgs(CmdArgs, options::OPT_L);
   8324   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   8325   Args.AddAllArgs(CmdArgs, options::OPT_e);
   8326 
   8327   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
   8328 
   8329   if (!Args.hasArg(options::OPT_nostdlib) &&
   8330       !Args.hasArg(options::OPT_nodefaultlibs)) {
   8331     // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
   8332     //         rpaths
   8333     if (UseGCC47)
   8334       CmdArgs.push_back("-L/usr/lib/gcc47");
   8335     else
   8336       CmdArgs.push_back("-L/usr/lib/gcc44");
   8337 
   8338     if (!Args.hasArg(options::OPT_static)) {
   8339       if (UseGCC47) {
   8340         CmdArgs.push_back("-rpath");
   8341         CmdArgs.push_back("/usr/lib/gcc47");
   8342       } else {
   8343         CmdArgs.push_back("-rpath");
   8344         CmdArgs.push_back("/usr/lib/gcc44");
   8345       }
   8346     }
   8347 
   8348     if (D.CCCIsCXX()) {
   8349       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
   8350       CmdArgs.push_back("-lm");
   8351     }
   8352 
   8353     if (Args.hasArg(options::OPT_pthread))
   8354       CmdArgs.push_back("-lpthread");
   8355 
   8356     if (!Args.hasArg(options::OPT_nolibc)) {
   8357       CmdArgs.push_back("-lc");
   8358     }
   8359 
   8360     if (UseGCC47) {
   8361       if (Args.hasArg(options::OPT_static) ||
   8362           Args.hasArg(options::OPT_static_libgcc)) {
   8363         CmdArgs.push_back("-lgcc");
   8364         CmdArgs.push_back("-lgcc_eh");
   8365       } else {
   8366         if (Args.hasArg(options::OPT_shared_libgcc)) {
   8367           CmdArgs.push_back("-lgcc_pic");
   8368           if (!Args.hasArg(options::OPT_shared))
   8369             CmdArgs.push_back("-lgcc");
   8370         } else {
   8371           CmdArgs.push_back("-lgcc");
   8372           CmdArgs.push_back("--as-needed");
   8373           CmdArgs.push_back("-lgcc_pic");
   8374           CmdArgs.push_back("--no-as-needed");
   8375         }
   8376       }
   8377     } else {
   8378       if (Args.hasArg(options::OPT_shared)) {
   8379         CmdArgs.push_back("-lgcc_pic");
   8380       } else {
   8381         CmdArgs.push_back("-lgcc");
   8382       }
   8383     }
   8384   }
   8385 
   8386   if (!Args.hasArg(options::OPT_nostdlib) &&
   8387       !Args.hasArg(options::OPT_nostartfiles)) {
   8388     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
   8389       CmdArgs.push_back(Args.MakeArgString(
   8390                               getToolChain().GetFilePath("crtendS.o")));
   8391     else
   8392       CmdArgs.push_back(Args.MakeArgString(
   8393                               getToolChain().GetFilePath("crtend.o")));
   8394     CmdArgs.push_back(Args.MakeArgString(
   8395                             getToolChain().GetFilePath("crtn.o")));
   8396   }
   8397 
   8398   addProfileRT(getToolChain(), Args, CmdArgs);
   8399 
   8400   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
   8401   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8402 }
   8403 
   8404 // Try to find Exe from a Visual Studio distribution.  This first tries to find
   8405 // an installed copy of Visual Studio and, failing that, looks in the PATH,
   8406 // making sure that whatever executable that's found is not a same-named exe
   8407 // from clang itself to prevent clang from falling back to itself.
   8408 static std::string FindVisualStudioExecutable(const ToolChain &TC,
   8409                                               const char *Exe,
   8410                                               const char *ClangProgramPath) {
   8411   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
   8412   std::string visualStudioBinDir;
   8413   if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
   8414                                          visualStudioBinDir)) {
   8415     SmallString<128> FilePath(visualStudioBinDir);
   8416     llvm::sys::path::append(FilePath, Exe);
   8417     if (llvm::sys::fs::can_execute(FilePath.c_str()))
   8418       return FilePath.str();
   8419   }
   8420 
   8421   return Exe;
   8422 }
   8423 
   8424 void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
   8425                                       const InputInfo &Output,
   8426                                       const InputInfoList &Inputs,
   8427                                       const ArgList &Args,
   8428                                       const char *LinkingOutput) const {
   8429   ArgStringList CmdArgs;
   8430   const ToolChain &TC = getToolChain();
   8431 
   8432   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
   8433   if (Output.isFilename())
   8434     CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
   8435                                          Output.getFilename()));
   8436 
   8437   if (!Args.hasArg(options::OPT_nostdlib) &&
   8438       !Args.hasArg(options::OPT_nostartfiles) && !C.getDriver().IsCLMode())
   8439     CmdArgs.push_back("-defaultlib:libcmt");
   8440 
   8441   if (!llvm::sys::Process::GetEnv("LIB")) {
   8442     // If the VC environment hasn't been configured (perhaps because the user
   8443     // did not run vcvarsall), try to build a consistent link environment.  If
   8444     // the environment variable is set however, assume the user knows what
   8445     // they're doing.
   8446     std::string VisualStudioDir;
   8447     const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
   8448     if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
   8449       SmallString<128> LibDir(VisualStudioDir);
   8450       llvm::sys::path::append(LibDir, "VC", "lib");
   8451       switch (MSVC.getArch()) {
   8452       case llvm::Triple::x86:
   8453         // x86 just puts the libraries directly in lib
   8454         break;
   8455       case llvm::Triple::x86_64:
   8456         llvm::sys::path::append(LibDir, "amd64");
   8457         break;
   8458       case llvm::Triple::arm:
   8459         llvm::sys::path::append(LibDir, "arm");
   8460         break;
   8461       default:
   8462         break;
   8463       }
   8464       CmdArgs.push_back(
   8465           Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
   8466     }
   8467 
   8468     std::string WindowsSdkLibPath;
   8469     if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
   8470       CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
   8471                                            WindowsSdkLibPath.c_str()));
   8472   }
   8473 
   8474   CmdArgs.push_back("-nologo");
   8475 
   8476   if (Args.hasArg(options::OPT_g_Group))
   8477     CmdArgs.push_back("-debug");
   8478 
   8479   bool DLL = Args.hasArg(options::OPT__SLASH_LD,
   8480                          options::OPT__SLASH_LDd,
   8481                          options::OPT_shared);
   8482   if (DLL) {
   8483     CmdArgs.push_back(Args.MakeArgString("-dll"));
   8484 
   8485     SmallString<128> ImplibName(Output.getFilename());
   8486     llvm::sys::path::replace_extension(ImplibName, "lib");
   8487     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") +
   8488                                          ImplibName));
   8489   }
   8490 
   8491   if (TC.getSanitizerArgs().needsAsanRt()) {
   8492     CmdArgs.push_back(Args.MakeArgString("-debug"));
   8493     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
   8494     if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
   8495       static const char *CompilerRTComponents[] = {
   8496         "asan_dynamic",
   8497         "asan_dynamic_runtime_thunk",
   8498       };
   8499       for (const auto &Component : CompilerRTComponents)
   8500         CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
   8501       // Make sure the dynamic runtime thunk is not optimized out at link time
   8502       // to ensure proper SEH handling.
   8503       CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
   8504     } else if (DLL) {
   8505       CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, "asan_dll_thunk")));
   8506     } else {
   8507       static const char *CompilerRTComponents[] = {
   8508         "asan",
   8509         "asan_cxx",
   8510       };
   8511       for (const auto &Component : CompilerRTComponents)
   8512         CmdArgs.push_back(Args.MakeArgString(getCompilerRT(TC, Component)));
   8513     }
   8514   }
   8515 
   8516   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
   8517 
   8518   // Add filenames, libraries, and other linker inputs.
   8519   for (const auto &Input : Inputs) {
   8520     if (Input.isFilename()) {
   8521       CmdArgs.push_back(Input.getFilename());
   8522       continue;
   8523     }
   8524 
   8525     const Arg &A = Input.getInputArg();
   8526 
   8527     // Render -l options differently for the MSVC linker.
   8528     if (A.getOption().matches(options::OPT_l)) {
   8529       StringRef Lib = A.getValue();
   8530       const char *LinkLibArg;
   8531       if (Lib.endswith(".lib"))
   8532         LinkLibArg = Args.MakeArgString(Lib);
   8533       else
   8534         LinkLibArg = Args.MakeArgString(Lib + ".lib");
   8535       CmdArgs.push_back(LinkLibArg);
   8536       continue;
   8537     }
   8538 
   8539     // Otherwise, this is some other kind of linker input option like -Wl, -z,
   8540     // or -L. Render it, even if MSVC doesn't understand it.
   8541     A.renderAsInput(Args, CmdArgs);
   8542   }
   8543 
   8544   // We need to special case some linker paths.  In the case of lld, we need to
   8545   // translate 'lld' into 'lld-link', and in the case of the regular msvc
   8546   // linker, we need to use a special search algorithm.
   8547   llvm::SmallString<128> linkPath;
   8548   StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
   8549   if (Linker.equals_lower("lld"))
   8550     Linker = "lld-link";
   8551 
   8552   if (Linker.equals_lower("link")) {
   8553     // If we're using the MSVC linker, it's not sufficient to just use link
   8554     // from the program PATH, because other environments like GnuWin32 install
   8555     // their own link.exe which may come first.
   8556     linkPath = FindVisualStudioExecutable(TC, "link.exe",
   8557                                           C.getDriver().getClangProgramPath());
   8558   } else {
   8559     linkPath = Linker;
   8560     llvm::sys::path::replace_extension(linkPath, "exe");
   8561     linkPath = TC.GetProgramPath(linkPath.c_str());
   8562   }
   8563 
   8564   const char *Exec = Args.MakeArgString(linkPath);
   8565   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8566 }
   8567 
   8568 void visualstudio::Compile::ConstructJob(Compilation &C, const JobAction &JA,
   8569                                          const InputInfo &Output,
   8570                                          const InputInfoList &Inputs,
   8571                                          const ArgList &Args,
   8572                                          const char *LinkingOutput) const {
   8573   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
   8574 }
   8575 
   8576 std::unique_ptr<Command> visualstudio::Compile::GetCommand(
   8577     Compilation &C, const JobAction &JA, const InputInfo &Output,
   8578     const InputInfoList &Inputs, const ArgList &Args,
   8579     const char *LinkingOutput) const {
   8580   ArgStringList CmdArgs;
   8581   CmdArgs.push_back("/nologo");
   8582   CmdArgs.push_back("/c"); // Compile only.
   8583   CmdArgs.push_back("/W0"); // No warnings.
   8584 
   8585   // The goal is to be able to invoke this tool correctly based on
   8586   // any flag accepted by clang-cl.
   8587 
   8588   // These are spelled the same way in clang and cl.exe,.
   8589   Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
   8590   Args.AddAllArgs(CmdArgs, options::OPT_I);
   8591 
   8592   // Optimization level.
   8593   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
   8594     if (A->getOption().getID() == options::OPT_O0) {
   8595       CmdArgs.push_back("/Od");
   8596     } else {
   8597       StringRef OptLevel = A->getValue();
   8598       if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
   8599         A->render(Args, CmdArgs);
   8600       else if (OptLevel == "3")
   8601         CmdArgs.push_back("/Ox");
   8602     }
   8603   }
   8604 
   8605   // Flags for which clang-cl has an alias.
   8606   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
   8607 
   8608   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
   8609                    /*default=*/false))
   8610     CmdArgs.push_back("/GR-");
   8611   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
   8612                                options::OPT_fno_function_sections))
   8613     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
   8614                           ? "/Gy"
   8615                           : "/Gy-");
   8616   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
   8617                                options::OPT_fno_data_sections))
   8618     CmdArgs.push_back(
   8619         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
   8620   if (Args.hasArg(options::OPT_fsyntax_only))
   8621     CmdArgs.push_back("/Zs");
   8622   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only))
   8623     CmdArgs.push_back("/Z7");
   8624 
   8625   std::vector<std::string> Includes =
   8626       Args.getAllArgValues(options::OPT_include);
   8627   for (const auto &Include : Includes)
   8628     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
   8629 
   8630   // Flags that can simply be passed through.
   8631   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
   8632   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
   8633   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
   8634 
   8635   // The order of these flags is relevant, so pick the last one.
   8636   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
   8637                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
   8638     A->render(Args, CmdArgs);
   8639 
   8640 
   8641   // Input filename.
   8642   assert(Inputs.size() == 1);
   8643   const InputInfo &II = Inputs[0];
   8644   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
   8645   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
   8646   if (II.isFilename())
   8647     CmdArgs.push_back(II.getFilename());
   8648   else
   8649     II.getInputArg().renderAsInput(Args, CmdArgs);
   8650 
   8651   // Output filename.
   8652   assert(Output.getType() == types::TY_Object);
   8653   const char *Fo = Args.MakeArgString(std::string("/Fo") +
   8654                                       Output.getFilename());
   8655   CmdArgs.push_back(Fo);
   8656 
   8657   const Driver &D = getToolChain().getDriver();
   8658   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
   8659                                                 D.getClangProgramPath());
   8660   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
   8661                                     CmdArgs);
   8662 }
   8663 
   8664 
   8665 /// XCore Tools
   8666 // We pass assemble and link construction to the xcc tool.
   8667 
   8668 void XCore::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   8669                                        const InputInfo &Output,
   8670                                        const InputInfoList &Inputs,
   8671                                        const ArgList &Args,
   8672                                        const char *LinkingOutput) const {
   8673   claimNoWarnArgs(Args);
   8674   ArgStringList CmdArgs;
   8675 
   8676   CmdArgs.push_back("-o");
   8677   CmdArgs.push_back(Output.getFilename());
   8678 
   8679   CmdArgs.push_back("-c");
   8680 
   8681   if (Args.hasArg(options::OPT_v))
   8682     CmdArgs.push_back("-v");
   8683 
   8684   if (Arg *A = Args.getLastArg(options::OPT_g_Group))
   8685     if (!A->getOption().matches(options::OPT_g0))
   8686       CmdArgs.push_back("-g");
   8687 
   8688   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
   8689                    false))
   8690     CmdArgs.push_back("-fverbose-asm");
   8691 
   8692   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
   8693                        options::OPT_Xassembler);
   8694 
   8695   for (const auto &II : Inputs)
   8696     CmdArgs.push_back(II.getFilename());
   8697 
   8698   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
   8699   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8700 }
   8701 
   8702 void XCore::Link::ConstructJob(Compilation &C, const JobAction &JA,
   8703                                    const InputInfo &Output,
   8704                                    const InputInfoList &Inputs,
   8705                                    const ArgList &Args,
   8706                                    const char *LinkingOutput) const {
   8707   ArgStringList CmdArgs;
   8708 
   8709   if (Output.isFilename()) {
   8710     CmdArgs.push_back("-o");
   8711     CmdArgs.push_back(Output.getFilename());
   8712   } else {
   8713     assert(Output.isNothing() && "Invalid output.");
   8714   }
   8715 
   8716   if (Args.hasArg(options::OPT_v))
   8717     CmdArgs.push_back("-v");
   8718 
   8719   if (exceptionSettings(Args, getToolChain().getTriple()))
   8720     CmdArgs.push_back("-fexceptions");
   8721 
   8722   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
   8723 
   8724   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
   8725   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8726 }
   8727 
   8728 void CrossWindows::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
   8729                                           const InputInfo &Output,
   8730                                           const InputInfoList &Inputs,
   8731                                           const ArgList &Args,
   8732                                           const char *LinkingOutput) const {
   8733   claimNoWarnArgs(Args);
   8734   const auto &TC =
   8735       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
   8736   ArgStringList CmdArgs;
   8737   const char *Exec;
   8738 
   8739   switch (TC.getArch()) {
   8740   default: llvm_unreachable("unsupported architecture");
   8741   case llvm::Triple::arm:
   8742   case llvm::Triple::thumb:
   8743     break;
   8744   case llvm::Triple::x86:
   8745     CmdArgs.push_back("--32");
   8746     break;
   8747   case llvm::Triple::x86_64:
   8748     CmdArgs.push_back("--64");
   8749     break;
   8750   }
   8751 
   8752   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
   8753 
   8754   CmdArgs.push_back("-o");
   8755   CmdArgs.push_back(Output.getFilename());
   8756 
   8757   for (const auto &Input : Inputs)
   8758     CmdArgs.push_back(Input.getFilename());
   8759 
   8760   const std::string Assembler = TC.GetProgramPath("as");
   8761   Exec = Args.MakeArgString(Assembler);
   8762 
   8763   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8764 }
   8765 
   8766 void CrossWindows::Link::ConstructJob(Compilation &C, const JobAction &JA,
   8767                                       const InputInfo &Output,
   8768                                       const InputInfoList &Inputs,
   8769                                       const ArgList &Args,
   8770                                       const char *LinkingOutput) const {
   8771   const auto &TC =
   8772       static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
   8773   const llvm::Triple &T = TC.getTriple();
   8774   const Driver &D = TC.getDriver();
   8775   SmallString<128> EntryPoint;
   8776   ArgStringList CmdArgs;
   8777   const char *Exec;
   8778 
   8779   // Silence warning for "clang -g foo.o -o foo"
   8780   Args.ClaimAllArgs(options::OPT_g_Group);
   8781   // and "clang -emit-llvm foo.o -o foo"
   8782   Args.ClaimAllArgs(options::OPT_emit_llvm);
   8783   // and for "clang -w foo.o -o foo"
   8784   Args.ClaimAllArgs(options::OPT_w);
   8785   // Other warning options are already handled somewhere else.
   8786 
   8787   if (!D.SysRoot.empty())
   8788     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
   8789 
   8790   if (Args.hasArg(options::OPT_pie))
   8791     CmdArgs.push_back("-pie");
   8792   if (Args.hasArg(options::OPT_rdynamic))
   8793     CmdArgs.push_back("-export-dynamic");
   8794   if (Args.hasArg(options::OPT_s))
   8795     CmdArgs.push_back("--strip-all");
   8796 
   8797   CmdArgs.push_back("-m");
   8798   switch (TC.getArch()) {
   8799   default: llvm_unreachable("unsupported architecture");
   8800   case llvm::Triple::arm:
   8801   case llvm::Triple::thumb:
   8802     // FIXME: this is incorrect for WinCE
   8803     CmdArgs.push_back("thumb2pe");
   8804     break;
   8805   case llvm::Triple::x86:
   8806     CmdArgs.push_back("i386pe");
   8807     EntryPoint.append("_");
   8808     break;
   8809   case llvm::Triple::x86_64:
   8810     CmdArgs.push_back("i386pep");
   8811     break;
   8812   }
   8813 
   8814   if (Args.hasArg(options::OPT_shared)) {
   8815     switch (T.getArch()) {
   8816     default: llvm_unreachable("unsupported architecture");
   8817     case llvm::Triple::arm:
   8818     case llvm::Triple::thumb:
   8819     case llvm::Triple::x86_64:
   8820       EntryPoint.append("_DllMainCRTStartup");
   8821       break;
   8822     case llvm::Triple::x86:
   8823       EntryPoint.append("_DllMainCRTStartup@12");
   8824       break;
   8825     }
   8826 
   8827     CmdArgs.push_back("-shared");
   8828     CmdArgs.push_back("-Bdynamic");
   8829 
   8830     CmdArgs.push_back("--enable-auto-image-base");
   8831 
   8832     CmdArgs.push_back("--entry");
   8833     CmdArgs.push_back(Args.MakeArgString(EntryPoint));
   8834   } else {
   8835     EntryPoint.append("mainCRTStartup");
   8836 
   8837     CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
   8838                                                        : "-Bdynamic");
   8839 
   8840     if (!Args.hasArg(options::OPT_nostdlib) &&
   8841         !Args.hasArg(options::OPT_nostartfiles)) {
   8842       CmdArgs.push_back("--entry");
   8843       CmdArgs.push_back(Args.MakeArgString(EntryPoint));
   8844     }
   8845 
   8846     // FIXME: handle subsystem
   8847   }
   8848 
   8849   // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
   8850   CmdArgs.push_back("--allow-multiple-definition");
   8851 
   8852   CmdArgs.push_back("-o");
   8853   CmdArgs.push_back(Output.getFilename());
   8854 
   8855   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
   8856     SmallString<261> ImpLib(Output.getFilename());
   8857     llvm::sys::path::replace_extension(ImpLib, ".lib");
   8858 
   8859     CmdArgs.push_back("--out-implib");
   8860     CmdArgs.push_back(Args.MakeArgString(ImpLib));
   8861   }
   8862 
   8863   if (!Args.hasArg(options::OPT_nostdlib) &&
   8864       !Args.hasArg(options::OPT_nostartfiles)) {
   8865     const std::string CRTPath(D.SysRoot + "/usr/lib/");
   8866     const char *CRTBegin;
   8867 
   8868     CRTBegin =
   8869         Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
   8870     CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
   8871   }
   8872 
   8873   Args.AddAllArgs(CmdArgs, options::OPT_L);
   8874 
   8875   const auto &Paths = TC.getFilePaths();
   8876   for (const auto &Path : Paths)
   8877     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + Path));
   8878 
   8879   AddLinkerInputs(TC, Inputs, Args, CmdArgs);
   8880 
   8881   if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
   8882       !Args.hasArg(options::OPT_nodefaultlibs)) {
   8883     bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
   8884                      !Args.hasArg(options::OPT_static);
   8885     if (StaticCXX)
   8886       CmdArgs.push_back("-Bstatic");
   8887     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
   8888     if (StaticCXX)
   8889       CmdArgs.push_back("-Bdynamic");
   8890   }
   8891 
   8892   if (!Args.hasArg(options::OPT_nostdlib)) {
   8893     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
   8894       // TODO handle /MT[d] /MD[d]
   8895       CmdArgs.push_back("-lmsvcrt");
   8896       AddRunTimeLibs(TC, D, CmdArgs, Args);
   8897     }
   8898   }
   8899 
   8900   const std::string Linker = TC.GetProgramPath("ld");
   8901   Exec = Args.MakeArgString(Linker);
   8902 
   8903   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs));
   8904 }
   8905