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