Tools.cpp revision 263984
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/ObjCRuntime.h"
14#include "clang/Basic/Version.h"
15#include "clang/Driver/Action.h"
16#include "clang/Driver/Compilation.h"
17#include "clang/Driver/Driver.h"
18#include "clang/Driver/DriverDiagnostic.h"
19#include "clang/Driver/Job.h"
20#include "clang/Driver/Options.h"
21#include "clang/Driver/SanitizerArgs.h"
22#include "clang/Driver/ToolChain.h"
23#include "clang/Driver/Util.h"
24#include "clang/Sema/SemaDiagnostic.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/StringSwitch.h"
28#include "llvm/ADT/Twine.h"
29#include "llvm/Option/Arg.h"
30#include "llvm/Option/ArgList.h"
31#include "llvm/Option/Option.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/Format.h"
35#include "llvm/Support/Host.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Program.h"
38#include "llvm/Support/Process.h"
39#include "llvm/Support/raw_ostream.h"
40#include <sys/stat.h>
41
42using namespace clang::driver;
43using namespace clang::driver::tools;
44using namespace clang;
45using namespace llvm::opt;
46
47/// CheckPreprocessingOptions - Perform some validation of preprocessing
48/// arguments that is shared with gcc.
49static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
50  if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC))
51    if (!Args.hasArg(options::OPT_E) && !D.CCCIsCPP())
52      D.Diag(diag::err_drv_argument_only_allowed_with)
53        << A->getAsString(Args) << "-E";
54}
55
56/// CheckCodeGenerationOptions - Perform some validation of code generation
57/// arguments that is shared with gcc.
58static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
59  // In gcc, only ARM checks this, but it seems reasonable to check universally.
60  if (Args.hasArg(options::OPT_static))
61    if (const Arg *A = Args.getLastArg(options::OPT_dynamic,
62                                       options::OPT_mdynamic_no_pic))
63      D.Diag(diag::err_drv_argument_not_allowed_with)
64        << A->getAsString(Args) << "-static";
65}
66
67// Quote target names for inclusion in GNU Make dependency files.
68// Only the characters '$', '#', ' ', '\t' are quoted.
69static void QuoteTarget(StringRef Target,
70                        SmallVectorImpl<char> &Res) {
71  for (unsigned i = 0, e = Target.size(); i != e; ++i) {
72    switch (Target[i]) {
73    case ' ':
74    case '\t':
75      // Escape the preceding backslashes
76      for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
77        Res.push_back('\\');
78
79      // Escape the space/tab
80      Res.push_back('\\');
81      break;
82    case '$':
83      Res.push_back('$');
84      break;
85    case '#':
86      Res.push_back('\\');
87      break;
88    default:
89      break;
90    }
91
92    Res.push_back(Target[i]);
93  }
94}
95
96static void addDirectoryList(const ArgList &Args,
97                             ArgStringList &CmdArgs,
98                             const char *ArgName,
99                             const char *EnvVar) {
100  const char *DirList = ::getenv(EnvVar);
101  bool CombinedArg = false;
102
103  if (!DirList)
104    return; // Nothing to do.
105
106  StringRef Name(ArgName);
107  if (Name.equals("-I") || Name.equals("-L"))
108    CombinedArg = true;
109
110  StringRef Dirs(DirList);
111  if (Dirs.empty()) // Empty string should not add '.'.
112    return;
113
114  StringRef::size_type Delim;
115  while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
116    if (Delim == 0) { // Leading colon.
117      if (CombinedArg) {
118        CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
119      } else {
120        CmdArgs.push_back(ArgName);
121        CmdArgs.push_back(".");
122      }
123    } else {
124      if (CombinedArg) {
125        CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
126      } else {
127        CmdArgs.push_back(ArgName);
128        CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
129      }
130    }
131    Dirs = Dirs.substr(Delim + 1);
132  }
133
134  if (Dirs.empty()) { // Trailing colon.
135    if (CombinedArg) {
136      CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
137    } else {
138      CmdArgs.push_back(ArgName);
139      CmdArgs.push_back(".");
140    }
141  } else { // Add the last path.
142    if (CombinedArg) {
143      CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
144    } else {
145      CmdArgs.push_back(ArgName);
146      CmdArgs.push_back(Args.MakeArgString(Dirs));
147    }
148  }
149}
150
151static void AddLinkerInputs(const ToolChain &TC,
152                            const InputInfoList &Inputs, const ArgList &Args,
153                            ArgStringList &CmdArgs) {
154  const Driver &D = TC.getDriver();
155
156  // Add extra linker input arguments which are not treated as inputs
157  // (constructed via -Xarch_).
158  Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
159
160  for (InputInfoList::const_iterator
161         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
162    const InputInfo &II = *it;
163
164    if (!TC.HasNativeLLVMSupport()) {
165      // Don't try to pass LLVM inputs unless we have native support.
166      if (II.getType() == types::TY_LLVM_IR ||
167          II.getType() == types::TY_LTO_IR ||
168          II.getType() == types::TY_LLVM_BC ||
169          II.getType() == types::TY_LTO_BC)
170        D.Diag(diag::err_drv_no_linker_llvm_support)
171          << TC.getTripleString();
172    }
173
174    // Add filenames immediately.
175    if (II.isFilename()) {
176      CmdArgs.push_back(II.getFilename());
177      continue;
178    }
179
180    // Otherwise, this is a linker input argument.
181    const Arg &A = II.getInputArg();
182
183    // Handle reserved library options.
184    if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
185      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
186    } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
187      TC.AddCCKextLibArgs(Args, CmdArgs);
188    } else
189      A.renderAsInput(Args, CmdArgs);
190  }
191
192  // LIBRARY_PATH - included following the user specified library paths.
193  addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
194}
195
196/// \brief Determine whether Objective-C automated reference counting is
197/// enabled.
198static bool isObjCAutoRefCount(const ArgList &Args) {
199  return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
200}
201
202/// \brief Determine whether we are linking the ObjC runtime.
203static bool isObjCRuntimeLinked(const ArgList &Args) {
204  if (isObjCAutoRefCount(Args)) {
205    Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
206    return true;
207  }
208  return Args.hasArg(options::OPT_fobjc_link_runtime);
209}
210
211static void addProfileRT(const ToolChain &TC, const ArgList &Args,
212                         ArgStringList &CmdArgs,
213                         llvm::Triple Triple) {
214  if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
215        Args.hasArg(options::OPT_fprofile_generate) ||
216        Args.hasArg(options::OPT_fcreate_profile) ||
217        Args.hasArg(options::OPT_coverage)))
218    return;
219
220  // GCC links libgcov.a by adding -L<inst>/gcc/lib/gcc/<triple>/<ver> -lgcov to
221  // the link line. We cannot do the same thing because unlike gcov there is a
222  // libprofile_rt.so. We used to use the -l:libprofile_rt.a syntax, but that is
223  // not supported by old linkers.
224  std::string ProfileRT =
225    std::string(TC.getDriver().Dir) + "/../lib/libprofile_rt.a";
226
227  CmdArgs.push_back(Args.MakeArgString(ProfileRT));
228}
229
230static bool forwardToGCC(const Option &O) {
231  // Don't forward inputs from the original command line.  They are added from
232  // InputInfoList.
233  return O.getKind() != Option::InputClass &&
234         !O.hasFlag(options::DriverOption) &&
235         !O.hasFlag(options::LinkerInput);
236}
237
238void Clang::AddPreprocessingOptions(Compilation &C,
239                                    const JobAction &JA,
240                                    const Driver &D,
241                                    const ArgList &Args,
242                                    ArgStringList &CmdArgs,
243                                    const InputInfo &Output,
244                                    const InputInfoList &Inputs) const {
245  Arg *A;
246
247  CheckPreprocessingOptions(D, Args);
248
249  Args.AddLastArg(CmdArgs, options::OPT_C);
250  Args.AddLastArg(CmdArgs, options::OPT_CC);
251
252  // Handle dependency file generation.
253  if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
254      (A = Args.getLastArg(options::OPT_MD)) ||
255      (A = Args.getLastArg(options::OPT_MMD))) {
256    // Determine the output location.
257    const char *DepFile;
258    if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
259      DepFile = MF->getValue();
260      C.addFailureResultFile(DepFile, &JA);
261    } else if (Output.getType() == types::TY_Dependencies) {
262      DepFile = Output.getFilename();
263    } else if (A->getOption().matches(options::OPT_M) ||
264               A->getOption().matches(options::OPT_MM)) {
265      DepFile = "-";
266    } else {
267      DepFile = getDependencyFileName(Args, Inputs);
268      C.addFailureResultFile(DepFile, &JA);
269    }
270    CmdArgs.push_back("-dependency-file");
271    CmdArgs.push_back(DepFile);
272
273    // Add a default target if one wasn't specified.
274    if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
275      const char *DepTarget;
276
277      // If user provided -o, that is the dependency target, except
278      // when we are only generating a dependency file.
279      Arg *OutputOpt = Args.getLastArg(options::OPT_o);
280      if (OutputOpt && Output.getType() != types::TY_Dependencies) {
281        DepTarget = OutputOpt->getValue();
282      } else {
283        // Otherwise derive from the base input.
284        //
285        // FIXME: This should use the computed output file location.
286        SmallString<128> P(Inputs[0].getBaseInput());
287        llvm::sys::path::replace_extension(P, "o");
288        DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
289      }
290
291      CmdArgs.push_back("-MT");
292      SmallString<128> Quoted;
293      QuoteTarget(DepTarget, Quoted);
294      CmdArgs.push_back(Args.MakeArgString(Quoted));
295    }
296
297    if (A->getOption().matches(options::OPT_M) ||
298        A->getOption().matches(options::OPT_MD))
299      CmdArgs.push_back("-sys-header-deps");
300  }
301
302  if (Args.hasArg(options::OPT_MG)) {
303    if (!A || A->getOption().matches(options::OPT_MD) ||
304              A->getOption().matches(options::OPT_MMD))
305      D.Diag(diag::err_drv_mg_requires_m_or_mm);
306    CmdArgs.push_back("-MG");
307  }
308
309  Args.AddLastArg(CmdArgs, options::OPT_MP);
310
311  // Convert all -MQ <target> args to -MT <quoted target>
312  for (arg_iterator it = Args.filtered_begin(options::OPT_MT,
313                                             options::OPT_MQ),
314         ie = Args.filtered_end(); it != ie; ++it) {
315    const Arg *A = *it;
316    A->claim();
317
318    if (A->getOption().matches(options::OPT_MQ)) {
319      CmdArgs.push_back("-MT");
320      SmallString<128> Quoted;
321      QuoteTarget(A->getValue(), Quoted);
322      CmdArgs.push_back(Args.MakeArgString(Quoted));
323
324    // -MT flag - no change
325    } else {
326      A->render(Args, CmdArgs);
327    }
328  }
329
330  // Add -i* options, and automatically translate to
331  // -include-pch/-include-pth for transparent PCH support. It's
332  // wonky, but we include looking for .gch so we can support seamless
333  // replacement into a build system already set up to be generating
334  // .gch files.
335  bool RenderedImplicitInclude = false;
336  for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group),
337         ie = Args.filtered_end(); it != ie; ++it) {
338    const Arg *A = it;
339
340    if (A->getOption().matches(options::OPT_include)) {
341      bool IsFirstImplicitInclude = !RenderedImplicitInclude;
342      RenderedImplicitInclude = true;
343
344      // Use PCH if the user requested it.
345      bool UsePCH = D.CCCUsePCH;
346
347      bool FoundPTH = false;
348      bool FoundPCH = false;
349      SmallString<128> P(A->getValue());
350      // We want the files to have a name like foo.h.pch. Add a dummy extension
351      // so that replace_extension does the right thing.
352      P += ".dummy";
353      if (UsePCH) {
354        llvm::sys::path::replace_extension(P, "pch");
355        if (llvm::sys::fs::exists(P.str()))
356          FoundPCH = true;
357      }
358
359      if (!FoundPCH) {
360        llvm::sys::path::replace_extension(P, "pth");
361        if (llvm::sys::fs::exists(P.str()))
362          FoundPTH = true;
363      }
364
365      if (!FoundPCH && !FoundPTH) {
366        llvm::sys::path::replace_extension(P, "gch");
367        if (llvm::sys::fs::exists(P.str())) {
368          FoundPCH = UsePCH;
369          FoundPTH = !UsePCH;
370        }
371      }
372
373      if (FoundPCH || FoundPTH) {
374        if (IsFirstImplicitInclude) {
375          A->claim();
376          if (UsePCH)
377            CmdArgs.push_back("-include-pch");
378          else
379            CmdArgs.push_back("-include-pth");
380          CmdArgs.push_back(Args.MakeArgString(P.str()));
381          continue;
382        } else {
383          // Ignore the PCH if not first on command line and emit warning.
384          D.Diag(diag::warn_drv_pch_not_first_include)
385              << P.str() << A->getAsString(Args);
386        }
387      }
388    }
389
390    // Not translated, render as usual.
391    A->claim();
392    A->render(Args, CmdArgs);
393  }
394
395  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
396  Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F,
397                  options::OPT_index_header_map);
398
399  // Add -Wp, and -Xassembler if using the preprocessor.
400
401  // FIXME: There is a very unfortunate problem here, some troubled
402  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
403  // really support that we would have to parse and then translate
404  // those options. :(
405  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
406                       options::OPT_Xpreprocessor);
407
408  // -I- is a deprecated GCC feature, reject it.
409  if (Arg *A = Args.getLastArg(options::OPT_I_))
410    D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
411
412  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
413  // -isysroot to the CC1 invocation.
414  StringRef sysroot = C.getSysRoot();
415  if (sysroot != "") {
416    if (!Args.hasArg(options::OPT_isysroot)) {
417      CmdArgs.push_back("-isysroot");
418      CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
419    }
420  }
421
422  // Parse additional include paths from environment variables.
423  // FIXME: We should probably sink the logic for handling these from the
424  // frontend into the driver. It will allow deleting 4 otherwise unused flags.
425  // CPATH - included following the user specified includes (but prior to
426  // builtin and standard includes).
427  addDirectoryList(Args, CmdArgs, "-I", "CPATH");
428  // C_INCLUDE_PATH - system includes enabled when compiling C.
429  addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
430  // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
431  addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
432  // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
433  addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
434  // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
435  addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
436
437  // Add C++ include arguments, if needed.
438  if (types::isCXX(Inputs[0].getType()))
439    getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
440
441  // Add system include arguments.
442  getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
443}
444
445/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
446/// CPU.
447//
448// FIXME: This is redundant with -mcpu, why does LLVM use this.
449// FIXME: tblgen this, or kill it!
450static const char *getLLVMArchSuffixForARM(StringRef CPU) {
451  return llvm::StringSwitch<const char *>(CPU)
452    .Case("strongarm", "v4")
453    .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
454    .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
455    .Cases("arm920", "arm920t", "arm922t", "v4t")
456    .Cases("arm940t", "ep9312","v4t")
457    .Cases("arm10tdmi",  "arm1020t", "v5")
458    .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
459    .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
460    .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
461    .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
462    .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
463    .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
464    .Cases("cortex-a5", "cortex-a7", "cortex-a8", "v7")
465    .Cases("cortex-a9", "cortex-a12", "cortex-a15", "v7")
466    .Cases("cortex-r4", "cortex-r5", "v7r")
467    .Case("cortex-m0", "v6m")
468    .Case("cortex-m3", "v7m")
469    .Case("cortex-m4", "v7em")
470    .Case("cortex-a9-mp", "v7f")
471    .Case("swift", "v7s")
472    .Cases("cortex-a53", "cortex-a57", "v8")
473    .Default("");
474}
475
476/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
477//
478// FIXME: tblgen this.
479static std::string getARMTargetCPU(const ArgList &Args,
480                                   const llvm::Triple &Triple) {
481  // FIXME: Warn on inconsistent use of -mcpu and -march.
482
483  // If we have -mcpu=, use that.
484  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
485    StringRef MCPU = A->getValue();
486    // Handle -mcpu=native.
487    if (MCPU == "native")
488      return llvm::sys::getHostCPUName();
489    else
490      return MCPU;
491  }
492
493  StringRef MArch;
494  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
495    // Otherwise, if we have -march= choose the base CPU for that arch.
496    MArch = A->getValue();
497  } else {
498    // Otherwise, use the Arch from the triple.
499    MArch = Triple.getArchName();
500  }
501
502  if (Triple.getOS() == llvm::Triple::NetBSD) {
503    if (MArch == "armv6")
504      return "arm1176jzf-s";
505  }
506
507  // Handle -march=native.
508  std::string NativeMArch;
509  if (MArch == "native") {
510    std::string CPU = llvm::sys::getHostCPUName();
511    if (CPU != "generic") {
512      // Translate the native cpu into the architecture. The switch below will
513      // then chose the minimum cpu for that arch.
514      NativeMArch = std::string("arm") + getLLVMArchSuffixForARM(CPU);
515      MArch = NativeMArch;
516    }
517  }
518
519  return llvm::StringSwitch<const char *>(MArch)
520    .Cases("armv2", "armv2a","arm2")
521    .Case("armv3", "arm6")
522    .Case("armv3m", "arm7m")
523    .Case("armv4", "strongarm")
524    .Case("armv4t", "arm7tdmi")
525    .Cases("armv5", "armv5t", "arm10tdmi")
526    .Cases("armv5e", "armv5te", "arm1022e")
527    .Case("armv5tej", "arm926ej-s")
528    .Cases("armv6", "armv6k", "arm1136jf-s")
529    .Case("armv6j", "arm1136j-s")
530    .Cases("armv6z", "armv6zk", "arm1176jzf-s")
531    .Case("armv6t2", "arm1156t2-s")
532    .Cases("armv6m", "armv6-m", "cortex-m0")
533    .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
534    .Cases("armv7em", "armv7e-m", "cortex-m4")
535    .Cases("armv7f", "armv7-f", "cortex-a9-mp")
536    .Cases("armv7s", "armv7-s", "swift")
537    .Cases("armv7r", "armv7-r", "cortex-r4")
538    .Cases("armv7m", "armv7-m", "cortex-m3")
539    .Cases("armv8", "armv8a", "armv8-a", "cortex-a53")
540    .Case("ep9312", "ep9312")
541    .Case("iwmmxt", "iwmmxt")
542    .Case("xscale", "xscale")
543    // If all else failed, return the most base CPU with thumb interworking
544    // supported by LLVM.
545    .Default("arm7tdmi");
546}
547
548/// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are targeting.
549//
550// FIXME: tblgen this.
551static std::string getAArch64TargetCPU(const ArgList &Args,
552                                       const llvm::Triple &Triple) {
553  // FIXME: Warn on inconsistent use of -mcpu and -march.
554
555  // If we have -mcpu=, use that.
556  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
557    StringRef MCPU = A->getValue();
558    // Handle -mcpu=native.
559    if (MCPU == "native")
560      return llvm::sys::getHostCPUName();
561    else
562      return MCPU;
563  }
564
565  return "generic";
566}
567
568// FIXME: Move to target hook.
569static bool isSignedCharDefault(const llvm::Triple &Triple) {
570  switch (Triple.getArch()) {
571  default:
572    return true;
573
574  case llvm::Triple::aarch64:
575  case llvm::Triple::arm:
576  case llvm::Triple::ppc:
577  case llvm::Triple::ppc64:
578    if (Triple.isOSDarwin())
579      return true;
580    return false;
581
582  case llvm::Triple::ppc64le:
583  case llvm::Triple::systemz:
584  case llvm::Triple::xcore:
585    return false;
586  }
587}
588
589static bool isNoCommonDefault(const llvm::Triple &Triple) {
590  switch (Triple.getArch()) {
591  default:
592    return false;
593
594  case llvm::Triple::xcore:
595    return true;
596  }
597}
598
599// Handle -mfpu=.
600//
601// FIXME: Centralize feature selection, defaulting shouldn't be also in the
602// frontend target.
603static void getAArch64FPUFeatures(const Driver &D, const Arg *A,
604                                  const ArgList &Args,
605                                  std::vector<const char *> &Features) {
606  StringRef FPU = A->getValue();
607  if (FPU == "fp-armv8") {
608    Features.push_back("+fp-armv8");
609  } else if (FPU == "neon-fp-armv8") {
610    Features.push_back("+fp-armv8");
611    Features.push_back("+neon");
612  } else if (FPU == "crypto-neon-fp-armv8") {
613    Features.push_back("+fp-armv8");
614    Features.push_back("+neon");
615    Features.push_back("+crypto");
616  } else if (FPU == "neon") {
617    Features.push_back("+neon");
618  } else if (FPU == "none") {
619    Features.push_back("-fp-armv8");
620    Features.push_back("-crypto");
621    Features.push_back("-neon");
622  } else
623    D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
624}
625
626// Handle -mhwdiv=.
627static void getARMHWDivFeatures(const Driver &D, const Arg *A,
628                              const ArgList &Args,
629                              std::vector<const char *> &Features) {
630  StringRef HWDiv = A->getValue();
631  if (HWDiv == "arm") {
632    Features.push_back("+hwdiv-arm");
633    Features.push_back("-hwdiv");
634  } else if (HWDiv == "thumb") {
635    Features.push_back("-hwdiv-arm");
636    Features.push_back("+hwdiv");
637  } else if (HWDiv == "arm,thumb" || HWDiv == "thumb,arm") {
638    Features.push_back("+hwdiv-arm");
639    Features.push_back("+hwdiv");
640  } else if (HWDiv == "none") {
641    Features.push_back("-hwdiv-arm");
642    Features.push_back("-hwdiv");
643  } else
644    D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
645}
646
647// Handle -mfpu=.
648//
649// FIXME: Centralize feature selection, defaulting shouldn't be also in the
650// frontend target.
651static void getARMFPUFeatures(const Driver &D, const Arg *A,
652                              const ArgList &Args,
653                              std::vector<const char *> &Features) {
654  StringRef FPU = A->getValue();
655
656  // Set the target features based on the FPU.
657  if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") {
658    // Disable any default FPU support.
659    Features.push_back("-vfp2");
660    Features.push_back("-vfp3");
661    Features.push_back("-neon");
662  } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") {
663    Features.push_back("+vfp3");
664    Features.push_back("+d16");
665    Features.push_back("-neon");
666  } else if (FPU == "vfp") {
667    Features.push_back("+vfp2");
668    Features.push_back("-neon");
669  } else if (FPU == "vfp3" || FPU == "vfpv3") {
670    Features.push_back("+vfp3");
671    Features.push_back("-neon");
672  } else if (FPU == "fp-armv8") {
673    Features.push_back("+fp-armv8");
674    Features.push_back("-neon");
675    Features.push_back("-crypto");
676  } else if (FPU == "neon-fp-armv8") {
677    Features.push_back("+fp-armv8");
678    Features.push_back("+neon");
679    Features.push_back("-crypto");
680  } else if (FPU == "crypto-neon-fp-armv8") {
681    Features.push_back("+fp-armv8");
682    Features.push_back("+neon");
683    Features.push_back("+crypto");
684  } else if (FPU == "neon") {
685    Features.push_back("+neon");
686  } else if (FPU == "none") {
687    Features.push_back("-vfp2");
688    Features.push_back("-vfp3");
689    Features.push_back("-vfp4");
690    Features.push_back("-fp-armv8");
691    Features.push_back("-crypto");
692    Features.push_back("-neon");
693  } else
694    D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
695}
696
697// Select the float ABI as determined by -msoft-float, -mhard-float, and
698// -mfloat-abi=.
699static StringRef getARMFloatABI(const Driver &D,
700                                const ArgList &Args,
701                                const llvm::Triple &Triple) {
702  StringRef FloatABI;
703  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
704                               options::OPT_mhard_float,
705                               options::OPT_mfloat_abi_EQ)) {
706    if (A->getOption().matches(options::OPT_msoft_float))
707      FloatABI = "soft";
708    else if (A->getOption().matches(options::OPT_mhard_float))
709      FloatABI = "hard";
710    else {
711      FloatABI = A->getValue();
712      if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") {
713        D.Diag(diag::err_drv_invalid_mfloat_abi)
714          << A->getAsString(Args);
715        FloatABI = "soft";
716      }
717    }
718  }
719
720  // If unspecified, choose the default based on the platform.
721  if (FloatABI.empty()) {
722    switch (Triple.getOS()) {
723    case llvm::Triple::Darwin:
724    case llvm::Triple::MacOSX:
725    case llvm::Triple::IOS: {
726      // Darwin defaults to "softfp" for v6 and v7.
727      //
728      // FIXME: Factor out an ARM class so we can cache the arch somewhere.
729      std::string ArchName =
730        getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
731      if (StringRef(ArchName).startswith("v6") ||
732          StringRef(ArchName).startswith("v7"))
733        FloatABI = "softfp";
734      else
735        FloatABI = "soft";
736      break;
737    }
738
739    case llvm::Triple::FreeBSD:
740      // FreeBSD defaults to soft float
741      FloatABI = "soft";
742      break;
743
744    default:
745      switch(Triple.getEnvironment()) {
746      case llvm::Triple::GNUEABIHF:
747        FloatABI = "hard";
748        break;
749      case llvm::Triple::GNUEABI:
750        FloatABI = "softfp";
751        break;
752      case llvm::Triple::EABI:
753        // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
754        FloatABI = "softfp";
755        break;
756      case llvm::Triple::Android: {
757        std::string ArchName =
758          getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
759        if (StringRef(ArchName).startswith("v7"))
760          FloatABI = "softfp";
761        else
762          FloatABI = "soft";
763        break;
764      }
765      default:
766        // Assume "soft", but warn the user we are guessing.
767        FloatABI = "soft";
768        D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
769        break;
770      }
771    }
772  }
773
774  return FloatABI;
775}
776
777static void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
778                                 const ArgList &Args,
779                                 std::vector<const char *> &Features) {
780  StringRef FloatABI = getARMFloatABI(D, Args, Triple);
781  // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
782  // yet (it uses the -mfloat-abi and -msoft-float options), and it is
783  // stripped out by the ARM target.
784  // Use software floating point operations?
785  if (FloatABI == "soft")
786    Features.push_back("+soft-float");
787
788  // Use software floating point argument passing?
789  if (FloatABI != "hard")
790    Features.push_back("+soft-float-abi");
791
792  // Honor -mfpu=.
793  if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
794    getARMFPUFeatures(D, A, Args, Features);
795  if (const Arg *A = Args.getLastArg(options::OPT_mhwdiv_EQ))
796    getARMHWDivFeatures(D, A, Args, Features);
797
798  // Setting -msoft-float effectively disables NEON because of the GCC
799  // implementation, although the same isn't true of VFP or VFP3.
800  if (FloatABI == "soft")
801    Features.push_back("-neon");
802
803  // En/disable crc
804  if (Arg *A = Args.getLastArg(options::OPT_mcrc,
805                               options::OPT_mnocrc)) {
806    if (A->getOption().matches(options::OPT_mcrc))
807      Features.push_back("+crc");
808    else
809      Features.push_back("-crc");
810  }
811}
812
813void Clang::AddARMTargetArgs(const ArgList &Args,
814                             ArgStringList &CmdArgs,
815                             bool KernelOrKext) const {
816  const Driver &D = getToolChain().getDriver();
817  // Get the effective triple, which takes into account the deployment target.
818  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
819  llvm::Triple Triple(TripleStr);
820  std::string CPUName = getARMTargetCPU(Args, Triple);
821
822  // Select the ABI to use.
823  //
824  // FIXME: Support -meabi.
825  const char *ABIName = 0;
826  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
827    ABIName = A->getValue();
828  } else if (Triple.isOSDarwin()) {
829    // The backend is hardwired to assume AAPCS for M-class processors, ensure
830    // the frontend matches that.
831    if (Triple.getEnvironment() == llvm::Triple::EABI ||
832        StringRef(CPUName).startswith("cortex-m")) {
833      ABIName = "aapcs";
834    } else {
835      ABIName = "apcs-gnu";
836    }
837  } else {
838    // Select the default based on the platform.
839    switch(Triple.getEnvironment()) {
840    case llvm::Triple::Android:
841    case llvm::Triple::GNUEABI:
842    case llvm::Triple::GNUEABIHF:
843      ABIName = "aapcs-linux";
844      break;
845    case llvm::Triple::EABI:
846      ABIName = "aapcs";
847      break;
848    default:
849      ABIName = "apcs-gnu";
850    }
851  }
852  CmdArgs.push_back("-target-abi");
853  CmdArgs.push_back(ABIName);
854
855  // Determine floating point ABI from the options & target defaults.
856  StringRef FloatABI = getARMFloatABI(D, Args, Triple);
857  if (FloatABI == "soft") {
858    // Floating point operations and argument passing are soft.
859    //
860    // FIXME: This changes CPP defines, we need -target-soft-float.
861    CmdArgs.push_back("-msoft-float");
862    CmdArgs.push_back("-mfloat-abi");
863    CmdArgs.push_back("soft");
864  } else if (FloatABI == "softfp") {
865    // Floating point operations are hard, but argument passing is soft.
866    CmdArgs.push_back("-mfloat-abi");
867    CmdArgs.push_back("soft");
868  } else {
869    // Floating point operations and argument passing are hard.
870    assert(FloatABI == "hard" && "Invalid float abi!");
871    CmdArgs.push_back("-mfloat-abi");
872    CmdArgs.push_back("hard");
873  }
874
875  // Kernel code has more strict alignment requirements.
876  if (KernelOrKext) {
877    if (!Triple.isiOS() || Triple.isOSVersionLT(6)) {
878      CmdArgs.push_back("-backend-option");
879      CmdArgs.push_back("-arm-long-calls");
880    }
881
882    CmdArgs.push_back("-backend-option");
883    CmdArgs.push_back("-arm-strict-align");
884
885    // The kext linker doesn't know how to deal with movw/movt.
886    CmdArgs.push_back("-backend-option");
887    CmdArgs.push_back("-arm-use-movt=0");
888  }
889
890  // Setting -mno-global-merge disables the codegen global merge pass. Setting
891  // -mglobal-merge has no effect as the pass is enabled by default.
892  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
893                               options::OPT_mno_global_merge)) {
894    if (A->getOption().matches(options::OPT_mno_global_merge))
895      CmdArgs.push_back("-mno-global-merge");
896  }
897
898  if (!Args.hasFlag(options::OPT_mimplicit_float,
899                    options::OPT_mno_implicit_float,
900                    true))
901    CmdArgs.push_back("-no-implicit-float");
902
903    // llvm does not support reserving registers in general. There is support
904    // for reserving r9 on ARM though (defined as a platform-specific register
905    // in ARM EABI).
906    if (Args.hasArg(options::OPT_ffixed_r9)) {
907      CmdArgs.push_back("-backend-option");
908      CmdArgs.push_back("-arm-reserve-r9");
909    }
910}
911
912// Get CPU and ABI names. They are not independent
913// so we have to calculate them together.
914static void getMipsCPUAndABI(const ArgList &Args,
915                             const llvm::Triple &Triple,
916                             StringRef &CPUName,
917                             StringRef &ABIName) {
918  const char *DefMips32CPU = "mips32";
919  const char *DefMips64CPU = "mips64";
920
921  if (Arg *A = Args.getLastArg(options::OPT_march_EQ,
922                               options::OPT_mcpu_EQ))
923    CPUName = A->getValue();
924
925  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
926    ABIName = A->getValue();
927    // Convert a GNU style Mips ABI name to the name
928    // accepted by LLVM Mips backend.
929    ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
930      .Case("32", "o32")
931      .Case("64", "n64")
932      .Default(ABIName);
933  }
934
935  // Setup default CPU and ABI names.
936  if (CPUName.empty() && ABIName.empty()) {
937    switch (Triple.getArch()) {
938    default:
939      llvm_unreachable("Unexpected triple arch name");
940    case llvm::Triple::mips:
941    case llvm::Triple::mipsel:
942      CPUName = DefMips32CPU;
943      break;
944    case llvm::Triple::mips64:
945    case llvm::Triple::mips64el:
946      CPUName = DefMips64CPU;
947      break;
948    }
949  }
950
951  if (!ABIName.empty()) {
952    // Deduce CPU name from ABI name.
953    CPUName = llvm::StringSwitch<const char *>(ABIName)
954      .Cases("32", "o32", "eabi", DefMips32CPU)
955      .Cases("n32", "n64", "64", DefMips64CPU)
956      .Default("");
957  }
958  else if (!CPUName.empty()) {
959    // Deduce ABI name from CPU name.
960    ABIName = llvm::StringSwitch<const char *>(CPUName)
961      .Cases("mips32", "mips32r2", "o32")
962      .Cases("mips64", "mips64r2", "n64")
963      .Default("");
964  }
965
966  // FIXME: Warn on inconsistent cpu and abi usage.
967}
968
969// Convert ABI name to the GNU tools acceptable variant.
970static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
971  return llvm::StringSwitch<llvm::StringRef>(ABI)
972    .Case("o32", "32")
973    .Case("n64", "64")
974    .Default(ABI);
975}
976
977// Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
978// and -mfloat-abi=.
979static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
980  StringRef FloatABI;
981  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
982                               options::OPT_mhard_float,
983                               options::OPT_mfloat_abi_EQ)) {
984    if (A->getOption().matches(options::OPT_msoft_float))
985      FloatABI = "soft";
986    else if (A->getOption().matches(options::OPT_mhard_float))
987      FloatABI = "hard";
988    else {
989      FloatABI = A->getValue();
990      if (FloatABI != "soft" && FloatABI != "hard") {
991        D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
992        FloatABI = "hard";
993      }
994    }
995  }
996
997  // If unspecified, choose the default based on the platform.
998  if (FloatABI.empty()) {
999    // Assume "hard", because it's a default value used by gcc.
1000    // When we start to recognize specific target MIPS processors,
1001    // we will be able to select the default more correctly.
1002    FloatABI = "hard";
1003  }
1004
1005  return FloatABI;
1006}
1007
1008static void AddTargetFeature(const ArgList &Args,
1009                             std::vector<const char *> &Features,
1010                             OptSpecifier OnOpt, OptSpecifier OffOpt,
1011                             StringRef FeatureName) {
1012  if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1013    if (A->getOption().matches(OnOpt))
1014      Features.push_back(Args.MakeArgString("+" + FeatureName));
1015    else
1016      Features.push_back(Args.MakeArgString("-" + FeatureName));
1017  }
1018}
1019
1020static void getMIPSTargetFeatures(const Driver &D, const ArgList &Args,
1021                                  std::vector<const char *> &Features) {
1022  StringRef FloatABI = getMipsFloatABI(D, Args);
1023  bool IsMips16 = Args.getLastArg(options::OPT_mips16) != NULL;
1024  if (FloatABI == "soft" || (FloatABI == "hard" && IsMips16)) {
1025    // FIXME: Note, this is a hack. We need to pass the selected float
1026    // mode to the MipsTargetInfoBase to define appropriate macros there.
1027    // Now it is the only method.
1028    Features.push_back("+soft-float");
1029  }
1030
1031  if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1032    if (StringRef(A->getValue()) == "2008")
1033      Features.push_back("+nan2008");
1034  }
1035
1036  AddTargetFeature(Args, Features, options::OPT_msingle_float,
1037                   options::OPT_mdouble_float, "single-float");
1038  AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1039                   "mips16");
1040  AddTargetFeature(Args, Features, options::OPT_mmicromips,
1041                   options::OPT_mno_micromips, "micromips");
1042  AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1043                   "dsp");
1044  AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1045                   "dspr2");
1046  AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1047                   "msa");
1048  AddTargetFeature(Args, Features, options::OPT_mfp64, options::OPT_mfp32,
1049                   "fp64");
1050}
1051
1052void Clang::AddMIPSTargetArgs(const ArgList &Args,
1053                              ArgStringList &CmdArgs) const {
1054  const Driver &D = getToolChain().getDriver();
1055  StringRef CPUName;
1056  StringRef ABIName;
1057  const llvm::Triple &Triple = getToolChain().getTriple();
1058  getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1059
1060  CmdArgs.push_back("-target-abi");
1061  CmdArgs.push_back(ABIName.data());
1062
1063  StringRef FloatABI = getMipsFloatABI(D, Args);
1064
1065  bool IsMips16 = Args.getLastArg(options::OPT_mips16) != NULL;
1066
1067  if (FloatABI == "soft" || (FloatABI == "hard" && IsMips16)) {
1068    // Floating point operations and argument passing are soft.
1069    CmdArgs.push_back("-msoft-float");
1070    CmdArgs.push_back("-mfloat-abi");
1071    CmdArgs.push_back("soft");
1072
1073    if (FloatABI == "hard" && IsMips16) {
1074      CmdArgs.push_back("-mllvm");
1075      CmdArgs.push_back("-mips16-hard-float");
1076    }
1077  }
1078  else {
1079    // Floating point operations and argument passing are hard.
1080    assert(FloatABI == "hard" && "Invalid float abi!");
1081    CmdArgs.push_back("-mfloat-abi");
1082    CmdArgs.push_back("hard");
1083  }
1084
1085  if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1086    if (A->getOption().matches(options::OPT_mxgot)) {
1087      CmdArgs.push_back("-mllvm");
1088      CmdArgs.push_back("-mxgot");
1089    }
1090  }
1091
1092  if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1093                               options::OPT_mno_ldc1_sdc1)) {
1094    if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1095      CmdArgs.push_back("-mllvm");
1096      CmdArgs.push_back("-mno-ldc1-sdc1");
1097    }
1098  }
1099
1100  if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1101                               options::OPT_mno_check_zero_division)) {
1102    if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1103      CmdArgs.push_back("-mllvm");
1104      CmdArgs.push_back("-mno-check-zero-division");
1105    }
1106  }
1107
1108  if (Arg *A = Args.getLastArg(options::OPT_G)) {
1109    StringRef v = A->getValue();
1110    CmdArgs.push_back("-mllvm");
1111    CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1112    A->claim();
1113  }
1114}
1115
1116/// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1117static std::string getPPCTargetCPU(const ArgList &Args) {
1118  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1119    StringRef CPUName = A->getValue();
1120
1121    if (CPUName == "native") {
1122      std::string CPU = llvm::sys::getHostCPUName();
1123      if (!CPU.empty() && CPU != "generic")
1124        return CPU;
1125      else
1126        return "";
1127    }
1128
1129    return llvm::StringSwitch<const char *>(CPUName)
1130      .Case("common", "generic")
1131      .Case("440", "440")
1132      .Case("440fp", "440")
1133      .Case("450", "450")
1134      .Case("601", "601")
1135      .Case("602", "602")
1136      .Case("603", "603")
1137      .Case("603e", "603e")
1138      .Case("603ev", "603ev")
1139      .Case("604", "604")
1140      .Case("604e", "604e")
1141      .Case("620", "620")
1142      .Case("630", "pwr3")
1143      .Case("G3", "g3")
1144      .Case("7400", "7400")
1145      .Case("G4", "g4")
1146      .Case("7450", "7450")
1147      .Case("G4+", "g4+")
1148      .Case("750", "750")
1149      .Case("970", "970")
1150      .Case("G5", "g5")
1151      .Case("a2", "a2")
1152      .Case("a2q", "a2q")
1153      .Case("e500mc", "e500mc")
1154      .Case("e5500", "e5500")
1155      .Case("power3", "pwr3")
1156      .Case("power4", "pwr4")
1157      .Case("power5", "pwr5")
1158      .Case("power5x", "pwr5x")
1159      .Case("power6", "pwr6")
1160      .Case("power6x", "pwr6x")
1161      .Case("power7", "pwr7")
1162      .Case("pwr3", "pwr3")
1163      .Case("pwr4", "pwr4")
1164      .Case("pwr5", "pwr5")
1165      .Case("pwr5x", "pwr5x")
1166      .Case("pwr6", "pwr6")
1167      .Case("pwr6x", "pwr6x")
1168      .Case("pwr7", "pwr7")
1169      .Case("powerpc", "ppc")
1170      .Case("powerpc64", "ppc64")
1171      .Case("powerpc64le", "ppc64le")
1172      .Default("");
1173  }
1174
1175  return "";
1176}
1177
1178static void getPPCTargetFeatures(const ArgList &Args,
1179                                 std::vector<const char *> &Features) {
1180  for (arg_iterator it = Args.filtered_begin(options::OPT_m_ppc_Features_Group),
1181                    ie = Args.filtered_end();
1182       it != ie; ++it) {
1183    StringRef Name = (*it)->getOption().getName();
1184    (*it)->claim();
1185
1186    // Skip over "-m".
1187    assert(Name.startswith("m") && "Invalid feature name.");
1188    Name = Name.substr(1);
1189
1190    bool IsNegative = Name.startswith("no-");
1191    if (IsNegative)
1192      Name = Name.substr(3);
1193
1194    // Note that gcc calls this mfcrf and LLVM calls this mfocrf so we
1195    // pass the correct option to the backend while calling the frontend
1196    // option the same.
1197    // TODO: Change the LLVM backend option maybe?
1198    if (Name == "mfcrf")
1199      Name = "mfocrf";
1200
1201    Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1202  }
1203
1204  // Altivec is a bit weird, allow overriding of the Altivec feature here.
1205  AddTargetFeature(Args, Features, options::OPT_faltivec,
1206                   options::OPT_fno_altivec, "altivec");
1207}
1208
1209/// Get the (LLVM) name of the R600 gpu we are targeting.
1210static std::string getR600TargetGPU(const ArgList &Args) {
1211  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1212    const char *GPUName = A->getValue();
1213    return llvm::StringSwitch<const char *>(GPUName)
1214      .Cases("rv630", "rv635", "r600")
1215      .Cases("rv610", "rv620", "rs780", "rs880")
1216      .Case("rv740", "rv770")
1217      .Case("palm", "cedar")
1218      .Cases("sumo", "sumo2", "sumo")
1219      .Case("hemlock", "cypress")
1220      .Case("aruba", "cayman")
1221      .Default(GPUName);
1222  }
1223  return "";
1224}
1225
1226static void getSparcTargetFeatures(const ArgList &Args,
1227                                   std::vector<const char *> Features) {
1228  bool SoftFloatABI = true;
1229  if (Arg *A =
1230          Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1231    if (A->getOption().matches(options::OPT_mhard_float))
1232      SoftFloatABI = false;
1233  }
1234  if (SoftFloatABI)
1235    Features.push_back("+soft-float");
1236}
1237
1238void Clang::AddSparcTargetArgs(const ArgList &Args,
1239                             ArgStringList &CmdArgs) const {
1240  const Driver &D = getToolChain().getDriver();
1241
1242  // Select the float ABI as determined by -msoft-float, -mhard-float, and
1243  StringRef FloatABI;
1244  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1245                               options::OPT_mhard_float)) {
1246    if (A->getOption().matches(options::OPT_msoft_float))
1247      FloatABI = "soft";
1248    else if (A->getOption().matches(options::OPT_mhard_float))
1249      FloatABI = "hard";
1250  }
1251
1252  // If unspecified, choose the default based on the platform.
1253  if (FloatABI.empty()) {
1254    // Assume "soft", but warn the user we are guessing.
1255    FloatABI = "soft";
1256    D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
1257  }
1258
1259  if (FloatABI == "soft") {
1260    // Floating point operations and argument passing are soft.
1261    //
1262    // FIXME: This changes CPP defines, we need -target-soft-float.
1263    CmdArgs.push_back("-msoft-float");
1264  } else {
1265    assert(FloatABI == "hard" && "Invalid float abi!");
1266    CmdArgs.push_back("-mhard-float");
1267  }
1268}
1269
1270static const char *getSystemZTargetCPU(const ArgList &Args) {
1271  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1272    return A->getValue();
1273  return "z10";
1274}
1275
1276static const char *getX86TargetCPU(const ArgList &Args,
1277                                   const llvm::Triple &Triple) {
1278  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1279    if (StringRef(A->getValue()) != "native") {
1280      if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1281        return "core-avx2";
1282
1283      return A->getValue();
1284    }
1285
1286    // FIXME: Reject attempts to use -march=native unless the target matches
1287    // the host.
1288    //
1289    // FIXME: We should also incorporate the detected target features for use
1290    // with -native.
1291    std::string CPU = llvm::sys::getHostCPUName();
1292    if (!CPU.empty() && CPU != "generic")
1293      return Args.MakeArgString(CPU);
1294  }
1295
1296  // Select the default CPU if none was given (or detection failed).
1297
1298  if (Triple.getArch() != llvm::Triple::x86_64 &&
1299      Triple.getArch() != llvm::Triple::x86)
1300    return 0; // This routine is only handling x86 targets.
1301
1302  bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1303
1304  // FIXME: Need target hooks.
1305  if (Triple.isOSDarwin()) {
1306    if (Triple.getArchName() == "x86_64h")
1307      return "core-avx2";
1308    return Is64Bit ? "core2" : "yonah";
1309  }
1310
1311  // All x86 devices running Android have core2 as their common
1312  // denominator. This makes a better choice than pentium4.
1313  if (Triple.getEnvironment() == llvm::Triple::Android)
1314    return "core2";
1315
1316  // Everything else goes to x86-64 in 64-bit mode.
1317  if (Is64Bit)
1318    return "x86-64";
1319
1320  switch (Triple.getOS()) {
1321  case llvm::Triple::FreeBSD:
1322  case llvm::Triple::NetBSD:
1323  case llvm::Triple::OpenBSD:
1324    return "i486";
1325  case llvm::Triple::Haiku:
1326    return "i586";
1327  case llvm::Triple::Bitrig:
1328    return "i686";
1329  default:
1330    // Fallback to p4.
1331    return "pentium4";
1332  }
1333}
1334
1335static std::string getCPUName(const ArgList &Args, const llvm::Triple &T) {
1336  switch(T.getArch()) {
1337  default:
1338    return "";
1339
1340  case llvm::Triple::aarch64:
1341    return getAArch64TargetCPU(Args, T);
1342
1343  case llvm::Triple::arm:
1344  case llvm::Triple::thumb:
1345    return getARMTargetCPU(Args, T);
1346
1347  case llvm::Triple::mips:
1348  case llvm::Triple::mipsel:
1349  case llvm::Triple::mips64:
1350  case llvm::Triple::mips64el: {
1351    StringRef CPUName;
1352    StringRef ABIName;
1353    getMipsCPUAndABI(Args, T, CPUName, ABIName);
1354    return CPUName;
1355  }
1356
1357  case llvm::Triple::ppc:
1358  case llvm::Triple::ppc64:
1359  case llvm::Triple::ppc64le: {
1360    std::string TargetCPUName = getPPCTargetCPU(Args);
1361    // LLVM may default to generating code for the native CPU,
1362    // but, like gcc, we default to a more generic option for
1363    // each architecture. (except on Darwin)
1364    if (TargetCPUName.empty() && !T.isOSDarwin()) {
1365      if (T.getArch() == llvm::Triple::ppc64)
1366        TargetCPUName = "ppc64";
1367      else if (T.getArch() == llvm::Triple::ppc64le)
1368        TargetCPUName = "ppc64le";
1369      else
1370        TargetCPUName = "ppc";
1371    }
1372    return TargetCPUName;
1373  }
1374
1375  case llvm::Triple::sparc:
1376  case llvm::Triple::sparcv9:
1377    if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1378      return A->getValue();
1379    return "";
1380
1381  case llvm::Triple::x86:
1382  case llvm::Triple::x86_64:
1383    return getX86TargetCPU(Args, T);
1384
1385  case llvm::Triple::hexagon:
1386    return "hexagon" + toolchains::Hexagon_TC::GetTargetCPU(Args).str();
1387
1388  case llvm::Triple::systemz:
1389    return getSystemZTargetCPU(Args);
1390
1391  case llvm::Triple::r600:
1392    return getR600TargetGPU(Args);
1393  }
1394}
1395
1396static void getX86TargetFeatures(const llvm::Triple &Triple,
1397                                 const ArgList &Args,
1398                                 std::vector<const char *> &Features) {
1399  if (Triple.getArchName() == "x86_64h") {
1400    // x86_64h implies quite a few of the more modern subtarget features
1401    // for Haswell class CPUs, but not all of them. Opt-out of a few.
1402    Features.push_back("-rdrnd");
1403    Features.push_back("-aes");
1404    Features.push_back("-pclmul");
1405    Features.push_back("-rtm");
1406    Features.push_back("-hle");
1407    Features.push_back("-fsgsbase");
1408  }
1409
1410  // Now add any that the user explicitly requested on the command line,
1411  // which may override the defaults.
1412  for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group),
1413                    ie = Args.filtered_end();
1414       it != ie; ++it) {
1415    StringRef Name = (*it)->getOption().getName();
1416    (*it)->claim();
1417
1418    // Skip over "-m".
1419    assert(Name.startswith("m") && "Invalid feature name.");
1420    Name = Name.substr(1);
1421
1422    bool IsNegative = Name.startswith("no-");
1423    if (IsNegative)
1424      Name = Name.substr(3);
1425
1426    Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
1427  }
1428}
1429
1430void Clang::AddX86TargetArgs(const ArgList &Args,
1431                             ArgStringList &CmdArgs) const {
1432  if (!Args.hasFlag(options::OPT_mred_zone,
1433                    options::OPT_mno_red_zone,
1434                    true) ||
1435      Args.hasArg(options::OPT_mkernel) ||
1436      Args.hasArg(options::OPT_fapple_kext))
1437    CmdArgs.push_back("-disable-red-zone");
1438
1439  // Default to avoid implicit floating-point for kernel/kext code, but allow
1440  // that to be overridden with -mno-soft-float.
1441  bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1442                          Args.hasArg(options::OPT_fapple_kext));
1443  if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
1444                               options::OPT_mno_soft_float,
1445                               options::OPT_mimplicit_float,
1446                               options::OPT_mno_implicit_float)) {
1447    const Option &O = A->getOption();
1448    NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1449                       O.matches(options::OPT_msoft_float));
1450  }
1451  if (NoImplicitFloat)
1452    CmdArgs.push_back("-no-implicit-float");
1453}
1454
1455static inline bool HasPICArg(const ArgList &Args) {
1456  return Args.hasArg(options::OPT_fPIC)
1457    || Args.hasArg(options::OPT_fpic);
1458}
1459
1460static Arg *GetLastSmallDataThresholdArg(const ArgList &Args) {
1461  return Args.getLastArg(options::OPT_G,
1462                         options::OPT_G_EQ,
1463                         options::OPT_msmall_data_threshold_EQ);
1464}
1465
1466static std::string GetHexagonSmallDataThresholdValue(const ArgList &Args) {
1467  std::string value;
1468  if (HasPICArg(Args))
1469    value = "0";
1470  else if (Arg *A = GetLastSmallDataThresholdArg(Args)) {
1471    value = A->getValue();
1472    A->claim();
1473  }
1474  return value;
1475}
1476
1477void Clang::AddHexagonTargetArgs(const ArgList &Args,
1478                                 ArgStringList &CmdArgs) const {
1479  CmdArgs.push_back("-fno-signed-char");
1480  CmdArgs.push_back("-mqdsp6-compat");
1481  CmdArgs.push_back("-Wreturn-type");
1482
1483  std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
1484  if (!SmallDataThreshold.empty()) {
1485    CmdArgs.push_back ("-mllvm");
1486    CmdArgs.push_back(Args.MakeArgString(
1487                        "-hexagon-small-data-threshold=" + SmallDataThreshold));
1488  }
1489
1490  if (!Args.hasArg(options::OPT_fno_short_enums))
1491    CmdArgs.push_back("-fshort-enums");
1492  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1493    CmdArgs.push_back ("-mllvm");
1494    CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near");
1495  }
1496  CmdArgs.push_back ("-mllvm");
1497  CmdArgs.push_back ("-machine-sink-split=0");
1498}
1499
1500static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
1501                                     std::vector<const char *> &Features) {
1502  // Honor -mfpu=.
1503  if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ))
1504    getAArch64FPUFeatures(D, A, Args, Features);
1505}
1506
1507static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1508                              const ArgList &Args, ArgStringList &CmdArgs) {
1509  std::vector<const char *> Features;
1510  switch (Triple.getArch()) {
1511  default:
1512    break;
1513  case llvm::Triple::mips:
1514  case llvm::Triple::mipsel:
1515  case llvm::Triple::mips64:
1516  case llvm::Triple::mips64el:
1517    getMIPSTargetFeatures(D, Args, Features);
1518    break;
1519
1520  case llvm::Triple::arm:
1521  case llvm::Triple::thumb:
1522    getARMTargetFeatures(D, Triple, Args, Features);
1523    break;
1524
1525  case llvm::Triple::ppc:
1526  case llvm::Triple::ppc64:
1527  case llvm::Triple::ppc64le:
1528    getPPCTargetFeatures(Args, Features);
1529    break;
1530  case llvm::Triple::sparc:
1531    getSparcTargetFeatures(Args, Features);
1532    break;
1533  case llvm::Triple::aarch64:
1534    getAArch64TargetFeatures(D, Args, Features);
1535    break;
1536  case llvm::Triple::x86:
1537  case llvm::Triple::x86_64:
1538    getX86TargetFeatures(Triple, Args, Features);
1539    break;
1540  }
1541
1542  // Find the last of each feature.
1543  llvm::StringMap<unsigned> LastOpt;
1544  for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1545    const char *Name = Features[I];
1546    assert(Name[0] == '-' || Name[0] == '+');
1547    LastOpt[Name + 1] = I;
1548  }
1549
1550  for (unsigned I = 0, N = Features.size(); I < N; ++I) {
1551    // If this feature was overridden, ignore it.
1552    const char *Name = Features[I];
1553    llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
1554    assert(LastI != LastOpt.end());
1555    unsigned Last = LastI->second;
1556    if (Last != I)
1557      continue;
1558
1559    CmdArgs.push_back("-target-feature");
1560    CmdArgs.push_back(Name);
1561  }
1562}
1563
1564static bool
1565shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
1566                                          const llvm::Triple &Triple) {
1567  // We use the zero-cost exception tables for Objective-C if the non-fragile
1568  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
1569  // later.
1570  if (runtime.isNonFragile())
1571    return true;
1572
1573  if (!Triple.isOSDarwin())
1574    return false;
1575
1576  return (!Triple.isMacOSXVersionLT(10,5) &&
1577          (Triple.getArch() == llvm::Triple::x86_64 ||
1578           Triple.getArch() == llvm::Triple::arm));
1579}
1580
1581/// addExceptionArgs - Adds exception related arguments to the driver command
1582/// arguments. There's a master flag, -fexceptions and also language specific
1583/// flags to enable/disable C++ and Objective-C exceptions.
1584/// This makes it possible to for example disable C++ exceptions but enable
1585/// Objective-C exceptions.
1586static void addExceptionArgs(const ArgList &Args, types::ID InputType,
1587                             const llvm::Triple &Triple,
1588                             bool KernelOrKext,
1589                             const ObjCRuntime &objcRuntime,
1590                             ArgStringList &CmdArgs) {
1591  if (KernelOrKext) {
1592    // -mkernel and -fapple-kext imply no exceptions, so claim exception related
1593    // arguments now to avoid warnings about unused arguments.
1594    Args.ClaimAllArgs(options::OPT_fexceptions);
1595    Args.ClaimAllArgs(options::OPT_fno_exceptions);
1596    Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
1597    Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
1598    Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
1599    Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
1600    return;
1601  }
1602
1603  // Exceptions are enabled by default.
1604  bool ExceptionsEnabled = true;
1605
1606  // This keeps track of whether exceptions were explicitly turned on or off.
1607  bool DidHaveExplicitExceptionFlag = false;
1608
1609  if (Arg *A = Args.getLastArg(options::OPT_fexceptions,
1610                               options::OPT_fno_exceptions)) {
1611    if (A->getOption().matches(options::OPT_fexceptions))
1612      ExceptionsEnabled = true;
1613    else
1614      ExceptionsEnabled = false;
1615
1616    DidHaveExplicitExceptionFlag = true;
1617  }
1618
1619  bool ShouldUseExceptionTables = false;
1620
1621  // Exception tables and cleanups can be enabled with -fexceptions even if the
1622  // language itself doesn't support exceptions.
1623  if (ExceptionsEnabled && DidHaveExplicitExceptionFlag)
1624    ShouldUseExceptionTables = true;
1625
1626  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
1627  // is not necessarily sensible, but follows GCC.
1628  if (types::isObjC(InputType) &&
1629      Args.hasFlag(options::OPT_fobjc_exceptions,
1630                   options::OPT_fno_objc_exceptions,
1631                   true)) {
1632    CmdArgs.push_back("-fobjc-exceptions");
1633
1634    ShouldUseExceptionTables |=
1635      shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
1636  }
1637
1638  if (types::isCXX(InputType)) {
1639    bool CXXExceptionsEnabled = ExceptionsEnabled;
1640
1641    if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions,
1642                                 options::OPT_fno_cxx_exceptions,
1643                                 options::OPT_fexceptions,
1644                                 options::OPT_fno_exceptions)) {
1645      if (A->getOption().matches(options::OPT_fcxx_exceptions))
1646        CXXExceptionsEnabled = true;
1647      else if (A->getOption().matches(options::OPT_fno_cxx_exceptions))
1648        CXXExceptionsEnabled = false;
1649    }
1650
1651    if (CXXExceptionsEnabled) {
1652      CmdArgs.push_back("-fcxx-exceptions");
1653
1654      ShouldUseExceptionTables = true;
1655    }
1656  }
1657
1658  if (ShouldUseExceptionTables)
1659    CmdArgs.push_back("-fexceptions");
1660}
1661
1662static bool ShouldDisableAutolink(const ArgList &Args,
1663                             const ToolChain &TC) {
1664  bool Default = true;
1665  if (TC.getTriple().isOSDarwin()) {
1666    // The native darwin assembler doesn't support the linker_option directives,
1667    // so we disable them if we think the .s file will be passed to it.
1668    Default = TC.useIntegratedAs();
1669  }
1670  return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
1671                       Default);
1672}
1673
1674static bool ShouldDisableCFI(const ArgList &Args,
1675                             const ToolChain &TC) {
1676  bool Default = true;
1677  if (TC.getTriple().isOSDarwin()) {
1678    // The native darwin assembler doesn't support cfi directives, so
1679    // we disable them if we think the .s file will be passed to it.
1680    Default = TC.useIntegratedAs();
1681  }
1682  return !Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
1683                       options::OPT_fno_dwarf2_cfi_asm,
1684                       Default);
1685}
1686
1687static bool ShouldDisableDwarfDirectory(const ArgList &Args,
1688                                        const ToolChain &TC) {
1689  bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm,
1690                                        options::OPT_fno_dwarf_directory_asm,
1691                                        TC.useIntegratedAs());
1692  return !UseDwarfDirectory;
1693}
1694
1695/// \brief Check whether the given input tree contains any compilation actions.
1696static bool ContainsCompileAction(const Action *A) {
1697  if (isa<CompileJobAction>(A))
1698    return true;
1699
1700  for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
1701    if (ContainsCompileAction(*it))
1702      return true;
1703
1704  return false;
1705}
1706
1707/// \brief Check if -relax-all should be passed to the internal assembler.
1708/// This is done by default when compiling non-assembler source with -O0.
1709static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
1710  bool RelaxDefault = true;
1711
1712  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1713    RelaxDefault = A->getOption().matches(options::OPT_O0);
1714
1715  if (RelaxDefault) {
1716    RelaxDefault = false;
1717    for (ActionList::const_iterator it = C.getActions().begin(),
1718           ie = C.getActions().end(); it != ie; ++it) {
1719      if (ContainsCompileAction(*it)) {
1720        RelaxDefault = true;
1721        break;
1722      }
1723    }
1724  }
1725
1726  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1727    RelaxDefault);
1728}
1729
1730static void CollectArgsForIntegratedAssembler(Compilation &C,
1731                                              const ArgList &Args,
1732                                              ArgStringList &CmdArgs,
1733                                              const Driver &D) {
1734    if (UseRelaxAll(C, Args))
1735      CmdArgs.push_back("-mrelax-all");
1736
1737    // When passing -I arguments to the assembler we sometimes need to
1738    // unconditionally take the next argument.  For example, when parsing
1739    // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1740    // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1741    // arg after parsing the '-I' arg.
1742    bool TakeNextArg = false;
1743
1744    // When using an integrated assembler, translate -Wa, and -Xassembler
1745    // options.
1746    for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA,
1747                                               options::OPT_Xassembler),
1748           ie = Args.filtered_end(); it != ie; ++it) {
1749      const Arg *A = *it;
1750      A->claim();
1751
1752      for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) {
1753        StringRef Value = A->getValue(i);
1754        if (TakeNextArg) {
1755          CmdArgs.push_back(Value.data());
1756          TakeNextArg = false;
1757          continue;
1758        }
1759
1760        if (Value == "-force_cpusubtype_ALL") {
1761          // Do nothing, this is the default and we don't support anything else.
1762        } else if (Value == "-L") {
1763          CmdArgs.push_back("-msave-temp-labels");
1764        } else if (Value == "--fatal-warnings") {
1765          CmdArgs.push_back("-mllvm");
1766          CmdArgs.push_back("-fatal-assembler-warnings");
1767        } else if (Value == "--noexecstack") {
1768          CmdArgs.push_back("-mnoexecstack");
1769        } else if (Value.startswith("-I")) {
1770          CmdArgs.push_back(Value.data());
1771          // We need to consume the next argument if the current arg is a plain
1772          // -I. The next arg will be the include directory.
1773          if (Value == "-I")
1774            TakeNextArg = true;
1775        } else {
1776          D.Diag(diag::err_drv_unsupported_option_argument)
1777            << A->getOption().getName() << Value;
1778        }
1779      }
1780    }
1781}
1782
1783static void addProfileRTLinux(
1784    const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs) {
1785  if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
1786        Args.hasArg(options::OPT_fprofile_generate) ||
1787        Args.hasArg(options::OPT_fcreate_profile) ||
1788        Args.hasArg(options::OPT_coverage)))
1789    return;
1790
1791  // The profile runtime is located in the Linux library directory and has name
1792  // "libclang_rt.profile-<ArchName>.a".
1793  SmallString<128> LibProfile(TC.getDriver().ResourceDir);
1794  llvm::sys::path::append(
1795      LibProfile, "lib", "linux",
1796      Twine("libclang_rt.profile-") + TC.getArchName() + ".a");
1797
1798  CmdArgs.push_back(Args.MakeArgString(LibProfile));
1799}
1800
1801static void addSanitizerRTLinkFlagsLinux(
1802    const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs,
1803    const StringRef Sanitizer, bool BeforeLibStdCXX,
1804    bool ExportSymbols = true) {
1805  // Sanitizer runtime is located in the Linux library directory and
1806  // has name "libclang_rt.<Sanitizer>-<ArchName>.a".
1807  SmallString<128> LibSanitizer(TC.getDriver().ResourceDir);
1808  llvm::sys::path::append(
1809      LibSanitizer, "lib", "linux",
1810      (Twine("libclang_rt.") + Sanitizer + "-" + TC.getArchName() + ".a"));
1811
1812  // Sanitizer runtime may need to come before -lstdc++ (or -lc++, libstdc++.a,
1813  // etc.) so that the linker picks custom versions of the global 'operator
1814  // new' and 'operator delete' symbols. We take the extreme (but simple)
1815  // strategy of inserting it at the front of the link command. It also
1816  // needs to be forced to end up in the executable, so wrap it in
1817  // whole-archive.
1818  SmallVector<const char *, 3> LibSanitizerArgs;
1819  LibSanitizerArgs.push_back("-whole-archive");
1820  LibSanitizerArgs.push_back(Args.MakeArgString(LibSanitizer));
1821  LibSanitizerArgs.push_back("-no-whole-archive");
1822
1823  CmdArgs.insert(BeforeLibStdCXX ? CmdArgs.begin() : CmdArgs.end(),
1824                 LibSanitizerArgs.begin(), LibSanitizerArgs.end());
1825
1826  CmdArgs.push_back("-lpthread");
1827  CmdArgs.push_back("-lrt");
1828  CmdArgs.push_back("-ldl");
1829  CmdArgs.push_back("-lm");
1830
1831  // If possible, use a dynamic symbols file to export the symbols from the
1832  // runtime library. If we can't do so, use -export-dynamic instead to export
1833  // all symbols from the binary.
1834  if (ExportSymbols) {
1835    if (llvm::sys::fs::exists(LibSanitizer + ".syms"))
1836      CmdArgs.push_back(
1837          Args.MakeArgString("--dynamic-list=" + LibSanitizer + ".syms"));
1838    else
1839      CmdArgs.push_back("-export-dynamic");
1840  }
1841}
1842
1843/// If AddressSanitizer is enabled, add appropriate linker flags (Linux).
1844/// This needs to be called before we add the C run-time (malloc, etc).
1845static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
1846                           ArgStringList &CmdArgs) {
1847  if (TC.getTriple().getEnvironment() == llvm::Triple::Android) {
1848    SmallString<128> LibAsan(TC.getDriver().ResourceDir);
1849    llvm::sys::path::append(LibAsan, "lib", "linux",
1850        (Twine("libclang_rt.asan-") +
1851            TC.getArchName() + "-android.so"));
1852    CmdArgs.insert(CmdArgs.begin(), Args.MakeArgString(LibAsan));
1853  } else {
1854    if (!Args.hasArg(options::OPT_shared))
1855      addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "asan", true);
1856  }
1857}
1858
1859/// If ThreadSanitizer is enabled, add appropriate linker flags (Linux).
1860/// This needs to be called before we add the C run-time (malloc, etc).
1861static void addTsanRTLinux(const ToolChain &TC, const ArgList &Args,
1862                           ArgStringList &CmdArgs) {
1863  if (!Args.hasArg(options::OPT_shared))
1864    addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "tsan", true);
1865}
1866
1867/// If MemorySanitizer is enabled, add appropriate linker flags (Linux).
1868/// This needs to be called before we add the C run-time (malloc, etc).
1869static void addMsanRTLinux(const ToolChain &TC, const ArgList &Args,
1870                           ArgStringList &CmdArgs) {
1871  if (!Args.hasArg(options::OPT_shared))
1872    addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "msan", true);
1873}
1874
1875/// If LeakSanitizer is enabled, add appropriate linker flags (Linux).
1876/// This needs to be called before we add the C run-time (malloc, etc).
1877static void addLsanRTLinux(const ToolChain &TC, const ArgList &Args,
1878                           ArgStringList &CmdArgs) {
1879  if (!Args.hasArg(options::OPT_shared))
1880    addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "lsan", true);
1881}
1882
1883/// If UndefinedBehaviorSanitizer is enabled, add appropriate linker flags
1884/// (Linux).
1885static void addUbsanRTLinux(const ToolChain &TC, const ArgList &Args,
1886                            ArgStringList &CmdArgs, bool IsCXX,
1887                            bool HasOtherSanitizerRt) {
1888  // Need a copy of sanitizer_common. This could come from another sanitizer
1889  // runtime; if we're not including one, include our own copy.
1890  if (!HasOtherSanitizerRt)
1891    addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "san", true, false);
1892
1893  addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "ubsan", false);
1894
1895  // Only include the bits of the runtime which need a C++ ABI library if
1896  // we're linking in C++ mode.
1897  if (IsCXX)
1898    addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "ubsan_cxx", false);
1899}
1900
1901static void addDfsanRTLinux(const ToolChain &TC, const ArgList &Args,
1902                            ArgStringList &CmdArgs) {
1903  if (!Args.hasArg(options::OPT_shared))
1904    addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "dfsan", true);
1905}
1906
1907static bool shouldUseFramePointerForTarget(const ArgList &Args,
1908                                           const llvm::Triple &Triple) {
1909  switch (Triple.getArch()) {
1910  // Don't use a frame pointer on linux if optimizing for certain targets.
1911  case llvm::Triple::mips64:
1912  case llvm::Triple::mips64el:
1913  case llvm::Triple::mips:
1914  case llvm::Triple::mipsel:
1915  case llvm::Triple::systemz:
1916  case llvm::Triple::x86:
1917  case llvm::Triple::x86_64:
1918    if (Triple.isOSLinux())
1919      if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1920        if (!A->getOption().matches(options::OPT_O0))
1921          return false;
1922    return true;
1923  case llvm::Triple::xcore:
1924    return false;
1925  default:
1926    return true;
1927  }
1928}
1929
1930static bool shouldUseFramePointer(const ArgList &Args,
1931                                  const llvm::Triple &Triple) {
1932  if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
1933                               options::OPT_fomit_frame_pointer))
1934    return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
1935
1936  return shouldUseFramePointerForTarget(Args, Triple);
1937}
1938
1939static bool shouldUseLeafFramePointer(const ArgList &Args,
1940                                      const llvm::Triple &Triple) {
1941  if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
1942                               options::OPT_momit_leaf_frame_pointer))
1943    return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
1944
1945  return shouldUseFramePointerForTarget(Args, Triple);
1946}
1947
1948/// Add a CC1 option to specify the debug compilation directory.
1949static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
1950  SmallString<128> cwd;
1951  if (!llvm::sys::fs::current_path(cwd)) {
1952    CmdArgs.push_back("-fdebug-compilation-dir");
1953    CmdArgs.push_back(Args.MakeArgString(cwd));
1954  }
1955}
1956
1957static const char *SplitDebugName(const ArgList &Args,
1958                                  const InputInfoList &Inputs) {
1959  Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1960  if (FinalOutput && Args.hasArg(options::OPT_c)) {
1961    SmallString<128> T(FinalOutput->getValue());
1962    llvm::sys::path::replace_extension(T, "dwo");
1963    return Args.MakeArgString(T);
1964  } else {
1965    // Use the compilation dir.
1966    SmallString<128> T(Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
1967    SmallString<128> F(llvm::sys::path::stem(Inputs[0].getBaseInput()));
1968    llvm::sys::path::replace_extension(F, "dwo");
1969    T += F;
1970    return Args.MakeArgString(F);
1971  }
1972}
1973
1974static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
1975                           const Tool &T, const JobAction &JA,
1976                           const ArgList &Args, const InputInfo &Output,
1977                           const char *OutFile) {
1978  ArgStringList ExtractArgs;
1979  ExtractArgs.push_back("--extract-dwo");
1980
1981  ArgStringList StripArgs;
1982  StripArgs.push_back("--strip-dwo");
1983
1984  // Grabbing the output of the earlier compile step.
1985  StripArgs.push_back(Output.getFilename());
1986  ExtractArgs.push_back(Output.getFilename());
1987  ExtractArgs.push_back(OutFile);
1988
1989  const char *Exec =
1990    Args.MakeArgString(TC.GetProgramPath("objcopy"));
1991
1992  // First extract the dwo sections.
1993  C.addCommand(new Command(JA, T, Exec, ExtractArgs));
1994
1995  // Then remove them from the original .o file.
1996  C.addCommand(new Command(JA, T, Exec, StripArgs));
1997}
1998
1999static bool isOptimizationLevelFast(const ArgList &Args) {
2000  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2001    if (A->getOption().matches(options::OPT_Ofast))
2002      return true;
2003  return false;
2004}
2005
2006/// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2007static bool shouldEnableVectorizerAtOLevel(const ArgList &Args) {
2008  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2009    if (A->getOption().matches(options::OPT_O4) ||
2010        A->getOption().matches(options::OPT_Ofast))
2011      return true;
2012
2013    if (A->getOption().matches(options::OPT_O0))
2014      return false;
2015
2016    assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
2017
2018    // Vectorize -Os.
2019    StringRef S(A->getValue());
2020    if (S == "s")
2021      return true;
2022
2023    // Don't vectorize -Oz.
2024    if (S == "z")
2025      return false;
2026
2027    unsigned OptLevel = 0;
2028    if (S.getAsInteger(10, OptLevel))
2029      return false;
2030
2031    return OptLevel > 1;
2032  }
2033
2034  return false;
2035}
2036
2037void Clang::ConstructJob(Compilation &C, const JobAction &JA,
2038                         const InputInfo &Output,
2039                         const InputInfoList &Inputs,
2040                         const ArgList &Args,
2041                         const char *LinkingOutput) const {
2042  bool KernelOrKext = Args.hasArg(options::OPT_mkernel,
2043                                  options::OPT_fapple_kext);
2044  const Driver &D = getToolChain().getDriver();
2045  ArgStringList CmdArgs;
2046
2047  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
2048
2049  // Invoke ourselves in -cc1 mode.
2050  //
2051  // FIXME: Implement custom jobs for internal actions.
2052  CmdArgs.push_back("-cc1");
2053
2054  // Add the "effective" target triple.
2055  CmdArgs.push_back("-triple");
2056  std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2057  CmdArgs.push_back(Args.MakeArgString(TripleStr));
2058
2059  // Select the appropriate action.
2060  RewriteKind rewriteKind = RK_None;
2061
2062  if (isa<AnalyzeJobAction>(JA)) {
2063    assert(JA.getType() == types::TY_Plist && "Invalid output type.");
2064    CmdArgs.push_back("-analyze");
2065  } else if (isa<MigrateJobAction>(JA)) {
2066    CmdArgs.push_back("-migrate");
2067  } else if (isa<PreprocessJobAction>(JA)) {
2068    if (Output.getType() == types::TY_Dependencies)
2069      CmdArgs.push_back("-Eonly");
2070    else {
2071      CmdArgs.push_back("-E");
2072      if (Args.hasArg(options::OPT_rewrite_objc) &&
2073          !Args.hasArg(options::OPT_g_Group))
2074        CmdArgs.push_back("-P");
2075    }
2076  } else if (isa<AssembleJobAction>(JA)) {
2077    CmdArgs.push_back("-emit-obj");
2078
2079    CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
2080
2081    // Also ignore explicit -force_cpusubtype_ALL option.
2082    (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
2083  } else if (isa<PrecompileJobAction>(JA)) {
2084    // Use PCH if the user requested it.
2085    bool UsePCH = D.CCCUsePCH;
2086
2087    if (JA.getType() == types::TY_Nothing)
2088      CmdArgs.push_back("-fsyntax-only");
2089    else if (UsePCH)
2090      CmdArgs.push_back("-emit-pch");
2091    else
2092      CmdArgs.push_back("-emit-pth");
2093  } else {
2094    assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool.");
2095
2096    if (JA.getType() == types::TY_Nothing) {
2097      CmdArgs.push_back("-fsyntax-only");
2098    } else if (JA.getType() == types::TY_LLVM_IR ||
2099               JA.getType() == types::TY_LTO_IR) {
2100      CmdArgs.push_back("-emit-llvm");
2101    } else if (JA.getType() == types::TY_LLVM_BC ||
2102               JA.getType() == types::TY_LTO_BC) {
2103      CmdArgs.push_back("-emit-llvm-bc");
2104    } else if (JA.getType() == types::TY_PP_Asm) {
2105      CmdArgs.push_back("-S");
2106    } else if (JA.getType() == types::TY_AST) {
2107      CmdArgs.push_back("-emit-pch");
2108    } else if (JA.getType() == types::TY_ModuleFile) {
2109      CmdArgs.push_back("-module-file-info");
2110    } else if (JA.getType() == types::TY_RewrittenObjC) {
2111      CmdArgs.push_back("-rewrite-objc");
2112      rewriteKind = RK_NonFragile;
2113    } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
2114      CmdArgs.push_back("-rewrite-objc");
2115      rewriteKind = RK_Fragile;
2116    } else {
2117      assert(JA.getType() == types::TY_PP_Asm &&
2118             "Unexpected output type!");
2119    }
2120  }
2121
2122  // The make clang go fast button.
2123  CmdArgs.push_back("-disable-free");
2124
2125  // Disable the verification pass in -asserts builds.
2126#ifdef NDEBUG
2127  CmdArgs.push_back("-disable-llvm-verifier");
2128#endif
2129
2130  // Set the main file name, so that debug info works even with
2131  // -save-temps.
2132  CmdArgs.push_back("-main-file-name");
2133  CmdArgs.push_back(getBaseInputName(Args, Inputs));
2134
2135  // Some flags which affect the language (via preprocessor
2136  // defines).
2137  if (Args.hasArg(options::OPT_static))
2138    CmdArgs.push_back("-static-define");
2139
2140  if (isa<AnalyzeJobAction>(JA)) {
2141    // Enable region store model by default.
2142    CmdArgs.push_back("-analyzer-store=region");
2143
2144    // Treat blocks as analysis entry points.
2145    CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2146
2147    CmdArgs.push_back("-analyzer-eagerly-assume");
2148
2149    // Add default argument set.
2150    if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2151      CmdArgs.push_back("-analyzer-checker=core");
2152
2153      if (getToolChain().getTriple().getOS() != llvm::Triple::Win32)
2154        CmdArgs.push_back("-analyzer-checker=unix");
2155
2156      if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
2157        CmdArgs.push_back("-analyzer-checker=osx");
2158
2159      CmdArgs.push_back("-analyzer-checker=deadcode");
2160
2161      if (types::isCXX(Inputs[0].getType()))
2162        CmdArgs.push_back("-analyzer-checker=cplusplus");
2163
2164      // Enable the following experimental checkers for testing.
2165      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2166      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2167      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2168      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2169      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2170      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2171    }
2172
2173    // Set the output format. The default is plist, for (lame) historical
2174    // reasons.
2175    CmdArgs.push_back("-analyzer-output");
2176    if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2177      CmdArgs.push_back(A->getValue());
2178    else
2179      CmdArgs.push_back("plist");
2180
2181    // Disable the presentation of standard compiler warnings when
2182    // using --analyze.  We only want to show static analyzer diagnostics
2183    // or frontend errors.
2184    CmdArgs.push_back("-w");
2185
2186    // Add -Xanalyzer arguments when running as analyzer.
2187    Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2188  }
2189
2190  CheckCodeGenerationOptions(D, Args);
2191
2192  bool PIE = getToolChain().isPIEDefault();
2193  bool PIC = PIE || getToolChain().isPICDefault();
2194  bool IsPICLevelTwo = PIC;
2195
2196  // For the PIC and PIE flag options, this logic is different from the
2197  // legacy logic in very old versions of GCC, as that logic was just
2198  // a bug no one had ever fixed. This logic is both more rational and
2199  // consistent with GCC's new logic now that the bugs are fixed. The last
2200  // argument relating to either PIC or PIE wins, and no other argument is
2201  // used. If the last argument is any flavor of the '-fno-...' arguments,
2202  // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
2203  // at the same level.
2204  Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
2205                                 options::OPT_fpic, options::OPT_fno_pic,
2206                                 options::OPT_fPIE, options::OPT_fno_PIE,
2207                                 options::OPT_fpie, options::OPT_fno_pie);
2208  // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
2209  // is forced, then neither PIC nor PIE flags will have no effect.
2210  if (!getToolChain().isPICDefaultForced()) {
2211    if (LastPICArg) {
2212      Option O = LastPICArg->getOption();
2213      if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
2214          O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
2215        PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
2216        PIC = PIE || O.matches(options::OPT_fPIC) ||
2217              O.matches(options::OPT_fpic);
2218        IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
2219                        O.matches(options::OPT_fPIC);
2220      } else {
2221        PIE = PIC = false;
2222      }
2223    }
2224  }
2225
2226  // Introduce a Darwin-specific hack. If the default is PIC but the flags
2227  // specified while enabling PIC enabled level 1 PIC, just force it back to
2228  // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my
2229  // informal testing).
2230  if (PIC && getToolChain().getTriple().isOSDarwin())
2231    IsPICLevelTwo |= getToolChain().isPICDefault();
2232
2233  // Note that these flags are trump-cards. Regardless of the order w.r.t. the
2234  // PIC or PIE options above, if these show up, PIC is disabled.
2235  llvm::Triple Triple(TripleStr);
2236  if (KernelOrKext &&
2237      (!Triple.isiOS() || Triple.isOSVersionLT(6)))
2238    PIC = PIE = false;
2239  if (Args.hasArg(options::OPT_static))
2240    PIC = PIE = false;
2241
2242  if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
2243    // This is a very special mode. It trumps the other modes, almost no one
2244    // uses it, and it isn't even valid on any OS but Darwin.
2245    if (!getToolChain().getTriple().isOSDarwin())
2246      D.Diag(diag::err_drv_unsupported_opt_for_target)
2247        << A->getSpelling() << getToolChain().getTriple().str();
2248
2249    // FIXME: Warn when this flag trumps some other PIC or PIE flag.
2250
2251    CmdArgs.push_back("-mrelocation-model");
2252    CmdArgs.push_back("dynamic-no-pic");
2253
2254    // Only a forced PIC mode can cause the actual compile to have PIC defines
2255    // etc., no flags are sufficient. This behavior was selected to closely
2256    // match that of llvm-gcc and Apple GCC before that.
2257    if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) {
2258      CmdArgs.push_back("-pic-level");
2259      CmdArgs.push_back("2");
2260    }
2261  } else {
2262    // Currently, LLVM only knows about PIC vs. static; the PIE differences are
2263    // handled in Clang's IRGen by the -pie-level flag.
2264    CmdArgs.push_back("-mrelocation-model");
2265    CmdArgs.push_back(PIC ? "pic" : "static");
2266
2267    if (PIC) {
2268      CmdArgs.push_back("-pic-level");
2269      CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2270      if (PIE) {
2271        CmdArgs.push_back("-pie-level");
2272        CmdArgs.push_back(IsPICLevelTwo ? "2" : "1");
2273      }
2274    }
2275  }
2276
2277  if (!Args.hasFlag(options::OPT_fmerge_all_constants,
2278                    options::OPT_fno_merge_all_constants))
2279    CmdArgs.push_back("-fno-merge-all-constants");
2280
2281  // LLVM Code Generator Options.
2282
2283  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2284    CmdArgs.push_back("-mregparm");
2285    CmdArgs.push_back(A->getValue());
2286  }
2287
2288  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
2289                               options::OPT_freg_struct_return)) {
2290    if (getToolChain().getArch() != llvm::Triple::x86) {
2291      D.Diag(diag::err_drv_unsupported_opt_for_target)
2292        << A->getSpelling() << getToolChain().getTriple().str();
2293    } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
2294      CmdArgs.push_back("-fpcc-struct-return");
2295    } else {
2296      assert(A->getOption().matches(options::OPT_freg_struct_return));
2297      CmdArgs.push_back("-freg-struct-return");
2298    }
2299  }
2300
2301  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
2302    CmdArgs.push_back("-mrtd");
2303
2304  if (shouldUseFramePointer(Args, getToolChain().getTriple()))
2305    CmdArgs.push_back("-mdisable-fp-elim");
2306  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
2307                    options::OPT_fno_zero_initialized_in_bss))
2308    CmdArgs.push_back("-mno-zero-initialized-in-bss");
2309
2310  bool OFastEnabled = isOptimizationLevelFast(Args);
2311  // If -Ofast is the optimization level, then -fstrict-aliasing should be
2312  // enabled.  This alias option is being used to simplify the hasFlag logic.
2313  OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
2314    options::OPT_fstrict_aliasing;
2315  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
2316                    options::OPT_fno_strict_aliasing, true))
2317    CmdArgs.push_back("-relaxed-aliasing");
2318  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
2319                    options::OPT_fno_struct_path_tbaa))
2320    CmdArgs.push_back("-no-struct-path-tbaa");
2321  if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
2322                   false))
2323    CmdArgs.push_back("-fstrict-enums");
2324  if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
2325                    options::OPT_fno_optimize_sibling_calls))
2326    CmdArgs.push_back("-mdisable-tail-calls");
2327
2328  // Handle segmented stacks.
2329  if (Args.hasArg(options::OPT_fsplit_stack))
2330    CmdArgs.push_back("-split-stacks");
2331
2332  // If -Ofast is the optimization level, then -ffast-math should be enabled.
2333  // This alias option is being used to simplify the getLastArg logic.
2334  OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
2335    options::OPT_ffast_math;
2336
2337  // Handle various floating point optimization flags, mapping them to the
2338  // appropriate LLVM code generation flags. The pattern for all of these is to
2339  // default off the codegen optimizations, and if any flag enables them and no
2340  // flag disables them after the flag enabling them, enable the codegen
2341  // optimization. This is complicated by several "umbrella" flags.
2342  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2343                               options::OPT_fno_fast_math,
2344                               options::OPT_ffinite_math_only,
2345                               options::OPT_fno_finite_math_only,
2346                               options::OPT_fhonor_infinities,
2347                               options::OPT_fno_honor_infinities))
2348    if (A->getOption().getID() != options::OPT_fno_fast_math &&
2349        A->getOption().getID() != options::OPT_fno_finite_math_only &&
2350        A->getOption().getID() != options::OPT_fhonor_infinities)
2351      CmdArgs.push_back("-menable-no-infs");
2352  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2353                               options::OPT_fno_fast_math,
2354                               options::OPT_ffinite_math_only,
2355                               options::OPT_fno_finite_math_only,
2356                               options::OPT_fhonor_nans,
2357                               options::OPT_fno_honor_nans))
2358    if (A->getOption().getID() != options::OPT_fno_fast_math &&
2359        A->getOption().getID() != options::OPT_fno_finite_math_only &&
2360        A->getOption().getID() != options::OPT_fhonor_nans)
2361      CmdArgs.push_back("-menable-no-nans");
2362
2363  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2364  bool MathErrno = getToolChain().IsMathErrnoDefault();
2365  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2366                               options::OPT_fno_fast_math,
2367                               options::OPT_fmath_errno,
2368                               options::OPT_fno_math_errno)) {
2369    // Turning on -ffast_math (with either flag) removes the need for MathErrno.
2370    // However, turning *off* -ffast_math merely restores the toolchain default
2371    // (which may be false).
2372    if (A->getOption().getID() == options::OPT_fno_math_errno ||
2373        A->getOption().getID() == options::OPT_ffast_math ||
2374        A->getOption().getID() == options::OPT_Ofast)
2375      MathErrno = false;
2376    else if (A->getOption().getID() == options::OPT_fmath_errno)
2377      MathErrno = true;
2378  }
2379  if (MathErrno)
2380    CmdArgs.push_back("-fmath-errno");
2381
2382  // There are several flags which require disabling very specific
2383  // optimizations. Any of these being disabled forces us to turn off the
2384  // entire set of LLVM optimizations, so collect them through all the flag
2385  // madness.
2386  bool AssociativeMath = false;
2387  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2388                               options::OPT_fno_fast_math,
2389                               options::OPT_funsafe_math_optimizations,
2390                               options::OPT_fno_unsafe_math_optimizations,
2391                               options::OPT_fassociative_math,
2392                               options::OPT_fno_associative_math))
2393    if (A->getOption().getID() != options::OPT_fno_fast_math &&
2394        A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2395        A->getOption().getID() != options::OPT_fno_associative_math)
2396      AssociativeMath = true;
2397  bool ReciprocalMath = false;
2398  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2399                               options::OPT_fno_fast_math,
2400                               options::OPT_funsafe_math_optimizations,
2401                               options::OPT_fno_unsafe_math_optimizations,
2402                               options::OPT_freciprocal_math,
2403                               options::OPT_fno_reciprocal_math))
2404    if (A->getOption().getID() != options::OPT_fno_fast_math &&
2405        A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2406        A->getOption().getID() != options::OPT_fno_reciprocal_math)
2407      ReciprocalMath = true;
2408  bool SignedZeros = true;
2409  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2410                               options::OPT_fno_fast_math,
2411                               options::OPT_funsafe_math_optimizations,
2412                               options::OPT_fno_unsafe_math_optimizations,
2413                               options::OPT_fsigned_zeros,
2414                               options::OPT_fno_signed_zeros))
2415    if (A->getOption().getID() != options::OPT_fno_fast_math &&
2416        A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2417        A->getOption().getID() != options::OPT_fsigned_zeros)
2418      SignedZeros = false;
2419  bool TrappingMath = true;
2420  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2421                               options::OPT_fno_fast_math,
2422                               options::OPT_funsafe_math_optimizations,
2423                               options::OPT_fno_unsafe_math_optimizations,
2424                               options::OPT_ftrapping_math,
2425                               options::OPT_fno_trapping_math))
2426    if (A->getOption().getID() != options::OPT_fno_fast_math &&
2427        A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
2428        A->getOption().getID() != options::OPT_ftrapping_math)
2429      TrappingMath = false;
2430  if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2431      !TrappingMath)
2432    CmdArgs.push_back("-menable-unsafe-fp-math");
2433
2434
2435  // Validate and pass through -fp-contract option.
2436  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2437                               options::OPT_fno_fast_math,
2438                               options::OPT_ffp_contract)) {
2439    if (A->getOption().getID() == options::OPT_ffp_contract) {
2440      StringRef Val = A->getValue();
2441      if (Val == "fast" || Val == "on" || Val == "off") {
2442        CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
2443      } else {
2444        D.Diag(diag::err_drv_unsupported_option_argument)
2445          << A->getOption().getName() << Val;
2446      }
2447    } else if (A->getOption().matches(options::OPT_ffast_math) ||
2448               (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
2449      // If fast-math is set then set the fp-contract mode to fast.
2450      CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2451    }
2452  }
2453
2454  // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
2455  // and if we find them, tell the frontend to provide the appropriate
2456  // preprocessor macros. This is distinct from enabling any optimizations as
2457  // these options induce language changes which must survive serialization
2458  // and deserialization, etc.
2459  if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
2460                               options::OPT_fno_fast_math))
2461      if (!A->getOption().matches(options::OPT_fno_fast_math))
2462        CmdArgs.push_back("-ffast-math");
2463  if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only, options::OPT_fno_fast_math))
2464    if (A->getOption().matches(options::OPT_ffinite_math_only))
2465      CmdArgs.push_back("-ffinite-math-only");
2466
2467  // Decide whether to use verbose asm. Verbose assembly is the default on
2468  // toolchains which have the integrated assembler on by default.
2469  bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault();
2470  if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
2471                   IsVerboseAsmDefault) ||
2472      Args.hasArg(options::OPT_dA))
2473    CmdArgs.push_back("-masm-verbose");
2474
2475  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
2476    CmdArgs.push_back("-mdebug-pass");
2477    CmdArgs.push_back("Structure");
2478  }
2479  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
2480    CmdArgs.push_back("-mdebug-pass");
2481    CmdArgs.push_back("Arguments");
2482  }
2483
2484  // Enable -mconstructor-aliases except on darwin, where we have to
2485  // work around a linker bug;  see <rdar://problem/7651567>.
2486  if (!getToolChain().getTriple().isOSDarwin())
2487    CmdArgs.push_back("-mconstructor-aliases");
2488
2489  // Darwin's kernel doesn't support guard variables; just die if we
2490  // try to use them.
2491  if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
2492    CmdArgs.push_back("-fforbid-guard-variables");
2493
2494  if (Args.hasArg(options::OPT_mms_bitfields)) {
2495    CmdArgs.push_back("-mms-bitfields");
2496  }
2497
2498  // This is a coarse approximation of what llvm-gcc actually does, both
2499  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
2500  // complicated ways.
2501  bool AsynchronousUnwindTables =
2502    Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
2503                 options::OPT_fno_asynchronous_unwind_tables,
2504                 getToolChain().IsUnwindTablesDefault() &&
2505                 !KernelOrKext);
2506  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
2507                   AsynchronousUnwindTables))
2508    CmdArgs.push_back("-munwind-tables");
2509
2510  getToolChain().addClangTargetOptions(Args, CmdArgs);
2511
2512  if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2513    CmdArgs.push_back("-mlimit-float-precision");
2514    CmdArgs.push_back(A->getValue());
2515  }
2516
2517  // FIXME: Handle -mtune=.
2518  (void) Args.hasArg(options::OPT_mtune_EQ);
2519
2520  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2521    CmdArgs.push_back("-mcode-model");
2522    CmdArgs.push_back(A->getValue());
2523  }
2524
2525  // Add the target cpu
2526  std::string ETripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
2527  llvm::Triple ETriple(ETripleStr);
2528  std::string CPU = getCPUName(Args, ETriple);
2529  if (!CPU.empty()) {
2530    CmdArgs.push_back("-target-cpu");
2531    CmdArgs.push_back(Args.MakeArgString(CPU));
2532  }
2533
2534  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2535    CmdArgs.push_back("-mfpmath");
2536    CmdArgs.push_back(A->getValue());
2537  }
2538
2539  // Add the target features
2540  getTargetFeatures(D, ETriple, Args, CmdArgs);
2541
2542  // Add target specific flags.
2543  switch(getToolChain().getArch()) {
2544  default:
2545    break;
2546
2547  case llvm::Triple::arm:
2548  case llvm::Triple::thumb:
2549    AddARMTargetArgs(Args, CmdArgs, KernelOrKext);
2550    break;
2551
2552  case llvm::Triple::mips:
2553  case llvm::Triple::mipsel:
2554  case llvm::Triple::mips64:
2555  case llvm::Triple::mips64el:
2556    AddMIPSTargetArgs(Args, CmdArgs);
2557    break;
2558
2559  case llvm::Triple::sparc:
2560    AddSparcTargetArgs(Args, CmdArgs);
2561    break;
2562
2563  case llvm::Triple::x86:
2564  case llvm::Triple::x86_64:
2565    AddX86TargetArgs(Args, CmdArgs);
2566    break;
2567
2568  case llvm::Triple::hexagon:
2569    AddHexagonTargetArgs(Args, CmdArgs);
2570    break;
2571  }
2572
2573  // Add clang-cl arguments.
2574  if (getToolChain().getDriver().IsCLMode())
2575    AddClangCLArgs(Args, CmdArgs);
2576
2577  // Pass the linker version in use.
2578  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
2579    CmdArgs.push_back("-target-linker-version");
2580    CmdArgs.push_back(A->getValue());
2581  }
2582
2583  if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
2584    CmdArgs.push_back("-momit-leaf-frame-pointer");
2585
2586  // Explicitly error on some things we know we don't support and can't just
2587  // ignore.
2588  types::ID InputType = Inputs[0].getType();
2589  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
2590    Arg *Unsupported;
2591    if (types::isCXX(InputType) &&
2592        getToolChain().getTriple().isOSDarwin() &&
2593        getToolChain().getArch() == llvm::Triple::x86) {
2594      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
2595          (Unsupported = Args.getLastArg(options::OPT_mkernel)))
2596        D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
2597          << Unsupported->getOption().getName();
2598    }
2599  }
2600
2601  Args.AddAllArgs(CmdArgs, options::OPT_v);
2602  Args.AddLastArg(CmdArgs, options::OPT_H);
2603  if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
2604    CmdArgs.push_back("-header-include-file");
2605    CmdArgs.push_back(D.CCPrintHeadersFilename ?
2606                      D.CCPrintHeadersFilename : "-");
2607  }
2608  Args.AddLastArg(CmdArgs, options::OPT_P);
2609  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
2610
2611  if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
2612    CmdArgs.push_back("-diagnostic-log-file");
2613    CmdArgs.push_back(D.CCLogDiagnosticsFilename ?
2614                      D.CCLogDiagnosticsFilename : "-");
2615  }
2616
2617  // Use the last option from "-g" group. "-gline-tables-only"
2618  // is preserved, all other debug options are substituted with "-g".
2619  Args.ClaimAllArgs(options::OPT_g_Group);
2620  if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2621    if (A->getOption().matches(options::OPT_gline_tables_only))
2622      CmdArgs.push_back("-gline-tables-only");
2623    else if (A->getOption().matches(options::OPT_gdwarf_2))
2624      CmdArgs.push_back("-gdwarf-2");
2625    else if (A->getOption().matches(options::OPT_gdwarf_3))
2626      CmdArgs.push_back("-gdwarf-3");
2627    else if (A->getOption().matches(options::OPT_gdwarf_4))
2628      CmdArgs.push_back("-gdwarf-4");
2629    else if (!A->getOption().matches(options::OPT_g0) &&
2630             !A->getOption().matches(options::OPT_ggdb0)) {
2631      // Default is dwarf-2 for darwin and FreeBSD <= 10.
2632      const llvm::Triple &Triple = getToolChain().getTriple();
2633      if (Triple.isOSDarwin() || (Triple.getOS() == llvm::Triple::FreeBSD &&
2634          Triple.getOSMajorVersion() <= 10))
2635        CmdArgs.push_back("-gdwarf-2");
2636      else
2637        CmdArgs.push_back("-g");
2638    }
2639  }
2640
2641  // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
2642  Args.ClaimAllArgs(options::OPT_g_flags_Group);
2643  if (Args.hasArg(options::OPT_gcolumn_info))
2644    CmdArgs.push_back("-dwarf-column-info");
2645
2646  // FIXME: Move backend command line options to the module.
2647  // -gsplit-dwarf should turn on -g and enable the backend dwarf
2648  // splitting and extraction.
2649  // FIXME: Currently only works on Linux.
2650  if (getToolChain().getTriple().isOSLinux() &&
2651      Args.hasArg(options::OPT_gsplit_dwarf)) {
2652    CmdArgs.push_back("-g");
2653    CmdArgs.push_back("-backend-option");
2654    CmdArgs.push_back("-split-dwarf=Enable");
2655  }
2656
2657  // -ggnu-pubnames turns on gnu style pubnames in the backend.
2658  if (Args.hasArg(options::OPT_ggnu_pubnames)) {
2659    CmdArgs.push_back("-backend-option");
2660    CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
2661  }
2662
2663  Args.AddAllArgs(CmdArgs, options::OPT_fdebug_types_section);
2664
2665  Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
2666  Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
2667
2668  Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2669
2670  if (Args.hasArg(options::OPT_ftest_coverage) ||
2671      Args.hasArg(options::OPT_coverage))
2672    CmdArgs.push_back("-femit-coverage-notes");
2673  if (Args.hasArg(options::OPT_fprofile_arcs) ||
2674      Args.hasArg(options::OPT_coverage))
2675    CmdArgs.push_back("-femit-coverage-data");
2676
2677  if (C.getArgs().hasArg(options::OPT_c) ||
2678      C.getArgs().hasArg(options::OPT_S)) {
2679    if (Output.isFilename()) {
2680      CmdArgs.push_back("-coverage-file");
2681      SmallString<128> CoverageFilename(Output.getFilename());
2682      if (llvm::sys::path::is_relative(CoverageFilename.str())) {
2683        SmallString<128> Pwd;
2684        if (!llvm::sys::fs::current_path(Pwd)) {
2685          llvm::sys::path::append(Pwd, CoverageFilename.str());
2686          CoverageFilename.swap(Pwd);
2687        }
2688      }
2689      CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
2690    }
2691  }
2692
2693  // Pass options for controlling the default header search paths.
2694  if (Args.hasArg(options::OPT_nostdinc)) {
2695    CmdArgs.push_back("-nostdsysteminc");
2696    CmdArgs.push_back("-nobuiltininc");
2697  } else {
2698    if (Args.hasArg(options::OPT_nostdlibinc))
2699        CmdArgs.push_back("-nostdsysteminc");
2700    Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2701    Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2702  }
2703
2704  // Pass the path to compiler resource files.
2705  CmdArgs.push_back("-resource-dir");
2706  CmdArgs.push_back(D.ResourceDir.c_str());
2707
2708  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2709
2710  bool ARCMTEnabled = false;
2711  if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2712    if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2713                                       options::OPT_ccc_arcmt_modify,
2714                                       options::OPT_ccc_arcmt_migrate)) {
2715      ARCMTEnabled = true;
2716      switch (A->getOption().getID()) {
2717      default:
2718        llvm_unreachable("missed a case");
2719      case options::OPT_ccc_arcmt_check:
2720        CmdArgs.push_back("-arcmt-check");
2721        break;
2722      case options::OPT_ccc_arcmt_modify:
2723        CmdArgs.push_back("-arcmt-modify");
2724        break;
2725      case options::OPT_ccc_arcmt_migrate:
2726        CmdArgs.push_back("-arcmt-migrate");
2727        CmdArgs.push_back("-mt-migrate-directory");
2728        CmdArgs.push_back(A->getValue());
2729
2730        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2731        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2732        break;
2733      }
2734    }
2735  } else {
2736    Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2737    Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2738    Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2739  }
2740
2741  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2742    if (ARCMTEnabled) {
2743      D.Diag(diag::err_drv_argument_not_allowed_with)
2744        << A->getAsString(Args) << "-ccc-arcmt-migrate";
2745    }
2746    CmdArgs.push_back("-mt-migrate-directory");
2747    CmdArgs.push_back(A->getValue());
2748
2749    if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2750                     options::OPT_objcmt_migrate_subscripting,
2751                     options::OPT_objcmt_migrate_property)) {
2752      // None specified, means enable them all.
2753      CmdArgs.push_back("-objcmt-migrate-literals");
2754      CmdArgs.push_back("-objcmt-migrate-subscripting");
2755      CmdArgs.push_back("-objcmt-migrate-property");
2756    } else {
2757      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2758      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2759      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2760    }
2761  } else {
2762    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2763    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2764    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2765    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2766    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2767    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2768    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2769    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2770    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2771    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2772    Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2773    Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2774    Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2775    Args.AddLastArg(CmdArgs, options::OPT_objcmt_white_list_dir_path);
2776  }
2777
2778  // Add preprocessing options like -I, -D, etc. if we are using the
2779  // preprocessor.
2780  //
2781  // FIXME: Support -fpreprocessed
2782  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2783    AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
2784
2785  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2786  // that "The compiler can only warn and ignore the option if not recognized".
2787  // When building with ccache, it will pass -D options to clang even on
2788  // preprocessed inputs and configure concludes that -fPIC is not supported.
2789  Args.ClaimAllArgs(options::OPT_D);
2790
2791  // Manually translate -O4 to -O3; let clang reject others.
2792  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2793    if (A->getOption().matches(options::OPT_O4)) {
2794      CmdArgs.push_back("-O3");
2795      D.Diag(diag::warn_O4_is_O3);
2796    } else {
2797      A->render(Args, CmdArgs);
2798    }
2799  }
2800
2801  // Don't warn about unused -flto.  This can happen when we're preprocessing or
2802  // precompiling.
2803  Args.ClaimAllArgs(options::OPT_flto);
2804
2805  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
2806  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
2807    CmdArgs.push_back("-pedantic");
2808  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
2809  Args.AddLastArg(CmdArgs, options::OPT_w);
2810
2811  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
2812  // (-ansi is equivalent to -std=c89 or -std=c++98).
2813  //
2814  // If a std is supplied, only add -trigraphs if it follows the
2815  // option.
2816  if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2817    if (Std->getOption().matches(options::OPT_ansi))
2818      if (types::isCXX(InputType))
2819        CmdArgs.push_back("-std=c++98");
2820      else
2821        CmdArgs.push_back("-std=c89");
2822    else
2823      Std->render(Args, CmdArgs);
2824
2825    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
2826                                 options::OPT_trigraphs))
2827      if (A != Std)
2828        A->render(Args, CmdArgs);
2829  } else {
2830    // Honor -std-default.
2831    //
2832    // FIXME: Clang doesn't correctly handle -std= when the input language
2833    // doesn't match. For the time being just ignore this for C++ inputs;
2834    // eventually we want to do all the standard defaulting here instead of
2835    // splitting it between the driver and clang -cc1.
2836    if (!types::isCXX(InputType))
2837      Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ,
2838                                "-std=", /*Joined=*/true);
2839    else if (getToolChain().getTriple().getOS() == llvm::Triple::Win32)
2840      CmdArgs.push_back("-std=c++11");
2841
2842    Args.AddLastArg(CmdArgs, options::OPT_trigraphs);
2843  }
2844
2845  // GCC's behavior for -Wwrite-strings is a bit strange:
2846  //  * In C, this "warning flag" changes the types of string literals from
2847  //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
2848  //    for the discarded qualifier.
2849  //  * In C++, this is just a normal warning flag.
2850  //
2851  // Implementing this warning correctly in C is hard, so we follow GCC's
2852  // behavior for now. FIXME: Directly diagnose uses of a string literal as
2853  // a non-const char* in C, rather than using this crude hack.
2854  if (!types::isCXX(InputType)) {
2855    DiagnosticsEngine::Level DiagLevel = D.getDiags().getDiagnosticLevel(
2856        diag::warn_deprecated_string_literal_conversion_c, SourceLocation());
2857    if (DiagLevel > DiagnosticsEngine::Ignored)
2858      CmdArgs.push_back("-fconst-strings");
2859  }
2860
2861  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
2862  // during C++ compilation, which it is by default. GCC keeps this define even
2863  // in the presence of '-w', match this behavior bug-for-bug.
2864  if (types::isCXX(InputType) &&
2865      Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
2866                   true)) {
2867    CmdArgs.push_back("-fdeprecated-macro");
2868  }
2869
2870  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
2871  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
2872    if (Asm->getOption().matches(options::OPT_fasm))
2873      CmdArgs.push_back("-fgnu-keywords");
2874    else
2875      CmdArgs.push_back("-fno-gnu-keywords");
2876  }
2877
2878  if (ShouldDisableCFI(Args, getToolChain()))
2879    CmdArgs.push_back("-fno-dwarf2-cfi-asm");
2880
2881  if (ShouldDisableDwarfDirectory(Args, getToolChain()))
2882    CmdArgs.push_back("-fno-dwarf-directory-asm");
2883
2884  if (ShouldDisableAutolink(Args, getToolChain()))
2885    CmdArgs.push_back("-fno-autolink");
2886
2887  // Add in -fdebug-compilation-dir if necessary.
2888  addDebugCompDirArg(Args, CmdArgs);
2889
2890  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
2891                               options::OPT_ftemplate_depth_EQ)) {
2892    CmdArgs.push_back("-ftemplate-depth");
2893    CmdArgs.push_back(A->getValue());
2894  }
2895
2896  if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
2897    CmdArgs.push_back("-foperator-arrow-depth");
2898    CmdArgs.push_back(A->getValue());
2899  }
2900
2901  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
2902    CmdArgs.push_back("-fconstexpr-depth");
2903    CmdArgs.push_back(A->getValue());
2904  }
2905
2906  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
2907    CmdArgs.push_back("-fconstexpr-steps");
2908    CmdArgs.push_back(A->getValue());
2909  }
2910
2911  if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
2912    CmdArgs.push_back("-fbracket-depth");
2913    CmdArgs.push_back(A->getValue());
2914  }
2915
2916  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
2917                               options::OPT_Wlarge_by_value_copy_def)) {
2918    if (A->getNumValues()) {
2919      StringRef bytes = A->getValue();
2920      CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
2921    } else
2922      CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
2923  }
2924
2925
2926  if (Args.hasArg(options::OPT_relocatable_pch))
2927    CmdArgs.push_back("-relocatable-pch");
2928
2929  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
2930    CmdArgs.push_back("-fconstant-string-class");
2931    CmdArgs.push_back(A->getValue());
2932  }
2933
2934  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
2935    CmdArgs.push_back("-ftabstop");
2936    CmdArgs.push_back(A->getValue());
2937  }
2938
2939  CmdArgs.push_back("-ferror-limit");
2940  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
2941    CmdArgs.push_back(A->getValue());
2942  else
2943    CmdArgs.push_back("19");
2944
2945  if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
2946    CmdArgs.push_back("-fmacro-backtrace-limit");
2947    CmdArgs.push_back(A->getValue());
2948  }
2949
2950  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
2951    CmdArgs.push_back("-ftemplate-backtrace-limit");
2952    CmdArgs.push_back(A->getValue());
2953  }
2954
2955  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
2956    CmdArgs.push_back("-fconstexpr-backtrace-limit");
2957    CmdArgs.push_back(A->getValue());
2958  }
2959
2960  // Pass -fmessage-length=.
2961  CmdArgs.push_back("-fmessage-length");
2962  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
2963    CmdArgs.push_back(A->getValue());
2964  } else {
2965    // If -fmessage-length=N was not specified, determine whether this is a
2966    // terminal and, if so, implicitly define -fmessage-length appropriately.
2967    unsigned N = llvm::sys::Process::StandardErrColumns();
2968    CmdArgs.push_back(Args.MakeArgString(Twine(N)));
2969  }
2970
2971  // -fvisibility= and -fvisibility-ms-compat are of a piece.
2972  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
2973                                     options::OPT_fvisibility_ms_compat)) {
2974    if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
2975      CmdArgs.push_back("-fvisibility");
2976      CmdArgs.push_back(A->getValue());
2977    } else {
2978      assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
2979      CmdArgs.push_back("-fvisibility");
2980      CmdArgs.push_back("hidden");
2981      CmdArgs.push_back("-ftype-visibility");
2982      CmdArgs.push_back("default");
2983    }
2984  }
2985
2986  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
2987
2988  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
2989
2990  // -fhosted is default.
2991  if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
2992      KernelOrKext)
2993    CmdArgs.push_back("-ffreestanding");
2994
2995  // Forward -f (flag) options which we can pass directly.
2996  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
2997  Args.AddLastArg(CmdArgs, options::OPT_fformat_extensions);
2998  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
2999  Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
3000  Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info);
3001  Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3002  // AltiVec language extensions aren't relevant for assembling.
3003  if (!isa<PreprocessJobAction>(JA) ||
3004      Output.getType() != types::TY_PP_Asm)
3005    Args.AddLastArg(CmdArgs, options::OPT_faltivec);
3006  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3007  Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3008
3009  const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3010  Sanitize.addArgs(Args, CmdArgs);
3011
3012  if (!Args.hasFlag(options::OPT_fsanitize_recover,
3013                    options::OPT_fno_sanitize_recover,
3014                    true))
3015    CmdArgs.push_back("-fno-sanitize-recover");
3016
3017  if (Args.hasArg(options::OPT_fcatch_undefined_behavior) ||
3018      Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
3019                   options::OPT_fno_sanitize_undefined_trap_on_error, false))
3020    CmdArgs.push_back("-fsanitize-undefined-trap-on-error");
3021
3022  // Report an error for -faltivec on anything other than PowerPC.
3023  if (const Arg *A = Args.getLastArg(options::OPT_faltivec))
3024    if (!(getToolChain().getArch() == llvm::Triple::ppc ||
3025          getToolChain().getArch() == llvm::Triple::ppc64 ||
3026          getToolChain().getArch() == llvm::Triple::ppc64le))
3027      D.Diag(diag::err_drv_argument_only_allowed_with)
3028        << A->getAsString(Args) << "ppc/ppc64/ppc64le";
3029
3030  if (getToolChain().SupportsProfiling())
3031    Args.AddLastArg(CmdArgs, options::OPT_pg);
3032
3033  // -flax-vector-conversions is default.
3034  if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3035                    options::OPT_fno_lax_vector_conversions))
3036    CmdArgs.push_back("-fno-lax-vector-conversions");
3037
3038  if (Args.getLastArg(options::OPT_fapple_kext))
3039    CmdArgs.push_back("-fapple-kext");
3040
3041  if (Args.hasFlag(options::OPT_frewrite_includes,
3042                   options::OPT_fno_rewrite_includes, false))
3043    CmdArgs.push_back("-frewrite-includes");
3044
3045  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3046  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3047  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3048  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3049  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3050
3051  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3052    CmdArgs.push_back("-ftrapv-handler");
3053    CmdArgs.push_back(A->getValue());
3054  }
3055
3056  Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3057
3058  // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3059  // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3060  if (Arg *A = Args.getLastArg(options::OPT_fwrapv,
3061                               options::OPT_fno_wrapv)) {
3062    if (A->getOption().matches(options::OPT_fwrapv))
3063      CmdArgs.push_back("-fwrapv");
3064  } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3065                                      options::OPT_fno_strict_overflow)) {
3066    if (A->getOption().matches(options::OPT_fno_strict_overflow))
3067      CmdArgs.push_back("-fwrapv");
3068  }
3069
3070  if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3071                               options::OPT_fno_reroll_loops))
3072    if (A->getOption().matches(options::OPT_freroll_loops))
3073      CmdArgs.push_back("-freroll-loops");
3074
3075  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3076  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3077                  options::OPT_fno_unroll_loops);
3078
3079  Args.AddLastArg(CmdArgs, options::OPT_pthread);
3080
3081
3082  // -stack-protector=0 is default.
3083  unsigned StackProtectorLevel = 0;
3084  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3085                               options::OPT_fstack_protector_all,
3086                               options::OPT_fstack_protector)) {
3087    if (A->getOption().matches(options::OPT_fstack_protector))
3088      StackProtectorLevel = 1;
3089    else if (A->getOption().matches(options::OPT_fstack_protector_all))
3090      StackProtectorLevel = 2;
3091  } else {
3092    StackProtectorLevel =
3093      getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3094  }
3095  if (StackProtectorLevel) {
3096    CmdArgs.push_back("-stack-protector");
3097    CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3098  }
3099
3100  // --param ssp-buffer-size=
3101  for (arg_iterator it = Args.filtered_begin(options::OPT__param),
3102       ie = Args.filtered_end(); it != ie; ++it) {
3103    StringRef Str((*it)->getValue());
3104    if (Str.startswith("ssp-buffer-size=")) {
3105      if (StackProtectorLevel) {
3106        CmdArgs.push_back("-stack-protector-buffer-size");
3107        // FIXME: Verify the argument is a valid integer.
3108        CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3109      }
3110      (*it)->claim();
3111    }
3112  }
3113
3114  // Translate -mstackrealign
3115  if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3116                   false)) {
3117    CmdArgs.push_back("-backend-option");
3118    CmdArgs.push_back("-force-align-stack");
3119  }
3120  if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign,
3121                   false)) {
3122    CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3123  }
3124
3125  if (Args.hasArg(options::OPT_mstack_alignment)) {
3126    StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3127    CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3128  }
3129  // -mkernel implies -mstrict-align; don't add the redundant option.
3130  if (!KernelOrKext) {
3131    if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
3132                                 options::OPT_munaligned_access)) {
3133      if (A->getOption().matches(options::OPT_mno_unaligned_access)) {
3134        CmdArgs.push_back("-backend-option");
3135        CmdArgs.push_back("-arm-strict-align");
3136      } else {
3137        CmdArgs.push_back("-backend-option");
3138        CmdArgs.push_back("-arm-no-strict-align");
3139      }
3140    }
3141  }
3142
3143  if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3144                               options::OPT_mno_restrict_it)) {
3145    if (A->getOption().matches(options::OPT_mrestrict_it)) {
3146      CmdArgs.push_back("-backend-option");
3147      CmdArgs.push_back("-arm-restrict-it");
3148    } else {
3149      CmdArgs.push_back("-backend-option");
3150      CmdArgs.push_back("-arm-no-restrict-it");
3151    }
3152  }
3153
3154  // Forward -f options with positive and negative forms; we translate
3155  // these by hand.
3156  if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
3157    StringRef fname = A->getValue();
3158    if (!llvm::sys::fs::exists(fname))
3159      D.Diag(diag::err_drv_no_such_file) << fname;
3160    else
3161      A->render(Args, CmdArgs);
3162  }
3163
3164  if (Args.hasArg(options::OPT_mkernel)) {
3165    if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType))
3166      CmdArgs.push_back("-fapple-kext");
3167    if (!Args.hasArg(options::OPT_fbuiltin))
3168      CmdArgs.push_back("-fno-builtin");
3169    Args.ClaimAllArgs(options::OPT_fno_builtin);
3170  }
3171  // -fbuiltin is default.
3172  else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
3173    CmdArgs.push_back("-fno-builtin");
3174
3175  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3176                    options::OPT_fno_assume_sane_operator_new))
3177    CmdArgs.push_back("-fno-assume-sane-operator-new");
3178
3179  // -fblocks=0 is default.
3180  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3181                   getToolChain().IsBlocksDefault()) ||
3182        (Args.hasArg(options::OPT_fgnu_runtime) &&
3183         Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3184         !Args.hasArg(options::OPT_fno_blocks))) {
3185    CmdArgs.push_back("-fblocks");
3186
3187    if (!Args.hasArg(options::OPT_fgnu_runtime) &&
3188        !getToolChain().hasBlocksRuntime())
3189      CmdArgs.push_back("-fblocks-runtime-optional");
3190  }
3191
3192  // -fmodules enables modules (off by default). However, for C++/Objective-C++,
3193  // users must also pass -fcxx-modules. The latter flag will disappear once the
3194  // modules implementation is solid for C++/Objective-C++ programs as well.
3195  bool HaveModules = false;
3196  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3197    bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3198                                     options::OPT_fno_cxx_modules,
3199                                     false);
3200    if (AllowedInCXX || !types::isCXX(InputType)) {
3201      CmdArgs.push_back("-fmodules");
3202      HaveModules = true;
3203    }
3204  }
3205
3206  // -fmodule-maps enables module map processing (off by default) for header
3207  // checking.  It is implied by -fmodules.
3208  if (Args.hasFlag(options::OPT_fmodule_maps, options::OPT_fno_module_maps,
3209                   false)) {
3210    CmdArgs.push_back("-fmodule-maps");
3211  }
3212
3213  // -fmodules-decluse checks that modules used are declared so (off by
3214  // default).
3215  if (Args.hasFlag(options::OPT_fmodules_decluse,
3216                   options::OPT_fno_modules_decluse,
3217                   false)) {
3218    CmdArgs.push_back("-fmodules-decluse");
3219  }
3220
3221  // -fmodule-name specifies the module that is currently being built (or
3222  // used for header checking by -fmodule-maps).
3223  if (Arg *A = Args.getLastArg(options::OPT_fmodule_name)) {
3224    A->claim();
3225    A->render(Args, CmdArgs);
3226  }
3227
3228  // -fmodule-map-file can be used to specify a file containing module
3229  // definitions.
3230  if (Arg *A = Args.getLastArg(options::OPT_fmodule_map_file)) {
3231    A->claim();
3232    A->render(Args, CmdArgs);
3233  }
3234
3235  // If a module path was provided, pass it along. Otherwise, use a temporary
3236  // directory.
3237  if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path)) {
3238    A->claim();
3239    if (HaveModules) {
3240      A->render(Args, CmdArgs);
3241    }
3242  } else if (HaveModules) {
3243    SmallString<128> DefaultModuleCache;
3244    llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false,
3245                                           DefaultModuleCache);
3246    llvm::sys::path::append(DefaultModuleCache, "org.llvm.clang");
3247    llvm::sys::path::append(DefaultModuleCache, "ModuleCache");
3248    const char Arg[] = "-fmodules-cache-path=";
3249    DefaultModuleCache.insert(DefaultModuleCache.begin(),
3250                              Arg, Arg + strlen(Arg));
3251    CmdArgs.push_back(Args.MakeArgString(DefaultModuleCache));
3252  }
3253
3254  // Pass through all -fmodules-ignore-macro arguments.
3255  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3256  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3257  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3258
3259  // -faccess-control is default.
3260  if (Args.hasFlag(options::OPT_fno_access_control,
3261                   options::OPT_faccess_control,
3262                   false))
3263    CmdArgs.push_back("-fno-access-control");
3264
3265  // -felide-constructors is the default.
3266  if (Args.hasFlag(options::OPT_fno_elide_constructors,
3267                   options::OPT_felide_constructors,
3268                   false))
3269    CmdArgs.push_back("-fno-elide-constructors");
3270
3271  // -frtti is default.
3272  if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
3273      KernelOrKext) {
3274    CmdArgs.push_back("-fno-rtti");
3275
3276    // -fno-rtti cannot usefully be combined with -fsanitize=vptr.
3277    if (Sanitize.sanitizesVptr()) {
3278      std::string NoRttiArg =
3279        Args.getLastArg(options::OPT_mkernel,
3280                        options::OPT_fapple_kext,
3281                        options::OPT_fno_rtti)->getAsString(Args);
3282      D.Diag(diag::err_drv_argument_not_allowed_with)
3283        << "-fsanitize=vptr" << NoRttiArg;
3284    }
3285  }
3286
3287  // -fshort-enums=0 is default for all architectures except Hexagon.
3288  if (Args.hasFlag(options::OPT_fshort_enums,
3289                   options::OPT_fno_short_enums,
3290                   getToolChain().getArch() ==
3291                   llvm::Triple::hexagon))
3292    CmdArgs.push_back("-fshort-enums");
3293
3294  // -fsigned-char is default.
3295  if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char,
3296                    isSignedCharDefault(getToolChain().getTriple())))
3297    CmdArgs.push_back("-fno-signed-char");
3298
3299  // -fthreadsafe-static is default.
3300  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3301                    options::OPT_fno_threadsafe_statics))
3302    CmdArgs.push_back("-fno-threadsafe-statics");
3303
3304  // -fuse-cxa-atexit is default.
3305  if (!Args.hasFlag(
3306           options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
3307           getToolChain().getTriple().getOS() != llvm::Triple::Cygwin &&
3308               getToolChain().getTriple().getOS() != llvm::Triple::MinGW32 &&
3309               getToolChain().getArch() != llvm::Triple::hexagon &&
3310               getToolChain().getArch() != llvm::Triple::xcore) ||
3311      KernelOrKext)
3312    CmdArgs.push_back("-fno-use-cxa-atexit");
3313
3314  // -fms-extensions=0 is default.
3315  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3316                   getToolChain().getTriple().getOS() == llvm::Triple::Win32))
3317    CmdArgs.push_back("-fms-extensions");
3318
3319  // -fms-compatibility=0 is default.
3320  if (Args.hasFlag(options::OPT_fms_compatibility,
3321                   options::OPT_fno_ms_compatibility,
3322                   (getToolChain().getTriple().getOS() == llvm::Triple::Win32 &&
3323                    Args.hasFlag(options::OPT_fms_extensions,
3324                                 options::OPT_fno_ms_extensions,
3325                                 true))))
3326    CmdArgs.push_back("-fms-compatibility");
3327
3328  // -fmsc-version=1700 is default.
3329  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3330                   getToolChain().getTriple().getOS() == llvm::Triple::Win32) ||
3331      Args.hasArg(options::OPT_fmsc_version)) {
3332    StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version);
3333    if (msc_ver.empty())
3334      CmdArgs.push_back("-fmsc-version=1700");
3335    else
3336      CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver));
3337  }
3338
3339
3340  // -fno-borland-extensions is default.
3341  if (Args.hasFlag(options::OPT_fborland_extensions,
3342                   options::OPT_fno_borland_extensions, false))
3343    CmdArgs.push_back("-fborland-extensions");
3344
3345  // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
3346  // needs it.
3347  if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
3348                   options::OPT_fno_delayed_template_parsing,
3349                   getToolChain().getTriple().getOS() == llvm::Triple::Win32))
3350    CmdArgs.push_back("-fdelayed-template-parsing");
3351
3352  // -fgnu-keywords default varies depending on language; only pass if
3353  // specified.
3354  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3355                               options::OPT_fno_gnu_keywords))
3356    A->render(Args, CmdArgs);
3357
3358  if (Args.hasFlag(options::OPT_fgnu89_inline,
3359                   options::OPT_fno_gnu89_inline,
3360                   false))
3361    CmdArgs.push_back("-fgnu89-inline");
3362
3363  if (Args.hasArg(options::OPT_fno_inline))
3364    CmdArgs.push_back("-fno-inline");
3365
3366  if (Args.hasArg(options::OPT_fno_inline_functions))
3367    CmdArgs.push_back("-fno-inline-functions");
3368
3369  ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3370
3371  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3372  // legacy is the default. Next runtime is always legacy dispatch and
3373  // -fno-objc-legacy-dispatch gets ignored silently.
3374  if (objcRuntime.isNonFragile() && !objcRuntime.isNeXTFamily()) {
3375    if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3376                      options::OPT_fno_objc_legacy_dispatch,
3377                      objcRuntime.isLegacyDispatchDefaultForArch(
3378                        getToolChain().getArch()))) {
3379      if (getToolChain().UseObjCMixedDispatch())
3380        CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3381      else
3382        CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3383    }
3384  }
3385
3386  // When ObjectiveC legacy runtime is in effect on MacOSX,
3387  // turn on the option to do Array/Dictionary subscripting
3388  // by default.
3389  if (getToolChain().getTriple().getArch() == llvm::Triple::x86 &&
3390      getToolChain().getTriple().isMacOSX() &&
3391      !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
3392      objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
3393      objcRuntime.isNeXTFamily())
3394    CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3395
3396  // -fencode-extended-block-signature=1 is default.
3397  if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3398    CmdArgs.push_back("-fencode-extended-block-signature");
3399  }
3400
3401  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3402  // NOTE: This logic is duplicated in ToolChains.cpp.
3403  bool ARC = isObjCAutoRefCount(Args);
3404  if (ARC) {
3405    getToolChain().CheckObjCARC();
3406
3407    CmdArgs.push_back("-fobjc-arc");
3408
3409    // FIXME: It seems like this entire block, and several around it should be
3410    // wrapped in isObjC, but for now we just use it here as this is where it
3411    // was being used previously.
3412    if (types::isCXX(InputType) && types::isObjC(InputType)) {
3413      if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3414        CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3415      else
3416        CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3417    }
3418
3419    // Allow the user to enable full exceptions code emission.
3420    // We define off for Objective-CC, on for Objective-C++.
3421    if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3422                     options::OPT_fno_objc_arc_exceptions,
3423                     /*default*/ types::isCXX(InputType)))
3424      CmdArgs.push_back("-fobjc-arc-exceptions");
3425  }
3426
3427  // -fobjc-infer-related-result-type is the default, except in the Objective-C
3428  // rewriter.
3429  if (rewriteKind != RK_None)
3430    CmdArgs.push_back("-fno-objc-infer-related-result-type");
3431
3432  // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
3433  // takes precedence.
3434  const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
3435  if (!GCArg)
3436    GCArg = Args.getLastArg(options::OPT_fobjc_gc);
3437  if (GCArg) {
3438    if (ARC) {
3439      D.Diag(diag::err_drv_objc_gc_arr)
3440        << GCArg->getAsString(Args);
3441    } else if (getToolChain().SupportsObjCGC()) {
3442      GCArg->render(Args, CmdArgs);
3443    } else {
3444      // FIXME: We should move this to a hard error.
3445      D.Diag(diag::warn_drv_objc_gc_unsupported)
3446        << GCArg->getAsString(Args);
3447    }
3448  }
3449
3450  // Add exception args.
3451  addExceptionArgs(Args, InputType, getToolChain().getTriple(),
3452                   KernelOrKext, objcRuntime, CmdArgs);
3453
3454  if (getToolChain().UseSjLjExceptions())
3455    CmdArgs.push_back("-fsjlj-exceptions");
3456
3457  // C++ "sane" operator new.
3458  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3459                    options::OPT_fno_assume_sane_operator_new))
3460    CmdArgs.push_back("-fno-assume-sane-operator-new");
3461
3462  // -fconstant-cfstrings is default, and may be subject to argument translation
3463  // on Darwin.
3464  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
3465                    options::OPT_fno_constant_cfstrings) ||
3466      !Args.hasFlag(options::OPT_mconstant_cfstrings,
3467                    options::OPT_mno_constant_cfstrings))
3468    CmdArgs.push_back("-fno-constant-cfstrings");
3469
3470  // -fshort-wchar default varies depending on platform; only
3471  // pass if specified.
3472  if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar))
3473    A->render(Args, CmdArgs);
3474
3475  // -fno-pascal-strings is default, only pass non-default.
3476  if (Args.hasFlag(options::OPT_fpascal_strings,
3477                   options::OPT_fno_pascal_strings,
3478                   false))
3479    CmdArgs.push_back("-fpascal-strings");
3480
3481  // Honor -fpack-struct= and -fpack-struct, if given. Note that
3482  // -fno-pack-struct doesn't apply to -fpack-struct=.
3483  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
3484    std::string PackStructStr = "-fpack-struct=";
3485    PackStructStr += A->getValue();
3486    CmdArgs.push_back(Args.MakeArgString(PackStructStr));
3487  } else if (Args.hasFlag(options::OPT_fpack_struct,
3488                          options::OPT_fno_pack_struct, false)) {
3489    CmdArgs.push_back("-fpack-struct=1");
3490  }
3491
3492  if (KernelOrKext || isNoCommonDefault(getToolChain().getTriple())) {
3493    if (!Args.hasArg(options::OPT_fcommon))
3494      CmdArgs.push_back("-fno-common");
3495    Args.ClaimAllArgs(options::OPT_fno_common);
3496  }
3497
3498  // -fcommon is default, only pass non-default.
3499  else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common))
3500    CmdArgs.push_back("-fno-common");
3501
3502  // -fsigned-bitfields is default, and clang doesn't yet support
3503  // -funsigned-bitfields.
3504  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
3505                    options::OPT_funsigned_bitfields))
3506    D.Diag(diag::warn_drv_clang_unsupported)
3507      << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
3508
3509  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
3510  if (!Args.hasFlag(options::OPT_ffor_scope,
3511                    options::OPT_fno_for_scope))
3512    D.Diag(diag::err_drv_clang_unsupported)
3513      << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
3514
3515  // -fcaret-diagnostics is default.
3516  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3517                    options::OPT_fno_caret_diagnostics, true))
3518    CmdArgs.push_back("-fno-caret-diagnostics");
3519
3520  // -fdiagnostics-fixit-info is default, only pass non-default.
3521  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3522                    options::OPT_fno_diagnostics_fixit_info))
3523    CmdArgs.push_back("-fno-diagnostics-fixit-info");
3524
3525  // Enable -fdiagnostics-show-option by default.
3526  if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3527                   options::OPT_fno_diagnostics_show_option))
3528    CmdArgs.push_back("-fdiagnostics-show-option");
3529
3530  if (const Arg *A =
3531        Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3532    CmdArgs.push_back("-fdiagnostics-show-category");
3533    CmdArgs.push_back(A->getValue());
3534  }
3535
3536  if (const Arg *A =
3537        Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3538    CmdArgs.push_back("-fdiagnostics-format");
3539    CmdArgs.push_back(A->getValue());
3540  }
3541
3542  if (Arg *A = Args.getLastArg(
3543      options::OPT_fdiagnostics_show_note_include_stack,
3544      options::OPT_fno_diagnostics_show_note_include_stack)) {
3545    if (A->getOption().matches(
3546        options::OPT_fdiagnostics_show_note_include_stack))
3547      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3548    else
3549      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3550  }
3551
3552  // Color diagnostics are the default, unless the terminal doesn't support
3553  // them.
3554  // Support both clang's -f[no-]color-diagnostics and gcc's
3555  // -f[no-]diagnostics-colors[=never|always|auto].
3556  enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
3557  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
3558       it != ie; ++it) {
3559    const Option &O = (*it)->getOption();
3560    if (!O.matches(options::OPT_fcolor_diagnostics) &&
3561        !O.matches(options::OPT_fdiagnostics_color) &&
3562        !O.matches(options::OPT_fno_color_diagnostics) &&
3563        !O.matches(options::OPT_fno_diagnostics_color) &&
3564        !O.matches(options::OPT_fdiagnostics_color_EQ))
3565      continue;
3566
3567    (*it)->claim();
3568    if (O.matches(options::OPT_fcolor_diagnostics) ||
3569        O.matches(options::OPT_fdiagnostics_color)) {
3570      ShowColors = Colors_On;
3571    } else if (O.matches(options::OPT_fno_color_diagnostics) ||
3572               O.matches(options::OPT_fno_diagnostics_color)) {
3573      ShowColors = Colors_Off;
3574    } else {
3575      assert(O.matches(options::OPT_fdiagnostics_color_EQ));
3576      StringRef value((*it)->getValue());
3577      if (value == "always")
3578        ShowColors = Colors_On;
3579      else if (value == "never")
3580        ShowColors = Colors_Off;
3581      else if (value == "auto")
3582        ShowColors = Colors_Auto;
3583      else
3584        getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3585          << ("-fdiagnostics-color=" + value).str();
3586    }
3587  }
3588  if (ShowColors == Colors_On ||
3589      (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
3590    CmdArgs.push_back("-fcolor-diagnostics");
3591
3592  if (Args.hasArg(options::OPT_fansi_escape_codes))
3593    CmdArgs.push_back("-fansi-escape-codes");
3594
3595  if (!Args.hasFlag(options::OPT_fshow_source_location,
3596                    options::OPT_fno_show_source_location))
3597    CmdArgs.push_back("-fno-show-source-location");
3598
3599  if (!Args.hasFlag(options::OPT_fshow_column,
3600                    options::OPT_fno_show_column,
3601                    true))
3602    CmdArgs.push_back("-fno-show-column");
3603
3604  if (!Args.hasFlag(options::OPT_fspell_checking,
3605                    options::OPT_fno_spell_checking))
3606    CmdArgs.push_back("-fno-spell-checking");
3607
3608
3609  // -fno-asm-blocks is default.
3610  if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
3611                   false))
3612    CmdArgs.push_back("-fasm-blocks");
3613
3614  // Enable vectorization per default according to the optimization level
3615  // selected. For optimization levels that want vectorization we use the alias
3616  // option to simplify the hasFlag logic.
3617  bool EnableVec = shouldEnableVectorizerAtOLevel(Args);
3618  OptSpecifier VectorizeAliasOption = EnableVec ? options::OPT_O_Group :
3619    options::OPT_fvectorize;
3620  if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
3621                   options::OPT_fno_vectorize, EnableVec))
3622    CmdArgs.push_back("-vectorize-loops");
3623
3624  // -fslp-vectorize is default.
3625  if (Args.hasFlag(options::OPT_fslp_vectorize,
3626                   options::OPT_fno_slp_vectorize, true))
3627    CmdArgs.push_back("-vectorize-slp");
3628
3629  // -fno-slp-vectorize-aggressive is default.
3630  if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
3631                   options::OPT_fno_slp_vectorize_aggressive, false))
3632    CmdArgs.push_back("-vectorize-slp-aggressive");
3633
3634  if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
3635    A->render(Args, CmdArgs);
3636
3637  // -fdollars-in-identifiers default varies depending on platform and
3638  // language; only pass if specified.
3639  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
3640                               options::OPT_fno_dollars_in_identifiers)) {
3641    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
3642      CmdArgs.push_back("-fdollars-in-identifiers");
3643    else
3644      CmdArgs.push_back("-fno-dollars-in-identifiers");
3645  }
3646
3647  // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
3648  // practical purposes.
3649  if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
3650                               options::OPT_fno_unit_at_a_time)) {
3651    if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
3652      D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
3653  }
3654
3655  if (Args.hasFlag(options::OPT_fapple_pragma_pack,
3656                   options::OPT_fno_apple_pragma_pack, false))
3657    CmdArgs.push_back("-fapple-pragma-pack");
3658
3659  // le32-specific flags:
3660  //  -fno-math-builtin: clang should not convert math builtins to intrinsics
3661  //                     by default.
3662  if (getToolChain().getArch() == llvm::Triple::le32) {
3663    CmdArgs.push_back("-fno-math-builtin");
3664  }
3665
3666  // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
3667  //
3668  // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
3669#if 0
3670  if (getToolChain().getTriple().isOSDarwin() &&
3671      (getToolChain().getArch() == llvm::Triple::arm ||
3672       getToolChain().getArch() == llvm::Triple::thumb)) {
3673    if (!Args.hasArg(options::OPT_fbuiltin_strcat))
3674      CmdArgs.push_back("-fno-builtin-strcat");
3675    if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
3676      CmdArgs.push_back("-fno-builtin-strcpy");
3677  }
3678#endif
3679
3680  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
3681  if (Arg *A = Args.getLastArg(options::OPT_traditional,
3682                               options::OPT_traditional_cpp)) {
3683    if (isa<PreprocessJobAction>(JA))
3684      CmdArgs.push_back("-traditional-cpp");
3685    else
3686      D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
3687  }
3688
3689  Args.AddLastArg(CmdArgs, options::OPT_dM);
3690  Args.AddLastArg(CmdArgs, options::OPT_dD);
3691
3692  // Handle serialized diagnostics.
3693  if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
3694    CmdArgs.push_back("-serialize-diagnostic-file");
3695    CmdArgs.push_back(Args.MakeArgString(A->getValue()));
3696  }
3697
3698  if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
3699    CmdArgs.push_back("-fretain-comments-from-system-headers");
3700
3701  // Forward -fcomment-block-commands to -cc1.
3702  Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
3703  // Forward -fparse-all-comments to -cc1.
3704  Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
3705
3706  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
3707  // parser.
3708  Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
3709  for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm),
3710         ie = Args.filtered_end(); it != ie; ++it) {
3711    (*it)->claim();
3712
3713    // We translate this by hand to the -cc1 argument, since nightly test uses
3714    // it and developers have been trained to spell it with -mllvm.
3715    if (StringRef((*it)->getValue(0)) == "-disable-llvm-optzns")
3716      CmdArgs.push_back("-disable-llvm-optzns");
3717    else
3718      (*it)->render(Args, CmdArgs);
3719  }
3720
3721  if (Output.getType() == types::TY_Dependencies) {
3722    // Handled with other dependency code.
3723  } else if (Output.isFilename()) {
3724    CmdArgs.push_back("-o");
3725    CmdArgs.push_back(Output.getFilename());
3726  } else {
3727    assert(Output.isNothing() && "Invalid output.");
3728  }
3729
3730  for (InputInfoList::const_iterator
3731         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
3732    const InputInfo &II = *it;
3733    CmdArgs.push_back("-x");
3734    if (Args.hasArg(options::OPT_rewrite_objc))
3735      CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3736    else
3737      CmdArgs.push_back(types::getTypeName(II.getType()));
3738    if (II.isFilename())
3739      CmdArgs.push_back(II.getFilename());
3740    else
3741      II.getInputArg().renderAsInput(Args, CmdArgs);
3742  }
3743
3744  Args.AddAllArgs(CmdArgs, options::OPT_undef);
3745
3746  const char *Exec = getToolChain().getDriver().getClangProgramPath();
3747
3748  // Optionally embed the -cc1 level arguments into the debug info, for build
3749  // analysis.
3750  if (getToolChain().UseDwarfDebugFlags()) {
3751    ArgStringList OriginalArgs;
3752    for (ArgList::const_iterator it = Args.begin(),
3753           ie = Args.end(); it != ie; ++it)
3754      (*it)->render(Args, OriginalArgs);
3755
3756    SmallString<256> Flags;
3757    Flags += Exec;
3758    for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
3759      Flags += " ";
3760      Flags += OriginalArgs[i];
3761    }
3762    CmdArgs.push_back("-dwarf-debug-flags");
3763    CmdArgs.push_back(Args.MakeArgString(Flags.str()));
3764  }
3765
3766  // Add the split debug info name to the command lines here so we
3767  // can propagate it to the backend.
3768  bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) &&
3769    getToolChain().getTriple().isOSLinux() &&
3770    (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA));
3771  const char *SplitDwarfOut;
3772  if (SplitDwarf) {
3773    CmdArgs.push_back("-split-dwarf-file");
3774    SplitDwarfOut = SplitDebugName(Args, Inputs);
3775    CmdArgs.push_back(SplitDwarfOut);
3776  }
3777
3778  // Finally add the compile command to the compilation.
3779  if (Args.hasArg(options::OPT__SLASH_fallback)) {
3780    tools::visualstudio::Compile CL(getToolChain());
3781    Command *CLCommand = CL.GetCommand(C, JA, Output, Inputs, Args,
3782                                       LinkingOutput);
3783    C.addCommand(new FallbackCommand(JA, *this, Exec, CmdArgs, CLCommand));
3784  } else {
3785    C.addCommand(new Command(JA, *this, Exec, CmdArgs));
3786  }
3787
3788
3789  // Handle the debug info splitting at object creation time if we're
3790  // creating an object.
3791  // TODO: Currently only works on linux with newer objcopy.
3792  if (SplitDwarf && !isa<CompileJobAction>(JA))
3793    SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
3794
3795  if (Arg *A = Args.getLastArg(options::OPT_pg))
3796    if (Args.hasArg(options::OPT_fomit_frame_pointer))
3797      D.Diag(diag::err_drv_argument_not_allowed_with)
3798        << "-fomit-frame-pointer" << A->getAsString(Args);
3799
3800  // Claim some arguments which clang supports automatically.
3801
3802  // -fpch-preprocess is used with gcc to add a special marker in the output to
3803  // include the PCH file. Clang's PTH solution is completely transparent, so we
3804  // do not need to deal with it at all.
3805  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
3806
3807  // Claim some arguments which clang doesn't support, but we don't
3808  // care to warn the user about.
3809  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
3810  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
3811
3812  // Disable warnings for clang -E -emit-llvm foo.c
3813  Args.ClaimAllArgs(options::OPT_emit_llvm);
3814}
3815
3816/// Add options related to the Objective-C runtime/ABI.
3817///
3818/// Returns true if the runtime is non-fragile.
3819ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
3820                                      ArgStringList &cmdArgs,
3821                                      RewriteKind rewriteKind) const {
3822  // Look for the controlling runtime option.
3823  Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime,
3824                                    options::OPT_fgnu_runtime,
3825                                    options::OPT_fobjc_runtime_EQ);
3826
3827  // Just forward -fobjc-runtime= to the frontend.  This supercedes
3828  // options about fragility.
3829  if (runtimeArg &&
3830      runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
3831    ObjCRuntime runtime;
3832    StringRef value = runtimeArg->getValue();
3833    if (runtime.tryParse(value)) {
3834      getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
3835        << value;
3836    }
3837
3838    runtimeArg->render(args, cmdArgs);
3839    return runtime;
3840  }
3841
3842  // Otherwise, we'll need the ABI "version".  Version numbers are
3843  // slightly confusing for historical reasons:
3844  //   1 - Traditional "fragile" ABI
3845  //   2 - Non-fragile ABI, version 1
3846  //   3 - Non-fragile ABI, version 2
3847  unsigned objcABIVersion = 1;
3848  // If -fobjc-abi-version= is present, use that to set the version.
3849  if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
3850    StringRef value = abiArg->getValue();
3851    if (value == "1")
3852      objcABIVersion = 1;
3853    else if (value == "2")
3854      objcABIVersion = 2;
3855    else if (value == "3")
3856      objcABIVersion = 3;
3857    else
3858      getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3859        << value;
3860  } else {
3861    // Otherwise, determine if we are using the non-fragile ABI.
3862    bool nonFragileABIIsDefault =
3863      (rewriteKind == RK_NonFragile ||
3864       (rewriteKind == RK_None &&
3865        getToolChain().IsObjCNonFragileABIDefault()));
3866    if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
3867                     options::OPT_fno_objc_nonfragile_abi,
3868                     nonFragileABIIsDefault)) {
3869      // Determine the non-fragile ABI version to use.
3870#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
3871      unsigned nonFragileABIVersion = 1;
3872#else
3873      unsigned nonFragileABIVersion = 2;
3874#endif
3875
3876      if (Arg *abiArg = args.getLastArg(
3877            options::OPT_fobjc_nonfragile_abi_version_EQ)) {
3878        StringRef value = abiArg->getValue();
3879        if (value == "1")
3880          nonFragileABIVersion = 1;
3881        else if (value == "2")
3882          nonFragileABIVersion = 2;
3883        else
3884          getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
3885            << value;
3886      }
3887
3888      objcABIVersion = 1 + nonFragileABIVersion;
3889    } else {
3890      objcABIVersion = 1;
3891    }
3892  }
3893
3894  // We don't actually care about the ABI version other than whether
3895  // it's non-fragile.
3896  bool isNonFragile = objcABIVersion != 1;
3897
3898  // If we have no runtime argument, ask the toolchain for its default runtime.
3899  // However, the rewriter only really supports the Mac runtime, so assume that.
3900  ObjCRuntime runtime;
3901  if (!runtimeArg) {
3902    switch (rewriteKind) {
3903    case RK_None:
3904      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
3905      break;
3906    case RK_Fragile:
3907      runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
3908      break;
3909    case RK_NonFragile:
3910      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
3911      break;
3912    }
3913
3914  // -fnext-runtime
3915  } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
3916    // On Darwin, make this use the default behavior for the toolchain.
3917    if (getToolChain().getTriple().isOSDarwin()) {
3918      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
3919
3920    // Otherwise, build for a generic macosx port.
3921    } else {
3922      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
3923    }
3924
3925  // -fgnu-runtime
3926  } else {
3927    assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
3928    // Legacy behaviour is to target the gnustep runtime if we are i
3929    // non-fragile mode or the GCC runtime in fragile mode.
3930    if (isNonFragile)
3931      runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6));
3932    else
3933      runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
3934  }
3935
3936  cmdArgs.push_back(args.MakeArgString(
3937                                 "-fobjc-runtime=" + runtime.getAsString()));
3938  return runtime;
3939}
3940
3941void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
3942  unsigned RTOptionID = options::OPT__SLASH_MT;
3943
3944  if (Args.hasArg(options::OPT__SLASH_LDd))
3945    // The /LDd option implies /MTd. The dependent lib part can be overridden,
3946    // but defining _DEBUG is sticky.
3947    RTOptionID = options::OPT__SLASH_MTd;
3948
3949  if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
3950    RTOptionID = A->getOption().getID();
3951
3952  switch(RTOptionID) {
3953    case options::OPT__SLASH_MD:
3954      if (Args.hasArg(options::OPT__SLASH_LDd))
3955        CmdArgs.push_back("-D_DEBUG");
3956      CmdArgs.push_back("-D_MT");
3957      CmdArgs.push_back("-D_DLL");
3958      CmdArgs.push_back("--dependent-lib=msvcrt");
3959      break;
3960    case options::OPT__SLASH_MDd:
3961      CmdArgs.push_back("-D_DEBUG");
3962      CmdArgs.push_back("-D_MT");
3963      CmdArgs.push_back("-D_DLL");
3964      CmdArgs.push_back("--dependent-lib=msvcrtd");
3965      break;
3966    case options::OPT__SLASH_MT:
3967      if (Args.hasArg(options::OPT__SLASH_LDd))
3968        CmdArgs.push_back("-D_DEBUG");
3969      CmdArgs.push_back("-D_MT");
3970      CmdArgs.push_back("--dependent-lib=libcmt");
3971      break;
3972    case options::OPT__SLASH_MTd:
3973      CmdArgs.push_back("-D_DEBUG");
3974      CmdArgs.push_back("-D_MT");
3975      CmdArgs.push_back("--dependent-lib=libcmtd");
3976      break;
3977    default:
3978      llvm_unreachable("Unexpected option ID.");
3979  }
3980
3981  // This provides POSIX compatibility (maps 'open' to '_open'), which most
3982  // users want.  The /Za flag to cl.exe turns this off, but it's not
3983  // implemented in clang.
3984  CmdArgs.push_back("--dependent-lib=oldnames");
3985
3986  // FIXME: Make this default for the win32 triple.
3987  CmdArgs.push_back("-cxx-abi");
3988  CmdArgs.push_back("microsoft");
3989
3990  if (Arg *A = Args.getLastArg(options::OPT_show_includes))
3991    A->render(Args, CmdArgs);
3992
3993  if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
3994    CmdArgs.push_back("-fdiagnostics-format");
3995    if (Args.hasArg(options::OPT__SLASH_fallback))
3996      CmdArgs.push_back("msvc-fallback");
3997    else
3998      CmdArgs.push_back("msvc");
3999  }
4000}
4001
4002void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
4003                           const InputInfo &Output,
4004                           const InputInfoList &Inputs,
4005                           const ArgList &Args,
4006                           const char *LinkingOutput) const {
4007  ArgStringList CmdArgs;
4008
4009  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4010  const InputInfo &Input = Inputs[0];
4011
4012  // Don't warn about "clang -w -c foo.s"
4013  Args.ClaimAllArgs(options::OPT_w);
4014  // and "clang -emit-llvm -c foo.s"
4015  Args.ClaimAllArgs(options::OPT_emit_llvm);
4016
4017  // Invoke ourselves in -cc1as mode.
4018  //
4019  // FIXME: Implement custom jobs for internal actions.
4020  CmdArgs.push_back("-cc1as");
4021
4022  // Add the "effective" target triple.
4023  CmdArgs.push_back("-triple");
4024  std::string TripleStr =
4025    getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
4026  CmdArgs.push_back(Args.MakeArgString(TripleStr));
4027
4028  // Set the output mode, we currently only expect to be used as a real
4029  // assembler.
4030  CmdArgs.push_back("-filetype");
4031  CmdArgs.push_back("obj");
4032
4033  // Set the main file name, so that debug info works even with
4034  // -save-temps or preprocessed assembly.
4035  CmdArgs.push_back("-main-file-name");
4036  CmdArgs.push_back(Clang::getBaseInputName(Args, Inputs));
4037
4038  // Add the target cpu
4039  const llvm::Triple &Triple = getToolChain().getTriple();
4040  std::string CPU = getCPUName(Args, Triple);
4041  if (!CPU.empty()) {
4042    CmdArgs.push_back("-target-cpu");
4043    CmdArgs.push_back(Args.MakeArgString(CPU));
4044  }
4045
4046  // Add the target features
4047  const Driver &D = getToolChain().getDriver();
4048  getTargetFeatures(D, Triple, Args, CmdArgs);
4049
4050  // Ignore explicit -force_cpusubtype_ALL option.
4051  (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
4052
4053  // Determine the original source input.
4054  const Action *SourceAction = &JA;
4055  while (SourceAction->getKind() != Action::InputClass) {
4056    assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4057    SourceAction = SourceAction->getInputs()[0];
4058  }
4059
4060  // Forward -g and handle debug info related flags, assuming we are dealing
4061  // with an actual assembly file.
4062  if (SourceAction->getType() == types::TY_Asm ||
4063      SourceAction->getType() == types::TY_PP_Asm) {
4064    Args.ClaimAllArgs(options::OPT_g_Group);
4065    if (Arg *A = Args.getLastArg(options::OPT_g_Group))
4066      if (!A->getOption().matches(options::OPT_g0))
4067        CmdArgs.push_back("-g");
4068
4069    // Add the -fdebug-compilation-dir flag if needed.
4070    addDebugCompDirArg(Args, CmdArgs);
4071
4072    // Set the AT_producer to the clang version when using the integrated
4073    // assembler on assembly source files.
4074    CmdArgs.push_back("-dwarf-debug-producer");
4075    CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
4076  }
4077
4078  // Optionally embed the -cc1as level arguments into the debug info, for build
4079  // analysis.
4080  if (getToolChain().UseDwarfDebugFlags()) {
4081    ArgStringList OriginalArgs;
4082    for (ArgList::const_iterator it = Args.begin(),
4083           ie = Args.end(); it != ie; ++it)
4084      (*it)->render(Args, OriginalArgs);
4085
4086    SmallString<256> Flags;
4087    const char *Exec = getToolChain().getDriver().getClangProgramPath();
4088    Flags += Exec;
4089    for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) {
4090      Flags += " ";
4091      Flags += OriginalArgs[i];
4092    }
4093    CmdArgs.push_back("-dwarf-debug-flags");
4094    CmdArgs.push_back(Args.MakeArgString(Flags.str()));
4095  }
4096
4097  // FIXME: Add -static support, once we have it.
4098
4099  CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
4100                                    getToolChain().getDriver());
4101
4102  Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
4103
4104  assert(Output.isFilename() && "Unexpected lipo output.");
4105  CmdArgs.push_back("-o");
4106  CmdArgs.push_back(Output.getFilename());
4107
4108  assert(Input.isFilename() && "Invalid input.");
4109  CmdArgs.push_back(Input.getFilename());
4110
4111  const char *Exec = getToolChain().getDriver().getClangProgramPath();
4112  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4113
4114  // Handle the debug info splitting at object creation time if we're
4115  // creating an object.
4116  // TODO: Currently only works on linux with newer objcopy.
4117  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
4118      getToolChain().getTriple().isOSLinux())
4119    SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
4120                   SplitDebugName(Args, Inputs));
4121}
4122
4123void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
4124                               const InputInfo &Output,
4125                               const InputInfoList &Inputs,
4126                               const ArgList &Args,
4127                               const char *LinkingOutput) const {
4128  const Driver &D = getToolChain().getDriver();
4129  ArgStringList CmdArgs;
4130
4131  for (ArgList::const_iterator
4132         it = Args.begin(), ie = Args.end(); it != ie; ++it) {
4133    Arg *A = *it;
4134    if (forwardToGCC(A->getOption())) {
4135      // Don't forward any -g arguments to assembly steps.
4136      if (isa<AssembleJobAction>(JA) &&
4137          A->getOption().matches(options::OPT_g_Group))
4138        continue;
4139
4140      // Don't forward any -W arguments to assembly and link steps.
4141      if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
4142          A->getOption().matches(options::OPT_W_Group))
4143        continue;
4144
4145      // It is unfortunate that we have to claim here, as this means
4146      // we will basically never report anything interesting for
4147      // platforms using a generic gcc, even if we are just using gcc
4148      // to get to the assembler.
4149      A->claim();
4150      A->render(Args, CmdArgs);
4151    }
4152  }
4153
4154  RenderExtraToolArgs(JA, CmdArgs);
4155
4156  // If using a driver driver, force the arch.
4157  llvm::Triple::ArchType Arch = getToolChain().getArch();
4158  if (getToolChain().getTriple().isOSDarwin()) {
4159    CmdArgs.push_back("-arch");
4160
4161    // FIXME: Remove these special cases.
4162    if (Arch == llvm::Triple::ppc)
4163      CmdArgs.push_back("ppc");
4164    else if (Arch == llvm::Triple::ppc64)
4165      CmdArgs.push_back("ppc64");
4166    else if (Arch == llvm::Triple::ppc64le)
4167      CmdArgs.push_back("ppc64le");
4168    else
4169      CmdArgs.push_back(Args.MakeArgString(getToolChain().getArchName()));
4170  }
4171
4172  // Try to force gcc to match the tool chain we want, if we recognize
4173  // the arch.
4174  //
4175  // FIXME: The triple class should directly provide the information we want
4176  // here.
4177  if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::ppc)
4178    CmdArgs.push_back("-m32");
4179  else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64 ||
4180           Arch == llvm::Triple::ppc64le)
4181    CmdArgs.push_back("-m64");
4182
4183  if (Output.isFilename()) {
4184    CmdArgs.push_back("-o");
4185    CmdArgs.push_back(Output.getFilename());
4186  } else {
4187    assert(Output.isNothing() && "Unexpected output");
4188    CmdArgs.push_back("-fsyntax-only");
4189  }
4190
4191  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4192                       options::OPT_Xassembler);
4193
4194  // Only pass -x if gcc will understand it; otherwise hope gcc
4195  // understands the suffix correctly. The main use case this would go
4196  // wrong in is for linker inputs if they happened to have an odd
4197  // suffix; really the only way to get this to happen is a command
4198  // like '-x foobar a.c' which will treat a.c like a linker input.
4199  //
4200  // FIXME: For the linker case specifically, can we safely convert
4201  // inputs into '-Wl,' options?
4202  for (InputInfoList::const_iterator
4203         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4204    const InputInfo &II = *it;
4205
4206    // Don't try to pass LLVM or AST inputs to a generic gcc.
4207    if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
4208        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
4209      D.Diag(diag::err_drv_no_linker_llvm_support)
4210        << getToolChain().getTripleString();
4211    else if (II.getType() == types::TY_AST)
4212      D.Diag(diag::err_drv_no_ast_support)
4213        << getToolChain().getTripleString();
4214    else if (II.getType() == types::TY_ModuleFile)
4215      D.Diag(diag::err_drv_no_module_support)
4216        << getToolChain().getTripleString();
4217
4218    if (types::canTypeBeUserSpecified(II.getType())) {
4219      CmdArgs.push_back("-x");
4220      CmdArgs.push_back(types::getTypeName(II.getType()));
4221    }
4222
4223    if (II.isFilename())
4224      CmdArgs.push_back(II.getFilename());
4225    else {
4226      const Arg &A = II.getInputArg();
4227
4228      // Reverse translate some rewritten options.
4229      if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
4230        CmdArgs.push_back("-lstdc++");
4231        continue;
4232      }
4233
4234      // Don't render as input, we need gcc to do the translations.
4235      A.render(Args, CmdArgs);
4236    }
4237  }
4238
4239  const std::string customGCCName = D.getCCCGenericGCCName();
4240  const char *GCCName;
4241  if (!customGCCName.empty())
4242    GCCName = customGCCName.c_str();
4243  else if (D.CCCIsCXX()) {
4244    GCCName = "g++";
4245  } else
4246    GCCName = "gcc";
4247
4248  const char *Exec =
4249    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
4250  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4251}
4252
4253void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA,
4254                                          ArgStringList &CmdArgs) const {
4255  CmdArgs.push_back("-E");
4256}
4257
4258void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA,
4259                                          ArgStringList &CmdArgs) const {
4260  // The type is good enough.
4261}
4262
4263void gcc::Compile::RenderExtraToolArgs(const JobAction &JA,
4264                                       ArgStringList &CmdArgs) const {
4265  const Driver &D = getToolChain().getDriver();
4266
4267  // If -flto, etc. are present then make sure not to force assembly output.
4268  if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR ||
4269      JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC)
4270    CmdArgs.push_back("-c");
4271  else {
4272    if (JA.getType() != types::TY_PP_Asm)
4273      D.Diag(diag::err_drv_invalid_gcc_output_type)
4274        << getTypeName(JA.getType());
4275
4276    CmdArgs.push_back("-S");
4277  }
4278}
4279
4280void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA,
4281                                        ArgStringList &CmdArgs) const {
4282  CmdArgs.push_back("-c");
4283}
4284
4285void gcc::Link::RenderExtraToolArgs(const JobAction &JA,
4286                                    ArgStringList &CmdArgs) const {
4287  // The types are (hopefully) good enough.
4288}
4289
4290// Hexagon tools start.
4291void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
4292                                        ArgStringList &CmdArgs) const {
4293
4294}
4295void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4296                               const InputInfo &Output,
4297                               const InputInfoList &Inputs,
4298                               const ArgList &Args,
4299                               const char *LinkingOutput) const {
4300
4301  const Driver &D = getToolChain().getDriver();
4302  ArgStringList CmdArgs;
4303
4304  std::string MarchString = "-march=";
4305  MarchString += toolchains::Hexagon_TC::GetTargetCPU(Args);
4306  CmdArgs.push_back(Args.MakeArgString(MarchString));
4307
4308  RenderExtraToolArgs(JA, CmdArgs);
4309
4310  if (Output.isFilename()) {
4311    CmdArgs.push_back("-o");
4312    CmdArgs.push_back(Output.getFilename());
4313  } else {
4314    assert(Output.isNothing() && "Unexpected output");
4315    CmdArgs.push_back("-fsyntax-only");
4316  }
4317
4318  std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
4319  if (!SmallDataThreshold.empty())
4320    CmdArgs.push_back(
4321      Args.MakeArgString(std::string("-G") + SmallDataThreshold));
4322
4323  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4324                       options::OPT_Xassembler);
4325
4326  // Only pass -x if gcc will understand it; otherwise hope gcc
4327  // understands the suffix correctly. The main use case this would go
4328  // wrong in is for linker inputs if they happened to have an odd
4329  // suffix; really the only way to get this to happen is a command
4330  // like '-x foobar a.c' which will treat a.c like a linker input.
4331  //
4332  // FIXME: For the linker case specifically, can we safely convert
4333  // inputs into '-Wl,' options?
4334  for (InputInfoList::const_iterator
4335         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
4336    const InputInfo &II = *it;
4337
4338    // Don't try to pass LLVM or AST inputs to a generic gcc.
4339    if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR ||
4340        II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC)
4341      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
4342        << getToolChain().getTripleString();
4343    else if (II.getType() == types::TY_AST)
4344      D.Diag(clang::diag::err_drv_no_ast_support)
4345        << getToolChain().getTripleString();
4346    else if (II.getType() == types::TY_ModuleFile)
4347      D.Diag(diag::err_drv_no_module_support)
4348      << getToolChain().getTripleString();
4349
4350    if (II.isFilename())
4351      CmdArgs.push_back(II.getFilename());
4352    else
4353      // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ?
4354      II.getInputArg().render(Args, CmdArgs);
4355  }
4356
4357  const char *GCCName = "hexagon-as";
4358  const char *Exec =
4359    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
4360  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4361
4362}
4363void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
4364                                    ArgStringList &CmdArgs) const {
4365  // The types are (hopefully) good enough.
4366}
4367
4368void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
4369                               const InputInfo &Output,
4370                               const InputInfoList &Inputs,
4371                               const ArgList &Args,
4372                               const char *LinkingOutput) const {
4373
4374  const toolchains::Hexagon_TC& ToolChain =
4375    static_cast<const toolchains::Hexagon_TC&>(getToolChain());
4376  const Driver &D = ToolChain.getDriver();
4377
4378  ArgStringList CmdArgs;
4379
4380  //----------------------------------------------------------------------------
4381  //
4382  //----------------------------------------------------------------------------
4383  bool hasStaticArg = Args.hasArg(options::OPT_static);
4384  bool buildingLib = Args.hasArg(options::OPT_shared);
4385  bool buildPIE = Args.hasArg(options::OPT_pie);
4386  bool incStdLib = !Args.hasArg(options::OPT_nostdlib);
4387  bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles);
4388  bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
4389  bool useShared = buildingLib && !hasStaticArg;
4390
4391  //----------------------------------------------------------------------------
4392  // Silence warnings for various options
4393  //----------------------------------------------------------------------------
4394
4395  Args.ClaimAllArgs(options::OPT_g_Group);
4396  Args.ClaimAllArgs(options::OPT_emit_llvm);
4397  Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
4398                                     // handled somewhere else.
4399  Args.ClaimAllArgs(options::OPT_static_libgcc);
4400
4401  //----------------------------------------------------------------------------
4402  //
4403  //----------------------------------------------------------------------------
4404  for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
4405         e = ToolChain.ExtraOpts.end();
4406       i != e; ++i)
4407    CmdArgs.push_back(i->c_str());
4408
4409  std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args);
4410  CmdArgs.push_back(Args.MakeArgString("-m" + MarchString));
4411
4412  if (buildingLib) {
4413    CmdArgs.push_back("-shared");
4414    CmdArgs.push_back("-call_shared"); // should be the default, but doing as
4415                                       // hexagon-gcc does
4416  }
4417
4418  if (hasStaticArg)
4419    CmdArgs.push_back("-static");
4420
4421  if (buildPIE && !buildingLib)
4422    CmdArgs.push_back("-pie");
4423
4424  std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args);
4425  if (!SmallDataThreshold.empty()) {
4426    CmdArgs.push_back(
4427      Args.MakeArgString(std::string("-G") + SmallDataThreshold));
4428  }
4429
4430  //----------------------------------------------------------------------------
4431  //
4432  //----------------------------------------------------------------------------
4433  CmdArgs.push_back("-o");
4434  CmdArgs.push_back(Output.getFilename());
4435
4436  const std::string MarchSuffix = "/" + MarchString;
4437  const std::string G0Suffix = "/G0";
4438  const std::string MarchG0Suffix = MarchSuffix + G0Suffix;
4439  const std::string RootDir = toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir)
4440                              + "/";
4441  const std::string StartFilesDir = RootDir
4442                                    + "hexagon/lib"
4443                                    + (buildingLib
4444                                       ? MarchG0Suffix : MarchSuffix);
4445
4446  //----------------------------------------------------------------------------
4447  // moslib
4448  //----------------------------------------------------------------------------
4449  std::vector<std::string> oslibs;
4450  bool hasStandalone= false;
4451
4452  for (arg_iterator it = Args.filtered_begin(options::OPT_moslib_EQ),
4453         ie = Args.filtered_end(); it != ie; ++it) {
4454    (*it)->claim();
4455    oslibs.push_back((*it)->getValue());
4456    hasStandalone = hasStandalone || (oslibs.back() == "standalone");
4457  }
4458  if (oslibs.empty()) {
4459    oslibs.push_back("standalone");
4460    hasStandalone = true;
4461  }
4462
4463  //----------------------------------------------------------------------------
4464  // Start Files
4465  //----------------------------------------------------------------------------
4466  if (incStdLib && incStartFiles) {
4467
4468    if (!buildingLib) {
4469      if (hasStandalone) {
4470        CmdArgs.push_back(
4471          Args.MakeArgString(StartFilesDir + "/crt0_standalone.o"));
4472      }
4473      CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o"));
4474    }
4475    std::string initObj = useShared ? "/initS.o" : "/init.o";
4476    CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj));
4477  }
4478
4479  //----------------------------------------------------------------------------
4480  // Library Search Paths
4481  //----------------------------------------------------------------------------
4482  const ToolChain::path_list &LibPaths = ToolChain.getFilePaths();
4483  for (ToolChain::path_list::const_iterator
4484         i = LibPaths.begin(),
4485         e = LibPaths.end();
4486       i != e;
4487       ++i)
4488    CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
4489
4490  //----------------------------------------------------------------------------
4491  //
4492  //----------------------------------------------------------------------------
4493  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
4494  Args.AddAllArgs(CmdArgs, options::OPT_e);
4495  Args.AddAllArgs(CmdArgs, options::OPT_s);
4496  Args.AddAllArgs(CmdArgs, options::OPT_t);
4497  Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4498
4499  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
4500
4501  //----------------------------------------------------------------------------
4502  // Libraries
4503  //----------------------------------------------------------------------------
4504  if (incStdLib && incDefLibs) {
4505    if (D.CCCIsCXX()) {
4506      ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
4507      CmdArgs.push_back("-lm");
4508    }
4509
4510    CmdArgs.push_back("--start-group");
4511
4512    if (!buildingLib) {
4513      for(std::vector<std::string>::iterator i = oslibs.begin(),
4514            e = oslibs.end(); i != e; ++i)
4515        CmdArgs.push_back(Args.MakeArgString("-l" + *i));
4516      CmdArgs.push_back("-lc");
4517    }
4518    CmdArgs.push_back("-lgcc");
4519
4520    CmdArgs.push_back("--end-group");
4521  }
4522
4523  //----------------------------------------------------------------------------
4524  // End files
4525  //----------------------------------------------------------------------------
4526  if (incStdLib && incStartFiles) {
4527    std::string finiObj = useShared ? "/finiS.o" : "/fini.o";
4528    CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj));
4529  }
4530
4531  std::string Linker = ToolChain.GetProgramPath("hexagon-ld");
4532  C.addCommand(new Command(JA, *this, Args.MakeArgString(Linker), CmdArgs));
4533}
4534// Hexagon tools end.
4535
4536llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Str) {
4537  // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
4538  // archs which Darwin doesn't use.
4539
4540  // The matching this routine does is fairly pointless, since it is neither the
4541  // complete architecture list, nor a reasonable subset. The problem is that
4542  // historically the driver driver accepts this and also ties its -march=
4543  // handling to the architecture name, so we need to be careful before removing
4544  // support for it.
4545
4546  // This code must be kept in sync with Clang's Darwin specific argument
4547  // translation.
4548
4549  return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
4550    .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
4551    .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
4552    .Case("ppc64", llvm::Triple::ppc64)
4553    .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
4554    .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
4555           llvm::Triple::x86)
4556    .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
4557    // This is derived from the driver driver.
4558    .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
4559    .Cases("armv7", "armv7em", "armv7f", "armv7k", "armv7m", llvm::Triple::arm)
4560    .Cases("armv7s", "xscale", llvm::Triple::arm)
4561    .Case("r600", llvm::Triple::r600)
4562    .Case("nvptx", llvm::Triple::nvptx)
4563    .Case("nvptx64", llvm::Triple::nvptx64)
4564    .Case("amdil", llvm::Triple::amdil)
4565    .Case("spir", llvm::Triple::spir)
4566    .Default(llvm::Triple::UnknownArch);
4567}
4568
4569const char *Clang::getBaseInputName(const ArgList &Args,
4570                                    const InputInfoList &Inputs) {
4571  return Args.MakeArgString(
4572    llvm::sys::path::filename(Inputs[0].getBaseInput()));
4573}
4574
4575const char *Clang::getBaseInputStem(const ArgList &Args,
4576                                    const InputInfoList &Inputs) {
4577  const char *Str = getBaseInputName(Args, Inputs);
4578
4579  if (const char *End = strrchr(Str, '.'))
4580    return Args.MakeArgString(std::string(Str, End));
4581
4582  return Str;
4583}
4584
4585const char *Clang::getDependencyFileName(const ArgList &Args,
4586                                         const InputInfoList &Inputs) {
4587  // FIXME: Think about this more.
4588  std::string Res;
4589
4590  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4591    std::string Str(OutputOpt->getValue());
4592    Res = Str.substr(0, Str.rfind('.'));
4593  } else {
4594    Res = getBaseInputStem(Args, Inputs);
4595  }
4596  return Args.MakeArgString(Res + ".d");
4597}
4598
4599void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
4600                                    const InputInfo &Output,
4601                                    const InputInfoList &Inputs,
4602                                    const ArgList &Args,
4603                                    const char *LinkingOutput) const {
4604  ArgStringList CmdArgs;
4605
4606  assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4607  const InputInfo &Input = Inputs[0];
4608
4609  // Determine the original source input.
4610  const Action *SourceAction = &JA;
4611  while (SourceAction->getKind() != Action::InputClass) {
4612    assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4613    SourceAction = SourceAction->getInputs()[0];
4614  }
4615
4616  // If -no_integrated_as is used add -Q to the darwin assember driver to make
4617  // sure it runs its system assembler not clang's integrated assembler.
4618  if (Args.hasArg(options::OPT_no_integrated_as))
4619    CmdArgs.push_back("-Q");
4620
4621  // Forward -g, assuming we are dealing with an actual assembly file.
4622  if (SourceAction->getType() == types::TY_Asm ||
4623      SourceAction->getType() == types::TY_PP_Asm) {
4624    if (Args.hasArg(options::OPT_gstabs))
4625      CmdArgs.push_back("--gstabs");
4626    else if (Args.hasArg(options::OPT_g_Group))
4627      CmdArgs.push_back("-g");
4628  }
4629
4630  // Derived from asm spec.
4631  AddDarwinArch(Args, CmdArgs);
4632
4633  // Use -force_cpusubtype_ALL on x86 by default.
4634  if (getToolChain().getArch() == llvm::Triple::x86 ||
4635      getToolChain().getArch() == llvm::Triple::x86_64 ||
4636      Args.hasArg(options::OPT_force__cpusubtype__ALL))
4637    CmdArgs.push_back("-force_cpusubtype_ALL");
4638
4639  if (getToolChain().getArch() != llvm::Triple::x86_64 &&
4640      (((Args.hasArg(options::OPT_mkernel) ||
4641         Args.hasArg(options::OPT_fapple_kext)) &&
4642        (!getDarwinToolChain().isTargetIPhoneOS() ||
4643         getDarwinToolChain().isIPhoneOSVersionLT(6, 0))) ||
4644       Args.hasArg(options::OPT_static)))
4645    CmdArgs.push_back("-static");
4646
4647  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
4648                       options::OPT_Xassembler);
4649
4650  assert(Output.isFilename() && "Unexpected lipo output.");
4651  CmdArgs.push_back("-o");
4652  CmdArgs.push_back(Output.getFilename());
4653
4654  assert(Input.isFilename() && "Invalid input.");
4655  CmdArgs.push_back(Input.getFilename());
4656
4657  // asm_final spec is empty.
4658
4659  const char *Exec =
4660    Args.MakeArgString(getToolChain().GetProgramPath("as"));
4661  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4662}
4663
4664void darwin::DarwinTool::anchor() {}
4665
4666void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
4667                                       ArgStringList &CmdArgs) const {
4668  StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args);
4669
4670  // Derived from darwin_arch spec.
4671  CmdArgs.push_back("-arch");
4672  CmdArgs.push_back(Args.MakeArgString(ArchName));
4673
4674  // FIXME: Is this needed anymore?
4675  if (ArchName == "arm")
4676    CmdArgs.push_back("-force_cpusubtype_ALL");
4677}
4678
4679bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const {
4680  // We only need to generate a temp path for LTO if we aren't compiling object
4681  // files. When compiling source files, we run 'dsymutil' after linking. We
4682  // don't run 'dsymutil' when compiling object files.
4683  for (InputInfoList::const_iterator
4684         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it)
4685    if (it->getType() != types::TY_Object)
4686      return true;
4687
4688  return false;
4689}
4690
4691void darwin::Link::AddLinkArgs(Compilation &C,
4692                               const ArgList &Args,
4693                               ArgStringList &CmdArgs,
4694                               const InputInfoList &Inputs) const {
4695  const Driver &D = getToolChain().getDriver();
4696  const toolchains::Darwin &DarwinTC = getDarwinToolChain();
4697
4698  unsigned Version[3] = { 0, 0, 0 };
4699  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4700    bool HadExtra;
4701    if (!Driver::GetReleaseVersion(A->getValue(), Version[0],
4702                                   Version[1], Version[2], HadExtra) ||
4703        HadExtra)
4704      D.Diag(diag::err_drv_invalid_version_number)
4705        << A->getAsString(Args);
4706  }
4707
4708  // Newer linkers support -demangle, pass it if supported and not disabled by
4709  // the user.
4710  if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) {
4711    // Don't pass -demangle to ld_classic.
4712    //
4713    // FIXME: This is a temporary workaround, ld should be handling this.
4714    bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 &&
4715                          Args.hasArg(options::OPT_static));
4716    if (getToolChain().getArch() == llvm::Triple::x86) {
4717      for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker,
4718                                                 options::OPT_Wl_COMMA),
4719             ie = Args.filtered_end(); it != ie; ++it) {
4720        const Arg *A = *it;
4721        for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
4722          if (StringRef(A->getValue(i)) == "-kext")
4723            UsesLdClassic = true;
4724      }
4725    }
4726    if (!UsesLdClassic)
4727      CmdArgs.push_back("-demangle");
4728  }
4729
4730  if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
4731    CmdArgs.push_back("-export_dynamic");
4732
4733  // If we are using LTO, then automatically create a temporary file path for
4734  // the linker to use, so that it's lifetime will extend past a possible
4735  // dsymutil step.
4736  if (Version[0] >= 116 && D.IsUsingLTO(Args) && NeedsTempPath(Inputs)) {
4737    const char *TmpPath = C.getArgs().MakeArgString(
4738      D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
4739    C.addTempFile(TmpPath);
4740    CmdArgs.push_back("-object_path_lto");
4741    CmdArgs.push_back(TmpPath);
4742  }
4743
4744  // Derived from the "link" spec.
4745  Args.AddAllArgs(CmdArgs, options::OPT_static);
4746  if (!Args.hasArg(options::OPT_static))
4747    CmdArgs.push_back("-dynamic");
4748  if (Args.hasArg(options::OPT_fgnu_runtime)) {
4749    // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
4750    // here. How do we wish to handle such things?
4751  }
4752
4753  if (!Args.hasArg(options::OPT_dynamiclib)) {
4754    AddDarwinArch(Args, CmdArgs);
4755    // FIXME: Why do this only on this path?
4756    Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
4757
4758    Args.AddLastArg(CmdArgs, options::OPT_bundle);
4759    Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
4760    Args.AddAllArgs(CmdArgs, options::OPT_client__name);
4761
4762    Arg *A;
4763    if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
4764        (A = Args.getLastArg(options::OPT_current__version)) ||
4765        (A = Args.getLastArg(options::OPT_install__name)))
4766      D.Diag(diag::err_drv_argument_only_allowed_with)
4767        << A->getAsString(Args) << "-dynamiclib";
4768
4769    Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
4770    Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
4771    Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
4772  } else {
4773    CmdArgs.push_back("-dylib");
4774
4775    Arg *A;
4776    if ((A = Args.getLastArg(options::OPT_bundle)) ||
4777        (A = Args.getLastArg(options::OPT_bundle__loader)) ||
4778        (A = Args.getLastArg(options::OPT_client__name)) ||
4779        (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
4780        (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
4781        (A = Args.getLastArg(options::OPT_private__bundle)))
4782      D.Diag(diag::err_drv_argument_not_allowed_with)
4783        << A->getAsString(Args) << "-dynamiclib";
4784
4785    Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
4786                              "-dylib_compatibility_version");
4787    Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
4788                              "-dylib_current_version");
4789
4790    AddDarwinArch(Args, CmdArgs);
4791
4792    Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
4793                              "-dylib_install_name");
4794  }
4795
4796  Args.AddLastArg(CmdArgs, options::OPT_all__load);
4797  Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
4798  Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
4799  if (DarwinTC.isTargetIPhoneOS())
4800    Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
4801  Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
4802  Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
4803  Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
4804  Args.AddLastArg(CmdArgs, options::OPT_dynamic);
4805  Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
4806  Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
4807  Args.AddAllArgs(CmdArgs, options::OPT_force__load);
4808  Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
4809  Args.AddAllArgs(CmdArgs, options::OPT_image__base);
4810  Args.AddAllArgs(CmdArgs, options::OPT_init);
4811
4812  // Add the deployment target.
4813  VersionTuple TargetVersion = DarwinTC.getTargetVersion();
4814
4815  // If we had an explicit -mios-simulator-version-min argument, honor that,
4816  // otherwise use the traditional deployment targets. We can't just check the
4817  // is-sim attribute because existing code follows this path, and the linker
4818  // may not handle the argument.
4819  //
4820  // FIXME: We may be able to remove this, once we can verify no one depends on
4821  // it.
4822  if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ))
4823    CmdArgs.push_back("-ios_simulator_version_min");
4824  else if (DarwinTC.isTargetIPhoneOS())
4825    CmdArgs.push_back("-iphoneos_version_min");
4826  else
4827    CmdArgs.push_back("-macosx_version_min");
4828  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
4829
4830  Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
4831  Args.AddLastArg(CmdArgs, options::OPT_multi__module);
4832  Args.AddLastArg(CmdArgs, options::OPT_single__module);
4833  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
4834  Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
4835
4836  if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
4837                                     options::OPT_fno_pie,
4838                                     options::OPT_fno_PIE)) {
4839    if (A->getOption().matches(options::OPT_fpie) ||
4840        A->getOption().matches(options::OPT_fPIE))
4841      CmdArgs.push_back("-pie");
4842    else
4843      CmdArgs.push_back("-no_pie");
4844  }
4845
4846  Args.AddLastArg(CmdArgs, options::OPT_prebind);
4847  Args.AddLastArg(CmdArgs, options::OPT_noprebind);
4848  Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
4849  Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
4850  Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
4851  Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
4852  Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
4853  Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
4854  Args.AddAllArgs(CmdArgs, options::OPT_segprot);
4855  Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
4856  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
4857  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
4858  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
4859  Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
4860  Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
4861  Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
4862
4863  // Give --sysroot= preference, over the Apple specific behavior to also use
4864  // --isysroot as the syslibroot.
4865  StringRef sysroot = C.getSysRoot();
4866  if (sysroot != "") {
4867    CmdArgs.push_back("-syslibroot");
4868    CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
4869  } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4870    CmdArgs.push_back("-syslibroot");
4871    CmdArgs.push_back(A->getValue());
4872  }
4873
4874  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
4875  Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
4876  Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
4877  Args.AddAllArgs(CmdArgs, options::OPT_undefined);
4878  Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
4879  Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
4880  Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
4881  Args.AddAllArgs(CmdArgs, options::OPT_y);
4882  Args.AddLastArg(CmdArgs, options::OPT_w);
4883  Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
4884  Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
4885  Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
4886  Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
4887  Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
4888  Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
4889  Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
4890  Args.AddLastArg(CmdArgs, options::OPT_whyload);
4891  Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
4892  Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
4893  Args.AddLastArg(CmdArgs, options::OPT_dylinker);
4894  Args.AddLastArg(CmdArgs, options::OPT_Mach);
4895}
4896
4897void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
4898                                const InputInfo &Output,
4899                                const InputInfoList &Inputs,
4900                                const ArgList &Args,
4901                                const char *LinkingOutput) const {
4902  assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
4903
4904  // The logic here is derived from gcc's behavior; most of which
4905  // comes from specs (starting with link_command). Consult gcc for
4906  // more information.
4907  ArgStringList CmdArgs;
4908
4909  /// Hack(tm) to ignore linking errors when we are doing ARC migration.
4910  if (Args.hasArg(options::OPT_ccc_arcmt_check,
4911                  options::OPT_ccc_arcmt_migrate)) {
4912    for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I)
4913      (*I)->claim();
4914    const char *Exec =
4915      Args.MakeArgString(getToolChain().GetProgramPath("touch"));
4916    CmdArgs.push_back(Output.getFilename());
4917    C.addCommand(new Command(JA, *this, Exec, CmdArgs));
4918    return;
4919  }
4920
4921  // I'm not sure why this particular decomposition exists in gcc, but
4922  // we follow suite for ease of comparison.
4923  AddLinkArgs(C, Args, CmdArgs, Inputs);
4924
4925  Args.AddAllArgs(CmdArgs, options::OPT_d_Flag);
4926  Args.AddAllArgs(CmdArgs, options::OPT_s);
4927  Args.AddAllArgs(CmdArgs, options::OPT_t);
4928  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
4929  Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
4930  Args.AddLastArg(CmdArgs, options::OPT_e);
4931  Args.AddAllArgs(CmdArgs, options::OPT_r);
4932
4933  // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
4934  // members of static archive libraries which implement Objective-C classes or
4935  // categories.
4936  if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
4937    CmdArgs.push_back("-ObjC");
4938
4939  CmdArgs.push_back("-o");
4940  CmdArgs.push_back(Output.getFilename());
4941
4942  if (!Args.hasArg(options::OPT_nostdlib) &&
4943      !Args.hasArg(options::OPT_nostartfiles)) {
4944    // Derived from startfile spec.
4945    if (Args.hasArg(options::OPT_dynamiclib)) {
4946      // Derived from darwin_dylib1 spec.
4947      if (getDarwinToolChain().isTargetIOSSimulator()) {
4948        // The simulator doesn't have a versioned crt1 file.
4949        CmdArgs.push_back("-ldylib1.o");
4950      } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4951        if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4952          CmdArgs.push_back("-ldylib1.o");
4953      } else {
4954        if (getDarwinToolChain().isMacosxVersionLT(10, 5))
4955          CmdArgs.push_back("-ldylib1.o");
4956        else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4957          CmdArgs.push_back("-ldylib1.10.5.o");
4958      }
4959    } else {
4960      if (Args.hasArg(options::OPT_bundle)) {
4961        if (!Args.hasArg(options::OPT_static)) {
4962          // Derived from darwin_bundle1 spec.
4963          if (getDarwinToolChain().isTargetIOSSimulator()) {
4964            // The simulator doesn't have a versioned crt1 file.
4965            CmdArgs.push_back("-lbundle1.o");
4966          } else if (getDarwinToolChain().isTargetIPhoneOS()) {
4967            if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
4968              CmdArgs.push_back("-lbundle1.o");
4969          } else {
4970            if (getDarwinToolChain().isMacosxVersionLT(10, 6))
4971              CmdArgs.push_back("-lbundle1.o");
4972          }
4973        }
4974      } else {
4975        if (Args.hasArg(options::OPT_pg) &&
4976            getToolChain().SupportsProfiling()) {
4977          if (Args.hasArg(options::OPT_static) ||
4978              Args.hasArg(options::OPT_object) ||
4979              Args.hasArg(options::OPT_preload)) {
4980            CmdArgs.push_back("-lgcrt0.o");
4981          } else {
4982            CmdArgs.push_back("-lgcrt1.o");
4983
4984            // darwin_crt2 spec is empty.
4985          }
4986          // By default on OS X 10.8 and later, we don't link with a crt1.o
4987          // file and the linker knows to use _main as the entry point.  But,
4988          // when compiling with -pg, we need to link with the gcrt1.o file,
4989          // so pass the -no_new_main option to tell the linker to use the
4990          // "start" symbol as the entry point.
4991          if (getDarwinToolChain().isTargetMacOS() &&
4992              !getDarwinToolChain().isMacosxVersionLT(10, 8))
4993            CmdArgs.push_back("-no_new_main");
4994        } else {
4995          if (Args.hasArg(options::OPT_static) ||
4996              Args.hasArg(options::OPT_object) ||
4997              Args.hasArg(options::OPT_preload)) {
4998            CmdArgs.push_back("-lcrt0.o");
4999          } else {
5000            // Derived from darwin_crt1 spec.
5001            if (getDarwinToolChain().isTargetIOSSimulator()) {
5002              // The simulator doesn't have a versioned crt1 file.
5003              CmdArgs.push_back("-lcrt1.o");
5004            } else if (getDarwinToolChain().isTargetIPhoneOS()) {
5005              if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1))
5006                CmdArgs.push_back("-lcrt1.o");
5007              else if (getDarwinToolChain().isIPhoneOSVersionLT(6, 0))
5008                CmdArgs.push_back("-lcrt1.3.1.o");
5009            } else {
5010              if (getDarwinToolChain().isMacosxVersionLT(10, 5))
5011                CmdArgs.push_back("-lcrt1.o");
5012              else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
5013                CmdArgs.push_back("-lcrt1.10.5.o");
5014              else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
5015                CmdArgs.push_back("-lcrt1.10.6.o");
5016
5017              // darwin_crt2 spec is empty.
5018            }
5019          }
5020        }
5021      }
5022    }
5023
5024    if (!getDarwinToolChain().isTargetIPhoneOS() &&
5025        Args.hasArg(options::OPT_shared_libgcc) &&
5026        getDarwinToolChain().isMacosxVersionLT(10, 5)) {
5027      const char *Str =
5028        Args.MakeArgString(getToolChain().GetFilePath("crt3.o"));
5029      CmdArgs.push_back(Str);
5030    }
5031  }
5032
5033  Args.AddAllArgs(CmdArgs, options::OPT_L);
5034
5035  if (Args.hasArg(options::OPT_fopenmp))
5036    // This is more complicated in gcc...
5037    CmdArgs.push_back("-lgomp");
5038
5039  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5040
5041  if (isObjCRuntimeLinked(Args) &&
5042      !Args.hasArg(options::OPT_nostdlib) &&
5043      !Args.hasArg(options::OPT_nodefaultlibs)) {
5044    // Avoid linking compatibility stubs on i386 mac.
5045    if (!getDarwinToolChain().isTargetMacOS() ||
5046        getDarwinToolChain().getArch() != llvm::Triple::x86) {
5047      // If we don't have ARC or subscripting runtime support, link in the
5048      // runtime stubs.  We have to do this *before* adding any of the normal
5049      // linker inputs so that its initializer gets run first.
5050      ObjCRuntime runtime =
5051        getDarwinToolChain().getDefaultObjCRuntime(/*nonfragile*/ true);
5052      // We use arclite library for both ARC and subscripting support.
5053      if ((!runtime.hasNativeARC() && isObjCAutoRefCount(Args)) ||
5054          !runtime.hasSubscripting())
5055        getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
5056    }
5057    CmdArgs.push_back("-framework");
5058    CmdArgs.push_back("Foundation");
5059    // Link libobj.
5060    CmdArgs.push_back("-lobjc");
5061  }
5062
5063  if (LinkingOutput) {
5064    CmdArgs.push_back("-arch_multiple");
5065    CmdArgs.push_back("-final_output");
5066    CmdArgs.push_back(LinkingOutput);
5067  }
5068
5069  if (Args.hasArg(options::OPT_fnested_functions))
5070    CmdArgs.push_back("-allow_stack_execute");
5071
5072  if (!Args.hasArg(options::OPT_nostdlib) &&
5073      !Args.hasArg(options::OPT_nodefaultlibs)) {
5074    if (getToolChain().getDriver().CCCIsCXX())
5075      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5076
5077    // link_ssp spec is empty.
5078
5079    // Let the tool chain choose which runtime library to link.
5080    getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
5081  }
5082
5083  if (!Args.hasArg(options::OPT_nostdlib) &&
5084      !Args.hasArg(options::OPT_nostartfiles)) {
5085    // endfile_spec is empty.
5086  }
5087
5088  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5089  Args.AddAllArgs(CmdArgs, options::OPT_F);
5090
5091  const char *Exec =
5092    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5093  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5094}
5095
5096void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
5097                                const InputInfo &Output,
5098                                const InputInfoList &Inputs,
5099                                const ArgList &Args,
5100                                const char *LinkingOutput) const {
5101  ArgStringList CmdArgs;
5102
5103  CmdArgs.push_back("-create");
5104  assert(Output.isFilename() && "Unexpected lipo output.");
5105
5106  CmdArgs.push_back("-output");
5107  CmdArgs.push_back(Output.getFilename());
5108
5109  for (InputInfoList::const_iterator
5110         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5111    const InputInfo &II = *it;
5112    assert(II.isFilename() && "Unexpected lipo input.");
5113    CmdArgs.push_back(II.getFilename());
5114  }
5115  const char *Exec =
5116    Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
5117  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5118}
5119
5120void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
5121                                    const InputInfo &Output,
5122                                    const InputInfoList &Inputs,
5123                                    const ArgList &Args,
5124                                    const char *LinkingOutput) const {
5125  ArgStringList CmdArgs;
5126
5127  CmdArgs.push_back("-o");
5128  CmdArgs.push_back(Output.getFilename());
5129
5130  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5131  const InputInfo &Input = Inputs[0];
5132  assert(Input.isFilename() && "Unexpected dsymutil input.");
5133  CmdArgs.push_back(Input.getFilename());
5134
5135  const char *Exec =
5136    Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
5137  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5138}
5139
5140void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
5141                                       const InputInfo &Output,
5142                                       const InputInfoList &Inputs,
5143                                       const ArgList &Args,
5144                                       const char *LinkingOutput) const {
5145  ArgStringList CmdArgs;
5146  CmdArgs.push_back("--verify");
5147  CmdArgs.push_back("--debug-info");
5148  CmdArgs.push_back("--eh-frame");
5149  CmdArgs.push_back("--quiet");
5150
5151  assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
5152  const InputInfo &Input = Inputs[0];
5153  assert(Input.isFilename() && "Unexpected verify input");
5154
5155  // Grabbing the output of the earlier dsymutil run.
5156  CmdArgs.push_back(Input.getFilename());
5157
5158  const char *Exec =
5159    Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
5160  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5161}
5162
5163void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5164                                      const InputInfo &Output,
5165                                      const InputInfoList &Inputs,
5166                                      const ArgList &Args,
5167                                      const char *LinkingOutput) const {
5168  ArgStringList CmdArgs;
5169
5170  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5171                       options::OPT_Xassembler);
5172
5173  CmdArgs.push_back("-o");
5174  CmdArgs.push_back(Output.getFilename());
5175
5176  for (InputInfoList::const_iterator
5177         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5178    const InputInfo &II = *it;
5179    CmdArgs.push_back(II.getFilename());
5180  }
5181
5182  const char *Exec =
5183    Args.MakeArgString(getToolChain().GetProgramPath("as"));
5184  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5185}
5186
5187
5188void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
5189                                  const InputInfo &Output,
5190                                  const InputInfoList &Inputs,
5191                                  const ArgList &Args,
5192                                  const char *LinkingOutput) const {
5193  // FIXME: Find a real GCC, don't hard-code versions here
5194  std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/";
5195  const llvm::Triple &T = getToolChain().getTriple();
5196  std::string LibPath = "/usr/lib/";
5197  llvm::Triple::ArchType Arch = T.getArch();
5198  switch (Arch) {
5199  case llvm::Triple::x86:
5200    GCCLibPath +=
5201        ("i386-" + T.getVendorName() + "-" + T.getOSName()).str() + "/4.5.2/";
5202    break;
5203  case llvm::Triple::x86_64:
5204    GCCLibPath += ("i386-" + T.getVendorName() + "-" + T.getOSName()).str();
5205    GCCLibPath += "/4.5.2/amd64/";
5206    LibPath += "amd64/";
5207    break;
5208  default:
5209    llvm_unreachable("Unsupported architecture");
5210  }
5211
5212  ArgStringList CmdArgs;
5213
5214  // Demangle C++ names in errors
5215  CmdArgs.push_back("-C");
5216
5217  if ((!Args.hasArg(options::OPT_nostdlib)) &&
5218      (!Args.hasArg(options::OPT_shared))) {
5219    CmdArgs.push_back("-e");
5220    CmdArgs.push_back("_start");
5221  }
5222
5223  if (Args.hasArg(options::OPT_static)) {
5224    CmdArgs.push_back("-Bstatic");
5225    CmdArgs.push_back("-dn");
5226  } else {
5227    CmdArgs.push_back("-Bdynamic");
5228    if (Args.hasArg(options::OPT_shared)) {
5229      CmdArgs.push_back("-shared");
5230    } else {
5231      CmdArgs.push_back("--dynamic-linker");
5232      CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
5233    }
5234  }
5235
5236  if (Output.isFilename()) {
5237    CmdArgs.push_back("-o");
5238    CmdArgs.push_back(Output.getFilename());
5239  } else {
5240    assert(Output.isNothing() && "Invalid output.");
5241  }
5242
5243  if (!Args.hasArg(options::OPT_nostdlib) &&
5244      !Args.hasArg(options::OPT_nostartfiles)) {
5245    if (!Args.hasArg(options::OPT_shared)) {
5246      CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
5247      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
5248      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
5249      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
5250    } else {
5251      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
5252      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
5253      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
5254    }
5255    if (getToolChain().getDriver().CCCIsCXX())
5256      CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
5257  }
5258
5259  CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
5260
5261  Args.AddAllArgs(CmdArgs, options::OPT_L);
5262  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5263  Args.AddAllArgs(CmdArgs, options::OPT_e);
5264  Args.AddAllArgs(CmdArgs, options::OPT_r);
5265
5266  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5267
5268  if (!Args.hasArg(options::OPT_nostdlib) &&
5269      !Args.hasArg(options::OPT_nodefaultlibs)) {
5270    if (getToolChain().getDriver().CCCIsCXX())
5271      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5272    CmdArgs.push_back("-lgcc_s");
5273    if (!Args.hasArg(options::OPT_shared)) {
5274      CmdArgs.push_back("-lgcc");
5275      CmdArgs.push_back("-lc");
5276      CmdArgs.push_back("-lm");
5277    }
5278  }
5279
5280  if (!Args.hasArg(options::OPT_nostdlib) &&
5281      !Args.hasArg(options::OPT_nostartfiles)) {
5282    CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
5283  }
5284  CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
5285
5286  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5287
5288  const char *Exec =
5289    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5290  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5291}
5292
5293void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5294                                      const InputInfo &Output,
5295                                      const InputInfoList &Inputs,
5296                                      const ArgList &Args,
5297                                      const char *LinkingOutput) const {
5298  ArgStringList CmdArgs;
5299
5300  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5301                       options::OPT_Xassembler);
5302
5303  CmdArgs.push_back("-o");
5304  CmdArgs.push_back(Output.getFilename());
5305
5306  for (InputInfoList::const_iterator
5307         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5308    const InputInfo &II = *it;
5309    CmdArgs.push_back(II.getFilename());
5310  }
5311
5312  const char *Exec =
5313    Args.MakeArgString(getToolChain().GetProgramPath("gas"));
5314  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5315}
5316
5317void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA,
5318                                  const InputInfo &Output,
5319                                  const InputInfoList &Inputs,
5320                                  const ArgList &Args,
5321                                  const char *LinkingOutput) const {
5322  ArgStringList CmdArgs;
5323
5324  if ((!Args.hasArg(options::OPT_nostdlib)) &&
5325      (!Args.hasArg(options::OPT_shared))) {
5326    CmdArgs.push_back("-e");
5327    CmdArgs.push_back("_start");
5328  }
5329
5330  if (Args.hasArg(options::OPT_static)) {
5331    CmdArgs.push_back("-Bstatic");
5332    CmdArgs.push_back("-dn");
5333  } else {
5334//    CmdArgs.push_back("--eh-frame-hdr");
5335    CmdArgs.push_back("-Bdynamic");
5336    if (Args.hasArg(options::OPT_shared)) {
5337      CmdArgs.push_back("-shared");
5338    } else {
5339      CmdArgs.push_back("--dynamic-linker");
5340      CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1
5341    }
5342  }
5343
5344  if (Output.isFilename()) {
5345    CmdArgs.push_back("-o");
5346    CmdArgs.push_back(Output.getFilename());
5347  } else {
5348    assert(Output.isNothing() && "Invalid output.");
5349  }
5350
5351  if (!Args.hasArg(options::OPT_nostdlib) &&
5352      !Args.hasArg(options::OPT_nostartfiles)) {
5353    if (!Args.hasArg(options::OPT_shared)) {
5354      CmdArgs.push_back(Args.MakeArgString(
5355                                getToolChain().GetFilePath("crt1.o")));
5356      CmdArgs.push_back(Args.MakeArgString(
5357                                getToolChain().GetFilePath("crti.o")));
5358      CmdArgs.push_back(Args.MakeArgString(
5359                                getToolChain().GetFilePath("crtbegin.o")));
5360    } else {
5361      CmdArgs.push_back(Args.MakeArgString(
5362                                getToolChain().GetFilePath("crti.o")));
5363    }
5364    CmdArgs.push_back(Args.MakeArgString(
5365                                getToolChain().GetFilePath("crtn.o")));
5366  }
5367
5368  CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/"
5369                                       + getToolChain().getTripleString()
5370                                       + "/4.2.4"));
5371
5372  Args.AddAllArgs(CmdArgs, options::OPT_L);
5373  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5374  Args.AddAllArgs(CmdArgs, options::OPT_e);
5375
5376  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5377
5378  if (!Args.hasArg(options::OPT_nostdlib) &&
5379      !Args.hasArg(options::OPT_nodefaultlibs)) {
5380    // FIXME: For some reason GCC passes -lgcc before adding
5381    // the default system libraries. Just mimic this for now.
5382    CmdArgs.push_back("-lgcc");
5383
5384    if (Args.hasArg(options::OPT_pthread))
5385      CmdArgs.push_back("-pthread");
5386    if (!Args.hasArg(options::OPT_shared))
5387      CmdArgs.push_back("-lc");
5388    CmdArgs.push_back("-lgcc");
5389  }
5390
5391  if (!Args.hasArg(options::OPT_nostdlib) &&
5392      !Args.hasArg(options::OPT_nostartfiles)) {
5393    if (!Args.hasArg(options::OPT_shared))
5394      CmdArgs.push_back(Args.MakeArgString(
5395                                getToolChain().GetFilePath("crtend.o")));
5396  }
5397
5398  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
5399
5400  const char *Exec =
5401    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5402  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5403}
5404
5405void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5406                                     const InputInfo &Output,
5407                                     const InputInfoList &Inputs,
5408                                     const ArgList &Args,
5409                                     const char *LinkingOutput) const {
5410  ArgStringList CmdArgs;
5411
5412  // When building 32-bit code on OpenBSD/amd64, we have to explicitly
5413  // instruct as in the base system to assemble 32-bit code.
5414  if (getToolChain().getArch() == llvm::Triple::x86)
5415    CmdArgs.push_back("--32");
5416  else if (getToolChain().getArch() == llvm::Triple::ppc) {
5417    CmdArgs.push_back("-mppc");
5418    CmdArgs.push_back("-many");
5419  } else if (getToolChain().getArch() == llvm::Triple::mips64 ||
5420             getToolChain().getArch() == llvm::Triple::mips64el) {
5421    StringRef CPUName;
5422    StringRef ABIName;
5423    getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
5424
5425    CmdArgs.push_back("-mabi");
5426    CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
5427
5428    if (getToolChain().getArch() == llvm::Triple::mips64)
5429      CmdArgs.push_back("-EB");
5430    else
5431      CmdArgs.push_back("-EL");
5432
5433    Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5434                                      options::OPT_fpic, options::OPT_fno_pic,
5435                                      options::OPT_fPIE, options::OPT_fno_PIE,
5436                                      options::OPT_fpie, options::OPT_fno_pie);
5437    if (LastPICArg &&
5438        (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5439         LastPICArg->getOption().matches(options::OPT_fpic) ||
5440         LastPICArg->getOption().matches(options::OPT_fPIE) ||
5441         LastPICArg->getOption().matches(options::OPT_fpie))) {
5442      CmdArgs.push_back("-KPIC");
5443    }
5444  }
5445
5446  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5447                       options::OPT_Xassembler);
5448
5449  CmdArgs.push_back("-o");
5450  CmdArgs.push_back(Output.getFilename());
5451
5452  for (InputInfoList::const_iterator
5453         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5454    const InputInfo &II = *it;
5455    CmdArgs.push_back(II.getFilename());
5456  }
5457
5458  const char *Exec =
5459    Args.MakeArgString(getToolChain().GetProgramPath("as"));
5460  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5461}
5462
5463void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5464                                 const InputInfo &Output,
5465                                 const InputInfoList &Inputs,
5466                                 const ArgList &Args,
5467                                 const char *LinkingOutput) const {
5468  const Driver &D = getToolChain().getDriver();
5469  ArgStringList CmdArgs;
5470
5471  // Silence warning for "clang -g foo.o -o foo"
5472  Args.ClaimAllArgs(options::OPT_g_Group);
5473  // and "clang -emit-llvm foo.o -o foo"
5474  Args.ClaimAllArgs(options::OPT_emit_llvm);
5475  // and for "clang -w foo.o -o foo". Other warning options are already
5476  // handled somewhere else.
5477  Args.ClaimAllArgs(options::OPT_w);
5478
5479  if (getToolChain().getArch() == llvm::Triple::mips64)
5480    CmdArgs.push_back("-EB");
5481  else if (getToolChain().getArch() == llvm::Triple::mips64el)
5482    CmdArgs.push_back("-EL");
5483
5484  if ((!Args.hasArg(options::OPT_nostdlib)) &&
5485      (!Args.hasArg(options::OPT_shared))) {
5486    CmdArgs.push_back("-e");
5487    CmdArgs.push_back("__start");
5488  }
5489
5490  if (Args.hasArg(options::OPT_static)) {
5491    CmdArgs.push_back("-Bstatic");
5492  } else {
5493    if (Args.hasArg(options::OPT_rdynamic))
5494      CmdArgs.push_back("-export-dynamic");
5495    CmdArgs.push_back("--eh-frame-hdr");
5496    CmdArgs.push_back("-Bdynamic");
5497    if (Args.hasArg(options::OPT_shared)) {
5498      CmdArgs.push_back("-shared");
5499    } else {
5500      CmdArgs.push_back("-dynamic-linker");
5501      CmdArgs.push_back("/usr/libexec/ld.so");
5502    }
5503  }
5504
5505  if (Args.hasArg(options::OPT_nopie))
5506    CmdArgs.push_back("-nopie");
5507
5508  if (Output.isFilename()) {
5509    CmdArgs.push_back("-o");
5510    CmdArgs.push_back(Output.getFilename());
5511  } else {
5512    assert(Output.isNothing() && "Invalid output.");
5513  }
5514
5515  if (!Args.hasArg(options::OPT_nostdlib) &&
5516      !Args.hasArg(options::OPT_nostartfiles)) {
5517    if (!Args.hasArg(options::OPT_shared)) {
5518      if (Args.hasArg(options::OPT_pg))
5519        CmdArgs.push_back(Args.MakeArgString(
5520                                getToolChain().GetFilePath("gcrt0.o")));
5521      else
5522        CmdArgs.push_back(Args.MakeArgString(
5523                                getToolChain().GetFilePath("crt0.o")));
5524      CmdArgs.push_back(Args.MakeArgString(
5525                              getToolChain().GetFilePath("crtbegin.o")));
5526    } else {
5527      CmdArgs.push_back(Args.MakeArgString(
5528                              getToolChain().GetFilePath("crtbeginS.o")));
5529    }
5530  }
5531
5532  std::string Triple = getToolChain().getTripleString();
5533  if (Triple.substr(0, 6) == "x86_64")
5534    Triple.replace(0, 6, "amd64");
5535  CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple +
5536                                       "/4.2.1"));
5537
5538  Args.AddAllArgs(CmdArgs, options::OPT_L);
5539  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5540  Args.AddAllArgs(CmdArgs, options::OPT_e);
5541  Args.AddAllArgs(CmdArgs, options::OPT_s);
5542  Args.AddAllArgs(CmdArgs, options::OPT_t);
5543  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5544  Args.AddAllArgs(CmdArgs, options::OPT_r);
5545
5546  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5547
5548  if (!Args.hasArg(options::OPT_nostdlib) &&
5549      !Args.hasArg(options::OPT_nodefaultlibs)) {
5550    if (D.CCCIsCXX()) {
5551      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5552      if (Args.hasArg(options::OPT_pg))
5553        CmdArgs.push_back("-lm_p");
5554      else
5555        CmdArgs.push_back("-lm");
5556    }
5557
5558    // FIXME: For some reason GCC passes -lgcc before adding
5559    // the default system libraries. Just mimic this for now.
5560    CmdArgs.push_back("-lgcc");
5561
5562    if (Args.hasArg(options::OPT_pthread)) {
5563      if (!Args.hasArg(options::OPT_shared) &&
5564          Args.hasArg(options::OPT_pg))
5565         CmdArgs.push_back("-lpthread_p");
5566      else
5567         CmdArgs.push_back("-lpthread");
5568    }
5569
5570    if (!Args.hasArg(options::OPT_shared)) {
5571      if (Args.hasArg(options::OPT_pg))
5572         CmdArgs.push_back("-lc_p");
5573      else
5574         CmdArgs.push_back("-lc");
5575    }
5576
5577    CmdArgs.push_back("-lgcc");
5578  }
5579
5580  if (!Args.hasArg(options::OPT_nostdlib) &&
5581      !Args.hasArg(options::OPT_nostartfiles)) {
5582    if (!Args.hasArg(options::OPT_shared))
5583      CmdArgs.push_back(Args.MakeArgString(
5584                              getToolChain().GetFilePath("crtend.o")));
5585    else
5586      CmdArgs.push_back(Args.MakeArgString(
5587                              getToolChain().GetFilePath("crtendS.o")));
5588  }
5589
5590  const char *Exec =
5591    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5592  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5593}
5594
5595void bitrig::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5596                                    const InputInfo &Output,
5597                                    const InputInfoList &Inputs,
5598                                    const ArgList &Args,
5599                                    const char *LinkingOutput) const {
5600  ArgStringList CmdArgs;
5601
5602  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5603                       options::OPT_Xassembler);
5604
5605  CmdArgs.push_back("-o");
5606  CmdArgs.push_back(Output.getFilename());
5607
5608  for (InputInfoList::const_iterator
5609         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5610    const InputInfo &II = *it;
5611    CmdArgs.push_back(II.getFilename());
5612  }
5613
5614  const char *Exec =
5615    Args.MakeArgString(getToolChain().GetProgramPath("as"));
5616  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5617}
5618
5619void bitrig::Link::ConstructJob(Compilation &C, const JobAction &JA,
5620                                const InputInfo &Output,
5621                                const InputInfoList &Inputs,
5622                                const ArgList &Args,
5623                                const char *LinkingOutput) const {
5624  const Driver &D = getToolChain().getDriver();
5625  ArgStringList CmdArgs;
5626
5627  if ((!Args.hasArg(options::OPT_nostdlib)) &&
5628      (!Args.hasArg(options::OPT_shared))) {
5629    CmdArgs.push_back("-e");
5630    CmdArgs.push_back("__start");
5631  }
5632
5633  if (Args.hasArg(options::OPT_static)) {
5634    CmdArgs.push_back("-Bstatic");
5635  } else {
5636    if (Args.hasArg(options::OPT_rdynamic))
5637      CmdArgs.push_back("-export-dynamic");
5638    CmdArgs.push_back("--eh-frame-hdr");
5639    CmdArgs.push_back("-Bdynamic");
5640    if (Args.hasArg(options::OPT_shared)) {
5641      CmdArgs.push_back("-shared");
5642    } else {
5643      CmdArgs.push_back("-dynamic-linker");
5644      CmdArgs.push_back("/usr/libexec/ld.so");
5645    }
5646  }
5647
5648  if (Output.isFilename()) {
5649    CmdArgs.push_back("-o");
5650    CmdArgs.push_back(Output.getFilename());
5651  } else {
5652    assert(Output.isNothing() && "Invalid output.");
5653  }
5654
5655  if (!Args.hasArg(options::OPT_nostdlib) &&
5656      !Args.hasArg(options::OPT_nostartfiles)) {
5657    if (!Args.hasArg(options::OPT_shared)) {
5658      if (Args.hasArg(options::OPT_pg))
5659        CmdArgs.push_back(Args.MakeArgString(
5660                                getToolChain().GetFilePath("gcrt0.o")));
5661      else
5662        CmdArgs.push_back(Args.MakeArgString(
5663                                getToolChain().GetFilePath("crt0.o")));
5664      CmdArgs.push_back(Args.MakeArgString(
5665                              getToolChain().GetFilePath("crtbegin.o")));
5666    } else {
5667      CmdArgs.push_back(Args.MakeArgString(
5668                              getToolChain().GetFilePath("crtbeginS.o")));
5669    }
5670  }
5671
5672  Args.AddAllArgs(CmdArgs, options::OPT_L);
5673  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5674  Args.AddAllArgs(CmdArgs, options::OPT_e);
5675
5676  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
5677
5678  if (!Args.hasArg(options::OPT_nostdlib) &&
5679      !Args.hasArg(options::OPT_nodefaultlibs)) {
5680    if (D.CCCIsCXX()) {
5681      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
5682      if (Args.hasArg(options::OPT_pg))
5683        CmdArgs.push_back("-lm_p");
5684      else
5685        CmdArgs.push_back("-lm");
5686    }
5687
5688    if (Args.hasArg(options::OPT_pthread)) {
5689      if (!Args.hasArg(options::OPT_shared) &&
5690          Args.hasArg(options::OPT_pg))
5691        CmdArgs.push_back("-lpthread_p");
5692      else
5693        CmdArgs.push_back("-lpthread");
5694    }
5695
5696    if (!Args.hasArg(options::OPT_shared)) {
5697      if (Args.hasArg(options::OPT_pg))
5698        CmdArgs.push_back("-lc_p");
5699      else
5700        CmdArgs.push_back("-lc");
5701    }
5702
5703    StringRef MyArch;
5704    switch (getToolChain().getTriple().getArch()) {
5705    case llvm::Triple::arm:
5706      MyArch = "arm";
5707      break;
5708    case llvm::Triple::x86:
5709      MyArch = "i386";
5710      break;
5711    case llvm::Triple::x86_64:
5712      MyArch = "amd64";
5713      break;
5714    default:
5715      llvm_unreachable("Unsupported architecture");
5716    }
5717    CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
5718  }
5719
5720  if (!Args.hasArg(options::OPT_nostdlib) &&
5721      !Args.hasArg(options::OPT_nostartfiles)) {
5722    if (!Args.hasArg(options::OPT_shared))
5723      CmdArgs.push_back(Args.MakeArgString(
5724                              getToolChain().GetFilePath("crtend.o")));
5725    else
5726      CmdArgs.push_back(Args.MakeArgString(
5727                              getToolChain().GetFilePath("crtendS.o")));
5728  }
5729
5730  const char *Exec =
5731    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
5732  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5733}
5734
5735void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
5736                                     const InputInfo &Output,
5737                                     const InputInfoList &Inputs,
5738                                     const ArgList &Args,
5739                                     const char *LinkingOutput) const {
5740  ArgStringList CmdArgs;
5741
5742  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5743  // instruct as in the base system to assemble 32-bit code.
5744  if (getToolChain().getArch() == llvm::Triple::x86)
5745    CmdArgs.push_back("--32");
5746  else if (getToolChain().getArch() == llvm::Triple::ppc)
5747    CmdArgs.push_back("-a32");
5748  else if (getToolChain().getArch() == llvm::Triple::mips ||
5749           getToolChain().getArch() == llvm::Triple::mipsel ||
5750           getToolChain().getArch() == llvm::Triple::mips64 ||
5751           getToolChain().getArch() == llvm::Triple::mips64el) {
5752    StringRef CPUName;
5753    StringRef ABIName;
5754    getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
5755
5756    CmdArgs.push_back("-march");
5757    CmdArgs.push_back(CPUName.data());
5758
5759    CmdArgs.push_back("-mabi");
5760    CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
5761
5762    if (getToolChain().getArch() == llvm::Triple::mips ||
5763        getToolChain().getArch() == llvm::Triple::mips64)
5764      CmdArgs.push_back("-EB");
5765    else
5766      CmdArgs.push_back("-EL");
5767
5768    Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5769                                      options::OPT_fpic, options::OPT_fno_pic,
5770                                      options::OPT_fPIE, options::OPT_fno_PIE,
5771                                      options::OPT_fpie, options::OPT_fno_pie);
5772    if (LastPICArg &&
5773        (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5774         LastPICArg->getOption().matches(options::OPT_fpic) ||
5775         LastPICArg->getOption().matches(options::OPT_fPIE) ||
5776         LastPICArg->getOption().matches(options::OPT_fpie))) {
5777      CmdArgs.push_back("-KPIC");
5778    }
5779  } else if (getToolChain().getArch() == llvm::Triple::arm ||
5780             getToolChain().getArch() == llvm::Triple::thumb) {
5781    CmdArgs.push_back("-mfpu=softvfp");
5782    switch(getToolChain().getTriple().getEnvironment()) {
5783    case llvm::Triple::GNUEABI:
5784    case llvm::Triple::EABI:
5785      CmdArgs.push_back("-meabi=5");
5786      break;
5787
5788    default:
5789      CmdArgs.push_back("-matpcs");
5790    }
5791  } else if (getToolChain().getArch() == llvm::Triple::sparc ||
5792             getToolChain().getArch() == llvm::Triple::sparcv9) {
5793    if (getToolChain().getArch() == llvm::Triple::sparc)
5794      CmdArgs.push_back("-Av8plusa");
5795    else
5796      CmdArgs.push_back("-Av9a");
5797
5798    Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
5799                                      options::OPT_fpic, options::OPT_fno_pic,
5800                                      options::OPT_fPIE, options::OPT_fno_PIE,
5801                                      options::OPT_fpie, options::OPT_fno_pie);
5802    if (LastPICArg &&
5803        (LastPICArg->getOption().matches(options::OPT_fPIC) ||
5804         LastPICArg->getOption().matches(options::OPT_fpic) ||
5805         LastPICArg->getOption().matches(options::OPT_fPIE) ||
5806         LastPICArg->getOption().matches(options::OPT_fpie))) {
5807      CmdArgs.push_back("-KPIC");
5808    }
5809  }
5810
5811  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
5812                       options::OPT_Xassembler);
5813
5814  CmdArgs.push_back("-o");
5815  CmdArgs.push_back(Output.getFilename());
5816
5817  for (InputInfoList::const_iterator
5818         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
5819    const InputInfo &II = *it;
5820    CmdArgs.push_back(II.getFilename());
5821  }
5822
5823  const char *Exec =
5824    Args.MakeArgString(getToolChain().GetProgramPath("as"));
5825  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
5826}
5827
5828void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
5829                                 const InputInfo &Output,
5830                                 const InputInfoList &Inputs,
5831                                 const ArgList &Args,
5832                                 const char *LinkingOutput) const {
5833  const toolchains::FreeBSD& ToolChain =
5834    static_cast<const toolchains::FreeBSD&>(getToolChain());
5835  const Driver &D = ToolChain.getDriver();
5836  ArgStringList CmdArgs;
5837
5838  // Silence warning for "clang -g foo.o -o foo"
5839  Args.ClaimAllArgs(options::OPT_g_Group);
5840  // and "clang -emit-llvm foo.o -o foo"
5841  Args.ClaimAllArgs(options::OPT_emit_llvm);
5842  // and for "clang -w foo.o -o foo". Other warning options are already
5843  // handled somewhere else.
5844  Args.ClaimAllArgs(options::OPT_w);
5845
5846  if (!D.SysRoot.empty())
5847    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
5848
5849  if (Args.hasArg(options::OPT_pie))
5850    CmdArgs.push_back("-pie");
5851
5852  if (Args.hasArg(options::OPT_static)) {
5853    CmdArgs.push_back("-Bstatic");
5854  } else {
5855    if (Args.hasArg(options::OPT_rdynamic))
5856      CmdArgs.push_back("-export-dynamic");
5857    CmdArgs.push_back("--eh-frame-hdr");
5858    if (Args.hasArg(options::OPT_shared)) {
5859      CmdArgs.push_back("-Bshareable");
5860    } else {
5861      CmdArgs.push_back("-dynamic-linker");
5862      CmdArgs.push_back("/libexec/ld-elf.so.1");
5863    }
5864    if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
5865      llvm::Triple::ArchType Arch = ToolChain.getArch();
5866      if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
5867          Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5868        CmdArgs.push_back("--hash-style=both");
5869      }
5870    }
5871    CmdArgs.push_back("--enable-new-dtags");
5872  }
5873
5874  // When building 32-bit code on FreeBSD/amd64, we have to explicitly
5875  // instruct ld in the base system to link 32-bit code.
5876  if (ToolChain.getArch() == llvm::Triple::x86) {
5877    CmdArgs.push_back("-m");
5878    CmdArgs.push_back("elf_i386_fbsd");
5879  }
5880
5881  if (ToolChain.getArch() == llvm::Triple::ppc) {
5882    CmdArgs.push_back("-m");
5883    CmdArgs.push_back("elf32ppc_fbsd");
5884  }
5885
5886  if (Output.isFilename()) {
5887    CmdArgs.push_back("-o");
5888    CmdArgs.push_back(Output.getFilename());
5889  } else {
5890    assert(Output.isNothing() && "Invalid output.");
5891  }
5892
5893  if (!Args.hasArg(options::OPT_nostdlib) &&
5894      !Args.hasArg(options::OPT_nostartfiles)) {
5895    const char *crt1 = NULL;
5896    if (!Args.hasArg(options::OPT_shared)) {
5897      if (Args.hasArg(options::OPT_pg))
5898        crt1 = "gcrt1.o";
5899      else if (Args.hasArg(options::OPT_pie))
5900        crt1 = "Scrt1.o";
5901      else
5902        crt1 = "crt1.o";
5903    }
5904    if (crt1)
5905      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
5906
5907    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
5908
5909    const char *crtbegin = NULL;
5910    if (Args.hasArg(options::OPT_static))
5911      crtbegin = "crtbeginT.o";
5912    else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
5913      crtbegin = "crtbeginS.o";
5914    else
5915      crtbegin = "crtbegin.o";
5916
5917    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
5918  }
5919
5920  Args.AddAllArgs(CmdArgs, options::OPT_L);
5921  const ToolChain::path_list Paths = ToolChain.getFilePaths();
5922  for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
5923       i != e; ++i)
5924    CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
5925  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
5926  Args.AddAllArgs(CmdArgs, options::OPT_e);
5927  Args.AddAllArgs(CmdArgs, options::OPT_s);
5928  Args.AddAllArgs(CmdArgs, options::OPT_t);
5929  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
5930  Args.AddAllArgs(CmdArgs, options::OPT_r);
5931
5932  // Tell the linker to load the plugin. This has to come before AddLinkerInputs
5933  // as gold requires -plugin to come before any -plugin-opt that -Wl might
5934  // forward.
5935  if (D.IsUsingLTO(Args)) {
5936    CmdArgs.push_back("-plugin");
5937    std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
5938    CmdArgs.push_back(Args.MakeArgString(Plugin));
5939
5940    // Try to pass driver level flags relevant to LTO code generation down to
5941    // the plugin.
5942
5943    // Handle flags for selecting CPU variants.
5944    std::string CPU = getCPUName(Args, ToolChain.getTriple());
5945    if (!CPU.empty()) {
5946      CmdArgs.push_back(
5947                        Args.MakeArgString(Twine("-plugin-opt=mcpu=") +
5948                                           CPU));
5949    }
5950  }
5951
5952  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
5953
5954  if (!Args.hasArg(options::OPT_nostdlib) &&
5955      !Args.hasArg(options::OPT_nodefaultlibs)) {
5956    if (D.CCCIsCXX()) {
5957      ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
5958      if (Args.hasArg(options::OPT_pg))
5959        CmdArgs.push_back("-lm_p");
5960      else
5961        CmdArgs.push_back("-lm");
5962    }
5963    // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
5964    // the default system libraries. Just mimic this for now.
5965    if (Args.hasArg(options::OPT_pg))
5966      CmdArgs.push_back("-lgcc_p");
5967    else
5968      CmdArgs.push_back("-lgcc");
5969    if (Args.hasArg(options::OPT_static)) {
5970      CmdArgs.push_back("-lgcc_eh");
5971    } else if (Args.hasArg(options::OPT_pg)) {
5972      CmdArgs.push_back("-lgcc_eh_p");
5973    } else {
5974      CmdArgs.push_back("--as-needed");
5975      CmdArgs.push_back("-lgcc_s");
5976      CmdArgs.push_back("--no-as-needed");
5977    }
5978
5979    if (Args.hasArg(options::OPT_pthread)) {
5980      if (Args.hasArg(options::OPT_pg))
5981        CmdArgs.push_back("-lpthread_p");
5982      else
5983        CmdArgs.push_back("-lpthread");
5984    }
5985
5986    if (Args.hasArg(options::OPT_pg)) {
5987      if (Args.hasArg(options::OPT_shared))
5988        CmdArgs.push_back("-lc");
5989      else
5990        CmdArgs.push_back("-lc_p");
5991      CmdArgs.push_back("-lgcc_p");
5992    } else {
5993      CmdArgs.push_back("-lc");
5994      CmdArgs.push_back("-lgcc");
5995    }
5996
5997    if (Args.hasArg(options::OPT_static)) {
5998      CmdArgs.push_back("-lgcc_eh");
5999    } else if (Args.hasArg(options::OPT_pg)) {
6000      CmdArgs.push_back("-lgcc_eh_p");
6001    } else {
6002      CmdArgs.push_back("--as-needed");
6003      CmdArgs.push_back("-lgcc_s");
6004      CmdArgs.push_back("--no-as-needed");
6005    }
6006  }
6007
6008  if (!Args.hasArg(options::OPT_nostdlib) &&
6009      !Args.hasArg(options::OPT_nostartfiles)) {
6010    if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
6011      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
6012    else
6013      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6014    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6015  }
6016
6017  addProfileRT(ToolChain, Args, CmdArgs, ToolChain.getTriple());
6018
6019  const char *Exec =
6020    Args.MakeArgString(ToolChain.GetProgramPath("ld"));
6021  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6022}
6023
6024void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6025                                     const InputInfo &Output,
6026                                     const InputInfoList &Inputs,
6027                                     const ArgList &Args,
6028                                     const char *LinkingOutput) const {
6029  ArgStringList CmdArgs;
6030
6031  // When building 32-bit code on NetBSD/amd64, we have to explicitly
6032  // instruct as in the base system to assemble 32-bit code.
6033  if (getToolChain().getArch() == llvm::Triple::x86)
6034    CmdArgs.push_back("--32");
6035
6036  // Pass the target CPU to GNU as for ARM, since the source code might
6037  // not have the correct .cpu annotation.
6038  if (getToolChain().getArch() == llvm::Triple::arm) {
6039    std::string MArch(getARMTargetCPU(Args, getToolChain().getTriple()));
6040    CmdArgs.push_back(Args.MakeArgString("-mcpu=" + MArch));
6041  }
6042
6043  if (getToolChain().getArch() == llvm::Triple::mips ||
6044      getToolChain().getArch() == llvm::Triple::mipsel ||
6045      getToolChain().getArch() == llvm::Triple::mips64 ||
6046      getToolChain().getArch() == llvm::Triple::mips64el) {
6047    StringRef CPUName;
6048    StringRef ABIName;
6049    getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6050
6051    CmdArgs.push_back("-march");
6052    CmdArgs.push_back(CPUName.data());
6053
6054    CmdArgs.push_back("-mabi");
6055    CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6056
6057    if (getToolChain().getArch() == llvm::Triple::mips ||
6058        getToolChain().getArch() == llvm::Triple::mips64)
6059      CmdArgs.push_back("-EB");
6060    else
6061      CmdArgs.push_back("-EL");
6062
6063    Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
6064                                      options::OPT_fpic, options::OPT_fno_pic,
6065                                      options::OPT_fPIE, options::OPT_fno_PIE,
6066                                      options::OPT_fpie, options::OPT_fno_pie);
6067    if (LastPICArg &&
6068        (LastPICArg->getOption().matches(options::OPT_fPIC) ||
6069         LastPICArg->getOption().matches(options::OPT_fpic) ||
6070         LastPICArg->getOption().matches(options::OPT_fPIE) ||
6071         LastPICArg->getOption().matches(options::OPT_fpie))) {
6072      CmdArgs.push_back("-KPIC");
6073    }
6074  }
6075
6076  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6077                       options::OPT_Xassembler);
6078
6079  CmdArgs.push_back("-o");
6080  CmdArgs.push_back(Output.getFilename());
6081
6082  for (InputInfoList::const_iterator
6083         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6084    const InputInfo &II = *it;
6085    CmdArgs.push_back(II.getFilename());
6086  }
6087
6088  const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
6089  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6090}
6091
6092void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA,
6093                                 const InputInfo &Output,
6094                                 const InputInfoList &Inputs,
6095                                 const ArgList &Args,
6096                                 const char *LinkingOutput) const {
6097  const Driver &D = getToolChain().getDriver();
6098  ArgStringList CmdArgs;
6099
6100  if (!D.SysRoot.empty())
6101    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6102
6103  if (Args.hasArg(options::OPT_static)) {
6104    CmdArgs.push_back("-Bstatic");
6105  } else {
6106    if (Args.hasArg(options::OPT_rdynamic))
6107      CmdArgs.push_back("-export-dynamic");
6108    CmdArgs.push_back("--eh-frame-hdr");
6109    if (Args.hasArg(options::OPT_shared)) {
6110      CmdArgs.push_back("-Bshareable");
6111    } else {
6112      CmdArgs.push_back("-dynamic-linker");
6113      CmdArgs.push_back("/libexec/ld.elf_so");
6114    }
6115  }
6116
6117  // When building 32-bit code on NetBSD/amd64, we have to explicitly
6118  // instruct ld in the base system to link 32-bit code.
6119  if (getToolChain().getArch() == llvm::Triple::x86) {
6120    CmdArgs.push_back("-m");
6121    CmdArgs.push_back("elf_i386");
6122  }
6123
6124  if (Output.isFilename()) {
6125    CmdArgs.push_back("-o");
6126    CmdArgs.push_back(Output.getFilename());
6127  } else {
6128    assert(Output.isNothing() && "Invalid output.");
6129  }
6130
6131  if (!Args.hasArg(options::OPT_nostdlib) &&
6132      !Args.hasArg(options::OPT_nostartfiles)) {
6133    if (!Args.hasArg(options::OPT_shared)) {
6134      CmdArgs.push_back(Args.MakeArgString(
6135                              getToolChain().GetFilePath("crt0.o")));
6136      CmdArgs.push_back(Args.MakeArgString(
6137                              getToolChain().GetFilePath("crti.o")));
6138      CmdArgs.push_back(Args.MakeArgString(
6139                              getToolChain().GetFilePath("crtbegin.o")));
6140    } else {
6141      CmdArgs.push_back(Args.MakeArgString(
6142                              getToolChain().GetFilePath("crti.o")));
6143      CmdArgs.push_back(Args.MakeArgString(
6144                              getToolChain().GetFilePath("crtbeginS.o")));
6145    }
6146  }
6147
6148  Args.AddAllArgs(CmdArgs, options::OPT_L);
6149  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6150  Args.AddAllArgs(CmdArgs, options::OPT_e);
6151  Args.AddAllArgs(CmdArgs, options::OPT_s);
6152  Args.AddAllArgs(CmdArgs, options::OPT_t);
6153  Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
6154  Args.AddAllArgs(CmdArgs, options::OPT_r);
6155
6156  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6157
6158  unsigned Major, Minor, Micro;
6159  getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
6160  bool useLibgcc = true;
6161  if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 23) || Major == 0) {
6162    if (getToolChain().getArch() == llvm::Triple::x86 ||
6163        getToolChain().getArch() == llvm::Triple::x86_64)
6164      useLibgcc = false;
6165  }
6166
6167  if (!Args.hasArg(options::OPT_nostdlib) &&
6168      !Args.hasArg(options::OPT_nodefaultlibs)) {
6169    if (D.CCCIsCXX()) {
6170      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6171      CmdArgs.push_back("-lm");
6172    }
6173    if (Args.hasArg(options::OPT_pthread))
6174      CmdArgs.push_back("-lpthread");
6175    CmdArgs.push_back("-lc");
6176
6177    if (useLibgcc) {
6178      if (Args.hasArg(options::OPT_static)) {
6179        // libgcc_eh depends on libc, so resolve as much as possible,
6180        // pull in any new requirements from libc and then get the rest
6181        // of libgcc.
6182        CmdArgs.push_back("-lgcc_eh");
6183        CmdArgs.push_back("-lc");
6184        CmdArgs.push_back("-lgcc");
6185      } else {
6186        CmdArgs.push_back("-lgcc");
6187        CmdArgs.push_back("--as-needed");
6188        CmdArgs.push_back("-lgcc_s");
6189        CmdArgs.push_back("--no-as-needed");
6190      }
6191    }
6192  }
6193
6194  if (!Args.hasArg(options::OPT_nostdlib) &&
6195      !Args.hasArg(options::OPT_nostartfiles)) {
6196    if (!Args.hasArg(options::OPT_shared))
6197      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6198                                                                  "crtend.o")));
6199    else
6200      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6201                                                                 "crtendS.o")));
6202    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
6203                                                                    "crtn.o")));
6204  }
6205
6206  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6207
6208  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6209  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6210}
6211
6212void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6213                                      const InputInfo &Output,
6214                                      const InputInfoList &Inputs,
6215                                      const ArgList &Args,
6216                                      const char *LinkingOutput) const {
6217  ArgStringList CmdArgs;
6218  bool NeedsKPIC = false;
6219
6220  // Add --32/--64 to make sure we get the format we want.
6221  // This is incomplete
6222  if (getToolChain().getArch() == llvm::Triple::x86) {
6223    CmdArgs.push_back("--32");
6224  } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
6225    CmdArgs.push_back("--64");
6226  } else if (getToolChain().getArch() == llvm::Triple::ppc) {
6227    CmdArgs.push_back("-a32");
6228    CmdArgs.push_back("-mppc");
6229    CmdArgs.push_back("-many");
6230  } else if (getToolChain().getArch() == llvm::Triple::ppc64) {
6231    CmdArgs.push_back("-a64");
6232    CmdArgs.push_back("-mppc64");
6233    CmdArgs.push_back("-many");
6234  } else if (getToolChain().getArch() == llvm::Triple::ppc64le) {
6235    CmdArgs.push_back("-a64");
6236    CmdArgs.push_back("-mppc64le");
6237    CmdArgs.push_back("-many");
6238  } else if (getToolChain().getArch() == llvm::Triple::sparc) {
6239    CmdArgs.push_back("-32");
6240    CmdArgs.push_back("-Av8plusa");
6241    NeedsKPIC = true;
6242  } else if (getToolChain().getArch() == llvm::Triple::sparcv9) {
6243    CmdArgs.push_back("-64");
6244    CmdArgs.push_back("-Av9a");
6245    NeedsKPIC = true;
6246  } else if (getToolChain().getArch() == llvm::Triple::arm) {
6247    StringRef MArch = getToolChain().getArchName();
6248    if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a")
6249      CmdArgs.push_back("-mfpu=neon");
6250    if (MArch == "armv8" || MArch == "armv8a" || MArch == "armv8-a")
6251      CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
6252
6253    StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args,
6254                                           getToolChain().getTriple());
6255    CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI));
6256
6257    Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
6258    Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
6259    Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
6260  } else if (getToolChain().getArch() == llvm::Triple::mips ||
6261             getToolChain().getArch() == llvm::Triple::mipsel ||
6262             getToolChain().getArch() == llvm::Triple::mips64 ||
6263             getToolChain().getArch() == llvm::Triple::mips64el) {
6264    StringRef CPUName;
6265    StringRef ABIName;
6266    getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
6267
6268    CmdArgs.push_back("-march");
6269    CmdArgs.push_back(CPUName.data());
6270
6271    CmdArgs.push_back("-mabi");
6272    CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
6273
6274    if (getToolChain().getArch() == llvm::Triple::mips ||
6275        getToolChain().getArch() == llvm::Triple::mips64)
6276      CmdArgs.push_back("-EB");
6277    else
6278      CmdArgs.push_back("-EL");
6279
6280    if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
6281      if (StringRef(A->getValue()) == "2008")
6282        CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
6283    }
6284
6285    if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfp64)) {
6286      if (A->getOption().matches(options::OPT_mfp32))
6287        CmdArgs.push_back(Args.MakeArgString("-mfp32"));
6288      else
6289        CmdArgs.push_back(Args.MakeArgString("-mfp64"));
6290    }
6291
6292    Args.AddLastArg(CmdArgs, options::OPT_mips16, options::OPT_mno_mips16);
6293    Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
6294                    options::OPT_mno_micromips);
6295    Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
6296    Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
6297
6298    if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
6299      // Do not use AddLastArg because not all versions of MIPS assembler
6300      // support -mmsa / -mno-msa options.
6301      if (A->getOption().matches(options::OPT_mmsa))
6302        CmdArgs.push_back(Args.MakeArgString("-mmsa"));
6303    }
6304
6305    NeedsKPIC = true;
6306  } else if (getToolChain().getArch() == llvm::Triple::systemz) {
6307    // Always pass an -march option, since our default of z10 is later
6308    // than the GNU assembler's default.
6309    StringRef CPUName = getSystemZTargetCPU(Args);
6310    CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
6311  }
6312
6313  if (NeedsKPIC) {
6314    Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
6315                                      options::OPT_fpic, options::OPT_fno_pic,
6316                                      options::OPT_fPIE, options::OPT_fno_PIE,
6317                                      options::OPT_fpie, options::OPT_fno_pie);
6318    if (LastPICArg &&
6319        (LastPICArg->getOption().matches(options::OPT_fPIC) ||
6320         LastPICArg->getOption().matches(options::OPT_fpic) ||
6321         LastPICArg->getOption().matches(options::OPT_fPIE) ||
6322         LastPICArg->getOption().matches(options::OPT_fpie))) {
6323      CmdArgs.push_back("-KPIC");
6324    }
6325  }
6326
6327  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6328                       options::OPT_Xassembler);
6329
6330  CmdArgs.push_back("-o");
6331  CmdArgs.push_back(Output.getFilename());
6332
6333  for (InputInfoList::const_iterator
6334         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6335    const InputInfo &II = *it;
6336    CmdArgs.push_back(II.getFilename());
6337  }
6338
6339  const char *Exec =
6340    Args.MakeArgString(getToolChain().GetProgramPath("as"));
6341  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6342
6343  // Handle the debug info splitting at object creation time if we're
6344  // creating an object.
6345  // TODO: Currently only works on linux with newer objcopy.
6346  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6347      getToolChain().getTriple().isOSLinux())
6348    SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6349                   SplitDebugName(Args, Inputs));
6350}
6351
6352static void AddLibgcc(llvm::Triple Triple, const Driver &D,
6353                      ArgStringList &CmdArgs, const ArgList &Args) {
6354  bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android;
6355  bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
6356                      Args.hasArg(options::OPT_static);
6357  if (!D.CCCIsCXX())
6358    CmdArgs.push_back("-lgcc");
6359
6360  if (StaticLibgcc || isAndroid) {
6361    if (D.CCCIsCXX())
6362      CmdArgs.push_back("-lgcc");
6363  } else {
6364    if (!D.CCCIsCXX())
6365      CmdArgs.push_back("--as-needed");
6366    CmdArgs.push_back("-lgcc_s");
6367    if (!D.CCCIsCXX())
6368      CmdArgs.push_back("--no-as-needed");
6369  }
6370
6371  if (StaticLibgcc && !isAndroid)
6372    CmdArgs.push_back("-lgcc_eh");
6373  else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
6374    CmdArgs.push_back("-lgcc");
6375
6376  // According to Android ABI, we have to link with libdl if we are
6377  // linking with non-static libgcc.
6378  //
6379  // NOTE: This fixes a link error on Android MIPS as well.  The non-static
6380  // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
6381  if (isAndroid && !StaticLibgcc)
6382    CmdArgs.push_back("-ldl");
6383}
6384
6385static bool hasMipsN32ABIArg(const ArgList &Args) {
6386  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6387  return A && (A->getValue() == StringRef("n32"));
6388}
6389
6390static StringRef getLinuxDynamicLinker(const ArgList &Args,
6391                                       const toolchains::Linux &ToolChain) {
6392  if (ToolChain.getTriple().getEnvironment() == llvm::Triple::Android)
6393    return "/system/bin/linker";
6394  else if (ToolChain.getArch() == llvm::Triple::x86 ||
6395           ToolChain.getArch() == llvm::Triple::sparc)
6396    return "/lib/ld-linux.so.2";
6397  else if (ToolChain.getArch() == llvm::Triple::aarch64)
6398    return "/lib/ld-linux-aarch64.so.1";
6399  else if (ToolChain.getArch() == llvm::Triple::arm ||
6400           ToolChain.getArch() == llvm::Triple::thumb) {
6401    if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
6402      return "/lib/ld-linux-armhf.so.3";
6403    else
6404      return "/lib/ld-linux.so.3";
6405  } else if (ToolChain.getArch() == llvm::Triple::mips ||
6406             ToolChain.getArch() == llvm::Triple::mipsel)
6407    return "/lib/ld.so.1";
6408  else if (ToolChain.getArch() == llvm::Triple::mips64 ||
6409           ToolChain.getArch() == llvm::Triple::mips64el) {
6410    if (hasMipsN32ABIArg(Args))
6411      return "/lib32/ld.so.1";
6412    else
6413      return "/lib64/ld.so.1";
6414  } else if (ToolChain.getArch() == llvm::Triple::ppc)
6415    return "/lib/ld.so.1";
6416  else if (ToolChain.getArch() == llvm::Triple::ppc64 ||
6417           ToolChain.getArch() == llvm::Triple::ppc64le ||
6418           ToolChain.getArch() == llvm::Triple::systemz)
6419    return "/lib64/ld64.so.1";
6420  else if (ToolChain.getArch() == llvm::Triple::sparcv9)
6421    return "/lib64/ld-linux.so.2";
6422  else
6423    return "/lib64/ld-linux-x86-64.so.2";
6424}
6425
6426void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
6427                                  const InputInfo &Output,
6428                                  const InputInfoList &Inputs,
6429                                  const ArgList &Args,
6430                                  const char *LinkingOutput) const {
6431  const toolchains::Linux& ToolChain =
6432    static_cast<const toolchains::Linux&>(getToolChain());
6433  const Driver &D = ToolChain.getDriver();
6434  const bool isAndroid =
6435    ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
6436  const SanitizerArgs &Sanitize = ToolChain.getSanitizerArgs();
6437  const bool IsPIE =
6438    !Args.hasArg(options::OPT_shared) &&
6439    (Args.hasArg(options::OPT_pie) || Sanitize.hasZeroBaseShadow());
6440
6441  ArgStringList CmdArgs;
6442
6443  // Silence warning for "clang -g foo.o -o foo"
6444  Args.ClaimAllArgs(options::OPT_g_Group);
6445  // and "clang -emit-llvm foo.o -o foo"
6446  Args.ClaimAllArgs(options::OPT_emit_llvm);
6447  // and for "clang -w foo.o -o foo". Other warning options are already
6448  // handled somewhere else.
6449  Args.ClaimAllArgs(options::OPT_w);
6450
6451  if (!D.SysRoot.empty())
6452    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6453
6454  if (IsPIE)
6455    CmdArgs.push_back("-pie");
6456
6457  if (Args.hasArg(options::OPT_rdynamic))
6458    CmdArgs.push_back("-export-dynamic");
6459
6460  if (Args.hasArg(options::OPT_s))
6461    CmdArgs.push_back("-s");
6462
6463  for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(),
6464         e = ToolChain.ExtraOpts.end();
6465       i != e; ++i)
6466    CmdArgs.push_back(i->c_str());
6467
6468  if (!Args.hasArg(options::OPT_static)) {
6469    CmdArgs.push_back("--eh-frame-hdr");
6470  }
6471
6472  CmdArgs.push_back("-m");
6473  if (ToolChain.getArch() == llvm::Triple::x86)
6474    CmdArgs.push_back("elf_i386");
6475  else if (ToolChain.getArch() == llvm::Triple::aarch64)
6476    CmdArgs.push_back("aarch64linux");
6477  else if (ToolChain.getArch() == llvm::Triple::arm
6478           ||  ToolChain.getArch() == llvm::Triple::thumb)
6479    CmdArgs.push_back("armelf_linux_eabi");
6480  else if (ToolChain.getArch() == llvm::Triple::ppc)
6481    CmdArgs.push_back("elf32ppclinux");
6482  else if (ToolChain.getArch() == llvm::Triple::ppc64)
6483    CmdArgs.push_back("elf64ppc");
6484  else if (ToolChain.getArch() == llvm::Triple::sparc)
6485    CmdArgs.push_back("elf32_sparc");
6486  else if (ToolChain.getArch() == llvm::Triple::sparcv9)
6487    CmdArgs.push_back("elf64_sparc");
6488  else if (ToolChain.getArch() == llvm::Triple::mips)
6489    CmdArgs.push_back("elf32btsmip");
6490  else if (ToolChain.getArch() == llvm::Triple::mipsel)
6491    CmdArgs.push_back("elf32ltsmip");
6492  else if (ToolChain.getArch() == llvm::Triple::mips64) {
6493    if (hasMipsN32ABIArg(Args))
6494      CmdArgs.push_back("elf32btsmipn32");
6495    else
6496      CmdArgs.push_back("elf64btsmip");
6497  }
6498  else if (ToolChain.getArch() == llvm::Triple::mips64el) {
6499    if (hasMipsN32ABIArg(Args))
6500      CmdArgs.push_back("elf32ltsmipn32");
6501    else
6502      CmdArgs.push_back("elf64ltsmip");
6503  }
6504  else if (ToolChain.getArch() == llvm::Triple::systemz)
6505    CmdArgs.push_back("elf64_s390");
6506  else
6507    CmdArgs.push_back("elf_x86_64");
6508
6509  if (Args.hasArg(options::OPT_static)) {
6510    if (ToolChain.getArch() == llvm::Triple::arm
6511        || ToolChain.getArch() == llvm::Triple::thumb)
6512      CmdArgs.push_back("-Bstatic");
6513    else
6514      CmdArgs.push_back("-static");
6515  } else if (Args.hasArg(options::OPT_shared)) {
6516    CmdArgs.push_back("-shared");
6517    if (isAndroid) {
6518      CmdArgs.push_back("-Bsymbolic");
6519    }
6520  }
6521
6522  if (ToolChain.getArch() == llvm::Triple::arm ||
6523      ToolChain.getArch() == llvm::Triple::thumb ||
6524      (!Args.hasArg(options::OPT_static) &&
6525       !Args.hasArg(options::OPT_shared))) {
6526    CmdArgs.push_back("-dynamic-linker");
6527    CmdArgs.push_back(Args.MakeArgString(
6528        D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
6529  }
6530
6531  CmdArgs.push_back("-o");
6532  CmdArgs.push_back(Output.getFilename());
6533
6534  if (!Args.hasArg(options::OPT_nostdlib) &&
6535      !Args.hasArg(options::OPT_nostartfiles)) {
6536    if (!isAndroid) {
6537      const char *crt1 = NULL;
6538      if (!Args.hasArg(options::OPT_shared)){
6539        if (Args.hasArg(options::OPT_pg))
6540          crt1 = "gcrt1.o";
6541        else if (IsPIE)
6542          crt1 = "Scrt1.o";
6543        else
6544          crt1 = "crt1.o";
6545      }
6546      if (crt1)
6547        CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
6548
6549      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
6550    }
6551
6552    const char *crtbegin;
6553    if (Args.hasArg(options::OPT_static))
6554      crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
6555    else if (Args.hasArg(options::OPT_shared))
6556      crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
6557    else if (IsPIE)
6558      crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
6559    else
6560      crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
6561    CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
6562
6563    // Add crtfastmath.o if available and fast math is enabled.
6564    ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
6565  }
6566
6567  Args.AddAllArgs(CmdArgs, options::OPT_L);
6568
6569  const ToolChain::path_list Paths = ToolChain.getFilePaths();
6570
6571  for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end();
6572       i != e; ++i)
6573    CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
6574
6575  // Tell the linker to load the plugin. This has to come before AddLinkerInputs
6576  // as gold requires -plugin to come before any -plugin-opt that -Wl might
6577  // forward.
6578  if (D.IsUsingLTO(Args)) {
6579    CmdArgs.push_back("-plugin");
6580    std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so";
6581    CmdArgs.push_back(Args.MakeArgString(Plugin));
6582
6583    // Try to pass driver level flags relevant to LTO code generation down to
6584    // the plugin.
6585
6586    // Handle flags for selecting CPU variants.
6587    std::string CPU = getCPUName(Args, ToolChain.getTriple());
6588    if (!CPU.empty()) {
6589      CmdArgs.push_back(
6590                        Args.MakeArgString(Twine("-plugin-opt=mcpu=") +
6591                                           CPU));
6592    }
6593  }
6594
6595
6596  if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6597    CmdArgs.push_back("--no-demangle");
6598
6599  AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6600
6601  // Call these before we add the C++ ABI library.
6602  if (Sanitize.needsUbsanRt())
6603    addUbsanRTLinux(getToolChain(), Args, CmdArgs, D.CCCIsCXX(),
6604                    Sanitize.needsAsanRt() || Sanitize.needsTsanRt() ||
6605                    Sanitize.needsMsanRt() || Sanitize.needsLsanRt());
6606  if (Sanitize.needsAsanRt())
6607    addAsanRTLinux(getToolChain(), Args, CmdArgs);
6608  if (Sanitize.needsTsanRt())
6609    addTsanRTLinux(getToolChain(), Args, CmdArgs);
6610  if (Sanitize.needsMsanRt())
6611    addMsanRTLinux(getToolChain(), Args, CmdArgs);
6612  if (Sanitize.needsLsanRt())
6613    addLsanRTLinux(getToolChain(), Args, CmdArgs);
6614  if (Sanitize.needsDfsanRt())
6615    addDfsanRTLinux(getToolChain(), Args, CmdArgs);
6616
6617  // The profile runtime also needs access to system libraries.
6618  addProfileRTLinux(getToolChain(), Args, CmdArgs);
6619
6620  if (D.CCCIsCXX() &&
6621      !Args.hasArg(options::OPT_nostdlib) &&
6622      !Args.hasArg(options::OPT_nodefaultlibs)) {
6623    bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
6624      !Args.hasArg(options::OPT_static);
6625    if (OnlyLibstdcxxStatic)
6626      CmdArgs.push_back("-Bstatic");
6627    ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6628    if (OnlyLibstdcxxStatic)
6629      CmdArgs.push_back("-Bdynamic");
6630    CmdArgs.push_back("-lm");
6631  }
6632
6633  if (!Args.hasArg(options::OPT_nostdlib)) {
6634    if (!Args.hasArg(options::OPT_nodefaultlibs)) {
6635      if (Args.hasArg(options::OPT_static))
6636        CmdArgs.push_back("--start-group");
6637
6638      bool OpenMP = Args.hasArg(options::OPT_fopenmp);
6639      if (OpenMP) {
6640        CmdArgs.push_back("-lgomp");
6641
6642        // FIXME: Exclude this for platforms whith libgomp that doesn't require
6643        // librt. Most modern Linux platfroms require it, but some may not.
6644        CmdArgs.push_back("-lrt");
6645      }
6646
6647      AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6648
6649      if (Args.hasArg(options::OPT_pthread) ||
6650          Args.hasArg(options::OPT_pthreads) || OpenMP)
6651        CmdArgs.push_back("-lpthread");
6652
6653      CmdArgs.push_back("-lc");
6654
6655      if (Args.hasArg(options::OPT_static))
6656        CmdArgs.push_back("--end-group");
6657      else
6658        AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args);
6659    }
6660
6661    if (!Args.hasArg(options::OPT_nostartfiles)) {
6662      const char *crtend;
6663      if (Args.hasArg(options::OPT_shared))
6664        crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
6665      else if (IsPIE)
6666        crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
6667      else
6668        crtend = isAndroid ? "crtend_android.o" : "crtend.o";
6669
6670      CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
6671      if (!isAndroid)
6672        CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
6673    }
6674  }
6675
6676  C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
6677}
6678
6679void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6680                                   const InputInfo &Output,
6681                                   const InputInfoList &Inputs,
6682                                   const ArgList &Args,
6683                                   const char *LinkingOutput) const {
6684  ArgStringList CmdArgs;
6685
6686  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6687                       options::OPT_Xassembler);
6688
6689  CmdArgs.push_back("-o");
6690  CmdArgs.push_back(Output.getFilename());
6691
6692  for (InputInfoList::const_iterator
6693         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6694    const InputInfo &II = *it;
6695    CmdArgs.push_back(II.getFilename());
6696  }
6697
6698  const char *Exec =
6699    Args.MakeArgString(getToolChain().GetProgramPath("as"));
6700  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6701}
6702
6703void minix::Link::ConstructJob(Compilation &C, const JobAction &JA,
6704                               const InputInfo &Output,
6705                               const InputInfoList &Inputs,
6706                               const ArgList &Args,
6707                               const char *LinkingOutput) const {
6708  const Driver &D = getToolChain().getDriver();
6709  ArgStringList CmdArgs;
6710
6711  if (Output.isFilename()) {
6712    CmdArgs.push_back("-o");
6713    CmdArgs.push_back(Output.getFilename());
6714  } else {
6715    assert(Output.isNothing() && "Invalid output.");
6716  }
6717
6718  if (!Args.hasArg(options::OPT_nostdlib) &&
6719      !Args.hasArg(options::OPT_nostartfiles)) {
6720      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
6721      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
6722      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
6723      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
6724  }
6725
6726  Args.AddAllArgs(CmdArgs, options::OPT_L);
6727  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6728  Args.AddAllArgs(CmdArgs, options::OPT_e);
6729
6730  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6731
6732  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6733
6734  if (!Args.hasArg(options::OPT_nostdlib) &&
6735      !Args.hasArg(options::OPT_nodefaultlibs)) {
6736    if (D.CCCIsCXX()) {
6737      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6738      CmdArgs.push_back("-lm");
6739    }
6740  }
6741
6742  if (!Args.hasArg(options::OPT_nostdlib) &&
6743      !Args.hasArg(options::OPT_nostartfiles)) {
6744    if (Args.hasArg(options::OPT_pthread))
6745      CmdArgs.push_back("-lpthread");
6746    CmdArgs.push_back("-lc");
6747    CmdArgs.push_back("-lCompilerRT-Generic");
6748    CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
6749    CmdArgs.push_back(
6750         Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
6751  }
6752
6753  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6754  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6755}
6756
6757/// DragonFly Tools
6758
6759// For now, DragonFly Assemble does just about the same as for
6760// FreeBSD, but this may change soon.
6761void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
6762                                       const InputInfo &Output,
6763                                       const InputInfoList &Inputs,
6764                                       const ArgList &Args,
6765                                       const char *LinkingOutput) const {
6766  ArgStringList CmdArgs;
6767
6768  // When building 32-bit code on DragonFly/pc64, we have to explicitly
6769  // instruct as in the base system to assemble 32-bit code.
6770  if (getToolChain().getArch() == llvm::Triple::x86)
6771    CmdArgs.push_back("--32");
6772
6773  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
6774                       options::OPT_Xassembler);
6775
6776  CmdArgs.push_back("-o");
6777  CmdArgs.push_back(Output.getFilename());
6778
6779  for (InputInfoList::const_iterator
6780         it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6781    const InputInfo &II = *it;
6782    CmdArgs.push_back(II.getFilename());
6783  }
6784
6785  const char *Exec =
6786    Args.MakeArgString(getToolChain().GetProgramPath("as"));
6787  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6788}
6789
6790void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
6791                                   const InputInfo &Output,
6792                                   const InputInfoList &Inputs,
6793                                   const ArgList &Args,
6794                                   const char *LinkingOutput) const {
6795  bool UseGCC47 = false;
6796  const Driver &D = getToolChain().getDriver();
6797  ArgStringList CmdArgs;
6798
6799  if (llvm::sys::fs::exists("/usr/lib/gcc47", UseGCC47))
6800    UseGCC47 = false;
6801
6802  if (!D.SysRoot.empty())
6803    CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6804
6805  CmdArgs.push_back("--eh-frame-hdr");
6806  if (Args.hasArg(options::OPT_static)) {
6807    CmdArgs.push_back("-Bstatic");
6808  } else {
6809    if (Args.hasArg(options::OPT_rdynamic))
6810      CmdArgs.push_back("-export-dynamic");
6811    if (Args.hasArg(options::OPT_shared))
6812      CmdArgs.push_back("-Bshareable");
6813    else {
6814      CmdArgs.push_back("-dynamic-linker");
6815      CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
6816    }
6817    CmdArgs.push_back("--hash-style=both");
6818  }
6819
6820  // When building 32-bit code on DragonFly/pc64, we have to explicitly
6821  // instruct ld in the base system to link 32-bit code.
6822  if (getToolChain().getArch() == llvm::Triple::x86) {
6823    CmdArgs.push_back("-m");
6824    CmdArgs.push_back("elf_i386");
6825  }
6826
6827  if (Output.isFilename()) {
6828    CmdArgs.push_back("-o");
6829    CmdArgs.push_back(Output.getFilename());
6830  } else {
6831    assert(Output.isNothing() && "Invalid output.");
6832  }
6833
6834  if (!Args.hasArg(options::OPT_nostdlib) &&
6835      !Args.hasArg(options::OPT_nostartfiles)) {
6836    if (!Args.hasArg(options::OPT_shared)) {
6837      if (Args.hasArg(options::OPT_pg))
6838        CmdArgs.push_back(Args.MakeArgString(
6839                                getToolChain().GetFilePath("gcrt1.o")));
6840      else {
6841        if (Args.hasArg(options::OPT_pie))
6842          CmdArgs.push_back(Args.MakeArgString(
6843                                  getToolChain().GetFilePath("Scrt1.o")));
6844        else
6845          CmdArgs.push_back(Args.MakeArgString(
6846                                  getToolChain().GetFilePath("crt1.o")));
6847      }
6848    }
6849    CmdArgs.push_back(Args.MakeArgString(
6850                            getToolChain().GetFilePath("crti.o")));
6851    if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
6852      CmdArgs.push_back(Args.MakeArgString(
6853                              getToolChain().GetFilePath("crtbeginS.o")));
6854    else
6855      CmdArgs.push_back(Args.MakeArgString(
6856                              getToolChain().GetFilePath("crtbegin.o")));
6857  }
6858
6859  Args.AddAllArgs(CmdArgs, options::OPT_L);
6860  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
6861  Args.AddAllArgs(CmdArgs, options::OPT_e);
6862
6863  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6864
6865  if (!Args.hasArg(options::OPT_nostdlib) &&
6866      !Args.hasArg(options::OPT_nodefaultlibs)) {
6867    // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
6868    //         rpaths
6869    if (UseGCC47)
6870      CmdArgs.push_back("-L/usr/lib/gcc47");
6871    else
6872      CmdArgs.push_back("-L/usr/lib/gcc44");
6873
6874    if (!Args.hasArg(options::OPT_static)) {
6875      if (UseGCC47) {
6876        CmdArgs.push_back("-rpath");
6877        CmdArgs.push_back("/usr/lib/gcc47");
6878      } else {
6879        CmdArgs.push_back("-rpath");
6880        CmdArgs.push_back("/usr/lib/gcc44");
6881      }
6882    }
6883
6884    if (D.CCCIsCXX()) {
6885      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
6886      CmdArgs.push_back("-lm");
6887    }
6888
6889    if (Args.hasArg(options::OPT_pthread))
6890      CmdArgs.push_back("-lpthread");
6891
6892    if (!Args.hasArg(options::OPT_nolibc)) {
6893      CmdArgs.push_back("-lc");
6894    }
6895
6896    if (UseGCC47) {
6897      if (Args.hasArg(options::OPT_static) ||
6898          Args.hasArg(options::OPT_static_libgcc)) {
6899        CmdArgs.push_back("-lgcc");
6900        CmdArgs.push_back("-lgcc_eh");
6901      } else {
6902        if (Args.hasArg(options::OPT_shared_libgcc)) {
6903          CmdArgs.push_back("-lgcc_pic");
6904          if (!Args.hasArg(options::OPT_shared))
6905            CmdArgs.push_back("-lgcc");
6906        } else {
6907          CmdArgs.push_back("-lgcc");
6908          CmdArgs.push_back("--as-needed");
6909          CmdArgs.push_back("-lgcc_pic");
6910          CmdArgs.push_back("--no-as-needed");
6911        }
6912      }
6913    } else {
6914      if (Args.hasArg(options::OPT_shared)) {
6915        CmdArgs.push_back("-lgcc_pic");
6916      } else {
6917        CmdArgs.push_back("-lgcc");
6918      }
6919    }
6920  }
6921
6922  if (!Args.hasArg(options::OPT_nostdlib) &&
6923      !Args.hasArg(options::OPT_nostartfiles)) {
6924    if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
6925      CmdArgs.push_back(Args.MakeArgString(
6926                              getToolChain().GetFilePath("crtendS.o")));
6927    else
6928      CmdArgs.push_back(Args.MakeArgString(
6929                              getToolChain().GetFilePath("crtend.o")));
6930    CmdArgs.push_back(Args.MakeArgString(
6931                            getToolChain().GetFilePath("crtn.o")));
6932  }
6933
6934  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
6935
6936  const char *Exec =
6937    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
6938  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
6939}
6940
6941void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA,
6942                                      const InputInfo &Output,
6943                                      const InputInfoList &Inputs,
6944                                      const ArgList &Args,
6945                                      const char *LinkingOutput) const {
6946  ArgStringList CmdArgs;
6947
6948  if (Output.isFilename()) {
6949    CmdArgs.push_back(Args.MakeArgString(std::string("-out:") +
6950                                         Output.getFilename()));
6951  } else {
6952    assert(Output.isNothing() && "Invalid output.");
6953  }
6954
6955  if (!Args.hasArg(options::OPT_nostdlib) &&
6956      !Args.hasArg(options::OPT_nostartfiles) &&
6957      !C.getDriver().IsCLMode()) {
6958    CmdArgs.push_back("-defaultlib:libcmt");
6959  }
6960
6961  CmdArgs.push_back("-nologo");
6962
6963  bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd);
6964
6965  if (DLL) {
6966    CmdArgs.push_back(Args.MakeArgString("-dll"));
6967
6968    SmallString<128> ImplibName(Output.getFilename());
6969    llvm::sys::path::replace_extension(ImplibName, "lib");
6970    CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") +
6971                                         ImplibName.str()));
6972  }
6973
6974  if (getToolChain().getSanitizerArgs().needsAsanRt()) {
6975    CmdArgs.push_back(Args.MakeArgString("-debug"));
6976    CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
6977    SmallString<128> LibSanitizer(getToolChain().getDriver().ResourceDir);
6978    llvm::sys::path::append(LibSanitizer, "lib", "windows");
6979    if (DLL) {
6980      llvm::sys::path::append(LibSanitizer, "clang_rt.asan_dll_thunk-i386.lib");
6981    } else {
6982      llvm::sys::path::append(LibSanitizer, "clang_rt.asan-i386.lib");
6983    }
6984    // FIXME: Handle 64-bit.
6985    CmdArgs.push_back(Args.MakeArgString(LibSanitizer));
6986  }
6987
6988  Args.AddAllArgValues(CmdArgs, options::OPT_l);
6989  Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
6990
6991  // Add filenames immediately.
6992  for (InputInfoList::const_iterator
6993       it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
6994    if (it->isFilename())
6995      CmdArgs.push_back(it->getFilename());
6996    else
6997      it->getInputArg().renderAsInput(Args, CmdArgs);
6998  }
6999
7000  const char *Exec =
7001    Args.MakeArgString(getToolChain().GetProgramPath("link.exe"));
7002  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7003}
7004
7005void visualstudio::Compile::ConstructJob(Compilation &C, const JobAction &JA,
7006                                         const InputInfo &Output,
7007                                         const InputInfoList &Inputs,
7008                                         const ArgList &Args,
7009                                         const char *LinkingOutput) const {
7010  C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
7011}
7012
7013// Try to find FallbackName on PATH that is not identical to ClangProgramPath.
7014// If one cannot be found, return FallbackName.
7015// We do this special search to prevent clang-cl from falling back onto itself
7016// if it's available as cl.exe on the path.
7017static std::string FindFallback(const char *FallbackName,
7018                                const char *ClangProgramPath) {
7019  llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
7020  if (!OptPath.hasValue())
7021    return FallbackName;
7022
7023#ifdef LLVM_ON_WIN32
7024  const StringRef PathSeparators = ";";
7025#else
7026  const StringRef PathSeparators = ":";
7027#endif
7028
7029  SmallVector<StringRef, 8> PathSegments;
7030  llvm::SplitString(OptPath.getValue(), PathSegments, PathSeparators);
7031
7032  for (size_t i = 0, e = PathSegments.size(); i != e; ++i) {
7033    const StringRef &PathSegment = PathSegments[i];
7034    if (PathSegment.empty())
7035      continue;
7036
7037    SmallString<128> FilePath(PathSegment);
7038    llvm::sys::path::append(FilePath, FallbackName);
7039    if (llvm::sys::fs::can_execute(Twine(FilePath)) &&
7040        !llvm::sys::fs::equivalent(Twine(FilePath), ClangProgramPath))
7041      return FilePath.str();
7042  }
7043
7044  return FallbackName;
7045}
7046
7047Command *visualstudio::Compile::GetCommand(Compilation &C, const JobAction &JA,
7048                                           const InputInfo &Output,
7049                                           const InputInfoList &Inputs,
7050                                           const ArgList &Args,
7051                                           const char *LinkingOutput) const {
7052  ArgStringList CmdArgs;
7053  CmdArgs.push_back("/nologo");
7054  CmdArgs.push_back("/c"); // Compile only.
7055  CmdArgs.push_back("/W0"); // No warnings.
7056
7057  // The goal is to be able to invoke this tool correctly based on
7058  // any flag accepted by clang-cl.
7059
7060  // These are spelled the same way in clang and cl.exe,.
7061  Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U);
7062  Args.AddAllArgs(CmdArgs, options::OPT_I);
7063
7064  // Optimization level.
7065  if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
7066    if (A->getOption().getID() == options::OPT_O0) {
7067      CmdArgs.push_back("/Od");
7068    } else {
7069      StringRef OptLevel = A->getValue();
7070      if (OptLevel == "1" || OptLevel == "2" || OptLevel == "s")
7071        A->render(Args, CmdArgs);
7072      else if (OptLevel == "3")
7073        CmdArgs.push_back("/Ox");
7074    }
7075  }
7076
7077  // Flags for which clang-cl have an alias.
7078  // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
7079
7080  if (Arg *A = Args.getLastArg(options::OPT_frtti, options::OPT_fno_rtti))
7081    CmdArgs.push_back(A->getOption().getID() == options::OPT_frtti ? "/GR"
7082                                                                   : "/GR-");
7083  if (Args.hasArg(options::OPT_fsyntax_only))
7084    CmdArgs.push_back("/Zs");
7085
7086  std::vector<std::string> Includes = Args.getAllArgValues(options::OPT_include);
7087  for (size_t I = 0, E = Includes.size(); I != E; ++I)
7088    CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Includes[I]));
7089
7090  // Flags that can simply be passed through.
7091  Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
7092  Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
7093
7094  // The order of these flags is relevant, so pick the last one.
7095  if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
7096                               options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
7097    A->render(Args, CmdArgs);
7098
7099
7100  // Input filename.
7101  assert(Inputs.size() == 1);
7102  const InputInfo &II = Inputs[0];
7103  assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
7104  CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
7105  if (II.isFilename())
7106    CmdArgs.push_back(II.getFilename());
7107  else
7108    II.getInputArg().renderAsInput(Args, CmdArgs);
7109
7110  // Output filename.
7111  assert(Output.getType() == types::TY_Object);
7112  const char *Fo = Args.MakeArgString(std::string("/Fo") +
7113                                      Output.getFilename());
7114  CmdArgs.push_back(Fo);
7115
7116  const Driver &D = getToolChain().getDriver();
7117  std::string Exec = FindFallback("cl.exe", D.getClangProgramPath());
7118
7119  return new Command(JA, *this, Args.MakeArgString(Exec), CmdArgs);
7120}
7121
7122
7123/// XCore Tools
7124// We pass assemble and link construction to the xcc tool.
7125
7126void XCore::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
7127                                       const InputInfo &Output,
7128                                       const InputInfoList &Inputs,
7129                                       const ArgList &Args,
7130                                       const char *LinkingOutput) const {
7131  ArgStringList CmdArgs;
7132
7133  CmdArgs.push_back("-o");
7134  CmdArgs.push_back(Output.getFilename());
7135
7136  CmdArgs.push_back("-c");
7137
7138  if (Args.hasArg(options::OPT_g_Group)) {
7139    CmdArgs.push_back("-g");
7140  }
7141
7142  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
7143                       options::OPT_Xassembler);
7144
7145  for (InputInfoList::const_iterator
7146       it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) {
7147    const InputInfo &II = *it;
7148    CmdArgs.push_back(II.getFilename());
7149  }
7150
7151  const char *Exec =
7152    Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
7153  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7154}
7155
7156void XCore::Link::ConstructJob(Compilation &C, const JobAction &JA,
7157                                   const InputInfo &Output,
7158                                   const InputInfoList &Inputs,
7159                                   const ArgList &Args,
7160                                   const char *LinkingOutput) const {
7161  ArgStringList CmdArgs;
7162
7163  if (Output.isFilename()) {
7164    CmdArgs.push_back("-o");
7165    CmdArgs.push_back(Output.getFilename());
7166  } else {
7167    assert(Output.isNothing() && "Invalid output.");
7168  }
7169
7170  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7171
7172  const char *Exec =
7173    Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
7174  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
7175}
7176