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