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