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