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