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