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