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