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