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