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