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